1use 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::{Imap, ServerMetadata};
24use crate::log::warn;
25use crate::logged_debug_assert;
26use crate::message::{self, MessageState, MsgId};
27use crate::net::tls::{SpkiHashStore, TlsSessionStore};
28use crate::peer_channels::Iroh;
29use crate::push::PushSubscriber;
30use crate::quota::QuotaInfo;
31use crate::scheduler::{ConnectivityStore, SchedulerState};
32use crate::sql::Sql;
33use crate::stock_str::StockStrings;
34use crate::tools::{self, duration_to_str, time, time_elapsed};
35use crate::transport::ConfiguredLoginParam;
36use crate::{chatlist_events, stats};
37
38pub use crate::scheduler::connectivity::Connectivity;
39
40#[derive(Clone, Debug)]
65pub struct ContextBuilder {
66 dbfile: PathBuf,
67 id: u32,
68 events: Events,
69 stock_strings: StockStrings,
70 password: Option<String>,
71
72 push_subscriber: Option<PushSubscriber>,
73}
74
75impl ContextBuilder {
76 pub fn new(dbfile: PathBuf) -> Self {
82 ContextBuilder {
83 dbfile,
84 id: rand::random(),
85 events: Events::new(),
86 stock_strings: StockStrings::new(),
87 password: None,
88 push_subscriber: None,
89 }
90 }
91
92 pub fn with_id(mut self, id: u32) -> Self {
102 self.id = id;
103 self
104 }
105
106 pub fn with_events(mut self, events: Events) -> Self {
115 self.events = events;
116 self
117 }
118
119 pub fn with_stock_strings(mut self, stock_strings: StockStrings) -> Self {
130 self.stock_strings = stock_strings;
131 self
132 }
133
134 #[deprecated(since = "TBD")]
142 pub fn with_password(mut self, password: String) -> Self {
143 self.password = Some(password);
144 self
145 }
146
147 pub(crate) fn with_push_subscriber(mut self, push_subscriber: PushSubscriber) -> Self {
149 self.push_subscriber = Some(push_subscriber);
150 self
151 }
152
153 pub async fn build(self) -> Result<Context> {
155 let push_subscriber = self.push_subscriber.unwrap_or_default();
156 let context = Context::new_closed(
157 &self.dbfile,
158 self.id,
159 self.events,
160 self.stock_strings,
161 push_subscriber,
162 )
163 .await?;
164 Ok(context)
165 }
166
167 pub async fn open(self) -> Result<Context> {
171 let password = self.password.clone().unwrap_or_default();
172 let context = self.build().await?;
173 match context.open(password).await? {
174 true => Ok(context),
175 false => bail!("database could not be decrypted, incorrect or missing password"),
176 }
177 }
178}
179
180#[derive(Clone, Debug)]
192pub struct Context {
193 pub(crate) inner: Arc<InnerContext>,
194}
195
196impl Deref for Context {
197 type Target = InnerContext;
198
199 fn deref(&self) -> &Self::Target {
200 &self.inner
201 }
202}
203
204#[derive(Clone, Debug)]
208pub(crate) struct WeakContext {
209 inner: Weak<InnerContext>,
210}
211
212impl WeakContext {
213 pub(crate) fn upgrade(&self) -> Result<Context> {
215 let inner = self
216 .inner
217 .upgrade()
218 .ok_or_else(|| anyhow::anyhow!("Inner struct has been dropped"))?;
219 Ok(Context { inner })
220 }
221}
222
223#[derive(Debug)]
225pub struct InnerContext {
226 pub(crate) blobdir: PathBuf,
228 pub(crate) sql: Sql,
229 running_state: RwLock<RunningState>,
234 pub(crate) oauth2_mutex: Mutex<()>,
236 pub(crate) wrong_pw_warning_mutex: Mutex<()>,
238 pub(crate) housekeeping_mutex: Mutex<()>,
240
241 pub(crate) fetch_msgs_mutex: Mutex<()>,
248
249 pub(crate) translated_stockstrings: StockStrings,
250 pub(crate) events: Events,
251
252 pub(crate) scheduler: SchedulerState,
253 pub(crate) ratelimit: RwLock<Ratelimit>,
254
255 pub(crate) quota: RwLock<BTreeMap<u32, QuotaInfo>>,
258
259 pub(crate) new_msgs_notify: Notify,
263
264 pub(crate) server_id: RwLock<Option<HashMap<String, String>>>,
268
269 pub(crate) metadata: RwLock<Option<ServerMetadata>>,
271
272 pub(crate) id: u32,
277
278 creation_time: tools::Time,
279
280 pub(crate) last_error: parking_lot::RwLock<String>,
284
285 pub(crate) migration_error: parking_lot::RwLock<Option<String>>,
291
292 pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>,
297
298 pub(crate) push_subscriber: PushSubscriber,
301
302 pub(crate) push_subscribed: AtomicBool,
304
305 pub(crate) tls_session_store: TlsSessionStore,
307
308 pub(crate) spki_hash_store: SpkiHashStore,
314
315 pub(crate) iroh: Arc<RwLock<Option<Iroh>>>,
317
318 pub(crate) self_fingerprint: OnceLock<String>,
322
323 pub(crate) self_public_key: Mutex<Option<SignedPublicKey>>,
329
330 pub(crate) connectivities: parking_lot::Mutex<Vec<ConnectivityStore>>,
333}
334
335#[derive(Debug, Default)]
337enum RunningState {
338 Running { cancel_sender: Sender<()> },
340
341 ShallStop { request: tools::Time },
343
344 #[default]
346 Stopped,
347}
348
349#[expect(clippy::arithmetic_side_effects)]
356pub fn get_info() -> BTreeMap<&'static str, String> {
357 let mut res = BTreeMap::new();
358
359 #[cfg(debug_assertions)]
360 res.insert(
361 "debug_assertions",
362 "On - DO NOT RELEASE THIS BUILD".to_string(),
363 );
364 #[cfg(not(debug_assertions))]
365 res.insert("debug_assertions", "Off".to_string());
366
367 res.insert("deltachat_core_version", format!("v{DC_VERSION_STR}"));
368 res.insert("sqlite_version", rusqlite::version().to_string());
369 res.insert("arch", (std::mem::size_of::<usize>() * 8).to_string());
370 res.insert("num_cpus", num_cpus::get().to_string());
371 res.insert("level", "awesome".into());
372 res
373}
374
375impl Context {
376 pub async fn new(
378 dbfile: &Path,
379 id: u32,
380 events: Events,
381 stock_strings: StockStrings,
382 ) -> Result<Context> {
383 let context =
384 Self::new_closed(dbfile, id, events, stock_strings, Default::default()).await?;
385
386 if context.check_passphrase("".to_string()).await? {
388 context.sql.open(&context, "".to_string()).await?;
389 }
390 Ok(context)
391 }
392
393 pub async fn new_closed(
395 dbfile: &Path,
396 id: u32,
397 events: Events,
398 stockstrings: StockStrings,
399 push_subscriber: PushSubscriber,
400 ) -> Result<Context> {
401 let mut blob_fname = OsString::new();
402 blob_fname.push(dbfile.file_name().unwrap_or_default());
403 blob_fname.push("-blobs");
404 let blobdir = dbfile.with_file_name(blob_fname);
405 if !blobdir.exists() {
406 tokio::fs::create_dir_all(&blobdir).await?;
407 }
408 let context = Context::with_blobdir(
409 dbfile.into(),
410 blobdir,
411 id,
412 events,
413 stockstrings,
414 push_subscriber,
415 )?;
416 Ok(context)
417 }
418
419 pub(crate) fn get_weak_context(&self) -> WeakContext {
421 WeakContext {
422 inner: Arc::downgrade(&self.inner),
423 }
424 }
425
426 #[deprecated(since = "TBD")]
433 pub async fn open(&self, passphrase: String) -> Result<bool> {
434 if self.sql.check_passphrase(passphrase.clone()).await? {
435 self.sql.open(self, passphrase).await?;
436 Ok(true)
437 } else {
438 Ok(false)
439 }
440 }
441
442 pub async fn change_passphrase(&self, passphrase: String) -> Result<()> {
445 self.sql.change_passphrase(passphrase).await?;
446 Ok(())
447 }
448
449 pub async fn is_open(&self) -> bool {
451 self.sql.is_open().await
452 }
453
454 pub(crate) async fn check_passphrase(&self, passphrase: String) -> Result<bool> {
460 self.sql.check_passphrase(passphrase).await
461 }
462
463 pub(crate) fn with_blobdir(
464 dbfile: PathBuf,
465 blobdir: PathBuf,
466 id: u32,
467 events: Events,
468 stockstrings: StockStrings,
469 push_subscriber: PushSubscriber,
470 ) -> Result<Context> {
471 ensure!(
472 blobdir.is_dir(),
473 "Blobdir does not exist: {}",
474 blobdir.display()
475 );
476
477 let new_msgs_notify = Notify::new();
478 new_msgs_notify.notify_one();
481
482 let inner = InnerContext {
483 id,
484 blobdir,
485 running_state: RwLock::new(Default::default()),
486 sql: Sql::new(dbfile),
487 oauth2_mutex: Mutex::new(()),
488 wrong_pw_warning_mutex: Mutex::new(()),
489 housekeeping_mutex: Mutex::new(()),
490 fetch_msgs_mutex: Mutex::new(()),
491 translated_stockstrings: stockstrings,
492 events,
493 scheduler: SchedulerState::new(),
494 ratelimit: RwLock::new(Ratelimit::new(Duration::new(3, 0), 3.0)), quota: RwLock::new(BTreeMap::new()),
496 new_msgs_notify,
497 server_id: RwLock::new(None),
498 metadata: RwLock::new(None),
499 creation_time: tools::Time::now(),
500 last_error: parking_lot::RwLock::new("".to_string()),
501 migration_error: parking_lot::RwLock::new(None),
502 debug_logging: std::sync::RwLock::new(None),
503 push_subscriber,
504 push_subscribed: AtomicBool::new(false),
505 tls_session_store: TlsSessionStore::new(),
506 spki_hash_store: SpkiHashStore::new(),
507 iroh: Arc::new(RwLock::new(None)),
508 self_fingerprint: OnceLock::new(),
509 self_public_key: Mutex::new(None),
510 connectivities: parking_lot::Mutex::new(Vec::new()),
511 };
512
513 let ctx = Context {
514 inner: Arc::new(inner),
515 };
516
517 Ok(ctx)
518 }
519
520 pub async fn start_io(&self) {
522 if !self.is_configured().await.unwrap_or_default() {
523 warn!(self, "can not start io on a context that is not configured");
524 return;
525 }
526
527 self.sql.config_cache.write().await.clear();
533
534 self.scheduler.start(self).await;
535 }
536
537 pub async fn stop_io(&self) {
539 self.scheduler.stop(self).await;
540 if let Some(iroh) = self.iroh.write().await.take() {
541 tokio::spawn(async move {
548 let _ = tokio::time::timeout(Duration::from_secs(60), iroh.close()).await;
551 });
552 }
553 }
554
555 pub async fn restart_io_if_running(&self) {
558 self.scheduler.restart(self).await;
559 }
560
561 pub async fn maybe_network(&self) {
563 if let Some(ref iroh) = *self.iroh.read().await {
564 iroh.network_change().await;
565 }
566 self.scheduler.maybe_network().await;
567 }
568
569 pub async fn is_chatmail(&self) -> Result<bool> {
571 self.get_config_bool(Config::IsChatmail).await
572 }
573
574 pub(crate) async fn get_max_smtp_rcpt_to(&self) -> Result<usize> {
576 let is_chatmail = self.is_chatmail().await?;
577 let val = self
578 .get_configured_provider()
579 .await?
580 .and_then(|provider| provider.opt.max_smtp_rcpt_to)
581 .map_or_else(
582 || match is_chatmail {
583 true => constants::DEFAULT_CHATMAIL_MAX_SMTP_RCPT_TO,
584 false => constants::DEFAULT_MAX_SMTP_RCPT_TO,
585 },
586 usize::from,
587 );
588 Ok(val)
589 }
590
591 pub async fn background_fetch(&self) -> Result<()> {
597 if !(self.is_configured().await?) {
598 return Ok(());
599 }
600
601 let address = self.get_primary_self_addr().await?;
602 let time_start = tools::Time::now();
603 info!(self, "background_fetch started fetching {address}.");
604
605 if self.scheduler.is_running().await {
606 self.scheduler.maybe_network().await;
607 self.wait_for_all_work_done().await;
608 } else {
609 let _pause_guard = self.scheduler.pause(self).await?;
612
613 let mut connection = Imap::new_configured(self, channel::bounded(1).1).await?;
615 let mut session = connection.prepare(self).await?;
616
617 let folder = connection.folder.clone();
619 connection
620 .fetch_move_delete(self, &mut session, &folder)
621 .await?;
622
623 if self
627 .quota_needs_update(
628 session.transport_id(),
629 DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT,
630 )
631 .await
632 && let Err(err) = self.update_recent_quota(&mut session, &folder).await
633 {
634 warn!(self, "Failed to update quota: {err:#}.");
635 }
636 }
637
638 info!(
639 self,
640 "background_fetch done for {address} took {:?}.",
641 time_elapsed(&time_start),
642 );
643
644 Ok(())
645 }
646
647 #[cfg(feature = "internals")]
651 pub fn sql(&self) -> &Sql {
652 &self.inner.sql
653 }
654
655 pub fn get_dbfile(&self) -> &Path {
657 self.sql.dbfile.as_path()
658 }
659
660 pub fn get_blobdir(&self) -> &Path {
662 self.blobdir.as_path()
663 }
664
665 pub fn emit_event(&self, event: EventType) {
667 {
668 let lock = self.debug_logging.read().expect("RwLock is poisoned");
669 if let Some(debug_logging) = &*lock {
670 debug_logging.log_event(event.clone());
671 }
672 }
673 self.events.emit(Event {
674 id: self.id,
675 typ: event,
676 });
677 }
678
679 pub fn emit_msgs_changed_without_ids(&self) {
681 self.emit_event(EventType::MsgsChanged {
682 chat_id: ChatId::new(0),
683 msg_id: MsgId::new(0),
684 });
685 }
686
687 pub fn emit_msgs_changed(&self, chat_id: ChatId, msg_id: MsgId) {
693 logged_debug_assert!(
694 self,
695 !chat_id.is_unset(),
696 "emit_msgs_changed: chat_id is unset."
697 );
698 logged_debug_assert!(
699 self,
700 !msg_id.is_unset(),
701 "emit_msgs_changed: msg_id is unset."
702 );
703
704 self.emit_event(EventType::MsgsChanged { chat_id, msg_id });
705 chatlist_events::emit_chatlist_changed(self);
706 chatlist_events::emit_chatlist_item_changed(self, chat_id);
707 }
708
709 pub fn emit_msgs_changed_without_msg_id(&self, chat_id: ChatId) {
711 logged_debug_assert!(
712 self,
713 !chat_id.is_unset(),
714 "emit_msgs_changed_without_msg_id: chat_id is unset."
715 );
716
717 self.emit_event(EventType::MsgsChanged {
718 chat_id,
719 msg_id: MsgId::new(0),
720 });
721 chatlist_events::emit_chatlist_changed(self);
722 chatlist_events::emit_chatlist_item_changed(self, chat_id);
723 }
724
725 pub fn emit_incoming_msg(&self, chat_id: ChatId, msg_id: MsgId) {
727 debug_assert!(!chat_id.is_unset());
728 debug_assert!(!msg_id.is_unset());
729
730 self.emit_event(EventType::IncomingMsg { chat_id, msg_id });
731 chatlist_events::emit_chatlist_changed(self);
732 chatlist_events::emit_chatlist_item_changed(self, chat_id);
733 }
734
735 pub async fn emit_location_changed(&self, contact_id: Option<ContactId>) -> Result<()> {
737 self.emit_event(EventType::LocationChanged(contact_id));
738
739 if let Some(msg_id) = self
740 .get_config_parsed::<u32>(Config::WebxdcIntegration)
741 .await?
742 {
743 self.emit_event(EventType::WebxdcStatusUpdate {
744 msg_id: MsgId::new(msg_id),
745 status_update_serial: Default::default(),
746 })
747 }
748
749 Ok(())
750 }
751
752 pub fn get_event_emitter(&self) -> EventEmitter {
757 self.events.get_emitter()
758 }
759
760 pub fn get_id(&self) -> u32 {
762 self.id
763 }
764
765 pub(crate) async fn alloc_ongoing(&self) -> Result<Receiver<()>> {
775 let mut s = self.running_state.write().await;
776 ensure!(
777 matches!(*s, RunningState::Stopped),
778 "There is already another ongoing process running."
779 );
780
781 let (sender, receiver) = channel::bounded(1);
782 *s = RunningState::Running {
783 cancel_sender: sender,
784 };
785
786 Ok(receiver)
787 }
788
789 pub(crate) async fn free_ongoing(&self) {
790 let mut s = self.running_state.write().await;
791 if let RunningState::ShallStop { request } = *s {
792 info!(self, "Ongoing stopped in {:?}", time_elapsed(&request));
793 }
794 *s = RunningState::Stopped;
795 }
796
797 pub async fn stop_ongoing(&self) {
799 let mut s = self.running_state.write().await;
800 match &*s {
801 RunningState::Running { cancel_sender } => {
802 if let Err(err) = cancel_sender.send(()).await {
803 warn!(self, "could not cancel ongoing: {:#}", err);
804 }
805 info!(self, "Signaling the ongoing process to stop ASAP.",);
806 *s = RunningState::ShallStop {
807 request: tools::Time::now(),
808 };
809 }
810 RunningState::ShallStop { .. } | RunningState::Stopped => {
811 info!(self, "No ongoing process to stop.",);
812 }
813 }
814 }
815
816 #[allow(unused)]
817 pub(crate) async fn shall_stop_ongoing(&self) -> bool {
818 match &*self.running_state.read().await {
819 RunningState::Running { .. } => false,
820 RunningState::ShallStop { .. } | RunningState::Stopped => true,
821 }
822 }
823
824 pub async fn get_info(&self) -> Result<BTreeMap<&'static str, String>> {
830 let all_transports: Vec<String> = ConfiguredLoginParam::load_all(self)
831 .await?
832 .into_iter()
833 .map(|(transport_id, param)| format!("{transport_id}: {param}"))
834 .collect();
835 let all_transports = if all_transports.is_empty() {
836 "Not configured".to_string()
837 } else {
838 all_transports.join(",")
839 };
840 let chats = get_chat_cnt(self).await?;
841 let unblocked_msgs = message::get_unblocked_msg_cnt(self).await;
842 let request_msgs = message::get_request_msg_cnt(self).await;
843 let contacts = Contact::get_real_cnt(self).await?;
844 let proxy_enabled = self.get_config_int(Config::ProxyEnabled).await?;
845 let dbversion = self
846 .sql
847 .get_raw_config_int("dbversion")
848 .await?
849 .unwrap_or_default();
850 let journal_mode = self
851 .sql
852 .query_get_value("PRAGMA journal_mode;", ())
853 .await?
854 .unwrap_or_else(|| "unknown".to_string());
855 let mdns_enabled = self.get_config_int(Config::MdnsEnabled).await?;
856 let bcc_self = self.get_config_int(Config::BccSelf).await?;
857 let sync_msgs = self.get_config_int(Config::SyncMsgs).await?;
858 let disable_idle = self.get_config_bool(Config::DisableIdle).await?;
859
860 let prv_key_cnt = self.sql.count("SELECT COUNT(*) FROM keypairs;", ()).await?;
861
862 let pub_key_cnt = self
863 .sql
864 .count("SELECT COUNT(*) FROM public_keys;", ())
865 .await?;
866
867 let mut res = get_info();
868
869 res.insert("bot", self.get_config_int(Config::Bot).await?.to_string());
871 res.insert("number_of_chats", chats.to_string());
872 res.insert("number_of_chat_messages", unblocked_msgs.to_string());
873 res.insert("messages_in_contact_requests", request_msgs.to_string());
874 res.insert("number_of_contacts", contacts.to_string());
875 res.insert("database_dir", self.get_dbfile().display().to_string());
876 res.insert("database_version", dbversion.to_string());
877 res.insert(
878 "database_encrypted",
879 self.sql
880 .is_encrypted()
881 .await
882 .map_or_else(|| "closed".to_string(), |b| b.to_string()),
883 );
884 res.insert("journal_mode", journal_mode);
885 res.insert("blobdir", self.get_blobdir().display().to_string());
886 res.insert(
887 "selfavatar",
888 self.get_config(Config::Selfavatar)
889 .await?
890 .unwrap_or_else(|| "<unset>".to_string()),
891 );
892 res.insert("proxy_enabled", proxy_enabled.to_string());
893 res.insert("used_transport_settings", all_transports);
894
895 if let Some(server_id) = &*self.server_id.read().await {
896 res.insert("imap_server_id", format!("{server_id:?}"));
897 }
898
899 res.insert("is_chatmail", self.is_chatmail().await?.to_string());
900 res.insert(
901 "fix_is_chatmail",
902 self.get_config_bool(Config::FixIsChatmail)
903 .await?
904 .to_string(),
905 );
906 res.insert(
907 "is_muted",
908 self.get_config_bool(Config::IsMuted).await?.to_string(),
909 );
910 res.insert(
911 "private_tag",
912 self.get_config(Config::PrivateTag)
913 .await?
914 .unwrap_or_else(|| "<unset>".to_string()),
915 );
916
917 if let Some(metadata) = &*self.metadata.read().await {
918 if let Some(comment) = &metadata.comment {
919 res.insert("imap_server_comment", format!("{comment:?}"));
920 }
921
922 if let Some(admin) = &metadata.admin {
923 res.insert("imap_server_admin", format!("{admin:?}"));
924 }
925 }
926
927 res.insert(
928 "who_can_call_me",
929 self.get_config_int(Config::WhoCanCallMe).await?.to_string(),
930 );
931 res.insert(
932 "download_limit",
933 self.get_config_int(Config::DownloadLimit)
934 .await?
935 .to_string(),
936 );
937 res.insert("mdns_enabled", mdns_enabled.to_string());
938 res.insert("bcc_self", bcc_self.to_string());
939 res.insert("sync_msgs", sync_msgs.to_string());
940 res.insert("disable_idle", disable_idle.to_string());
941 res.insert("private_key_count", prv_key_cnt.to_string());
942 res.insert("public_key_count", pub_key_cnt.to_string());
943 res.insert(
944 "media_quality",
945 self.get_config_int(Config::MediaQuality).await?.to_string(),
946 );
947 res.insert(
948 "delete_device_after",
949 self.get_config_int(Config::DeleteDeviceAfter)
950 .await?
951 .to_string(),
952 );
953 res.insert(
954 "last_housekeeping",
955 self.get_config_int(Config::LastHousekeeping)
956 .await?
957 .to_string(),
958 );
959 res.insert(
960 "last_cant_decrypt_outgoing_msgs",
961 self.get_config_int(Config::LastCantDecryptOutgoingMsgs)
962 .await?
963 .to_string(),
964 );
965 res.insert(
966 "debug_logging",
967 self.get_config_int(Config::DebugLogging).await?.to_string(),
968 );
969 res.insert(
970 "last_msg_id",
971 self.get_config_int(Config::LastMsgId).await?.to_string(),
972 );
973 res.insert(
974 "gossip_period",
975 self.get_config_int(Config::GossipPeriod).await?.to_string(),
976 );
977 res.insert(
978 "webxdc_realtime_enabled",
979 self.get_config_bool(Config::WebxdcRealtimeEnabled)
980 .await?
981 .to_string(),
982 );
983 res.insert(
984 "donation_request_next_check",
985 self.get_config_i64(Config::DonationRequestNextCheck)
986 .await?
987 .to_string(),
988 );
989 res.insert(
990 "first_key_contacts_msg_id",
991 self.sql
992 .get_raw_config("first_key_contacts_msg_id")
993 .await?
994 .unwrap_or_default(),
995 );
996 res.insert(
997 "stats_id",
998 self.get_config(Config::StatsId)
999 .await?
1000 .unwrap_or_else(|| "<unset>".to_string()),
1001 );
1002 res.insert(
1003 "stats_sending",
1004 stats::should_send_stats(self).await?.to_string(),
1005 );
1006 res.insert(
1007 "stats_last_sent",
1008 self.get_config_i64(Config::StatsLastSent)
1009 .await?
1010 .to_string(),
1011 );
1012 res.insert(
1013 "test_hooks",
1014 self.sql
1015 .get_raw_config("test_hooks")
1016 .await?
1017 .unwrap_or_default(),
1018 );
1019 res.insert(
1020 "std_header_protection_composing",
1021 self.sql
1022 .get_raw_config("std_header_protection_composing")
1023 .await?
1024 .unwrap_or_default(),
1025 );
1026 res.insert(
1027 "team_profile",
1028 self.get_config_bool(Config::TeamProfile).await?.to_string(),
1029 );
1030 res.insert(
1031 "force_encryption",
1032 self.get_config_bool(Config::ForceEncryption)
1033 .await?
1034 .to_string(),
1035 );
1036
1037 let elapsed = time_elapsed(&self.creation_time);
1038 res.insert("uptime", duration_to_str(elapsed));
1039
1040 Ok(res)
1041 }
1042
1043 pub async fn get_fresh_msgs(&self) -> Result<Vec<MsgId>> {
1050 let list = self
1051 .sql
1052 .query_map_vec(
1053 "SELECT m.id
1054FROM msgs m
1055LEFT JOIN contacts ct
1056 ON m.from_id=ct.id
1057LEFT JOIN chats c
1058 ON m.chat_id=c.id
1059WHERE m.state=?
1060AND m.hidden=0
1061AND m.chat_id>9
1062AND ct.blocked=0
1063AND c.blocked=0
1064AND NOT(c.muted_until=-1 OR c.muted_until>?)
1065ORDER BY m.timestamp DESC,m.id DESC",
1066 (MessageState::InFresh, time()),
1067 |row| {
1068 let msg_id: MsgId = row.get(0)?;
1069 Ok(msg_id)
1070 },
1071 )
1072 .await?;
1073 Ok(list)
1074 }
1075
1076 pub async fn get_next_msgs(&self) -> Result<Vec<MsgId>> {
1088 let last_msg_id = match self.get_config(Config::LastMsgId).await? {
1089 Some(s) => MsgId::new(s.parse()?),
1090 None => {
1091 self.sql
1096 .query_row(
1097 "SELECT IFNULL((SELECT MAX(id) - 1 FROM msgs), 0)",
1098 (),
1099 |row| {
1100 let msg_id: MsgId = row.get(0)?;
1101 Ok(msg_id)
1102 },
1103 )
1104 .await?
1105 }
1106 };
1107
1108 let list = self
1109 .sql
1110 .query_map_vec(
1111 "SELECT m.id
1112 FROM msgs m
1113 LEFT JOIN contacts ct
1114 ON m.from_id=ct.id
1115 LEFT JOIN chats c
1116 ON m.chat_id=c.id
1117 WHERE m.id>?
1118 AND m.hidden=0
1119 AND m.chat_id>9
1120 AND ct.blocked=0
1121 AND c.blocked!=1
1122 ORDER BY m.id ASC",
1123 (
1124 last_msg_id.to_u32(), ),
1126 |row| {
1127 let msg_id: MsgId = row.get(0)?;
1128 Ok(msg_id)
1129 },
1130 )
1131 .await?;
1132 Ok(list)
1133 }
1134
1135 pub async fn wait_next_msgs(&self) -> Result<Vec<MsgId>> {
1153 self.new_msgs_notify.notified().await;
1154 let list = self.get_next_msgs().await?;
1155 Ok(list)
1156 }
1157
1158 pub async fn search_msgs(&self, chat_id: Option<ChatId>, query: &str) -> Result<Vec<MsgId>> {
1169 let real_query = query.trim().to_lowercase();
1170 if real_query.is_empty() {
1171 return Ok(Vec::new());
1172 }
1173 let str_like_in_text = format!("%{real_query}%");
1174
1175 let list = if let Some(chat_id) = chat_id {
1176 self.sql
1177 .query_map_vec(
1178 "SELECT m.id AS id
1179 FROM msgs m
1180 LEFT JOIN contacts ct
1181 ON m.from_id=ct.id
1182 WHERE m.chat_id=?
1183 AND m.hidden=0
1184 AND ct.blocked=0
1185 AND IFNULL(txt_normalized, txt) LIKE ?
1186 ORDER BY m.timestamp,m.id;",
1187 (chat_id, str_like_in_text),
1188 |row| {
1189 let msg_id: MsgId = row.get("id")?;
1190 Ok(msg_id)
1191 },
1192 )
1193 .await?
1194 } else {
1195 self.sql
1206 .query_map_vec(
1207 "SELECT m.id AS id
1208 FROM msgs m
1209 LEFT JOIN contacts ct
1210 ON m.from_id=ct.id
1211 LEFT JOIN chats c
1212 ON m.chat_id=c.id
1213 WHERE m.chat_id>9
1214 AND m.hidden=0
1215 AND c.blocked!=1
1216 AND ct.blocked=0
1217 AND IFNULL(txt_normalized, txt) LIKE ?
1218 ORDER BY m.id DESC LIMIT 1000",
1219 (str_like_in_text,),
1220 |row| {
1221 let msg_id: MsgId = row.get("id")?;
1222 Ok(msg_id)
1223 },
1224 )
1225 .await?
1226 };
1227
1228 Ok(list)
1229 }
1230
1231 pub(crate) fn derive_blobdir(dbfile: &Path) -> PathBuf {
1232 let mut blob_fname = OsString::new();
1233 blob_fname.push(dbfile.file_name().unwrap_or_default());
1234 blob_fname.push("-blobs");
1235 dbfile.with_file_name(blob_fname)
1236 }
1237
1238 pub(crate) fn derive_walfile(dbfile: &Path) -> PathBuf {
1239 let mut wal_fname = OsString::new();
1240 wal_fname.push(dbfile.file_name().unwrap_or_default());
1241 wal_fname.push("-wal");
1242 dbfile.with_file_name(wal_fname)
1243 }
1244}
1245
1246#[cfg(test)]
1247mod context_tests;