diff --git a/assets/self-reporting-bot.vcf b/assets/statistics-bot.vcf similarity index 100% rename from assets/self-reporting-bot.vcf rename to assets/statistics-bot.vcf diff --git a/deltachat-jsonrpc/src/api.rs b/deltachat-jsonrpc/src/api.rs index fe6d2e7444..803132969b 100644 --- a/deltachat-jsonrpc/src/api.rs +++ b/deltachat-jsonrpc/src/api.rs @@ -383,11 +383,6 @@ impl CommandApi { Ok(BlobObject::create_and_deduplicate(&ctx, file, file)?.to_abs_path()) } - async fn draft_self_report(&self, account_id: u32) -> Result { - let ctx = self.get_context(account_id).await?; - Ok(ctx.draft_self_report().await?.to_u32()) - } - /// Sets the given configuration key. async fn set_config(&self, account_id: u32, key: String, value: Option) -> Result<()> { let ctx = self.get_context(account_id).await?; @@ -886,6 +881,54 @@ impl CommandApi { Ok(chat_id.to_u32()) } + /// Like `secure_join()`, but allows to pass a source and a UI-path. + /// You only need this if your UI has an option to send statistics + /// to Delta Chat's developers. + /// + /// **source**: The source where the QR code came from. One of: + /// ```rust + /// enum SecurejoinSource { + /// /// Because of some problem, it is unknown where the QR code came from. + /// Unknown = 0, + /// /// The user opened a link somewhere outside Delta Chat + /// ExternalLink = 1, + /// /// The user clicked on a link in a message inside Delta Chat + /// InternalLink = 2, + /// /// The user clicked "Paste from Clipboard" in the QR scan activity + /// Clipboard = 3, + /// /// The user clicked "Load QR code as image" in the QR scan activity + /// ImageLoaded = 4, + /// /// The user scanned a QR code + /// Scan = 5, + /// } + /// ``` + /// + /// **uipath**: Which UI path did the user use to arrive at the QR code screen. + /// If the SecurejoinSource was ExternalLink or InternalLink, + /// you can just pass 0 here, because the QR code screen wasn't even opened. + /// ```rust + /// enum SecurejoinUIPath { + /// /// The UI path is unknown, or the user didn't open the QR code screen at all. + /// Unknown = 0, + /// /// The user directly clicked on the QR icon in the main screen + /// QrIcon = 1, + /// /// The user first clicked on the `+` button in the main screen, + /// /// and then on "New Contact" + /// NewContact = 2, + /// } + /// ``` + async fn secure_join_with_ux_info( + &self, + account_id: u32, + qr: String, + source: Option, + uipath: Option, + ) -> Result { + let ctx = self.get_context(account_id).await?; + let chat_id = securejoin::join_securejoin_with_ux_info(&ctx, &qr, source, uipath).await?; + Ok(chat_id.to_u32()) + } + async fn leave_group(&self, account_id: u32, chat_id: u32) -> Result<()> { let ctx = self.get_context(account_id).await?; remove_contact_from_chat(&ctx, ChatId::new(chat_id), ContactId::SELF).await diff --git a/deltachat-time/src/lib.rs b/deltachat-time/src/lib.rs index c8d7d6f6c2..7e92a3f61a 100644 --- a/deltachat-time/src/lib.rs +++ b/deltachat-time/src/lib.rs @@ -20,6 +20,11 @@ impl SystemTimeTools { pub fn shift(duration: Duration) { *SYSTEM_TIME_SHIFT.write().unwrap() += duration; } + + /// Simulates the system clock being rewound by `duration`. + pub fn shift_backwards(duration: Duration) { + *SYSTEM_TIME_SHIFT.write().unwrap() -= duration; + } } #[cfg(test)] diff --git a/src/config.rs b/src/config.rs index 7bfebd868e..8d62e29077 100644 --- a/src/config.rs +++ b/src/config.rs @@ -14,7 +14,6 @@ use tokio::fs; use crate::blob::BlobObject; use crate::configure::EnteredLoginParam; -use crate::constants; use crate::context::Context; use crate::events::EventType; use crate::log::{LogExt, info}; @@ -23,6 +22,7 @@ use crate::mimefactory::RECOMMENDED_FILE_SIZE; use crate::provider::{Provider, get_provider_by_id}; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::get_abs_path; +use crate::{constants, statistics}; /// The available configuration keys. #[derive( @@ -431,9 +431,25 @@ pub enum Config { /// used for signatures, encryption to self and included in `Autocrypt` header. KeyId, - /// This key is sent to the self_reporting bot so that the bot can recognize the user + /// Send statistics to Delta Chat's developers. + /// Can be exposed to the user as a setting. + StatsSending, + + /// Last time statistics were sent to Delta Chat's developers + StatsLastSent, + + /// This key is sent to the statistics bot so that the bot can recognize the user /// without storing the email address - SelfReportingId, + StatsId, + + /// The last message id that was already included in the previously sent statistics, + /// or that already existed before the user opted in. + /// Only messages with an id larger than this + /// will be counted in the next statistics. + StatsLastCountedMsgId, + + /// The last contact id that already existed when statistics-sending was enabled. + StatsLastOldContactId, /// MsgId of webxdc map integration. WebxdcIntegration, @@ -827,6 +843,11 @@ impl Context { .await?; } } + Config::StatsSending => { + self.sql.set_raw_config(key.as_ref(), value).await?; + statistics::set_last_counted_msg_id(self).await?; + statistics::set_last_old_contact_id(self).await?; + } _ => { self.sql.set_raw_config(key.as_ref(), value).await?; } diff --git a/src/context.rs b/src/context.rs index 0272a74c06..8b634355a6 100644 --- a/src/context.rs +++ b/src/context.rs @@ -10,27 +10,21 @@ use std::time::Duration; use anyhow::{Context as _, Result, bail, ensure}; use async_channel::{self as channel, Receiver, Sender}; -use pgp::types::PublicKeyTrait; use ratelimit::Ratelimit; use tokio::sync::{Mutex, Notify, RwLock}; -use crate::chat::{ChatId, ProtectionStatus, get_chat_cnt}; -use crate::chatlist_events; +use crate::chat::{ChatId, get_chat_cnt}; use crate::config::Config; -use crate::constants::{ - self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR, -}; -use crate::contact::{Contact, ContactId, import_vcard, mark_contact_id_as_verified}; +use crate::constants::{self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_VERSION_STR}; +use crate::contact::{Contact, ContactId}; use crate::debug_logging::DebugLogging; -use crate::download::DownloadState; use crate::events::{Event, EventEmitter, EventType, Events}; use crate::imap::{FolderMeaning, Imap, ServerMetadata}; -use crate::key::{load_self_secret_key, self_fingerprint}; +use crate::key::self_fingerprint; use crate::log::{info, warn}; use crate::logged_debug_assert; use crate::login_param::{ConfiguredLoginParam, EnteredLoginParam}; -use crate::message::{self, Message, MessageState, MsgId}; -use crate::param::{Param, Params}; +use crate::message::{self, MessageState, MsgId}; use crate::peer_channels::Iroh; use crate::push::PushSubscriber; use crate::quota::QuotaInfo; @@ -38,7 +32,8 @@ use crate::scheduler::{ConnectivityStore, SchedulerState, convert_folder_meaning use crate::sql::Sql; use crate::stock_str::StockStrings; use crate::timesmearing::SmearedTimestamp; -use crate::tools::{self, create_id, duration_to_str, time, time_elapsed}; +use crate::tools::{self, duration_to_str, time, time_elapsed}; +use crate::{chatlist_events, statistics}; /// Builder for the [`Context`]. /// @@ -1081,6 +1076,20 @@ impl Context { .await? .unwrap_or_default(), ); + res.insert( + "stats_id", + self.get_config_bool(Config::StatsId).await?.to_string(), + ); + res.insert( + "stats_sending", + statistics::should_send_statistics(self).await?.to_string(), + ); + res.insert( + "stats_last_sent", + self.get_config_i64(Config::StatsLastSent) + .await? + .to_string(), + ); let elapsed = time_elapsed(&self.creation_time); res.insert("uptime", duration_to_str(elapsed)); @@ -1088,147 +1097,6 @@ impl Context { Ok(res) } - async fn get_self_report(&self) -> Result { - #[derive(Default)] - struct ChatNumbers { - protected: u32, - opportunistic_dc: u32, - opportunistic_mua: u32, - unencrypted_dc: u32, - unencrypted_mua: u32, - } - - let mut res = String::new(); - res += &format!("core_version {}\n", get_version_str()); - - let num_msgs: u32 = self - .sql - .query_get_value( - "SELECT COUNT(*) FROM msgs WHERE hidden=0 AND chat_id!=?", - (DC_CHAT_ID_TRASH,), - ) - .await? - .unwrap_or_default(); - res += &format!("num_msgs {num_msgs}\n"); - - let num_chats: u32 = self - .sql - .query_get_value("SELECT COUNT(*) FROM chats WHERE id>9 AND blocked!=1", ()) - .await? - .unwrap_or_default(); - res += &format!("num_chats {num_chats}\n"); - - let db_size = tokio::fs::metadata(&self.sql.dbfile).await?.len(); - res += &format!("db_size_bytes {db_size}\n"); - - let secret_key = &load_self_secret_key(self).await?.primary_key; - let key_created = secret_key.public_key().created_at().timestamp(); - res += &format!("key_created {key_created}\n"); - - // how many of the chats active in the last months are: - // - protected - // - opportunistic-encrypted and the contact uses Delta Chat - // - opportunistic-encrypted and the contact uses a classical MUA - // - unencrypted and the contact uses Delta Chat - // - unencrypted and the contact uses a classical MUA - let three_months_ago = time().saturating_sub(3600 * 24 * 30 * 3); - let chats = self - .sql - .query_map( - "SELECT c.protected, m.param, m.msgrmsg - FROM chats c - JOIN msgs m - ON c.id=m.chat_id - AND m.id=( - SELECT id - FROM msgs - WHERE chat_id=c.id - AND hidden=0 - AND download_state=? - AND to_id!=? - ORDER BY timestamp DESC, id DESC LIMIT 1) - WHERE c.id>9 - AND (c.blocked=0 OR c.blocked=2) - AND IFNULL(m.timestamp,c.created_timestamp) > ? - GROUP BY c.id", - (DownloadState::Done, ContactId::INFO, three_months_ago), - |row| { - let protected: ProtectionStatus = row.get(0)?; - let message_param: Params = - row.get::<_, String>(1)?.parse().unwrap_or_default(); - let is_dc_message: bool = row.get(2)?; - Ok((protected, message_param, is_dc_message)) - }, - |rows| { - let mut chats = ChatNumbers::default(); - for row in rows { - let (protected, message_param, is_dc_message) = row?; - let encrypted = message_param - .get_bool(Param::GuaranteeE2ee) - .unwrap_or(false); - - if protected == ProtectionStatus::Protected { - chats.protected += 1; - } else if encrypted { - if is_dc_message { - chats.opportunistic_dc += 1; - } else { - chats.opportunistic_mua += 1; - } - } else if is_dc_message { - chats.unencrypted_dc += 1; - } else { - chats.unencrypted_mua += 1; - } - } - Ok(chats) - }, - ) - .await?; - res += &format!("chats_protected {}\n", chats.protected); - res += &format!("chats_opportunistic_dc {}\n", chats.opportunistic_dc); - res += &format!("chats_opportunistic_mua {}\n", chats.opportunistic_mua); - res += &format!("chats_unencrypted_dc {}\n", chats.unencrypted_dc); - res += &format!("chats_unencrypted_mua {}\n", chats.unencrypted_mua); - - let self_reporting_id = match self.get_config(Config::SelfReportingId).await? { - Some(id) => id, - None => { - let id = create_id(); - self.set_config(Config::SelfReportingId, Some(&id)).await?; - id - } - }; - res += &format!("self_reporting_id {self_reporting_id}"); - - Ok(res) - } - - /// Drafts a message with statistics about the usage of Delta Chat. - /// The user can inspect the message if they want, and then hit "Send". - /// - /// On the other end, a bot will receive the message and make it available - /// to Delta Chat's developers. - pub async fn draft_self_report(&self) -> Result { - const SELF_REPORTING_BOT_VCARD: &str = include_str!("../assets/self-reporting-bot.vcf"); - let contact_id: ContactId = *import_vcard(self, SELF_REPORTING_BOT_VCARD) - .await? - .first() - .context("Self reporting bot vCard does not contain a contact")?; - mark_contact_id_as_verified(self, contact_id, ContactId::SELF).await?; - - let chat_id = ChatId::create_for_contact(self, contact_id).await?; - chat_id - .set_protection(self, ProtectionStatus::Protected, time(), Some(contact_id)) - .await?; - - let mut msg = Message::new_text(self.get_self_report().await?); - - chat_id.set_draft(self, Some(&mut msg)).await?; - - Ok(chat_id) - } - /// Get a list of fresh, unmuted messages in unblocked chats. /// /// The list starts with the most recent message diff --git a/src/context/context_tests.rs b/src/context/context_tests.rs index e80c17448f..af103f8e3a 100644 --- a/src/context/context_tests.rs +++ b/src/context/context_tests.rs @@ -6,9 +6,9 @@ use super::*; use crate::chat::{Chat, MuteDuration, get_chat_contacts, get_chat_msgs, send_msg, set_muted}; use crate::chatlist::Chatlist; use crate::constants::Chattype; -use crate::mimeparser::SystemMessage; +use crate::message::Message; use crate::receive_imf::receive_imf; -use crate::test_utils::{E2EE_INFO_MSGS, TestContext, get_chat_msg}; +use crate::test_utils::{E2EE_INFO_MSGS, TestContext}; use crate::tools::{SystemTime, create_outgoing_rfc724_mid}; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -276,7 +276,6 @@ async fn test_get_info_completeness() { "mail_port", "mail_security", "notify_about_wrong_pw", - "self_reporting_id", "selfstatus", "send_server", "send_user", @@ -296,6 +295,8 @@ async fn test_get_info_completeness() { "webxdc_integration", "device_token", "encrypted_device_token", + "stats_last_counted_msg_id", + "stats_last_old_contact_id", ]; let t = TestContext::new().await; let info = t.get_info().await.unwrap(); @@ -598,26 +599,6 @@ async fn test_get_next_msgs() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn test_draft_self_report() -> Result<()> { - let alice = TestContext::new_alice().await; - - let chat_id = alice.draft_self_report().await?; - let msg = get_chat_msg(&alice, chat_id, 0, 1).await; - assert_eq!(msg.get_info_type(), SystemMessage::ChatProtectionEnabled); - - let chat = Chat::load_from_db(&alice, chat_id).await?; - assert!(chat.is_protected()); - - let mut draft = chat_id.get_draft(&alice).await?.unwrap(); - assert!(draft.text.starts_with("core_version")); - - // Test that sending into the protected chat works: - let _sent = alice.send_msg(chat_id, &mut draft).await; - - Ok(()) -} - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_cache_is_cleared_when_io_is_started() -> Result<()> { let alice = TestContext::new_alice().await; diff --git a/src/lib.rs b/src/lib.rs index 3c6402cbfe..61879d65e5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -98,6 +98,7 @@ pub mod html; pub mod net; pub mod plaintext; mod push; +pub(crate) mod statistics; pub mod summary; mod debug_logging; diff --git a/src/receive_imf.rs b/src/receive_imf.rs index 03375862f4..aef0fea7eb 100644 --- a/src/receive_imf.rs +++ b/src/receive_imf.rs @@ -42,6 +42,7 @@ use crate::reaction::{Reaction, set_msg_reaction}; use crate::rusqlite::OptionalExtension; use crate::securejoin::{self, handle_securejoin_handshake, observe_securejoin_on_other_device}; use crate::simplify; +use crate::statistics::STATISTICS_BOT_EMAIL; use crate::stock_str; use crate::sync::Sync::*; use crate::tools::{self, buf_compress, remove_subject_prefix}; @@ -1743,7 +1744,11 @@ async fn add_parts( let state = if !mime_parser.incoming { MessageState::OutDelivered - } else if seen || is_mdn || chat_id_blocked == Blocked::Yes || group_changes.silent + } else if seen + || is_mdn + || chat_id_blocked == Blocked::Yes + || group_changes.silent + || mime_parser.from.addr == STATISTICS_BOT_EMAIL // No check for `hidden` because only reactions are such and they should be `InFresh`. { MessageState::InSeen diff --git a/src/scheduler.rs b/src/scheduler.rs index 621a799eb0..c81dca3937 100644 --- a/src/scheduler.rs +++ b/src/scheduler.rs @@ -27,6 +27,7 @@ use crate::log::{LogExt, error, info, warn}; use crate::message::MsgId; use crate::smtp::{Smtp, send_smtp_messages}; use crate::sql; +use crate::statistics::maybe_send_statistics; use crate::tools::{self, duration_to_str, maybe_add_time_based_warnings, time, time_elapsed}; pub(crate) mod connectivity; @@ -513,6 +514,7 @@ async fn inbox_fetch_idle(ctx: &Context, imap: &mut Imap, mut session: Session) } }; + maybe_send_statistics(ctx).await.log_err(ctx).ok(); match ctx.get_config_bool(Config::FetchedExistingMsgs).await { Ok(fetched_existing_msgs) => { if !fetched_existing_msgs { diff --git a/src/securejoin.rs b/src/securejoin.rs index 4fff0eca28..11622c664b 100644 --- a/src/securejoin.rs +++ b/src/securejoin.rs @@ -5,7 +5,6 @@ use deltachat_contact_tools::ContactAddress; use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode}; use crate::chat::{self, Chat, ChatId, ChatIdBlocked, ProtectionStatus, get_chat_id_by_grpid}; -use crate::chatlist_events; use crate::config::Config; use crate::constants::{Blocked, Chattype, NON_ALPHANUMERIC_WITHOUT_DOT}; use crate::contact::mark_contact_id_as_verified; @@ -15,6 +14,7 @@ use crate::e2ee::ensure_secret_key_exists; use crate::events::EventType; use crate::headerdef::HeaderDef; use crate::key::{DcKey, Fingerprint, load_self_public_key}; +use crate::log::LogExt as _; use crate::log::{error, info, warn}; use crate::logged_debug_assert; use crate::message::{Message, Viewtype}; @@ -24,11 +24,12 @@ use crate::qr::check_qr; use crate::securejoin::bob::JoinerProgress; use crate::sync::Sync::*; use crate::token; +use crate::{chatlist_events, statistics}; mod bob; mod qrinvite; -use qrinvite::QrInvite; +pub(crate) use qrinvite::QrInvite; use crate::token::Namespace; @@ -146,12 +147,38 @@ async fn get_self_fingerprint(context: &Context) -> Result { /// /// The function returns immediately and the handshake will run in background. pub async fn join_securejoin(context: &Context, qr: &str) -> Result { - securejoin(context, qr).await.map_err(|err| { + join_securejoin_with_ux_info(context, qr, None, None).await +} + +/// Take a scanned QR-code and do the setup-contact/join-group/invite handshake. +/// +/// This is the start of the process for the joiner. See the module and ffi documentation +/// for more details. +/// +/// The function returns immediately and the handshake will run in background. +/// +/// **source** and **uipath** are for statistics-sending, +/// if the user enabled it in the settings; +/// if you don't have statistics-sending implemented, just pass `None` here. +pub async fn join_securejoin_with_ux_info( + context: &Context, + qr: &str, + source: Option, + uipath: Option, +) -> Result { + let res = securejoin(context, qr).await.map_err(|err| { warn!(context, "Fatal joiner error: {:#}", err); // The user just scanned this QR code so has context on what failed. error!(context, "QR process failed"); err - }) + })?; + + statistics::count_securejoin_ux_info(context, source, uipath) + .await + .log_err(context) + .ok(); + + Ok(res) } async fn securejoin(context: &Context, qr: &str) -> Result { @@ -165,6 +192,11 @@ async fn securejoin(context: &Context, qr: &str) -> Result { let invite = QrInvite::try_from(qr_scan)?; + statistics::count_securejoin_invite(context, &invite) + .await + .log_err(context) + .ok(); + bob::start_protocol(context, invite).await } diff --git a/src/sql/migrations.rs b/src/sql/migrations.rs index 4a7c40e911..045918681a 100644 --- a/src/sql/migrations.rs +++ b/src/sql/migrations.rs @@ -1261,6 +1261,27 @@ CREATE INDEX gossip_timestamp_index ON gossip_timestamp (chat_id, fingerprint); .await?; } + inc_and_check(&mut migration_version, 134)?; + if dbversion < migration_version { + sql.execute_migration( + "CREATE TABLE statistics_securejoin_sources( + source INTEGER PRIMARY KEY, + count INTEGER NOT NULL DEFAULT 0 + ) STRICT; + CREATE TABLE statistics_securejoin_uipaths( + uipath INTEGER PRIMARY KEY, + count INTEGER NOT NULL DEFAULT 0 + ) STRICT; + CREATE TABLE statistics_securejoin_invites( + contact_created INTEGER NOT NULL, + already_verified INTEGER NOT NULL, + type TEXT NOT NULL + ) STRICT;", + migration_version, + ) + .await?; + } + let new_version = sql .get_raw_config_int(VERSION_CFG) .await? diff --git a/src/statistics.rs b/src/statistics.rs new file mode 100644 index 0000000000..efd2a52775 --- /dev/null +++ b/src/statistics.rs @@ -0,0 +1,764 @@ +//! Delta Chat has an advanced option +//! "Send statistics to the developers of Delta Chat". +//! If this is enabled, a JSON file with some anonymous statistics +//! will be sent to a bot once a week. + +use std::collections::{BTreeMap, BTreeSet}; + +use anyhow::{Context as _, Result, ensure}; +use deltachat_derive::FromSql; +use pgp::types::PublicKeyTrait; +use serde::Serialize; + +use crate::chat::{self, ChatId, ChatVisibility, MuteDuration, ProtectionStatus}; +use crate::config::Config; +use crate::constants::Chattype; +use crate::contact::{Contact, ContactId, Origin, import_vcard, mark_contact_id_as_verified}; +use crate::context::{Context, get_version_str}; +use crate::key::load_self_public_keyring; +use crate::log::LogExt; +use crate::message::{Message, Viewtype}; +use crate::securejoin::QrInvite; +use crate::tools::{create_id, time}; + +pub(crate) const STATISTICS_BOT_EMAIL: &str = "self_reporting@testrun.org"; +const STATISTICS_BOT_VCARD: &str = include_str!("../assets/statistics-bot.vcf"); +const SENDING_INTERVAL_SECONDS: i64 = 3600 * 24 * 7; // 1 week + +#[derive(Serialize)] +struct Statistics { + core_version: String, + key_create_timestamps: Vec, + statistics_id: String, + is_chatmail: bool, + contact_stats: Vec, + message_stats_one_one: MessageStats, + message_stats_multi_user: MessageStats, + securejoin_sources: SecurejoinSources, + securejoin_uipaths: SecurejoinUIPaths, + securejoin_invites: Vec, +} + +#[derive(Serialize, PartialEq)] +enum VerifiedStatus { + Direct, + Transitive, + TransitiveViaBot, + Opportunistic, + Unencrypted, +} + +#[derive(Serialize)] +struct ContactStat { + #[serde(skip_serializing)] + id: ContactId, + + verified: VerifiedStatus, + + // If one of the boolean properties is false, + // we leave them away. + // This way, the Json file becomes a lot smaller. + #[serde(skip_serializing_if = "is_false")] + bot: bool, + + #[serde(skip_serializing_if = "is_false")] + direct_chat: bool, + + last_seen: u64, + + #[serde(skip_serializing_if = "Option::is_none")] + transitive_chain: Option, + + /// Whether the contact was established after stats-sending was enabled + #[serde(skip_serializing_if = "is_false")] + new: bool, +} + +fn is_false(b: &bool) -> bool { + !b +} + +#[derive(Serialize)] +struct MessageStats { + to_verified: u32, + unverified_encrypted: u32, + unencrypted: u32, + only_to_self: u32, +} + +#[repr(u32)] +#[derive(Debug, Clone, Copy, FromPrimitive, FromSql, PartialEq, Eq, PartialOrd, Ord)] +enum SecurejoinSource { + /// Because of some problem, it is unknown where the QR code came from. + Unknown = 0, + /// The user opened a link somewhere outside Delta Chat + ExternalLink = 1, + /// The user clicked on a link in a message inside Delta Chat + InternalLink = 2, + /// The user clicked "Paste from Clipboard" in the QR scan activity + Clipboard = 3, + /// The user clicked "Load QR code as image" in the QR scan activity + ImageLoaded = 4, + /// The user scanned a QR code + Scan = 5, +} + +#[derive(Serialize)] +struct SecurejoinSources { + unknown: u32, + external_link: u32, + internal_link: u32, + clipboard: u32, + image_loaded: u32, + scan: u32, +} + +#[derive(Debug, Clone, Copy, FromPrimitive, FromSql, PartialEq, Eq, PartialOrd, Ord)] +enum SecurejoinUIPath { + /// The UI path is unknown, or the user didn't open the QR code screen at all. + Unknown = 0, + /// The user directly clicked on the QR icon in the main screen + QrIcon = 1, + /// The user first clicked on the `+` button in the main screen, + /// and then on "New Contact" + NewContact = 2, +} + +#[derive(Serialize)] +struct SecurejoinUIPaths { + other: u32, + qr_icon: u32, + new_contact: u32, +} + +/// Some information on an invite-joining event +/// (i.e. a qr scan or a clicked link). +#[derive(Serialize)] +struct JoinedInvite { + /// Whether the contact was newly created right now. + /// If this is false, then a contact existed already before. + contact_created: bool, + /// If a contact already existed, + /// this tells us whether the contact was verified already. + already_verified: bool, + /// The type of the invite: + /// "contact" for 1:1 invites that setup a verified contact, + /// "group" for invites that invite to a group + /// and also perform the contact verification 'along the way'. + typ: String, +} + +/// Sends a message with statistics about the usage of Delta Chat, +/// if the last time such a message was sent +/// was more than a week ago. +/// +/// On the other end, a bot will receive the message and make it available +/// to Delta Chat's developers. +pub async fn maybe_send_statistics(context: &Context) -> Result> { + if should_send_statistics(context).await? { + let last_sending_time = context.get_config_i64(Config::StatsLastSent).await?; + let next_sending_time = last_sending_time.saturating_add(SENDING_INTERVAL_SECONDS); + if next_sending_time <= time() { + // Setting this config at the beginning avoids endless loops when things do not + // work out for whatever reason. + context + .set_config_internal(Config::StatsLastSent, Some(&time().to_string())) + .await?; + + return Ok(Some(send_statistics(context).await?)); + } else if time() < last_sending_time { + // The clock was rewound. + // Reset the config, so that the statistics will be sent normally in a week. + context + .set_config_internal(Config::StatsLastSent, Some(&time().to_string())) + .await?; + } + } + Ok(None) +} + +#[allow(clippy::unused_async, unused)] +pub(crate) async fn should_send_statistics(context: &Context) -> Result { + #[cfg(any(target_os = "android", test))] + { + context.get_config_bool(Config::StatsSending).await + } + + // If the user enables statistics-sending on Android, + // and then transfers the account to e.g. Desktop, + // we should not send any statistics: + #[cfg(not(any(target_os = "android", test)))] + { + Ok(false) + } +} + +async fn send_statistics(context: &Context) -> Result { + info!(context, "Sending statistics."); + + let chat_id = get_statistics_chat_id(context).await?; + + let mut msg = Message::new(Viewtype::File); + msg.set_text( + "The attachment contains anonymous usage statistics, \ +because you enabled this in the settings. \ +This helps us improve Delta Chat. \ +See TODO[blog post] for more information." + .to_string(), + ); + + let statistics = get_statistics(context).await?; + + msg.set_file_from_bytes( + context, + "statistics.txt", + statistics.as_bytes(), + Some("text/plain"), + )?; + + chat::send_msg(context, chat_id, &mut msg) + .await + .context("Failed to send statistics message") + .log_err(context) + .ok(); + + set_last_counted_msg_id(context).await?; + + Ok(chat_id) +} + +pub(crate) async fn set_last_counted_msg_id(context: &Context) -> Result<()> { + let last_msgid: u64 = context + .sql + .query_get_value("SELECT MAX(id) FROM msgs", ()) + .await? + .unwrap_or(0); + + context + .sql + .set_raw_config( + Config::StatsLastCountedMsgId.as_ref(), + Some(&last_msgid.to_string()), + ) + .await?; + + Ok(()) +} + +pub(crate) async fn set_last_old_contact_id(context: &Context) -> Result<()> { + let config_exists = context + .sql + .get_raw_config(Config::StatsLastOldContactId.as_ref()) + .await? + .is_some(); + if config_exists { + // The user had statistics-sending enabled already in the past, + // keep the 'last old contact id' as-is + return Ok(()); + } + + let last_contact_id: u64 = context + .sql + .query_get_value("SELECT MAX(id) FROM contacts", ()) + .await? + .unwrap_or(0); + + context + .sql + .set_raw_config( + Config::StatsLastOldContactId.as_ref(), + Some(&last_contact_id.to_string()), + ) + .await?; + + Ok(()) +} + +async fn get_statistics(context: &Context) -> Result { + // The ID of the last msg that was already counted in the previously sent statistics. + // Only newer messages will be counted in the current statistics. + let last_counted_msg = context + .get_config_u32(Config::StatsLastCountedMsgId) + .await?; + + // The Id of the last contact that already existed when the user enabled the setting. + // Newer contacts will get the `new` flag set. + let last_old_contact = context + .get_config_u32(Config::StatsLastOldContactId) + .await?; + + let key_create_timestamps: Vec = load_self_public_keyring(context) + .await? + .iter() + .map(|k| k.created_at().timestamp()) + .collect(); + + let statistics_id = match context.get_config(Config::StatsId).await? { + Some(id) => id, + None => { + let id = create_id(); + context + .set_config_internal(Config::StatsId, Some(&id)) + .await?; + id + } + }; + + let statistics = Statistics { + core_version: get_version_str().to_string(), + key_create_timestamps, + statistics_id, + is_chatmail: context.is_chatmail().await?, + contact_stats: get_contact_stats(context, last_old_contact).await?, + message_stats_one_one: get_message_stats(context, last_counted_msg, true).await?, + message_stats_multi_user: get_message_stats(context, last_counted_msg, false).await?, + securejoin_sources: get_securejoin_source_stats(context).await?, + securejoin_uipaths: get_securejoin_uipath_stats(context).await?, + securejoin_invites: get_securejoin_invite_stats(context).await?, + }; + + Ok(serde_json::to_string_pretty(&statistics)?) +} + +async fn get_statistics_chat_id(context: &Context) -> Result { + let contact_id: ContactId = *import_vcard(context, STATISTICS_BOT_VCARD) + .await? + .first() + .context("Statistics bot vCard does not contain a contact")?; + mark_contact_id_as_verified(context, contact_id, ContactId::SELF).await?; + + let chat_id = if let Some(res) = ChatId::lookup_by_contact(context, contact_id).await? { + // Already exists, no need to create. + res + } else { + let chat_id = ChatId::get_for_contact(context, contact_id).await?; + chat_id + .set_visibility(context, ChatVisibility::Archived) + .await?; + chat::set_muted(context, chat_id, MuteDuration::Forever).await?; + chat_id + }; + + chat_id + .set_protection( + context, + ProtectionStatus::Protected, + time(), + Some(contact_id), + ) + .await?; + + Ok(chat_id) +} + +async fn get_contact_stats(context: &Context, last_old_contact: u32) -> Result> { + let mut verified_by_map: BTreeMap = BTreeMap::new(); + let mut bot_ids: BTreeSet = BTreeSet::new(); + + let mut contacts: Vec = context + .sql + .query_map( + "SELECT id, fingerprint<>'', verifier, last_seen, is_bot FROM contacts c + WHERE id>9 AND origin>? AND addr<>?", + (Origin::Hidden, STATISTICS_BOT_EMAIL), + |row| { + let id = row.get(0)?; + let is_encrypted: bool = row.get(1)?; + let verifier: ContactId = row.get(2)?; + let last_seen: u64 = row.get(3)?; + let bot: bool = row.get(4)?; + + let verified = match (is_encrypted, verifier) { + (true, ContactId::SELF) => VerifiedStatus::Direct, + (true, ContactId::UNDEFINED) => VerifiedStatus::Opportunistic, + (true, _) => VerifiedStatus::Transitive, // TransitiveViaBot will be filled later + (false, _) => VerifiedStatus::Unencrypted, + }; + + if verifier != ContactId::UNDEFINED { + verified_by_map.insert(id, verifier); + } + + if bot { + bot_ids.insert(id); + } + + Ok(ContactStat { + id, + verified, + bot, + direct_chat: false, // will be filled later + last_seen, + transitive_chain: None, // will be filled later + new: id.to_u32() > last_old_contact, + }) + }, + |rows| { + rows.collect::, _>>() + .map_err(Into::into) + }, + ) + .await?; + + // Fill TransitiveViaBot and transitive_chain + for contact in &mut contacts { + if contact.verified == VerifiedStatus::Transitive { + let mut transitive_chain: u32 = 0; + let mut has_bot = false; + let mut current_verifier_id = contact.id; + + while current_verifier_id != ContactId::SELF && transitive_chain < 100 { + current_verifier_id = match verified_by_map.get(¤t_verifier_id) { + Some(id) => *id, + None => { + // The chain ends here, probably because some verification was done + // before we started recording verifiers. + // It's unclear how long the chain really is. + transitive_chain = 0; + break; + } + }; + if bot_ids.contains(¤t_verifier_id) { + has_bot = true; + } + transitive_chain = transitive_chain.saturating_add(1); + } + + if transitive_chain > 0 { + contact.transitive_chain = Some(transitive_chain); + } + + if has_bot { + contact.verified = VerifiedStatus::TransitiveViaBot; + } + } + } + + // Fill direct_chat + for contact in &mut contacts { + let direct_chat = context + .sql + .exists( + "SELECT COUNT(*) + FROM chats_contacts cc INNER JOIN chats + WHERE cc.contact_id=? AND chats.type=?", + (contact.id, Chattype::Single), + ) + .await?; + contact.direct_chat = direct_chat; + } + + Ok(contacts) +} + +/// - `last_msg_id`: The last msg_id that was already counted in the previous stats. +/// Only messages newer than that will be counted. +/// - `one_one_chats`: If true, only messages in 1:1 chats are counted. +/// If false, only messages in other chats (groups and broadcast channels) are counted. +async fn get_message_stats( + context: &Context, + last_counted_msg: u32, + one_one_chats: bool, +) -> Result { + ensure!( + last_counted_msg >= 9, + "Last_msgid < 9 would mean including 'special' messages in the statistics" + ); + + let statistics_bot_chat_id = get_statistics_chat_id(context).await?; + + let trans_fn = |t: &mut rusqlite::Transaction| { + t.pragma_update(None, "query_only", "0")?; + + // This table will hold all empty chats, + // i.e. all chats that do not contain any members except for self. + // Messages in these chats are not actually sent out. + t.execute( + "CREATE TEMP TABLE temp.empty_chats ( + id INTEGER PRIMARY KEY + ) STRICT", + (), + )?; + + // id>9 because chat ids 0..9 are "special" chats like the trash chat, + // and contact ids 0..9 are "special" contact ids like the 'device'. + t.execute( + "INSERT INTO temp.empty_chats + SELECT id FROM chats + WHERE id>9 AND NOT EXISTS( + SELECT * + FROM contacts, chats_contacts + WHERE chats_contacts.contact_id=contacts.id AND chats_contacts.chat_id=chats.id + AND contacts.id>9 + )", + (), + )?; + + // This table will hold all verified chats, + // i.e. all chats that only contain verified contacts. + t.execute( + "CREATE TEMP TABLE temp.verified_chats ( + id INTEGER PRIMARY KEY + ) STRICT", + (), + )?; + + // Verified chats are chats that are not empty, + // and do not contain any unverified contacts + t.execute( + "INSERT INTO temp.verified_chats + SELECT id FROM chats + WHERE id>9 + AND id NOT IN (SELECT id FROM temp.empty_chats) + AND NOT EXISTS( + SELECT * + FROM contacts, chats_contacts + WHERE chats_contacts.contact_id=contacts.id AND chats_contacts.chat_id=chats.id + AND contacts.id>9 + AND contacts.verifier=0 + )", + (), + )?; + + // This table will hold all 1:1 chats. + t.execute( + "CREATE TEMP TABLE temp.one_one_chats ( + id INTEGER PRIMARY KEY + ) STRICT", + (), + )?; + + t.execute( + "INSERT INTO temp.one_one_chats + SELECT id FROM chats + WHERE type=?;", + (Chattype::Single,), + )?; + + // - `from_id=?` is to count only outgoing messages. + // - `chat_id<>?` excludes the chat with the statistics bot itself, + // - `id>?` excludes messages that were already counted in the previously sent statistics, or messages sent before the config was enabled + // - `hidden=0` excludes hidden system messages, which are not actually shown to the user + // - `chat_id>9` excludes messages in the 'Trash' chat, which is an internal chat assigned to messages that are not shown to the user + let mut general_requirements = + "from_id=? AND chat_id<>? AND id>? AND hidden=0 AND chat_id>9".to_string(); + if one_one_chats { + general_requirements += " AND chat_id IN temp.one_one_chats"; + } else { + general_requirements += " AND chat_id NOT IN temp.one_one_chats"; + } + let params = (ContactId::SELF, statistics_bot_chat_id, last_counted_msg); + + let to_verified = t.query_row( + &format!( + "SELECT COUNT(*) FROM msgs + WHERE chat_id IN temp.verified_chats + AND {general_requirements}" + ), + params, + |row| row.get(0), + )?; + + let unverified_encrypted = t.query_row( + &format!( + // (param GLOB '*\nc=1*' OR param GLOB 'c=1*') matches all messages that are end-to-end encrypted + "SELECT COUNT(*) FROM msgs + WHERE chat_id NOT IN temp.verified_chats AND chat_id NOT IN temp.empty_chats + AND (param GLOB '*\nc=1*' OR param GLOB 'c=1*') + AND {general_requirements}" + ), + params, + |row| row.get(0), + )?; + + let unencrypted = t.query_row( + &format!( + "SELECT COUNT(*) FROM msgs + WHERE chat_id NOT IN temp.verified_chats AND chat_id NOT IN temp.empty_chats + AND NOT (param GLOB '*\nc=1*' OR param GLOB 'c=1*') + AND {general_requirements}" + ), + params, + |row| row.get(0), + )?; + + let only_to_self = t.query_row( + &format!( + "SELECT COUNT(*) FROM msgs + WHERE chat_id IN temp.empty_chats + AND {general_requirements}" + ), + params, + |row| row.get(0), + )?; + + t.execute("DROP TABLE temp.verified_chats", ())?; + t.execute("DROP TABLE temp.empty_chats", ())?; + t.execute("DROP TABLE temp.one_one_chats", ())?; + + Ok(MessageStats { + to_verified, + unverified_encrypted, + unencrypted, + only_to_self, + }) + }; + + let query_only = true; + let message_stats: MessageStats = context.sql.transaction_ex(query_only, trans_fn).await?; + + Ok(message_stats) +} + +pub(crate) async fn count_securejoin_ux_info( + context: &Context, + source: Option, + uipath: Option, +) -> Result<()> { + if !should_send_statistics(context).await? { + return Ok(()); + } + + let source = source + .context("Missing securejoin source") + .log_err(context) + .unwrap_or(0); + + context + .sql + .execute( + "INSERT INTO statistics_securejoin_sources VALUES (?, 1) + ON CONFLICT (source) DO UPDATE SET count=count+1;", + (source,), + ) + .await?; + + // We only get a UI path if the source is a QR code scan, + // a loaded image, or a link pasted from the QR code, + // so, no need to log an error if `uipath` is None: + let uipath = uipath.unwrap_or(0); + context + .sql + .execute( + "INSERT INTO statistics_securejoin_uipaths VALUES (?, 1) + ON CONFLICT (uipath) DO UPDATE SET count=count+1;", + (uipath,), + ) + .await?; + Ok(()) +} + +async fn get_securejoin_source_stats(context: &Context) -> Result { + let map = context + .sql + .query_map( + "SELECT source, count FROM statistics_securejoin_sources", + (), + |row| { + let source: SecurejoinSource = row.get(0)?; + let count: u32 = row.get(1)?; + Ok((source, count)) + }, + |rows| Ok(rows.collect::>>()?), + ) + .await?; + + let stats = SecurejoinSources { + unknown: *map.get(&SecurejoinSource::Unknown).unwrap_or(&0), + external_link: *map.get(&SecurejoinSource::ExternalLink).unwrap_or(&0), + internal_link: *map.get(&SecurejoinSource::InternalLink).unwrap_or(&0), + clipboard: *map.get(&SecurejoinSource::Clipboard).unwrap_or(&0), + image_loaded: *map.get(&SecurejoinSource::ImageLoaded).unwrap_or(&0), + scan: *map.get(&SecurejoinSource::Scan).unwrap_or(&0), + }; + + Ok(stats) +} + +async fn get_securejoin_uipath_stats(context: &Context) -> Result { + let map = context + .sql + .query_map( + "SELECT uipath, count FROM statistics_securejoin_uipaths", + (), + |row| { + let uipath: SecurejoinUIPath = row.get(0)?; + let count: u32 = row.get(1)?; + Ok((uipath, count)) + }, + |rows| Ok(rows.collect::>>()?), + ) + .await?; + + let stats = SecurejoinUIPaths { + other: *map.get(&SecurejoinUIPath::Unknown).unwrap_or(&0), + qr_icon: *map.get(&SecurejoinUIPath::QrIcon).unwrap_or(&0), + new_contact: *map.get(&SecurejoinUIPath::NewContact).unwrap_or(&0), + }; + + Ok(stats) +} + +pub(crate) async fn count_securejoin_invite(context: &Context, invite: &QrInvite) -> Result<()> { + if !should_send_statistics(context).await? { + return Ok(()); + } + + let contact = Contact::get_by_id(context, invite.contact_id()).await?; + + // If the contact was created just now by the QR code scan, + // (or if a contact existed in the database + // but it was not visible in the contacts list in the UI + // e.g. because it's a past contact of a group we're in), + // then its origin is UnhandledSecurejoinQrScan. + let contact_created = contact.origin == Origin::UnhandledSecurejoinQrScan; + + // Check whether the contact was verified already before the QR scan. + let already_verified = contact.is_verified(context).await?; + + let typ = match invite { + QrInvite::Contact { .. } => "contact", + QrInvite::Group { .. } => "group", + }; + + context + .sql + .execute( + "INSERT INTO statistics_securejoin_invites (contact_created, already_verified, type) + VALUES (?, ?, ?)", + (contact_created, already_verified, typ), + ) + .await?; + + Ok(()) +} + +async fn get_securejoin_invite_stats(context: &Context) -> Result> { + let qr_scans: Vec = context + .sql + .query_map( + "SELECT contact_created, already_verified, type FROM statistics_securejoin_invites", + (), + |row| { + let contact_created: bool = row.get(0)?; + let already_verified: bool = row.get(1)?; + let typ: String = row.get(2)?; + + Ok(JoinedInvite { + contact_created, + already_verified, + typ, + }) + }, + |rows| { + rows.collect::, _>>() + .map_err(Into::into) + }, + ) + .await?; + + Ok(qr_scans) +} + +#[cfg(test)] +mod statistics_tests; diff --git a/src/statistics/statistics_tests.rs b/src/statistics/statistics_tests.rs new file mode 100644 index 0000000000..393678e39f --- /dev/null +++ b/src/statistics/statistics_tests.rs @@ -0,0 +1,534 @@ +use std::time::Duration; + +use super::*; +use crate::chat::{Chat, create_broadcast, create_group_chat, create_group_ex}; +use crate::mimeparser::SystemMessage; +use crate::qr::check_qr; +use crate::securejoin::{get_securejoin_qr, join_securejoin, join_securejoin_with_ux_info}; +use crate::test_utils::{TestContext, TestContextManager, get_chat_msg}; +use crate::tools::SystemTime; +use pretty_assertions::assert_eq; +use serde_json::{Number, Value}; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_maybe_send_statistics() -> Result<()> { + let alice = &TestContext::new_alice().await; + + alice.set_config_bool(Config::StatsSending, true).await?; + + let chat_id = maybe_send_statistics(alice).await?.unwrap(); + let msg = get_chat_msg(alice, chat_id, 0, 2).await; + assert_eq!(msg.get_info_type(), SystemMessage::ChatProtectionEnabled); + + let chat = Chat::load_from_db(alice, chat_id).await?; + assert!(chat.is_protected()); + + let msg = get_chat_msg(alice, chat_id, 1, 2).await; + assert_eq!(msg.get_filename().unwrap(), "statistics.txt"); + + let stats = tokio::fs::read(msg.get_file(alice).unwrap()).await?; + let stats = std::str::from_utf8(&stats)?; + println!("\nEmpty account:\n{stats}\n"); + assert!(stats.contains(r#""contact_stats": []"#)); + + let r: serde_json::Value = serde_json::from_str(stats)?; + assert_eq!( + r.get("contact_stats").unwrap(), + &serde_json::Value::Array(vec![]) + ); + assert_eq!(r.get("core_version").unwrap(), get_version_str()); + + assert_eq!(maybe_send_statistics(alice).await?, None); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_rewound_time() -> Result<()> { + let alice = &TestContext::new_alice().await; + alice.set_config_bool(Config::StatsSending, true).await?; + + const EIGHT_DAYS: Duration = Duration::from_secs(3600 * 24 * 14); + SystemTime::shift(EIGHT_DAYS); + + maybe_send_statistics(alice).await?.unwrap(); + + // The system's time is rewound + SystemTime::shift_backwards(EIGHT_DAYS); + + assert!(maybe_send_statistics(alice).await?.is_none()); + + // After eight days pass again, statistics are sent again + SystemTime::shift(EIGHT_DAYS); + maybe_send_statistics(alice).await?.unwrap(); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_statistics_one_contact() -> Result<()> { + let mut tcm = TestContextManager::new(); + let alice = &tcm.alice().await; + let bob = &tcm.bob().await; + alice.set_config_bool(Config::StatsSending, true).await?; + + let stats = get_statistics(alice).await?; + let r: serde_json::Value = serde_json::from_str(&stats)?; + + tcm.send_recv_accept(bob, alice, "Hi!").await; + + let stats = get_statistics(alice).await?; + println!("\nWith Bob:\n{stats}\n"); + let r2: serde_json::Value = serde_json::from_str(&stats)?; + + assert_eq!( + r.get("key_create_timestamps").unwrap(), + r2.get("key_create_timestamps").unwrap() + ); + assert_eq!( + r.get("statistics_id").unwrap(), + r2.get("statistics_id").unwrap() + ); + let contact_stats = r2.get("contact_stats").unwrap().as_array().unwrap(); + assert_eq!(contact_stats.len(), 1); + let contact_info = &contact_stats[0]; + assert!(contact_info.get("bot").is_none()); + assert_eq!( + contact_info.get("direct_chat").unwrap(), + &serde_json::Value::Bool(true) + ); + assert!(contact_info.get("transitive_chain").is_none(),); + assert_eq!( + contact_info.get("verified").unwrap(), + &serde_json::Value::String("Opportunistic".to_string()) + ); + assert_eq!( + contact_info.get("new").unwrap(), + &serde_json::Value::Bool(true) + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_message_stats() -> Result<()> { + #[track_caller] + fn check_statistics( + stats: &str, + expected_one_one: &MessageStats, + expected_multi_user: &MessageStats, + ) { + let actual: serde_json::Value = serde_json::from_str(stats).unwrap(); + + for (expected, key) in [ + (expected_one_one, "message_stats_one_one"), + (expected_multi_user, "message_stats_multi_user"), + ] { + let actual = &actual[key]; + + let expected = serde_json::to_string_pretty(&expected).unwrap(); + let expected: serde_json::Value = serde_json::from_str(&expected).unwrap(); + + assert_eq!(actual, &expected, "Wrong {key}"); + } + } + + let mut tcm = TestContextManager::new(); + let alice = &tcm.alice().await; + let bob = &tcm.bob().await; + alice.set_config_bool(Config::StatsSending, true).await?; + let email_chat = alice.create_email_chat(bob).await; + let encrypted_chat = alice.create_chat(bob).await; + + let mut one_one = MessageStats { + to_verified: 0, + unverified_encrypted: 0, + unencrypted: 0, + only_to_self: 0, + }; + let mut multi_user = MessageStats { + to_verified: 0, + unverified_encrypted: 0, + unencrypted: 0, + only_to_self: 0, + }; + + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + alice.send_text(email_chat.id, "foo").await; + one_one.unencrypted += 1; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + alice.send_text(encrypted_chat.id, "foo").await; + one_one.unverified_encrypted += 1; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + alice.send_text(encrypted_chat.id, "foo").await; + one_one.unverified_encrypted += 1; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + let group = alice + .create_group_with_members(ProtectionStatus::Unprotected, "Pizza", &[bob]) + .await; + alice.send_text(group, "foo").await; + multi_user.unverified_encrypted += 1; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + tcm.execute_securejoin(alice, bob).await; + one_one.to_verified = one_one.unverified_encrypted; + one_one.unverified_encrypted = 0; + multi_user.to_verified = multi_user.unverified_encrypted; + multi_user.unverified_encrypted = 0; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + alice.send_text(alice.get_self_chat().await.id, "foo").await; + one_one.only_to_self += 1; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + let empty_group = create_group_chat(alice, ProtectionStatus::Unprotected, "Notes").await?; + alice.send_text(empty_group, "foo").await; + multi_user.only_to_self += 1; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + let empty_unencrypted = create_group_ex(alice, None, "Email thread").await?; + alice.send_text(empty_unencrypted, "foo").await; + multi_user.only_to_self += 1; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + let group = alice + .create_group_with_members(ProtectionStatus::Unprotected, "Pizza 2", &[bob]) + .await; + alice.send_text(group, "foo").await; + multi_user.to_verified += 1; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + let empty_broadcast = create_broadcast(alice, "Channel".to_string()).await?; + alice.send_text(empty_broadcast, "foo").await; + multi_user.only_to_self += 1; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + // Incoming messages are not counted: + let rcvd = tcm.send_recv(bob, alice, "bar").await; + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + // Reactions are not counted: + crate::reaction::send_reaction(alice, rcvd.id, "👍") + .await + .unwrap(); + check_statistics(&get_statistics(alice).await?, &one_one, &multi_user); + + tcm.section("Test that after actually sending statistics, the message numbers are reset."); + let before_sending = get_statistics(alice).await.unwrap(); + + let stats = send_and_read_statistics(alice).await; + // The statistics are supposed not to have changed yet + assert_eq!(before_sending, stats); + + // Shift by 8 days so that the next statistics-sending is due: + SystemTime::shift(Duration::from_secs(8 * 24 * 3600)); + + let stats = send_and_read_statistics(alice).await; + assert_ne!(before_sending, stats); + + one_one = MessageStats { + to_verified: 0, + unverified_encrypted: 0, + unencrypted: 0, + only_to_self: 0, + }; + multi_user = MessageStats { + to_verified: 0, + unverified_encrypted: 0, + unencrypted: 0, + only_to_self: 0, + }; + check_statistics(&stats, &one_one, &multi_user); + + tcm.section( + "Test that after sending a message again, the message statistics start to fill again.", + ); + SystemTime::shift(Duration::from_secs(8 * 24 * 3600)); + tcm.send_recv(alice, bob, "Hi").await; + one_one.to_verified += 1; + check_statistics( + &send_and_read_statistics(alice).await, + &one_one, + &multi_user, + ); + + Ok(()) +} + +async fn send_and_read_statistics(context: &TestContext) -> String { + let chat_id = maybe_send_statistics(context).await.unwrap().unwrap(); + let msg = context.get_last_msg_in(chat_id).await; + assert_eq!(msg.get_filename().unwrap(), "statistics.txt"); + + let stats = tokio::fs::read(msg.get_file(context).unwrap()) + .await + .unwrap(); + String::from_utf8(stats).unwrap() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_statistics_securejoin_sources() -> Result<()> { + async fn check_statistics(context: &TestContext, expected: &SecurejoinSources) { + let statistics = get_statistics(context).await.unwrap(); + let actual: serde_json::Value = serde_json::from_str(&statistics).unwrap(); + let actual = &actual["securejoin_sources"]; + + let expected = serde_json::to_string_pretty(&expected).unwrap(); + let expected: serde_json::Value = serde_json::from_str(&expected).unwrap(); + + assert_eq!(actual, &expected); + } + + let mut tcm = TestContextManager::new(); + let alice = &tcm.alice().await; + let bob = &tcm.bob().await; + alice.set_config_bool(Config::StatsSending, true).await?; + + let mut expected = SecurejoinSources { + unknown: 0, + external_link: 0, + internal_link: 0, + clipboard: 0, + image_loaded: 0, + scan: 0, + }; + + check_statistics(alice, &expected).await; + + let qr = get_securejoin_qr(bob, None).await?; + + join_securejoin(alice, &qr).await?; + expected.unknown += 1; + check_statistics(alice, &expected).await; + + join_securejoin(alice, &qr).await?; + expected.unknown += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info(alice, &qr, Some(SecurejoinSource::Clipboard as u32), None) + .await?; + expected.clipboard += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info( + alice, + &qr, + Some(SecurejoinSource::ExternalLink as u32), + None, + ) + .await?; + expected.external_link += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info( + alice, + &qr, + Some(SecurejoinSource::InternalLink as u32), + None, + ) + .await?; + expected.internal_link += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info(alice, &qr, Some(SecurejoinSource::ImageLoaded as u32), None) + .await?; + expected.image_loaded += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info(alice, &qr, Some(SecurejoinSource::Scan as u32), None).await?; + expected.scan += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info(alice, &qr, Some(SecurejoinSource::Clipboard as u32), None) + .await?; + expected.clipboard += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info(alice, &qr, Some(SecurejoinSource::Clipboard as u32), None) + .await?; + expected.clipboard += 1; + check_statistics(alice, &expected).await; + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_statistics_securejoin_uipaths() -> Result<()> { + async fn check_statistics(context: &TestContext, expected: &SecurejoinUIPaths) { + let stats = get_statistics(context).await.unwrap(); + let actual: serde_json::Value = serde_json::from_str(&stats).unwrap(); + let actual = &actual["securejoin_uipaths"]; + + let expected = serde_json::to_string_pretty(&expected).unwrap(); + let expected: serde_json::Value = serde_json::from_str(&expected).unwrap(); + + assert_eq!(actual, &expected); + } + + let mut tcm = TestContextManager::new(); + let alice = &tcm.alice().await; + let bob = &tcm.bob().await; + alice.set_config_bool(Config::StatsSending, true).await?; + + let mut expected = SecurejoinUIPaths { + other: 0, + qr_icon: 0, + new_contact: 0, + }; + + check_statistics(alice, &expected).await; + + let qr = get_securejoin_qr(bob, None).await?; + + join_securejoin(alice, &qr).await?; + expected.other += 1; + check_statistics(alice, &expected).await; + + join_securejoin(alice, &qr).await?; + expected.other += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info( + alice, + &qr, + Some(0), + Some(SecurejoinUIPath::NewContact as u32), + ) + .await?; + expected.new_contact += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info( + alice, + &qr, + Some(0), + Some(SecurejoinUIPath::NewContact as u32), + ) + .await?; + expected.new_contact += 1; + check_statistics(alice, &expected).await; + + join_securejoin_with_ux_info(alice, &qr, Some(0), Some(SecurejoinUIPath::QrIcon as u32)) + .await?; + expected.qr_icon += 1; + check_statistics(alice, &expected).await; + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_statistics_securejoin_invites() -> Result<()> { + async fn check_statistics(context: &TestContext, expected: &[JoinedInvite]) { + let stats = get_statistics(context).await.unwrap(); + let actual: serde_json::Value = serde_json::from_str(&stats).unwrap(); + let actual = &actual["securejoin_invites"]; + + let expected = serde_json::to_string_pretty(&expected).unwrap(); + let expected: serde_json::Value = serde_json::from_str(&expected).unwrap(); + + assert_eq!(actual, &expected); + } + + let mut tcm = TestContextManager::new(); + let alice = &tcm.alice().await; + let bob = &tcm.bob().await; + let charlie = &tcm.charlie().await; + alice.set_config_bool(Config::StatsSending, true).await?; + + let mut expected = vec![]; + + check_statistics(alice, &expected).await; + + let qr = get_securejoin_qr(bob, None).await?; + + // The UI will call `check_qr()` first, which must not make the statistics wrong: + check_qr(alice, &qr).await?; + tcm.exec_securejoin_qr(alice, bob, &qr).await; + expected.push(JoinedInvite { + contact_created: true, + already_verified: false, + typ: "contact".to_string(), + }); + check_statistics(alice, &expected).await; + + check_qr(alice, &qr).await?; + tcm.exec_securejoin_qr(alice, bob, &qr).await; + expected.push(JoinedInvite { + contact_created: false, + already_verified: true, + typ: "contact".to_string(), + }); + check_statistics(alice, &expected).await; + + let group_id = create_group_chat(bob, ProtectionStatus::Unprotected, "Group chat").await?; + let qr = get_securejoin_qr(bob, Some(group_id)).await?; + + check_qr(alice, &qr).await?; + tcm.exec_securejoin_qr(alice, bob, &qr).await; + expected.push(JoinedInvite { + contact_created: false, + already_verified: true, + typ: "group".to_string(), + }); + check_statistics(alice, &expected).await; + + // A contact with Charlie exists already: + alice.add_or_lookup_contact(charlie).await; + let group_id = + create_group_chat(charlie, ProtectionStatus::Unprotected, "Group chat 2").await?; + let qr = get_securejoin_qr(charlie, Some(group_id)).await?; + + check_qr(alice, &qr).await?; + tcm.exec_securejoin_qr(alice, bob, &qr).await; + expected.push(JoinedInvite { + contact_created: false, + already_verified: false, + typ: "group".to_string(), + }); + check_statistics(alice, &expected).await; + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_statistics_is_chatmail() -> Result<()> { + let alice = &TestContext::new_alice().await; + alice.set_config_bool(Config::StatsSending, true).await?; + + let r = get_statistics(alice).await?; + let r: serde_json::Value = serde_json::from_str(&r)?; + assert_eq!(r.get("is_chatmail").unwrap().as_bool().unwrap(), false); + + alice.set_config_bool(Config::IsChatmail, true).await?; + + let r = get_statistics(alice).await?; + let r: serde_json::Value = serde_json::from_str(&r)?; + assert_eq!(r.get("is_chatmail").unwrap().as_bool().unwrap(), true); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_statistics_key_creation_timestamp() -> Result<()> { + // Alice uses a pregenerated key. It was created at this timestamp: + const ALICE_KEY_CREATION_TIME: u128 = 1582855645; + + let alice = &TestContext::new_alice().await; + alice.set_config_bool(Config::StatsSending, true).await?; + + let r = get_statistics(alice).await?; + let r: serde_json::Value = serde_json::from_str(&r)?; + let key_create_timestamps = r.get("key_create_timestamps").unwrap().as_array().unwrap(); + assert_eq!( + key_create_timestamps, + &vec![Value::Number( + Number::from_u128(ALICE_KEY_CREATION_TIME).unwrap() + )] + ); + + Ok(()) +}