c_path
stringclasses
21 values
c_func
stringlengths
92
17.1k
rust_path
stringclasses
23 values
rust_func
stringlengths
53
16.4k
rust_context
stringlengths
0
36.3k
rust_imports
stringclasses
23 values
rustrepotrans_file
stringlengths
56
66
c2rust_func
stringlengths
0
38.5k
projects/deltachat-core/c/dc_oauth2.c
char* dc_get_oauth2_addr(dc_context_t* context, const char* addr, const char* code) { char* access_token = NULL; char* addr_out = NULL; oauth2_t* oauth2 = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || (oauth2=get_info(addr))==NULL || oauth2->get_userinfo==NULL) { goto cleanup; } access_token = dc_get_oauth2_access_token(context, addr, code, 0); addr_out = get_oauth2_addr(context, oauth2, access_token); if (addr_out==NULL) { free(access_token); access_token = dc_get_oauth2_access_token(context, addr, code, DC_REGENERATE); addr_out = get_oauth2_addr(context, oauth2, access_token); } cleanup: free(access_token); free(oauth2); return addr_out; }
projects/deltachat-core/rust/oauth2.rs
pub(crate) async fn get_oauth2_addr( context: &Context, addr: &str, code: &str, ) -> Result<Option<String>> { let socks5_enabled = context.get_config_bool(Config::Socks5Enabled).await?; let oauth2 = match Oauth2::from_address(context, addr, socks5_enabled).await { Some(o) => o, None => return Ok(None), }; if oauth2.get_userinfo.is_none() { return Ok(None); } if let Some(access_token) = get_oauth2_access_token(context, addr, code, false).await? { let addr_out = oauth2.get_addr(context, &access_token).await; if addr_out.is_none() { // regenerate if let Some(access_token) = get_oauth2_access_token(context, addr, code, true).await? { Ok(oauth2.get_addr(context, &access_token).await) } else { Ok(None) } } else { Ok(addr_out) } } else { Ok(None) } }
pub async fn get_config_bool(&self, key: Config) -> Result<bool> { Ok(self.get_config_bool_opt(key).await?.unwrap_or_default()) } async fn get_addr(&self, context: &Context, access_token: &str) -> Option<String> { let userinfo_url = self.get_userinfo.unwrap_or(""); let userinfo_url = replace_in_uri(userinfo_url, "$ACCESS_TOKEN", access_token); // should returns sth. as // { // "id": "100000000831024152393", // "email": "[email protected]", // "verified_email": true, // "picture": "https://lh4.googleusercontent.com/-Gj5jh_9R0BY/AAAAAAAAAAI/AAAAAAAAAAA/IAjtjfjtjNA/photo.jpg" // } let socks5_config = Socks5Config::from_database(&context.sql).await.ok()?; let client = match crate::net::http::get_client(socks5_config) { Ok(cl) => cl, Err(err) => { warn!(context, "failed to get HTTP client: {}", err); return None; } }; let response = match client.get(userinfo_url).send().await { Ok(response) => response, Err(err) => { warn!(context, "failed to get userinfo: {}", err); return None; } }; let response: Result<HashMap<String, serde_json::Value>, _> = response.json().await; let parsed = match response { Ok(parsed) => parsed, Err(err) => { warn!(context, "Error getting userinfo: {}", err); return None; } }; // CAVE: serde_json::Value.as_str() removes the quotes of json-strings // but serde_json::Value.to_string() does not! if let Some(addr) = parsed.get("email") { if let Some(s) = addr.as_str() { Some(s.to_string()) } else { warn!(context, "E-mail in userinfo is not a string: {}", addr); None } } else { warn!(context, "E-mail missing in userinfo."); None } } pub(crate) async fn get_oauth2_access_token( context: &Context, addr: &str, code: &str, regenerate: bool, ) -> Result<Option<String>> { let socks5_enabled = context.get_config_bool(Config::Socks5Enabled).await?; if let Some(oauth2) = Oauth2::from_address(context, addr, socks5_enabled).await { let lock = context.oauth2_mutex.lock().await; // read generated token if !regenerate && !is_expired(context).await? { let access_token = context.sql.get_raw_config("oauth2_access_token").await?; if access_token.is_some() { // success return Ok(access_token); } } // generate new token: build & call auth url let refresh_token = context.sql.get_raw_config("oauth2_refresh_token").await?; let refresh_token_for = context .sql .get_raw_config("oauth2_refresh_token_for") .await? .unwrap_or_else(|| "unset".into()); let (redirect_uri, token_url, update_redirect_uri_on_success) = if refresh_token.is_none() || refresh_token_for != code { info!(context, "Generate OAuth2 refresh_token and access_token...",); ( context .sql .get_raw_config("oauth2_pending_redirect_uri") .await? .unwrap_or_else(|| "unset".into()), oauth2.init_token, true, ) } else { info!( context, "Regenerate OAuth2 access_token by refresh_token...", ); ( context .sql .get_raw_config("oauth2_redirect_uri") .await? .unwrap_or_else(|| "unset".into()), oauth2.refresh_token, false, ) }; // to allow easier specification of different configurations, // token_url is in GET-method-format, sth. as <https://domain?param1=val1&param2=val2> - // convert this to POST-format ... let mut parts = token_url.splitn(2, '?'); let post_url = parts.next().unwrap_or_default(); let post_args = parts.next().unwrap_or_default(); let mut post_param = HashMap::new(); for key_value_pair in post_args.split('&') { let mut parts = key_value_pair.splitn(2, '='); let key = parts.next().unwrap_or_default(); let mut value = parts.next().unwrap_or_default(); if value == "$CLIENT_ID" { value = oauth2.client_id; } else if value == "$REDIRECT_URI" { value = &redirect_uri; } else if value == "$CODE" { value = code; } else if value == "$REFRESH_TOKEN" { if let Some(refresh_token) = refresh_token.as_ref() { value = refresh_token; } } post_param.insert(key, value); } // ... and POST let socks5_config = Socks5Config::from_database(&context.sql).await?; let client = crate::net::http::get_client(socks5_config)?; let response: Response = match client.post(post_url).form(&post_param).send().await { Ok(resp) => match resp.json().await { Ok(response) => response, Err(err) => { warn!( context, "Failed to parse OAuth2 JSON response from {}: error: {}", token_url, err ); return Ok(None); } }, Err(err) => { warn!(context, "Error calling OAuth2 at {}: {:?}", token_url, err); return Ok(None); } }; // update refresh_token if given, typically on the first round, but we update it later as well. if let Some(ref token) = response.refresh_token { context .sql .set_raw_config("oauth2_refresh_token", Some(token)) .await?; context .sql .set_raw_config("oauth2_refresh_token_for", Some(code)) .await?; } // after that, save the access token. // if it's unset, we may get it in the next round as we have the refresh_token now. if let Some(ref token) = response.access_token { context .sql .set_raw_config("oauth2_access_token", Some(token)) .await?; let expires_in = response .expires_in // refresh a bit before .map(|t| time() + t as i64 - 5) .unwrap_or_else(|| 0); context .sql .set_raw_config_int64("oauth2_timestamp_expires", expires_in) .await?; if update_redirect_uri_on_success { context .sql .set_raw_config("oauth2_redirect_uri", Some(redirect_uri.as_ref())) .await?; } } else { warn!(context, "Failed to find OAuth2 access token"); } drop(lock); Ok(response.access_token) } else { warn!(context, "Internal OAuth2 error: 2"); Ok(None) } } async fn from_address(context: &Context, addr: &str, skip_mx: bool) -> Option<Self> { let addr_normalized = normalize_addr(addr); if let Some(domain) = addr_normalized .find('@') .map(|index| addr_normalized.split_at(index + 1).1) { if let Some(oauth2_authorizer) = provider::get_provider_info(context, domain, skip_mx) .await .and_then(|provider| provider.oauth2_authorizer.as_ref()) { return Some(match oauth2_authorizer { Oauth2Authorizer::Gmail => OAUTH2_GMAIL, Oauth2Authorizer::Yandex => OAUTH2_YANDEX, }); } } None } pub enum Config { /// Email address, used in the `From:` field. Addr, /// IMAP server hostname. MailServer, /// IMAP server username. MailUser, /// IMAP server password. MailPw, /// IMAP server port. MailPort, /// IMAP server security (e.g. TLS, STARTTLS). MailSecurity, /// How to check IMAP server TLS certificates. ImapCertificateChecks, /// SMTP server hostname. SendServer, /// SMTP server username. SendUser, /// SMTP server password. SendPw, /// SMTP server port. SendPort, /// SMTP server security (e.g. TLS, STARTTLS). SendSecurity, /// How to check SMTP server TLS certificates. SmtpCertificateChecks, /// Whether to use OAuth 2. /// /// Historically contained other bitflags, which are now deprecated. /// Should not be extended in the future, create new config keys instead. ServerFlags, /// True if SOCKS5 is enabled. /// /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration. Socks5Enabled, /// SOCKS5 proxy server hostname or address. Socks5Host, /// SOCKS5 proxy server port. Socks5Port, /// SOCKS5 proxy server username. Socks5User, /// SOCKS5 proxy server password. Socks5Password, /// Own name to use in the `From:` field when sending messages. Displayname, /// Own status to display, sent in message footer. Selfstatus, /// Own avatar filename. Selfavatar, /// Send BCC copy to self. /// /// Should be enabled for multidevice setups. #[strum(props(default = "1"))] BccSelf, /// True if encryption is preferred according to Autocrypt standard. #[strum(props(default = "1"))] E2eeEnabled, /// True if Message Delivery Notifications (read receipts) should /// be sent and requested. #[strum(props(default = "1"))] MdnsEnabled, /// True if "Sent" folder should be watched for changes. #[strum(props(default = "0"))] SentboxWatch, /// True if chat messages should be moved to a separate folder. #[strum(props(default = "1"))] MvboxMove, /// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only. /// /// This will not entirely disable other folders, e.g. the spam folder will also still /// be watched for new messages. #[strum(props(default = "0"))] OnlyFetchMvbox, /// Whether to show classic emails or only chat messages. #[strum(props(default = "2"))] // also change ShowEmails.default() on changes ShowEmails, /// Quality of the media files to send. #[strum(props(default = "0"))] // also change MediaQuality.default() on changes MediaQuality, /// If set to "1", on the first time `start_io()` is called after configuring, /// the newest existing messages are fetched. /// Existing recipients are added to the contact database regardless of this setting. #[strum(props(default = "0"))] FetchExistingMsgs, /// If set to "1", then existing messages are considered to be already fetched. /// This flag is reset after successful configuration. #[strum(props(default = "1"))] FetchedExistingMsgs, /// Type of the OpenPGP key to generate. #[strum(props(default = "0"))] KeyGenType, /// Timer in seconds after which the message is deleted from the /// server. /// /// Equals to 0 by default, which means the message is never /// deleted. /// /// Value 1 is treated as "delete at once": messages are deleted /// immediately, without moving to DeltaChat folder. #[strum(props(default = "0"))] DeleteServerAfter, /// Timer in seconds after which the message is deleted from the /// device. /// /// Equals to 0 by default, which means the message is never /// deleted. #[strum(props(default = "0"))] DeleteDeviceAfter, /// Move messages to the Trash folder instead of marking them "\Deleted". Overrides /// `ProviderOptions::delete_to_trash`. DeleteToTrash, /// Save raw MIME messages with headers in the database if true. SaveMimeHeaders, /// The primary email address. Also see `SecondaryAddrs`. ConfiguredAddr, /// Configured IMAP server hostname. ConfiguredMailServer, /// Configured IMAP server username. ConfiguredMailUser, /// Configured IMAP server password. ConfiguredMailPw, /// Configured IMAP server port. ConfiguredMailPort, /// Configured IMAP server security (e.g. TLS, STARTTLS). ConfiguredMailSecurity, /// How to check IMAP server TLS certificates. ConfiguredImapCertificateChecks, /// Configured SMTP server hostname. ConfiguredSendServer, /// Configured SMTP server username. ConfiguredSendUser, /// Configured SMTP server password. ConfiguredSendPw, /// Configured SMTP server port. ConfiguredSendPort, /// How to check SMTP server TLS certificates. ConfiguredSmtpCertificateChecks, /// Whether OAuth 2 is used with configured provider. ConfiguredServerFlags, /// Configured SMTP server security (e.g. TLS, STARTTLS). ConfiguredSendSecurity, /// Configured folder for incoming messages. ConfiguredInboxFolder, /// Configured folder for chat messages. ConfiguredMvboxFolder, /// Configured "Sent" folder. ConfiguredSentboxFolder, /// Configured "Trash" folder. ConfiguredTrashFolder, /// Unix timestamp of the last successful configuration. ConfiguredTimestamp, /// ID of the configured provider from the provider database. ConfiguredProvider, /// True if account is configured. Configured, /// True if account is a chatmail account. IsChatmail, /// All secondary self addresses separated by spaces /// (`[email protected] [email protected] [email protected]`) SecondaryAddrs, /// Read-only core version string. #[strum(serialize = "sys.version")] SysVersion, /// Maximal recommended attachment size in bytes. #[strum(serialize = "sys.msgsize_max_recommended")] SysMsgsizeMaxRecommended, /// Space separated list of all config keys available. #[strum(serialize = "sys.config_keys")] SysConfigKeys, /// True if it is a bot account. Bot, /// True when to skip initial start messages in groups. #[strum(props(default = "0"))] SkipStartMessages, /// Whether we send a warning if the password is wrong (set to false when we send a warning /// because we do not want to send a second warning) #[strum(props(default = "0"))] NotifyAboutWrongPw, /// If a warning about exceeding quota was shown recently, /// this is the percentage of quota at the time the warning was given. /// Unset, when quota falls below minimal warning threshold again. QuotaExceeding, /// address to webrtc instance to use for videochats WebrtcInstance, /// Timestamp of the last time housekeeping was run LastHousekeeping, /// Timestamp of the last `CantDecryptOutgoingMsgs` notification. LastCantDecryptOutgoingMsgs, /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely. #[strum(props(default = "60"))] ScanAllFoldersDebounceSecs, /// Whether to avoid using IMAP IDLE even if the server supports it. /// /// This is a developer option for testing "fake idle". #[strum(props(default = "0"))] DisableIdle, /// Defines the max. size (in bytes) of messages downloaded automatically. /// 0 = no limit. #[strum(props(default = "0"))] DownloadLimit, /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set. #[strum(props(default = "1"))] SyncMsgs, /// Space-separated list of all the authserv-ids which we believe /// may be the one of our email server. /// /// See `crate::authres::update_authservid_candidates`. AuthservIdCandidates, /// Make all outgoing messages with Autocrypt header "multipart/signed". SignUnencrypted, /// Let the core save all events to the database. /// This value is used internally to remember the MsgId of the logging xdc #[strum(props(default = "0"))] DebugLogging, /// Last message processed by the bot. LastMsgId, /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by /// default. /// /// This is not supposed to be changed by UIs and only used for testing. #[strum(props(default = "172800"))] GossipPeriod, /// Feature flag for verified 1:1 chats; the UI should set it /// to 1 if it supports verified 1:1 chats. /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified, /// and when the key changes, an info message is posted into the chat. /// 0=Nothing else happens when the key changes. /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true /// until `chat_id.accept()` is called. #[strum(props(default = "0"))] VerifiedOneOnOneChats, /// Row ID of the key in the `keypairs` table /// 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 /// without storing the email address SelfReportingId, /// MsgId of webxdc map integration. WebxdcIntegration, /// Iroh secret key. IrohSecretKey, } pub struct Context { pub(crate) inner: Arc<InnerContext>, }
use std::collections::HashMap; use anyhow::Result; use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC}; use serde::Deserialize; use crate::config::Config; use crate::context::Context; use crate::provider; use crate::provider::Oauth2Authorizer; use crate::socks::Socks5Config; use crate::tools::time; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__oauth2__.rs__function__3.txt
pub unsafe extern "C" fn dc_get_oauth2_addr( mut context: *mut dc_context_t, mut addr: *const libc::c_char, mut code: *const libc::c_char, ) -> *mut libc::c_char { let mut access_token: *mut libc::c_char = 0 as *mut libc::c_char; let mut addr_out: *mut libc::c_char = 0 as *mut libc::c_char; let mut oauth2: *mut oauth2_t = 0 as *mut oauth2_t; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || { oauth2 = get_info(addr); oauth2.is_null() } || ((*oauth2).get_userinfo).is_null()) { access_token = dc_get_oauth2_access_token(context, addr, code, 0 as libc::c_int); addr_out = get_oauth2_addr(context, oauth2, access_token); if addr_out.is_null() { free(access_token as *mut libc::c_void); access_token = dc_get_oauth2_access_token( context, addr, code, 0x1 as libc::c_int, ); addr_out = get_oauth2_addr(context, oauth2, access_token); } } free(access_token as *mut libc::c_void); free(oauth2 as *mut libc::c_void); return addr_out; }
projects/deltachat-core/c/dc_tools.c
int dc_get_filemeta(const void* buf_start, size_t buf_bytes, uint32_t* ret_width, uint32_t *ret_height) { /* Strategy: reading GIF dimensions requires the first 10 bytes of the file reading PNG dimensions requires the first 24 bytes of the file reading JPEG dimensions requires scanning through jpeg chunks In all formats, the file is at least 24 bytes big, so we'll read that always inspired by http://www.cplusplus.com/forum/beginner/45217/ */ const unsigned char* buf = buf_start; if (buf_bytes<24) { return 0; } /* For JPEGs, we need to check the first bytes of each DCT chunk. */ if (buf[0]==0xFF && buf[1]==0xD8 && buf[2]==0xFF) { long pos = 2; while (buf[pos]==0xFF) { if (buf[pos+1]==0xC0 || buf[pos+1]==0xC1 || buf[pos+1]==0xC2 || buf[pos+1]==0xC3 || buf[pos+1]==0xC9 || buf[pos+1]==0xCA || buf[pos+1]==0xCB) { *ret_height = (buf[pos+5]<<8) + buf[pos+6]; /* sic! height is first */ *ret_width = (buf[pos+7]<<8) + buf[pos+8]; return 1; } pos += 2+(buf[pos+2]<<8)+buf[pos+3]; if (pos+12>buf_bytes) { break; } } } /* GIF: first three bytes say "GIF", next three give version number. Then dimensions */ if (buf[0]=='G' && buf[1]=='I' && buf[2]=='F') { *ret_width = buf[6] + (buf[7]<<8); *ret_height = buf[8] + (buf[9]<<8); return 1; } /* PNG: the first frame is by definition an IHDR frame, which gives dimensions */ if (buf[0]==0x89 && buf[1]=='P' && buf[2]=='N' && buf[3]=='G' && buf[4]==0x0D && buf[5]==0x0A && buf[6]==0x1A && buf[7]==0x0A && buf[12]=='I' && buf[13]=='H' && buf[14]=='D' && buf[15]=='R') { *ret_width = (buf[16]<<24) + (buf[17]<<16) + (buf[18]<<8) + (buf[19]<<0); *ret_height = (buf[20]<<24) + (buf[21]<<16) + (buf[22]<<8) + (buf[23]<<0); return 1; } return 0; }
projects/deltachat-core/rust/tools.rs
pub fn get_filemeta(buf: &[u8]) -> Result<(u32, u32)> { let image = image::io::Reader::new(Cursor::new(buf)).with_guessed_format()?; let dimensions = image.into_dimensions()?; Ok(dimensions) }
use std::borrow::Cow; use std::io::{Cursor, Write}; use std::mem; use std::path::{Path, PathBuf}; use std::str::from_utf8; use std::time::Duration; use std::time::SystemTime as Time; use std::time::SystemTime; use anyhow::{bail, Context as _, Result}; use base64::Engine as _; use chrono::{Local, NaiveDateTime, NaiveTime, TimeZone}; use deltachat_contact_tools::{strip_rtlo_characters, EmailAddress}; use deltachat_time::SystemTimeTools as SystemTime; use futures::{StreamExt, TryStreamExt}; use mailparse::dateparse; use mailparse::headers::Headers; use mailparse::MailHeaderMap; use rand::{thread_rng, Rng}; use tokio::{fs, io}; use url::Url; use crate::chat::{add_device_msg, add_device_msg_with_importance}; use crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS}; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, Viewtype}; use crate::stock_str; use chrono::NaiveDate; use proptest::prelude::*; use super::*; use crate::chatlist::Chatlist; use crate::{chat, test_utils}; use crate::{receive_imf::receive_imf, test_utils::TestContext}; use super::*;
projects__deltachat-core__rust__tools__.rs__function__17.txt
pub unsafe extern "C" fn dc_get_filemeta( mut buf_start: *const libc::c_void, mut buf_bytes: size_t, mut ret_width: *mut uint32_t, mut ret_height: *mut uint32_t, ) -> libc::c_int { let mut buf: *const libc::c_uchar = buf_start as *const libc::c_uchar; if buf_bytes < 24 as libc::c_int as libc::c_ulong { return 0 as libc::c_int; } if *buf.offset(0 as libc::c_int as isize) as libc::c_int == 0xff as libc::c_int && *buf.offset(1 as libc::c_int as isize) as libc::c_int == 0xd8 as libc::c_int && *buf.offset(2 as libc::c_int as isize) as libc::c_int == 0xff as libc::c_int { let mut pos: libc::c_long = 2 as libc::c_int as libc::c_long; while *buf.offset(pos as isize) as libc::c_int == 0xff as libc::c_int { if *buf.offset((pos + 1 as libc::c_int as libc::c_long) as isize) as libc::c_int == 0xc0 as libc::c_int || *buf.offset((pos + 1 as libc::c_int as libc::c_long) as isize) as libc::c_int == 0xc1 as libc::c_int || *buf.offset((pos + 1 as libc::c_int as libc::c_long) as isize) as libc::c_int == 0xc2 as libc::c_int || *buf.offset((pos + 1 as libc::c_int as libc::c_long) as isize) as libc::c_int == 0xc3 as libc::c_int || *buf.offset((pos + 1 as libc::c_int as libc::c_long) as isize) as libc::c_int == 0xc9 as libc::c_int || *buf.offset((pos + 1 as libc::c_int as libc::c_long) as isize) as libc::c_int == 0xca as libc::c_int || *buf.offset((pos + 1 as libc::c_int as libc::c_long) as isize) as libc::c_int == 0xcb as libc::c_int { *ret_height = (((*buf .offset((pos + 5 as libc::c_int as libc::c_long) as isize) as libc::c_int) << 8 as libc::c_int) + *buf.offset((pos + 6 as libc::c_int as libc::c_long) as isize) as libc::c_int) as uint32_t; *ret_width = (((*buf .offset((pos + 7 as libc::c_int as libc::c_long) as isize) as libc::c_int) << 8 as libc::c_int) + *buf.offset((pos + 8 as libc::c_int as libc::c_long) as isize) as libc::c_int) as uint32_t; return 1 as libc::c_int; } pos += (2 as libc::c_int + ((*buf.offset((pos + 2 as libc::c_int as libc::c_long) as isize) as libc::c_int) << 8 as libc::c_int) + *buf.offset((pos + 3 as libc::c_int as libc::c_long) as isize) as libc::c_int) as libc::c_long; if (pos + 12 as libc::c_int as libc::c_long) as libc::c_ulong > buf_bytes { break; } } } if *buf.offset(0 as libc::c_int as isize) as libc::c_int == 'G' as i32 && *buf.offset(1 as libc::c_int as isize) as libc::c_int == 'I' as i32 && *buf.offset(2 as libc::c_int as isize) as libc::c_int == 'F' as i32 { *ret_width = (*buf.offset(6 as libc::c_int as isize) as libc::c_int + ((*buf.offset(7 as libc::c_int as isize) as libc::c_int) << 8 as libc::c_int)) as uint32_t; *ret_height = (*buf.offset(8 as libc::c_int as isize) as libc::c_int + ((*buf.offset(9 as libc::c_int as isize) as libc::c_int) << 8 as libc::c_int)) as uint32_t; return 1 as libc::c_int; } if *buf.offset(0 as libc::c_int as isize) as libc::c_int == 0x89 as libc::c_int && *buf.offset(1 as libc::c_int as isize) as libc::c_int == 'P' as i32 && *buf.offset(2 as libc::c_int as isize) as libc::c_int == 'N' as i32 && *buf.offset(3 as libc::c_int as isize) as libc::c_int == 'G' as i32 && *buf.offset(4 as libc::c_int as isize) as libc::c_int == 0xd as libc::c_int && *buf.offset(5 as libc::c_int as isize) as libc::c_int == 0xa as libc::c_int && *buf.offset(6 as libc::c_int as isize) as libc::c_int == 0x1a as libc::c_int && *buf.offset(7 as libc::c_int as isize) as libc::c_int == 0xa as libc::c_int && *buf.offset(12 as libc::c_int as isize) as libc::c_int == 'I' as i32 && *buf.offset(13 as libc::c_int as isize) as libc::c_int == 'H' as i32 && *buf.offset(14 as libc::c_int as isize) as libc::c_int == 'D' as i32 && *buf.offset(15 as libc::c_int as isize) as libc::c_int == 'R' as i32 { *ret_width = (((*buf.offset(16 as libc::c_int as isize) as libc::c_int) << 24 as libc::c_int) + ((*buf.offset(17 as libc::c_int as isize) as libc::c_int) << 16 as libc::c_int) + ((*buf.offset(18 as libc::c_int as isize) as libc::c_int) << 8 as libc::c_int) + ((*buf.offset(19 as libc::c_int as isize) as libc::c_int) << 0 as libc::c_int)) as uint32_t; *ret_height = (((*buf.offset(20 as libc::c_int as isize) as libc::c_int) << 24 as libc::c_int) + ((*buf.offset(21 as libc::c_int as isize) as libc::c_int) << 16 as libc::c_int) + ((*buf.offset(22 as libc::c_int as isize) as libc::c_int) << 8 as libc::c_int) + ((*buf.offset(23 as libc::c_int as isize) as libc::c_int) << 0 as libc::c_int)) as uint32_t; return 1 as libc::c_int; } return 0 as libc::c_int; }
projects/deltachat-core/c/dc_chatlist.c
dc_lot_t* dc_chatlist_get_summary(const dc_chatlist_t* chatlist, size_t index, dc_chat_t* chat /*may be NULL*/) { /* The summary is created by the chat, not by the last message. This is because we may want to display drafts here or stuff as "is typing". Also, sth. as "No messages" would not work if the summary comes from a message. */ dc_lot_t* ret = dc_lot_new(); /* the function never returns NULL */ uint32_t lastmsg_id = 0; dc_msg_t* lastmsg = NULL; dc_contact_t* lastcontact = NULL; dc_chat_t* chat_to_delete = NULL; if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC || index>=chatlist->cnt) { ret->text2 = dc_strdup("ErrBadChatlistIndex"); goto cleanup; } lastmsg_id = dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT+1); if (chat==NULL) { chat = dc_chat_new(chatlist->context); chat_to_delete = chat; if (!dc_chat_load_from_db(chat, dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT))) { ret->text2 = dc_strdup("ErrCannotReadChat"); goto cleanup; } } if (lastmsg_id) { lastmsg = dc_msg_new_untyped(chatlist->context); dc_msg_load_from_db(lastmsg, chatlist->context, lastmsg_id); if (lastmsg->from_id!=DC_CONTACT_ID_SELF && DC_CHAT_TYPE_IS_MULTI(chat->type)) { lastcontact = dc_contact_new(chatlist->context); dc_contact_load_from_db(lastcontact, chatlist->context->sql, lastmsg->from_id); } } if (chat->id==DC_CHAT_ID_ARCHIVED_LINK) { ret->text2 = dc_strdup(NULL); } else if (lastmsg==NULL || lastmsg->from_id==0) { /* no messages */ ret->text2 = dc_stock_str(chatlist->context, DC_STR_NOMESSAGES); } else { /* show the last message */ dc_lot_fill(ret, lastmsg, chat, lastcontact, chatlist->context); } cleanup: dc_msg_unref(lastmsg); dc_contact_unref(lastcontact); dc_chat_unref(chat_to_delete); return ret; }
projects/deltachat-core/rust/chatlist.rs
pub async fn get_summary( &self, context: &Context, index: usize, chat: Option<&Chat>, ) -> Result<Summary> { // The summary is created by the chat, not by the last message. // This is because we may want to display drafts here or stuff as // "is typing". // Also, sth. as "No messages" would not work if the summary comes from a message. let (chat_id, lastmsg_id) = self .ids .get(index) .context("chatlist index is out of range")?; Chatlist::get_summary2(context, *chat_id, *lastmsg_id, chat).await }
pub fn get(&self, key: Param) -> Option<&str> { self.inner.get(&key).map(|s| s.as_str()) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct Chatlist { /// Stores pairs of `chat_id, message_id` ids: Vec<(ChatId, Option<MsgId>)>, } pub async fn get_summary2( context: &Context, chat_id: ChatId, lastmsg_id: Option<MsgId>, chat: Option<&Chat>, ) -> Result<Summary> { let chat_loaded: Chat; let chat = if let Some(chat) = chat { chat } else { let chat = Chat::load_from_db(context, chat_id).await?; chat_loaded = chat; &chat_loaded }; let (lastmsg, lastcontact) = if let Some(lastmsg_id) = lastmsg_id { let lastmsg = Message::load_from_db(context, lastmsg_id) .await .context("loading message failed")?; if lastmsg.from_id == ContactId::SELF { (Some(lastmsg), None) } else { match chat.typ { Chattype::Group | Chattype::Broadcast | Chattype::Mailinglist => { let lastcontact = Contact::get_by_id(context, lastmsg.from_id) .await .context("loading contact failed")?; (Some(lastmsg), Some(lastcontact)) } Chattype::Single => (Some(lastmsg), None), } } } else { (None, None) }; if chat.id.is_archived_link() { Ok(Default::default()) } else if let Some(lastmsg) = lastmsg.filter(|msg| msg.from_id != ContactId::UNDEFINED) { Summary::new_with_reaction_details(context, &lastmsg, chat, lastcontact.as_ref()).await } else { Ok(Summary { text: stock_str::no_messages(context).await, ..Default::default() }) } } pub struct Summary { /// Part displayed before ":", such as an username or a string "Draft". pub prefix: Option<SummaryPrefix>, /// Summary text, always present. pub text: String, /// Message timestamp. pub timestamp: i64, /// Message state. pub state: MessageState, /// Message preview image path pub thumbnail_path: Option<String>, }
use anyhow::{ensure, Context as _, Result}; use once_cell::sync::Lazy; use crate::chat::{update_special_chat_names, Chat, ChatId, ChatVisibility}; use crate::constants::{ Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_GCL_ADD_ALLDONE_HINT, DC_GCL_ARCHIVED_ONLY, DC_GCL_FOR_FORWARDING, DC_GCL_NO_SPECIALS, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::message::{Message, MessageState, MsgId}; use crate::param::{Param, Params}; use crate::stock_str; use crate::summary::Summary; use crate::tools::IsNoneOrEmpty; use super::*; use crate::chat::{ add_contact_to_chat, create_group_chat, get_chat_contacts, remove_contact_from_chat, send_text_msg, ProtectionStatus, }; use crate::message::Viewtype; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::TestContext;
projects__deltachat-core__rust__chatlist__.rs__function__7.txt
pub unsafe extern "C" fn dc_chatlist_get_summary( mut chatlist: *const dc_chatlist_t, mut index: size_t, mut chat: *mut dc_chat_t, ) -> *mut dc_lot_t { let mut current_block: u64; let mut ret: *mut dc_lot_t = dc_lot_new(); let mut lastmsg_id: uint32_t = 0 as libc::c_int as uint32_t; let mut lastmsg: *mut dc_msg_t = 0 as *mut dc_msg_t; let mut lastcontact: *mut dc_contact_t = 0 as *mut dc_contact_t; let mut chat_to_delete: *mut dc_chat_t = 0 as *mut dc_chat_t; if chatlist.is_null() || (*chatlist).magic != 0xc4a71157 as libc::c_uint || index >= (*chatlist).cnt { (*ret) .text2 = dc_strdup( b"ErrBadChatlistIndex\0" as *const u8 as *const libc::c_char, ); } else { lastmsg_id = dc_array_get_id( (*chatlist).chatNlastmsg_ids, index .wrapping_mul(2 as libc::c_int as libc::c_ulong) .wrapping_add(1 as libc::c_int as libc::c_ulong), ); if chat.is_null() { chat = dc_chat_new((*chatlist).context); chat_to_delete = chat; if dc_chat_load_from_db( chat, dc_array_get_id( (*chatlist).chatNlastmsg_ids, index.wrapping_mul(2 as libc::c_int as libc::c_ulong), ), ) == 0 { (*ret) .text2 = dc_strdup( b"ErrCannotReadChat\0" as *const u8 as *const libc::c_char, ); current_block = 5211493298207122346; } else { current_block = 5720623009719927633; } } else { current_block = 5720623009719927633; } match current_block { 5211493298207122346 => {} _ => { if lastmsg_id != 0 { lastmsg = dc_msg_new_untyped((*chatlist).context); dc_msg_load_from_db(lastmsg, (*chatlist).context, lastmsg_id); if (*lastmsg).from_id != 1 as libc::c_int as libc::c_uint && ((*chat).type_0 == 120 as libc::c_int || (*chat).type_0 == 130 as libc::c_int) { lastcontact = dc_contact_new((*chatlist).context); dc_contact_load_from_db( lastcontact, (*(*chatlist).context).sql, (*lastmsg).from_id, ); } } if (*chat).id == 6 as libc::c_int as libc::c_uint { (*ret).text2 = dc_strdup(0 as *const libc::c_char); } else if lastmsg.is_null() || (*lastmsg).from_id == 0 as libc::c_int as libc::c_uint { (*ret).text2 = dc_stock_str((*chatlist).context, 1 as libc::c_int); } else { dc_lot_fill(ret, lastmsg, chat, lastcontact, (*chatlist).context); } } } } dc_msg_unref(lastmsg); dc_contact_unref(lastcontact); dc_chat_unref(chat_to_delete); return ret; }
projects/deltachat-core/c/dc_configure.c
* Frees the process allocated with dc_alloc_ongoing() - independingly of dc_shall_stop_ongoing. * If dc_alloc_ongoing() fails, this function MUST NOT be called. */ void dc_free_ongoing(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } context->ongoing_running = 0; context->shall_stop_ongoing = 1; /* avoids dc_stop_ongoing_process() to stop the thread */ }
projects/deltachat-core/rust/context.rs
pub(crate) async fn free_ongoing(&self) { let mut s = self.running_state.write().await; if let RunningState::ShallStop { request } = *s { info!(self, "Ongoing stopped in {:?}", time_elapsed(&request)); } *s = RunningState::Stopped; }
macro_rules! info { ($ctx:expr, $msg:expr) => { info!($ctx, $msg,) }; ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{ let formatted = format!($msg, $($args),*); let full = format!("{file}:{line}: {msg}", file = file!(), line = line!(), msg = &formatted); $ctx.emit_event($crate::EventType::Info(full)); }}; } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } enum RunningState { /// Ongoing process is allocated. Running { cancel_sender: Sender<()> }, /// Cancel signal has been sent, waiting for ongoing process to be freed. ShallStop { request: tools::Time }, /// There is no ongoing process, a new one can be allocated. Stopped, }
use std::collections::{BTreeMap, HashMap}; use std::ffi::OsString; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use pgp::SignedPublicKey; use ratelimit::Ratelimit; use tokio::sync::{Mutex, Notify, OnceCell, RwLock}; use crate::aheader::EncryptPreference; use crate::chat::{get_chat_cnt, ChatId, ProtectionStatus}; use crate::chatlist_events; 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}; 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_public_key, load_self_secret_key, DcKey as _}; use crate::login_param::LoginParam; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::param::{Param, Params}; use crate::peer_channels::Iroh; use crate::peerstate::Peerstate; use crate::push::PushSubscriber; use crate::quota::QuotaInfo; use crate::scheduler::{convert_folder_meaning, SchedulerState}; 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 anyhow::Context as _; use strum::IntoEnumIterator; use tempfile::tempdir; use super::*; use crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration}; use crate::chatlist::Chatlist; use crate::constants::Chattype; use crate::mimeparser::SystemMessage; use crate::receive_imf::receive_imf; use crate::test_utils::{get_chat_msg, TestContext}; use crate::tools::{create_outgoing_rfc724_mid, SystemTime};
projects__deltachat-core__rust__context__.rs__function__38.txt
pub unsafe extern "C" fn dc_alloc_ongoing( mut context: *mut dc_context_t, ) -> libc::c_int { if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint { return 0 as libc::c_int; } if dc_has_ongoing(context) != 0 { dc_log_warning( context, 0 as libc::c_int, b"There is already another ongoing process running.\0" as *const u8 as *const libc::c_char, ); return 0 as libc::c_int; } (*context).ongoing_running = 1 as libc::c_int; (*context).shall_stop_ongoing = 0 as libc::c_int; return 1 as libc::c_int; }
projects/deltachat-core/c/dc_param.c
int32_t dc_param_get_int(const dc_param_t* param, int key, int32_t def) { if (param==NULL || key==0) { return def; } char* str = dc_param_get(param, key, NULL); if (str==NULL) { return def; } int32_t ret = atol(str); free(str); return ret; }
projects/deltachat-core/rust/param.rs
pub fn get_int(&self, key: Param) -> Option<i32> { self.get(key).and_then(|s| s.parse().ok()) }
pub fn get(&self, key: Param) -> Option<&str> { self.inner.get(&key).map(|s| s.as_str()) } pub struct Params { inner: BTreeMap<Param, String>, }
use std::collections::BTreeMap; use std::fmt; use std::path::PathBuf; use std::str; use anyhow::{bail, Error, Result}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use crate::blob::BlobObject; use crate::context::Context; use crate::mimeparser::SystemMessage; use std::path::Path; use std::str::FromStr; use tokio::fs; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__param__.rs__function__11.txt
pub unsafe extern "C" fn dc_param_get_int( mut param: *const dc_param_t, mut key: libc::c_int, mut def: int32_t, ) -> int32_t { if param.is_null() || key == 0 as libc::c_int { return def; } let mut str: *mut libc::c_char = dc_param_get(param, key, 0 as *const libc::c_char); if str.is_null() { return def; } let mut ret: int32_t = atol(str) as int32_t; free(str as *mut libc::c_void); return ret; }
projects/deltachat-core/c/dc_chat.c
static uint32_t get_draft_msg_id(dc_context_t* context, uint32_t chat_id) { uint32_t draft_msg_id = 0; sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM msgs WHERE chat_id=? AND state=?;"); sqlite3_bind_int(stmt, 1, chat_id); sqlite3_bind_int(stmt, 2, DC_STATE_OUT_DRAFT); if (sqlite3_step(stmt)==SQLITE_ROW) { draft_msg_id = sqlite3_column_int(stmt, 0); } sqlite3_finalize(stmt); return draft_msg_id; }
projects/deltachat-core/rust/chat.rs
async fn get_draft_msg_id(self, context: &Context) -> Result<Option<MsgId>> { let msg_id: Option<MsgId> = context .sql .query_get_value( "SELECT id FROM msgs WHERE chat_id=? AND state=?;", (self, MessageState::OutDraft), ) .await?; Ok(msg_id) }
pub struct Context { pub(crate) inner: Arc<InnerContext>, } ub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub async fn query_get_value<T>( &self, query: &str, params: impl rusqlite::Params + Send, ) -> Result<Option<T>> where T: rusqlite::types::FromSql + Send + 'static, { self.query_row_optional(query, params, |row| row.get::<_, T>(0)) .await } pub enum MessageState { /// Undefined message state. #[default] Undefined = 0, /// Incoming *fresh* message. Fresh messages are neither noticed /// nor seen and are typically shown in notifications. InFresh = 10, /// Incoming *noticed* message. E.g. chat opened but message not /// yet read - noticed messages are not counted as unread but did /// not marked as read nor resulted in MDNs. InNoticed = 13, /// Incoming message, really *seen* by the user. Marked as read on /// IMAP and MDN may be sent. InSeen = 16, /// For files which need time to be prepared before they can be /// sent, the message enters this state before /// OutPending. OutPreparing = 18, /// Message saved as draft. OutDraft = 19, /// The user has pressed the "send" button but the message is not /// yet sent and is pending in some way. Maybe we're offline (no /// checkmark). OutPending = 20, /// *Unrecoverable* error (*recoverable* errors result in pending /// messages). OutFailed = 24, /// Outgoing message successfully delivered to server (one /// checkmark). Note, that already delivered messages may get into /// the OutFailed state if we get such a hint from the server. OutDelivered = 26, /// Outgoing message read by the recipient (two checkmarks; this /// requires goodwill on the receiver's side) OutMdnRcvd = 28, } pub struct MsgId(u32); pub struct ChatId(u32);
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__32.txt
unsafe extern "C" fn get_draft_msg_id( mut context: *mut dc_context_t, mut chat_id: uint32_t, ) -> uint32_t { let mut draft_msg_id: uint32_t = 0 as libc::c_int as uint32_t; let mut stmt: *mut sqlite3_stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT id FROM msgs WHERE chat_id=? AND state=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, chat_id as libc::c_int); sqlite3_bind_int(stmt, 2 as libc::c_int, 19 as libc::c_int); if sqlite3_step(stmt) == 100 as libc::c_int { draft_msg_id = sqlite3_column_int(stmt, 0 as libc::c_int) as uint32_t; } sqlite3_finalize(stmt); return draft_msg_id; }
projects/deltachat-core/c/dc_msg.c
int dc_msg_is_info(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } int cmd = dc_param_get_int(msg->param, DC_PARAM_CMD, 0); if (msg->from_id==DC_CONTACT_ID_INFO || msg->to_id==DC_CONTACT_ID_INFO || (cmd && cmd!=DC_CMD_AUTOCRYPT_SETUP_MESSAGE)) { return 1; } return 0; }
projects/deltachat-core/rust/message.rs
pub fn is_info(&self) -> bool { let cmd = self.param.get_cmd(); self.from_id == ContactId::INFO || self.to_id == ContactId::INFO || cmd != SystemMessage::Unknown && cmd != SystemMessage::AutocryptSetupMessage }
pub fn get_cmd(&self) -> SystemMessage { self.get_int(Param::Cmd) .and_then(SystemMessage::from_i32) .unwrap_or_default() } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub struct ContactId(u32); impl ContactId { /// Undefined contact. Used as a placeholder for trashed messages. pub const UNDEFINED: ContactId = ContactId::new(0); /// The owner of the account. /// /// The email-address is set by `set_config` using "addr". pub const SELF: ContactId = ContactId::new(1); /// ID of the contact for info messages. pub const INFO: ContactId = ContactId::new(2); /// ID of the contact for device messages. pub const DEVICE: ContactId = ContactId::new(5); pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9); /// Address to go with [`ContactId::DEVICE`]. /// /// This is used by APIs which need to return an email address for this contact. pub const DEVICE_ADDR: &'static str = "device@localhost"; } pub enum SystemMessage { /// Unknown type of system message. #[default] Unknown = 0, /// Group name changed. GroupNameChanged = 2, /// Group avatar changed. GroupImageChanged = 3, /// Member was added to the group. MemberAddedToGroup = 4, /// Member was removed from the group. MemberRemovedFromGroup = 5, /// Autocrypt Setup Message. AutocryptSetupMessage = 6, /// Secure-join message. SecurejoinMessage = 7, /// Location streaming is enabled. LocationStreamingEnabled = 8, /// Location-only message. LocationOnly = 9, /// Chat ephemeral message timer is changed. EphemeralTimerChanged = 10, /// "Messages are guaranteed to be end-to-end encrypted from now on." ChatProtectionEnabled = 11, /// "%1$s sent a message from another device." ChatProtectionDisabled = 12, /// Message can't be sent because of `Invalid unencrypted mail to <>` /// which is sent by chatmail servers. InvalidUnencryptedMail = 13, /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it /// to complete. SecurejoinWait = 14, /// 1:1 chats info message telling that SecureJoin is still running, but the user may already /// send messages. SecurejoinWaitTimeout = 15, /// Self-sent-message that contains only json used for multi-device-sync; /// if possible, we attach that to other messages as for locations. MultiDeviceSync = 20, /// Sync message that contains a json payload /// sent to the other webxdc instances /// These messages are not shown in the chat. WebxdcStatusUpdate = 30, /// Webxdc info added with `info` set in `send_webxdc_status_update()`. WebxdcInfoMessage = 32, /// This message contains a users iroh node address. IrohNodeAddr = 40, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__56.txt
pub unsafe extern "C" fn dc_msg_is_info(mut msg: *const dc_msg_t) -> libc::c_int { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return 0 as libc::c_int; } let mut cmd: libc::c_int = dc_param_get_int( (*msg).param, 'S' as i32, 0 as libc::c_int, ); if (*msg).from_id == 2 as libc::c_int as libc::c_uint || (*msg).to_id == 2 as libc::c_int as libc::c_uint || cmd != 0 && cmd != 6 as libc::c_int { return 1 as libc::c_int; } return 0 as libc::c_int; }
projects/deltachat-core/c/dc_simplify.c
static int is_plain_quote(const char* buf) { if (buf[0]=='>') { return 1; } return 0; }
projects/deltachat-core/rust/simplify.rs
fn is_plain_quote(buf: &str) -> bool { buf.starts_with('>') }
projects__deltachat-core__rust__simplify__.rs__function__14.txt
unsafe extern "C" fn is_plain_quote(mut buf: *const libc::c_char) -> libc::c_int { if *buf.offset(0 as libc::c_int as isize) as libc::c_int == '>' as i32 { return 1 as libc::c_int; } return 0 as libc::c_int; }
projects/deltachat-core/c/dc_chat.c
* If the group is already _promoted_ (any message was sent to the group), * all group members are informed by a special status message that is sent automatically by this function. * * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param chat_id The chat ID to remove the contact from. Must be a group chat. * @param contact_id The contact ID to remove from the chat. * @return 1=member removed from group, 0=error */ int dc_remove_contact_from_chat(dc_context_t* context, uint32_t chat_id, uint32_t contact_id /*may be DC_CONTACT_ID_SELF*/) { int success = 0; dc_contact_t* contact = dc_get_contact(context, contact_id); dc_chat_t* chat = dc_chat_new(context); dc_msg_t* msg = dc_msg_new_untyped(context); char* q3 = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL || (contact_id<=DC_CONTACT_ID_LAST_SPECIAL && contact_id!=DC_CONTACT_ID_SELF)) { goto cleanup; /* we do not check if "contact_id" exists but just delete all records with the id from chats_contacts */ } /* this allows to delete pending references to deleted contacts. Of course, this should _not_ happen. */ if (0==real_group_exists(context, chat_id) || 0==dc_chat_load_from_db(chat, chat_id)) { goto cleanup; } if (!IS_SELF_IN_GROUP) { dc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0, "Cannot remove contact from chat; self not in group."); goto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */ } /* send a status mail to all group members - we need to do this before we update the database - otherwise the !IS_SELF_IN_GROUP__-check in dc_chat_send_msg() will fail. */ if (contact) { if (DO_SEND_STATUS_MAILS) { msg->type = DC_MSG_TEXT; if (contact->id==DC_CONTACT_ID_SELF) { dc_set_group_explicitly_left(context, chat->grpid); msg->text = dc_stock_system_msg(context, DC_STR_MSGGROUPLEFT, NULL, NULL, DC_CONTACT_ID_SELF); } else { msg->text = dc_stock_system_msg(context, DC_STR_MSGDELMEMBER, contact->addr, NULL, DC_CONTACT_ID_SELF); } dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_MEMBER_REMOVED_FROM_GROUP); dc_param_set (msg->param, DC_PARAM_CMD_ARG, contact->addr); msg->id = dc_send_msg(context, chat_id, msg); context->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, msg->id); } } q3 = sqlite3_mprintf("DELETE FROM chats_contacts WHERE chat_id=%i AND contact_id=%i;", chat_id, contact_id); if (!dc_sqlite3_execute(context->sql, q3)) { goto cleanup; } context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); success = 1; cleanup: sqlite3_free(q3); dc_chat_unref(chat); dc_contact_unref(contact); dc_msg_unref(msg); return success; }
projects/deltachat-core/rust/chat.rs
pub async fn remove_contact_from_chat( context: &Context, chat_id: ChatId, contact_id: ContactId, ) -> Result<()> { ensure!( !chat_id.is_special(), "bad chat_id, can not be special chat: {}", chat_id ); ensure!( !contact_id.is_special() || contact_id == ContactId::SELF, "Cannot remove special contact" ); let mut msg = Message::default(); let chat = Chat::load_from_db(context, chat_id).await?; if chat.typ == Chattype::Group || chat.typ == Chattype::Broadcast { if !chat.is_self_in_chat(context).await? { let err_msg = format!( "Cannot remove contact {contact_id} from chat {chat_id}: self not in group." ); context.emit_event(EventType::ErrorSelfNotInGroup(err_msg.clone())); bail!("{}", err_msg); } else { let mut sync = Nosync; // We do not return an error if the contact does not exist in the database. // This allows to delete dangling references to deleted contacts // in case of the database becoming inconsistent due to a bug. if let Some(contact) = Contact::get_by_id_optional(context, contact_id).await? { if chat.typ == Chattype::Group && chat.is_promoted() { msg.viewtype = Viewtype::Text; if contact.id == ContactId::SELF { set_group_explicitly_left(context, &chat.grpid).await?; msg.text = stock_str::msg_group_left_local(context, ContactId::SELF).await; } else { msg.text = stock_str::msg_del_member_local( context, contact.get_addr(), ContactId::SELF, ) .await; } msg.param.set_cmd(SystemMessage::MemberRemovedFromGroup); msg.param.set(Param::Arg, contact.get_addr().to_lowercase()); msg.id = send_msg(context, chat_id, &mut msg).await?; } else { sync = Sync; } } // we remove the member from the chat after constructing the // to-be-send message. If between send_msg() and here the // process dies the user will have to re-do the action. It's // better than the other way round: you removed // someone from DB but no peer or device gets to know about it and // group membership is thus different on different devices. // Note also that sending a message needs all recipients // in order to correctly determine encryption so if we // removed it first, it would complicate the // check/encryption logic. remove_from_chat_contacts_table(context, chat_id, contact_id).await?; context.emit_event(EventType::ChatModified(chat_id)); if sync.into() { chat.sync_contacts(context).await.log_err(context).ok(); } } } else { bail!("Cannot remove members from non-group chats."); } Ok(()) }
async fn set_group_explicitly_left(context: &Context, grpid: &str) -> Result<()> { if !is_group_explicitly_left(context, grpid).await? { context .sql .execute("INSERT INTO leftgrps (grpid) VALUES(?);", (grpid,)) .await?; } Ok(()) } pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> { if chat_id.is_unset() { let forwards = msg.param.get(Param::PrepForwards); if let Some(forwards) = forwards { for forward in forwards.split(' ') { if let Ok(msg_id) = forward.parse::<u32>().map(MsgId::new) { if let Ok(mut msg) = Message::load_from_db(context, msg_id).await { send_msg_inner(context, chat_id, &mut msg).await?; }; } } msg.param.remove(Param::PrepForwards); msg.update_param(context).await?; } return send_msg_inner(context, chat_id, msg).await; } if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing { msg.param.remove(Param::GuaranteeE2ee); msg.param.remove(Param::ForcePlaintext); msg.update_param(context).await?; } send_msg_inner(context, chat_id, msg).await } pub(crate) async fn sync_contacts(&self, context: &Context) -> Result<()> { let addrs = context .sql .query_map( "SELECT c.addr \ FROM contacts c INNER JOIN chats_contacts cc \ ON c.id=cc.contact_id \ WHERE cc.chat_id=?", (self.id,), |row| row.get::<_, String>(0), |addrs| addrs.collect::<Result<Vec<_>, _>>().map_err(Into::into), ) .await?; self.sync(context, SyncAction::SetContacts(addrs)).await } pub fn set_cmd(&mut self, value: SystemMessage) { self.set_int(Param::Cmd, value as i32); } pub fn is_promoted(&self) -> bool { !self.is_unpromoted() } pub(crate) async fn is_self_in_chat(&self, context: &Context) -> Result<bool> { match self.typ { Chattype::Single | Chattype::Broadcast | Chattype::Mailinglist => Ok(true), Chattype::Group => is_contact_in_chat(context, self.id, ContactId::SELF).await, } } fn log_err(self, context: &Context) -> Result<T, E> { if let Err(e) = &self { let location = std::panic::Location::caller(); // We are using Anyhow's .context() and to show the inner error, too, we need the {:#}: let full = format!( "{file}:{line}: {e:#}", file = location.file(), line = location.line(), e = e ); // We can't use the warn!() macro here as the file!() and line!() macros // don't work with #[track_caller] context.emit_event(crate::EventType::Warning(full)); }; self } pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self { self.inner.insert(key, value.to_string()); self } pub fn emit_event(&self, event: EventType) { { let lock = self.debug_logging.read().expect("RwLock is poisoned"); if let Some(debug_logging) = &*lock { debug_logging.log_event(event.clone()); } } self.events.emit(Event { id: self.id, typ: event, }); } pub(crate) async fn remove_from_chat_contacts_table( context: &Context, chat_id: ChatId, contact_id: ContactId, ) -> Result<()> { context .sql .execute( "DELETE FROM chats_contacts WHERE chat_id=? AND contact_id=?", (chat_id, contact_id), ) .await?; Ok(()) } pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> { let mut chat = context .sql .query_row( "SELECT c.type, c.name, c.grpid, c.param, c.archived, c.blocked, c.locations_send_until, c.muted_until, c.protected FROM chats c WHERE c.id=?;", (chat_id,), |row| { let c = Chat { id: chat_id, typ: row.get(0)?, name: row.get::<_, String>(1)?, grpid: row.get::<_, String>(2)?, param: row.get::<_, String>(3)?.parse().unwrap_or_default(), visibility: row.get(4)?, blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(), is_sending_locations: row.get(6)?, mute_duration: row.get(7)?, protected: row.get(8)?, }; Ok(c) }, ) .await .context(format!("Failed loading chat {chat_id} from database"))?; if chat.id.is_archived_link() { chat.name = stock_str::archived_chats(context).await; } else { if chat.typ == Chattype::Single && chat.name.is_empty() { // chat.name is set to contact.display_name on changes, // however, if things went wrong somehow, we do this here explicitly. let mut chat_name = "Err [Name not found]".to_owned(); match get_chat_contacts(context, chat.id).await { Ok(contacts) => { if let Some(contact_id) = contacts.first() { if let Ok(contact) = Contact::get_by_id(context, *contact_id).await { contact.get_display_name().clone_into(&mut chat_name); } } } Err(err) => { error!( context, "Failed to load contacts for {}: {:#}.", chat.id, err ); } } chat.name = chat_name; } if chat.param.exists(Param::Selftalk) { chat.name = stock_str::saved_messages(context).await; } else if chat.param.exists(Param::Devicetalk) { chat.name = stock_str::device_messages(context).await; } } Ok(chat) } pub fn get_addr(&self) -> &str { &self.addr } pub async fn get_by_id_optional( context: &Context, contact_id: ContactId, ) -> Result<Option<Self>> { if let Some(mut contact) = context .sql .query_row_optional( "SELECT c.name, c.addr, c.origin, c.blocked, c.last_seen, c.authname, c.param, c.status, c.is_bot FROM contacts c WHERE c.id=?;", (contact_id,), |row| { let name: String = row.get(0)?; let addr: String = row.get(1)?; let origin: Origin = row.get(2)?; let blocked: Option<bool> = row.get(3)?; let last_seen: i64 = row.get(4)?; let authname: String = row.get(5)?; let param: String = row.get(6)?; let status: Option<String> = row.get(7)?; let is_bot: bool = row.get(8)?; let contact = Self { id: contact_id, name, authname, addr, blocked: blocked.unwrap_or_default(), last_seen, origin, param: param.parse().unwrap_or_default(), status: status.unwrap_or_default(), is_bot, }; Ok(contact) }, ) .await? { if contact_id == ContactId::SELF { contact.name = stock_str::self_msg(context).await; contact.authname = context .get_config(Config::Displayname) .await? .unwrap_or_default(); contact.addr = context .get_config(Config::ConfiguredAddr) .await? .unwrap_or_default(); contact.status = context .get_config(Config::Selfstatus) .await? .unwrap_or_default(); } else if contact_id == ContactId::DEVICE { contact.name = stock_str::device_messages(context).await; contact.addr = ContactId::DEVICE_ADDR.to_string(); contact.status = stock_str::device_messages_hint(context).await; } Ok(Some(contact)) } else { Ok(None) } } pub(crate) async fn msg_group_left_local(context: &Context, by_contact: ContactId) -> String { if by_contact == ContactId::SELF { translated(context, StockMessage::MsgYouLeftGroup).await } else { translated(context, StockMessage::MsgGroupLeftBy) .await .replace1(&by_contact.get_stock_name_n_addr(context).await) } } pub(crate) async fn msg_del_member_local( context: &Context, removed_member_addr: &str, by_contact: ContactId, ) -> String { let addr = removed_member_addr; let whom = &match Contact::lookup_id_by_addr(context, addr, Origin::Unknown).await { Ok(Some(contact_id)) => Contact::get_by_id(context, contact_id) .await .map(|contact| contact.get_name_n_addr()) .unwrap_or_else(|_| addr.to_string()), _ => addr.to_string(), }; if by_contact == ContactId::SELF { translated(context, StockMessage::MsgYouDelMember) .await .replace1(whom) } else { translated(context, StockMessage::MsgDelMemberBy) .await .replace1(whom) .replace2(&by_contact.get_stock_name_n_addr(context).await) } } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. } pub struct ContactId(u32); pub struct ChatId(u32); impl ContactId { /// The owner of the account. /// /// The email-address is set by `set_config` using "addr". pub const SELF: ContactId = ContactId::new(1); } pub enum Chattype { /// 1:1 chat. Single = 100, /// Group chat. Group = 120, /// Mailing list. Mailinglist = 140, /// Broadcast list. Broadcast = 160, } pub enum SystemMessage { /// Unknown type of system message. #[default] Unknown = 0, /// Group name changed. GroupNameChanged = 2, /// Group avatar changed. GroupImageChanged = 3, /// Member was added to the group. MemberAddedToGroup = 4, /// Member was removed from the group. MemberRemovedFromGroup = 5, /// Autocrypt Setup Message. AutocryptSetupMessage = 6, /// Secure-join message. SecurejoinMessage = 7, /// Location streaming is enabled. LocationStreamingEnabled = 8, /// Location-only message. LocationOnly = 9, /// Chat ephemeral message timer is changed. EphemeralTimerChanged = 10, /// "Messages are guaranteed to be end-to-end encrypted from now on." ChatProtectionEnabled = 11, /// "%1$s sent a message from another device." ChatProtectionDisabled = 12, /// Message can't be sent because of `Invalid unencrypted mail to <>` /// which is sent by chatmail servers. InvalidUnencryptedMail = 13, /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it /// to complete. SecurejoinWait = 14, /// 1:1 chats info message telling that SecureJoin is still running, but the user may already /// send messages. SecurejoinWaitTimeout = 15, /// Self-sent-message that contains only json used for multi-device-sync; /// if possible, we attach that to other messages as for locations. MultiDeviceSync = 20, /// Sync message that contains a json payload /// sent to the other webxdc instances /// These messages are not shown in the chat. WebxdcStatusUpdate = 30, /// Webxdc info added with `info` set in `send_webxdc_status_update()`. WebxdcInfoMessage = 32, /// This message contains a users iroh node address. IrohNodeAddr = 40, } pub enum EventType { /// The library-user may write an informational string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Info(String), /// Emitted when SMTP connection is established and login was successful. SmtpConnected(String), /// Emitted when IMAP connection is established and login was successful. ImapConnected(String), /// Emitted when a message was successfully sent to the SMTP server. SmtpMessageSent(String), /// Emitted when an IMAP message has been marked as deleted ImapMessageDeleted(String), /// Emitted when an IMAP message has been moved ImapMessageMoved(String), /// Emitted before going into IDLE on the Inbox folder. ImapInboxIdle, /// Emitted when an new file in the $BLOBDIR was created NewBlobFile(String), /// Emitted when an file in the $BLOBDIR was deleted DeletedBlobFile(String), /// The library-user should write a warning string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Warning(String), /// The library-user should report an error to the end-user. /// /// As most things are asynchronous, things may go wrong at any time and the user /// should not be disturbed by a dialog or so. Instead, use a bubble or so. /// /// However, for ongoing processes (eg. configure()) /// or for functions that are expected to fail (eg. dc_continue_key_transfer()) /// it might be better to delay showing these events until the function has really /// failed (returned false). It should be sufficient to report only the *last* error /// in a messasge box then. Error(String), /// An action cannot be performed because the user is not in the group. /// Reported eg. after a call to /// dc_set_chat_name(), dc_set_chat_profile_image(), /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(), /// dc_send_text_msg() or another sending function. ErrorSelfNotInGroup(String), /// Messages or chats changed. One or more messages or chats changed for various /// reasons in the database: /// - Messages sent, received or removed /// - Chats created, deleted or archived /// - A draft has been set /// MsgsChanged { /// Set if only a single chat is affected by the changes, otherwise 0. chat_id: ChatId, /// Set if only a single message is affected by the changes, otherwise 0. msg_id: MsgId, }, /// Reactions for the message changed. ReactionsChanged { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message for which reactions were changed. msg_id: MsgId, /// ID of the contact whose reaction set is changed. contact_id: ContactId, }, /// There is a fresh message. Typically, the user will show an notification /// when receiving this message. /// /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event. IncomingMsg { /// ID of the chat where the message is assigned. chat_id: ChatId, /// ID of the message. msg_id: MsgId, }, /// Downloading a bunch of messages just finished. IncomingMsgBunch, /// Messages were seen or noticed. /// chat id is always set. MsgsNoticed(ChatId), /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state(). MsgDelivered { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was successfully sent. msg_id: MsgId, }, /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_FAILED, see dc_msg_get_state(). MsgFailed { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that could not be sent. msg_id: MsgId, }, /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state(). MsgRead { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was read. msg_id: MsgId, }, /// A single message was deleted. /// /// This event means that the message will no longer appear in the messagelist. /// UI should remove the message from the messagelist /// in response to this event if the message is currently displayed. /// /// The message may have been explicitly deleted by the user or expired. /// Internally the message may have been removed from the database, /// moved to the trash chat or hidden. /// /// This event does not indicate the message /// deletion from the server. MsgDeleted { /// ID of the chat where the message was prior to deletion. /// Never 0 or trash chat. chat_id: ChatId, /// ID of the deleted message. Never 0. msg_id: MsgId, }, /// Chat changed. The name or the image of a chat group was changed or members were added or removed. /// Or the verify state of a chat has changed. /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat() /// and dc_remove_contact_from_chat(). /// /// This event does not include ephemeral timer modification, which /// is a separate event. ChatModified(ChatId), /// Chat ephemeral timer changed. ChatEphemeralTimerModified { /// Chat ID. chat_id: ChatId, /// New ephemeral timer value. timer: EphemeralTimer, }, /// Contact(s) created, renamed, blocked, deleted or changed their "recently seen" status. /// /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected. ContactsChanged(Option<ContactId>), /// Location of one or more contact has changed. /// /// @param data1 (u32) contact_id of the contact for which the location has changed. /// If the locations of several contacts have been changed, /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`. LocationChanged(Option<ContactId>), /// Inform about the configuration progress started by configure(). ConfigureProgress { /// Progress. /// /// 0=error, 1-999=progress in permille, 1000=success and done progress: usize, /// Progress comment or error, something to display to the user. comment: Option<String>, }, /// Inform about the import/export progress started by imex(). /// /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done /// @param data2 0 ImexProgress(usize), /// A file has been exported. A file has been written by imex(). /// This event may be sent multiple times by a single call to imex(). /// /// A typical purpose for a handler of this event may be to make the file public to some system /// services. /// /// @param data2 0 ImexFileWritten(PathBuf), /// Progress information of a secure-join handshake from the view of the inviter /// (Alice, the person who shows the QR code). /// /// These events are typically sent after a joiner has scanned the QR code /// generated by dc_get_securejoin_qr(). SecurejoinInviterProgress { /// ID of the contact that wants to join. contact_id: ContactId, /// Progress as: /// 300=vg-/vc-request received, typically shown as "bob@addr joins". /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as "bob@addr verified". /// 800=contact added to chat, shown as "bob@addr securely joined GROUP". Only for the verified-group-protocol. /// 1000=Protocol finished for this contact. progress: usize, }, /// Progress information of a secure-join handshake from the view of the joiner /// (Bob, the person who scans the QR code). /// The events are typically sent while dc_join_securejoin(), which /// may take some time, is executed. SecurejoinJoinerProgress { /// ID of the inviting contact. contact_id: ContactId, /// Progress as: /// 400=vg-/vc-request-with-auth sent, typically shown as "alice@addr verified, introducing myself." /// (Bob has verified alice and waits until Alice does the same for him) /// 1000=vg-member-added/vc-contact-confirm received progress: usize, }, /// The connectivity to the server changed. /// This means that you should refresh the connectivity view /// and possibly the connectivtiy HTML; see dc_get_connectivity() and /// dc_get_connectivity_html() for details. ConnectivityChanged, /// The user's avatar changed. /// Deprecated by `ConfigSynced`. SelfavatarChanged, /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For /// uniformity this is emitted on the source device too. The value isn't here, otherwise it /// would be logged which might not be good for privacy. ConfigSynced { /// Configuration key. key: Config, }, /// Webxdc status update received. WebxdcStatusUpdate { /// Message ID. msg_id: MsgId, /// Status update ID. status_update_serial: StatusUpdateSerial, }, /// Data received over an ephemeral peer channel. WebxdcRealtimeData { /// Message ID. msg_id: MsgId, /// Realtime data. data: Vec<u8>, }, /// Inform that a message containing a webxdc instance has been deleted. WebxdcInstanceDeleted { /// ID of the deleted message. msg_id: MsgId, }, /// Tells that the Background fetch was completed (or timed out). /// This event acts as a marker, when you reach this event you can be sure /// that all events emitted during the background fetch were processed. /// /// This event is only emitted by the account manager AccountsBackgroundFetchDone, /// Inform that set of chats or the order of the chats in the chatlist has changed. /// /// Sometimes this is emitted together with `UIChatlistItemChanged`. ChatlistChanged, /// Inform that a single chat list item changed and needs to be rerendered. /// If `chat_id` is set to None, then all currently visible chats need to be rerendered, and all not-visible items need to be cleared from cache if the UI has a cache. ChatlistItemChanged { /// ID of the changed chat chat_id: Option<ChatId>, }, /// Event for using in tests, e.g. as a fence between normally generated events. #[cfg(test)] Test, /// Inform than some events have been skipped due to event channel overflow. EventChannelOverflow { /// Number of events skipped. n: u64, }, } pub enum Viewtype { /// Unknown message type. #[default] Unknown = 0, /// Text message. /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text(). Text = 10, /// Image message. /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to /// `Gif` when sending the message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension(). Image = 20, /// Animated GIF message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension() /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height(). Gif = 21, /// Message containing a sticker, similar to image. /// If possible, the ui should display the image without borders in a transparent way. /// A click on a sticker will offer to install the sticker set in some future. Sticker = 23, /// Message containing an Audio file. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration(). Audio = 40, /// A voice message that was directly recorded by the user. /// For all other audio messages, the type #DC_MSG_AUDIO should be used. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration() Voice = 41, /// Video messages. /// File, width, height and durarion /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration() /// and retrieved via /// dc_msg_get_file(), dc_msg_get_width(), /// dc_msg_get_height(), dc_msg_get_duration(). Video = 50, /// Message containing any file, eg. a PDF. /// The file is set via dc_msg_set_file() /// and retrieved via dc_msg_get_file(). File = 60, /// Message is an invitation to a videochat. VideochatInvitation = 70, /// Message is an webxdc instance. Webxdc = 80, /// Message containing shared contacts represented as a vCard (virtual contact file) /// with email addresses and possibly other fields. /// Use `parse_vcard()` to retrieve them. Vcard = 90, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__133.txt
pub unsafe extern "C" fn dc_remove_contact_from_chat( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut contact_id: uint32_t, ) -> libc::c_int { let mut success: libc::c_int = 0 as libc::c_int; let mut contact: *mut dc_contact_t = dc_get_contact(context, contact_id); let mut chat: *mut dc_chat_t = dc_chat_new(context); let mut msg: *mut dc_msg_t = dc_msg_new_untyped(context); let mut q3: *mut libc::c_char = 0 as *mut libc::c_char; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || chat_id <= 9 as libc::c_int as libc::c_uint || contact_id <= 9 as libc::c_int as libc::c_uint && contact_id != 1 as libc::c_int as libc::c_uint) { if !(0 as libc::c_int == real_group_exists(context, chat_id) || 0 as libc::c_int == dc_chat_load_from_db(chat, chat_id)) { if !(dc_is_contact_in_chat(context, chat_id, 1 as libc::c_int as uint32_t) == 1 as libc::c_int) { dc_log_event( context, 410 as libc::c_int, 0 as libc::c_int, b"Cannot remove contact from chat; self not in group.\0" as *const u8 as *const libc::c_char, ); } else { if !contact.is_null() { if dc_param_get_int((*chat).param, 'U' as i32, 0 as libc::c_int) == 0 as libc::c_int { (*msg).type_0 = 10 as libc::c_int; if (*contact).id == 1 as libc::c_int as libc::c_uint { dc_set_group_explicitly_left(context, (*chat).grpid); (*msg) .text = dc_stock_system_msg( context, 19 as libc::c_int, 0 as *const libc::c_char, 0 as *const libc::c_char, 1 as libc::c_int as uint32_t, ); } else { (*msg) .text = dc_stock_system_msg( context, 18 as libc::c_int, (*contact).addr, 0 as *const libc::c_char, 1 as libc::c_int as uint32_t, ); } dc_param_set_int((*msg).param, 'S' as i32, 5 as libc::c_int); dc_param_set((*msg).param, 'E' as i32, (*contact).addr); (*msg).id = dc_send_msg(context, chat_id, msg); ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, chat_id as uintptr_t, (*msg).id as uintptr_t, ); } } q3 = sqlite3_mprintf( b"DELETE FROM chats_contacts WHERE chat_id=%i AND contact_id=%i;\0" as *const u8 as *const libc::c_char, chat_id, contact_id, ); if !(dc_sqlite3_execute((*context).sql, q3) == 0) { ((*context).cb) .expect( "non-null function pointer", )( context, 2020 as libc::c_int, chat_id as uintptr_t, 0 as libc::c_int as uintptr_t, ); success = 1 as libc::c_int; } } } } sqlite3_free(q3 as *mut libc::c_void); dc_chat_unref(chat); dc_contact_unref(contact); dc_msg_unref(msg); return success; }
projects/deltachat-core/c/dc_chat.c
int dc_chat_is_self_talk(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return dc_param_exists(chat->param, DC_PARAM_SELFTALK); }
projects/deltachat-core/rust/chat.rs
pub fn is_self_talk(&self) -> bool { self.param.exists(Param::Selftalk) }
pub fn exists(&self, key: Param) -> bool { self.inner.contains_key(&key) } pub struct Chat { /// Database ID. pub id: ChatId, /// Chat type, e.g. 1:1 chat, group chat, mailing list. pub typ: Chattype, /// Chat name. pub name: String, /// Whether the chat is archived or pinned. pub visibility: ChatVisibility, /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and /// ad-hoc groups. pub grpid: String, /// Whether the chat is blocked, unblocked or a contact request. pub blocked: Blocked, /// Additional chat parameters stored in the database. pub param: Params, /// If location streaming is enabled in the chat. is_sending_locations: bool, /// Duration of the chat being muted. pub mute_duration: MuteDuration, /// If the chat is protected (verified). pub(crate) protected: ProtectionStatus, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. } pub struct ChatId(u32);
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__61.txt
pub unsafe extern "C" fn dc_chat_is_self_talk( mut chat: *const dc_chat_t, ) -> libc::c_int { if chat.is_null() || (*chat).magic != 0xc4a7c4a7 as libc::c_uint { return 0 as libc::c_int; } return dc_param_exists((*chat).param, 'K' as i32); }
projects/deltachat-core/c/dc_msg.c
void dc_msg_set_file(dc_msg_t* msg, const char* file, const char* filemime) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return; } dc_param_set(msg->param, DC_PARAM_FILE, file); dc_param_set_optional(msg->param, DC_PARAM_MIMETYPE, filemime); }
projects/deltachat-core/rust/message.rs
pub fn set_file(&mut self, file: impl ToString, filemime: Option<&str>) { if let Some(name) = Path::new(&file.to_string()).file_name() { if let Some(name) = name.to_str() { self.param.set(Param::Filename, name); } } self.param.set(Param::File, file); self.param.set_optional(Param::MimeType, filemime); }
pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self { self.inner.insert(key, value.to_string()); self } pub fn set_optional(&mut self, key: Param, value: Option<impl ToString>) -> &mut Self { if let Some(value) = value { self.set(key, value) } else { self.remove(key) } } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__68.txt
pub unsafe extern "C" fn dc_msg_set_file( mut msg: *mut dc_msg_t, mut file: *const libc::c_char, mut filemime: *const libc::c_char, ) { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return; } dc_param_set((*msg).param, 'f' as i32, file); dc_param_set((*msg).param, 'm' as i32, filemime); }
projects/deltachat-core/c/dc_chat.c
int dc_is_contact_in_chat(dc_context_t* context, uint32_t chat_id, uint32_t contact_id) { /* this function works for group and for normal chats, however, it is more useful for group chats. DC_CONTACT_ID_SELF may be used to check, if the user itself is in a group chat (DC_CONTACT_ID_SELF is not added to normal chats) */ int ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM chats_contacts WHERE chat_id=? AND contact_id=?;"); sqlite3_bind_int(stmt, 1, chat_id); sqlite3_bind_int(stmt, 2, contact_id); ret = sqlite3_step(stmt); cleanup: sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/rust/chat.rs
pub async fn is_contact_in_chat( context: &Context, chat_id: ChatId, contact_id: ContactId, ) -> Result<bool> { // this function works for group and for normal chats, however, it is more useful // for group chats. // ContactId::SELF may be used to check, if the user itself is in a group // chat (ContactId::SELF is not added to normal chats) let exists = context .sql .exists( "SELECT COUNT(*) FROM chats_contacts WHERE chat_id=? AND contact_id=?;", (chat_id, contact_id), ) .await?; Ok(exists) }
pub async fn exists(&self, sql: &str, params: impl rusqlite::Params + Send) -> Result<bool> { let count = self.count(sql, params).await?; Ok(count > 0) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub struct ContactId(u32); pub struct ChatId(u32);
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__103.txt
pub unsafe extern "C" fn dc_is_contact_in_chat( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut contact_id: uint32_t, ) -> libc::c_int { let mut ret: libc::c_int = 0 as libc::c_int; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint) { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT contact_id FROM chats_contacts WHERE chat_id=? AND contact_id=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, chat_id as libc::c_int); sqlite3_bind_int(stmt, 2 as libc::c_int, contact_id as libc::c_int); ret = if sqlite3_step(stmt) == 100 as libc::c_int { 1 as libc::c_int } else { 0 as libc::c_int }; } sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/c/dc_context.c
* The returned string must be free()'d. */ char* dc_get_blobdir(const dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return dc_strdup(NULL); } return dc_strdup(context->blobdir); }
projects/deltachat-core/rust/context.rs
pub fn get_blobdir(&self) -> &Path { self.blobdir.as_path() }
pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, }
use std::collections::{BTreeMap, HashMap}; use std::ffi::OsString; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use pgp::SignedPublicKey; use ratelimit::Ratelimit; use tokio::sync::{Mutex, Notify, OnceCell, RwLock}; use crate::aheader::EncryptPreference; use crate::chat::{get_chat_cnt, ChatId, ProtectionStatus}; use crate::chatlist_events; 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}; 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_public_key, load_self_secret_key, DcKey as _}; use crate::login_param::LoginParam; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::param::{Param, Params}; use crate::peer_channels::Iroh; use crate::peerstate::Peerstate; use crate::push::PushSubscriber; use crate::quota::QuotaInfo; use crate::scheduler::{convert_folder_meaning, SchedulerState}; 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 anyhow::Context as _; use strum::IntoEnumIterator; use tempfile::tempdir; use super::*; use crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration}; use crate::chatlist::Chatlist; use crate::constants::Chattype; use crate::mimeparser::SystemMessage; use crate::receive_imf::receive_imf; use crate::test_utils::{get_chat_msg, TestContext}; use crate::tools::{create_outgoing_rfc724_mid, SystemTime};
projects__deltachat-core__rust__context__.rs__function__29.txt
pub unsafe extern "C" fn dc_get_blobdir( mut context: *const dc_context_t, ) -> *mut libc::c_char { if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint { return dc_strdup(0 as *const libc::c_char); } return dc_strdup((*context).blobdir); }
projects/deltachat-core/c/dc_e2ee.c
static int has_decrypted_pgp_armor(const char* str__, int str_bytes) { const unsigned char* str_end = (const unsigned char*)str__+str_bytes; const unsigned char* p=(const unsigned char*)str__; while (p < str_end) { if (*p > ' ') { break; } p++; str_bytes--; } if (str_bytes>26 && strncmp((const char*)p, "-----BEGIN PGP MESSAGE-----", 27)==0) { return 1; } return 0; }
projects/deltachat-core/rust/decrypt.rs
fn has_decrypted_pgp_armor(input: &[u8]) -> bool { if let Some(index) = input.iter().position(|b| *b > b' ') { if input.len() - index > 26 { let start = index; let end = start + 27; return &input[start..end] == b"-----BEGIN PGP MESSAGE-----"; } } false }
use std::collections::HashSet; use std::str::FromStr; use anyhow::Result; use deltachat_contact_tools::addr_cmp; use mailparse::ParsedMail; use crate::aheader::Aheader; use crate::authres::handle_authres; use crate::authres::{self, DkimResults}; use crate::context::Context; use crate::headerdef::{HeaderDef, HeaderDefMap}; use crate::key::{DcKey, Fingerprint, SignedPublicKey, SignedSecretKey}; use crate::peerstate::Peerstate; use crate::pgp; use super::*; use crate::receive_imf::receive_imf; use crate::test_utils::TestContext;
projects__deltachat-core__rust__decrypt__.rs__function__8.txt
unsafe extern "C" fn has_decrypted_pgp_armor( mut str__: *const libc::c_char, mut str_bytes: libc::c_int, ) -> libc::c_int { let mut str_end: *const libc::c_uchar = (str__ as *const libc::c_uchar) .offset(str_bytes as isize); let mut p: *const libc::c_uchar = str__ as *const libc::c_uchar; while p < str_end { if *p as libc::c_int > ' ' as i32 { break; } p = p.offset(1); p; str_bytes -= 1; str_bytes; } if str_bytes > 27 as libc::c_int && strncmp( p as *const libc::c_char, b"-----BEGIN PGP MESSAGE-----\0" as *const u8 as *const libc::c_char, 27 as libc::c_int as libc::c_ulong, ) == 0 as libc::c_int { return 1 as libc::c_int; } return 0 as libc::c_int; }
projects/deltachat-core/c/dc_tools.c
int dc_write_file(dc_context_t* context, const char* pathNfilename, const void* buf, size_t buf_bytes) { int success = 0; char* pathNfilename_abs = NULL; if ((pathNfilename_abs=dc_get_abs_path(context, pathNfilename))==NULL) { goto cleanup; } FILE* f = fopen(pathNfilename_abs, "wb"); if (f) { if (fwrite(buf, 1, buf_bytes, f)==buf_bytes) { success = 1; } else { dc_log_warning(context, 0, "Cannot write %lu bytes to \"%s\".", (unsigned long)buf_bytes, pathNfilename); } fclose(f); } else { dc_log_warning(context, 0, "Cannot open \"%s\" for writing.", pathNfilename); } cleanup: free(pathNfilename_abs); return success; }
projects/deltachat-core/rust/tools.rs
pub(crate) async fn write_file( context: &Context, path: impl AsRef<Path>, buf: &[u8], ) -> Result<(), io::Error> { let path_abs = get_abs_path(context, path.as_ref()); fs::write(&path_abs, buf).await.map_err(|err| { warn!( context, "Cannot write {} bytes to \"{}\": {}", buf.len(), path.as_ref().display(), err ); err }) }
pub(crate) fn get_abs_path(context: &Context, path: &Path) -> PathBuf { if let Ok(p) = path.strip_prefix("$BLOBDIR") { context.get_blobdir().join(p) } else { path.into() } } pub struct Context { pub(crate) inner: Arc<InnerContext>, }
use std::borrow::Cow; use std::io::{Cursor, Write}; use std::mem; use std::path::{Path, PathBuf}; use std::str::from_utf8; use std::time::Duration; use std::time::SystemTime as Time; use std::time::SystemTime; use anyhow::{bail, Context as _, Result}; use base64::Engine as _; use chrono::{Local, NaiveDateTime, NaiveTime, TimeZone}; use deltachat_contact_tools::{strip_rtlo_characters, EmailAddress}; use deltachat_time::SystemTimeTools as SystemTime; use futures::{StreamExt, TryStreamExt}; use mailparse::dateparse; use mailparse::headers::Headers; use mailparse::MailHeaderMap; use rand::{thread_rng, Rng}; use tokio::{fs, io}; use url::Url; use crate::chat::{add_device_msg, add_device_msg_with_importance}; use crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS}; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, Viewtype}; use crate::stock_str; use chrono::NaiveDate; use proptest::prelude::*; use super::*; use crate::chatlist::Chatlist; use crate::{chat, test_utils}; use crate::{receive_imf::receive_imf, test_utils::TestContext}; use super::*;
projects__deltachat-core__rust__tools__.rs__function__23.txt
pub unsafe extern "C" fn dc_write_file( mut context: *mut dc_context_t, mut pathNfilename: *const libc::c_char, mut buf: *const libc::c_void, mut buf_bytes: size_t, ) -> libc::c_int { let mut f: *mut FILE = 0 as *mut FILE; let mut success: libc::c_int = 0 as libc::c_int; let mut pathNfilename_abs: *mut libc::c_char = 0 as *mut libc::c_char; pathNfilename_abs = dc_get_abs_path(context, pathNfilename); if !pathNfilename_abs.is_null() { f = fopen(pathNfilename_abs, b"wb\0" as *const u8 as *const libc::c_char); if !f.is_null() { if fwrite(buf, 1 as libc::c_int as libc::c_ulong, buf_bytes, f) == buf_bytes { success = 1 as libc::c_int; } else { dc_log_warning( context, 0 as libc::c_int, b"Cannot write %lu bytes to \"%s\".\0" as *const u8 as *const libc::c_char, buf_bytes, pathNfilename, ); } fclose(f); } else { dc_log_warning( context, 0 as libc::c_int, b"Cannot open \"%s\" for writing.\0" as *const u8 as *const libc::c_char, pathNfilename, ); } } free(pathNfilename_abs as *mut libc::c_void); return success; }
projects/deltachat-core/c/dc_msg.c
int dc_msg_get_height(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return dc_param_get_int(msg->param, DC_PARAM_HEIGHT, 0); }
projects/deltachat-core/rust/message.rs
pub fn get_height(&self) -> i32 { self.param.get_int(Param::Height).unwrap_or_default() }
pub fn get_int(&self, key: Param) -> Option<i32> { self.get(key).and_then(|s| s.parse().ok()) } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__44.txt
pub unsafe extern "C" fn dc_msg_get_height(mut msg: *const dc_msg_t) -> libc::c_int { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return 0 as libc::c_int; } return dc_param_get_int((*msg).param, 'h' as i32, 0 as libc::c_int); }
projects/deltachat-core/c/dc_chat.c
uint32_t dc_chat_get_id(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return chat->id; }
projects/deltachat-core/rust/chat.rs
pub fn get_id(&self) -> ChatId { self.id }
pub struct Chat { /// Database ID. pub id: ChatId, /// Chat type, e.g. 1:1 chat, group chat, mailing list. pub typ: Chattype, /// Chat name. pub name: String, /// Whether the chat is archived or pinned. pub visibility: ChatVisibility, /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and /// ad-hoc groups. pub grpid: String, /// Whether the chat is blocked, unblocked or a contact request. pub blocked: Blocked, /// Additional chat parameters stored in the database. pub param: Params, /// If location streaming is enabled in the chat. is_sending_locations: bool, /// Duration of the chat being muted. pub mute_duration: MuteDuration, /// If the chat is protected (verified). pub(crate) protected: ProtectionStatus, } pub struct ChatId(u32);
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__69.txt
pub unsafe extern "C" fn dc_chat_get_id(mut chat: *const dc_chat_t) -> uint32_t { if chat.is_null() || (*chat).magic != 0xc4a7c4a7 as libc::c_uint { return 0 as libc::c_int as uint32_t; } return (*chat).id; }
projects/deltachat-core/c/dc_msg.c
void dc_msg_set_text(dc_msg_t* msg, const char* text) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return; } free(msg->text); msg->text = dc_strdup(text); }
projects/deltachat-core/rust/message.rs
pub fn set_text(&mut self, text: String) { self.text = text; }
pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__66.txt
pub unsafe extern "C" fn dc_msg_set_text( mut msg: *mut dc_msg_t, mut text: *const libc::c_char, ) { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return; } free((*msg).text as *mut libc::c_void); (*msg).text = dc_strdup(text); }
projects/deltachat-core/c/dc_chat.c
uint32_t dc_get_chat_id_by_grpid(dc_context_t* context, const char* grpid, int* ret_blocked, int* ret_verified) { uint32_t chat_id = 0; sqlite3_stmt* stmt = NULL; if(ret_blocked) { *ret_blocked = 0; } if(ret_verified) { *ret_verified = 0; } if (context==NULL || grpid==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT id, blocked, protected FROM chats WHERE grpid=?;"); sqlite3_bind_text (stmt, 1, grpid, -1, SQLITE_STATIC); if (sqlite3_step(stmt)==SQLITE_ROW) { chat_id = sqlite3_column_int(stmt, 0); if(ret_blocked) { *ret_blocked = sqlite3_column_int(stmt, 1); } if(ret_verified) { *ret_verified = (sqlite3_column_int(stmt, 2)==DC_CHAT_PROTECTIONSTATUS_PROTECTED); } } cleanup: sqlite3_finalize(stmt); return chat_id; }
projects/deltachat-core/rust/chat.rs
pub(crate) async fn get_chat_id_by_grpid( context: &Context, grpid: &str, ) -> Result<Option<(ChatId, bool, Blocked)>> { context .sql .query_row_optional( "SELECT id, blocked, protected FROM chats WHERE grpid=?;", (grpid,), |row| { let chat_id = row.get::<_, ChatId>(0)?; let b = row.get::<_, Option<Blocked>>(1)?.unwrap_or_default(); let p = row .get::<_, Option<ProtectionStatus>>(2)? .unwrap_or_default(); Ok((chat_id, p == ProtectionStatus::Protected, b)) }, ) .await }
pub async fn query_row_optional<T, F>( &self, sql: &str, params: impl rusqlite::Params + Send, f: F, ) -> Result<Option<T>> where F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result<T>, T: Send + 'static, { self.call(move |conn| match conn.query_row(sql.as_ref(), params, f) { Ok(res) => Ok(Some(res)), Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), Err(rusqlite::Error::InvalidColumnType(_, _, rusqlite::types::Type::Null)) => Ok(None), Err(err) => Err(err.into()), }) .await } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct ChatId(u32); pub enum Blocked { #[default] Not = 0, Yes = 1, Request = 2, } pub enum ProtectionStatus { /// Chat is not protected. #[default] Unprotected = 0, /// Chat is protected. /// /// All members of the chat must be verified. Protected = 1, /// The chat was protected, but now a new message came in /// which was not encrypted / signed correctly. /// The user has to confirm that this is OK. /// /// We only do this in 1:1 chats; in group chats, the chat just /// stays protected. ProtectionBroken = 3, // `2` was never used as a value. } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__142.txt
pub unsafe extern "C" fn dc_get_chat_id_by_grpid( mut context: *mut dc_context_t, mut grpid: *const libc::c_char, mut ret_blocked: *mut libc::c_int, mut ret_verified: *mut libc::c_int, ) -> uint32_t { let mut chat_id: uint32_t = 0 as libc::c_int as uint32_t; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !ret_blocked.is_null() { *ret_blocked = 0 as libc::c_int; } if !ret_verified.is_null() { *ret_verified = 0 as libc::c_int; } if !(context.is_null() || grpid.is_null()) { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT id, blocked, type FROM chats WHERE grpid=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_text(stmt, 1 as libc::c_int, grpid, -(1 as libc::c_int), None); if sqlite3_step(stmt) == 100 as libc::c_int { chat_id = sqlite3_column_int(stmt, 0 as libc::c_int) as uint32_t; if !ret_blocked.is_null() { *ret_blocked = sqlite3_column_int(stmt, 1 as libc::c_int); } if !ret_verified.is_null() { *ret_verified = (sqlite3_column_int(stmt, 2 as libc::c_int) == 130 as libc::c_int) as libc::c_int; } } } sqlite3_finalize(stmt); return chat_id; }
projects/deltachat-core/c/dc_strencode.c
int dc_needs_ext_header(const char* to_check) { if (to_check) { while (*to_check) { if (!isalnum(*to_check) && *to_check!='-' && *to_check!='_' && *to_check!='.' && *to_check!='~' && *to_check!='%') { return 1; } to_check++; } } return 0; }
projects/deltachat-core/rust/mimefactory.rs
fn needs_encoding(to_check: &str) -> bool { !to_check.chars().all(|c| { c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' || c == '%' }) }
use deltachat_contact_tools::ContactAddress; use mailparse::{addrparse_header, MailHeaderMap}; use std::str; use super::*; use crate::chat::{ add_contact_to_chat, create_group_chat, remove_contact_from_chat, send_text_msg, ChatId, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::constants; use crate::contact::Origin; use crate::mimeparser::MimeMessage; use crate::receive_imf::receive_imf; use crate::test_utils::{get_chat_msg, TestContext, TestContextManager};
projects__deltachat-core__rust__mimefactory__.rs__function__26.txt
pub unsafe extern "C" fn dc_needs_ext_header( mut to_check: *const libc::c_char, ) -> libc::c_int { if !to_check.is_null() { while *to_check != 0 { if *(*__ctype_b_loc()).offset(*to_check as libc::c_int as isize) as libc::c_int & _ISalnum as libc::c_int as libc::c_ushort as libc::c_int == 0 && *to_check as libc::c_int != '-' as i32 && *to_check as libc::c_int != '_' as i32 && *to_check as libc::c_int != '.' as i32 && *to_check as libc::c_int != '~' as i32 { return 1 as libc::c_int; } to_check = to_check.offset(1); to_check; } } return 0 as libc::c_int; }
projects/deltachat-core/c/dc_msg.c
void dc_set_msg_failed(dc_context_t* context, uint32_t msg_id, const char* error) { dc_msg_t* msg = dc_msg_new_untyped(context); sqlite3_stmt* stmt = NULL; if (!dc_msg_load_from_db(msg, context, msg_id)) { goto cleanup; } if (DC_STATE_OUT_PREPARING==msg->state || DC_STATE_OUT_PENDING ==msg->state || DC_STATE_OUT_DELIVERED==msg->state) { msg->state = DC_STATE_OUT_FAILED; } if (error) { dc_param_set(msg->param, DC_PARAM_ERROR, error); dc_log_error(context, 0, "%s", error); } stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET state=?, param=? WHERE id=?;"); sqlite3_bind_int (stmt, 1, msg->state); sqlite3_bind_text(stmt, 2, msg->param->packed, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 3, msg_id); sqlite3_step(stmt); context->cb(context, DC_EVENT_MSG_FAILED, msg->chat_id, msg_id); cleanup: sqlite3_finalize(stmt); dc_msg_unref(msg); }
projects/deltachat-core/rust/message.rs
pub(crate) async fn set_msg_failed( context: &Context, msg: &mut Message, error: &str, ) -> Result<()> { if msg.state.can_fail() { msg.state = MessageState::OutFailed; warn!(context, "{} failed: {}", msg.id, error); } else { warn!( context, "{} seems to have failed ({}), but state is {}", msg.id, error, msg.state ) } msg.error = Some(error.to_string()); context .sql .execute( "UPDATE msgs SET state=?, error=? WHERE id=?;", (msg.state, error, msg.id), ) .await?; context.emit_event(EventType::MsgFailed { chat_id: msg.chat_id, msg_id: msg.id, }); chatlist_events::emit_chatlist_item_changed(context, msg.chat_id); Ok(()) }
pub fn can_fail(self) -> bool { use MessageState::*; matches!( self, OutPreparing | OutPending | OutDelivered | OutMdnRcvd // OutMdnRcvd can still fail because it could be a group message and only some recipients failed. ) } macro_rules! warn { ($ctx:expr, $msg:expr) => { warn!($ctx, $msg,) }; ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{ let formatted = format!($msg, $($args),*); let full = format!("{file}:{line}: {msg}", file = file!(), line = line!(), msg = &formatted); $ctx.emit_event($crate::EventType::Warning(full)); }}; } pub fn emit_event(&self, event: EventType) { { let lock = self.debug_logging.read().expect("RwLock is poisoned"); if let Some(debug_logging) = &*lock { debug_logging.log_event(event.clone()); } } self.events.emit(Event { id: self.id, typ: event, }); } pub(crate) fn emit_chatlist_item_changed(context: &Context, chat_id: ChatId) { context.emit_event(EventType::ChatlistItemChanged { chat_id: Some(chat_id), }); } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum MessageState { /// Undefined message state. #[default] Undefined = 0, /// Incoming *fresh* message. Fresh messages are neither noticed /// nor seen and are typically shown in notifications. InFresh = 10, /// Incoming *noticed* message. E.g. chat opened but message not /// yet read - noticed messages are not counted as unread but did /// not marked as read nor resulted in MDNs. InNoticed = 13, /// Incoming message, really *seen* by the user. Marked as read on /// IMAP and MDN may be sent. InSeen = 16, /// For files which need time to be prepared before they can be /// sent, the message enters this state before /// OutPending. OutPreparing = 18, /// Message saved as draft. OutDraft = 19, /// The user has pressed the "send" button but the message is not /// yet sent and is pending in some way. Maybe we're offline (no /// checkmark). OutPending = 20, /// *Unrecoverable* error (*recoverable* errors result in pending /// messages). OutFailed = 24, /// Outgoing message successfully delivered to server (one /// checkmark). Note, that already delivered messages may get into /// the OutFailed state if we get such a hint from the server. OutDelivered = 26, /// Outgoing message read by the recipient (two checkmarks; this /// requires goodwill on the receiver's side) OutMdnRcvd = 28, } pub enum EventType { /// The library-user may write an informational string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Info(String), /// Emitted when SMTP connection is established and login was successful. SmtpConnected(String), /// Emitted when IMAP connection is established and login was successful. ImapConnected(String), /// Emitted when a message was successfully sent to the SMTP server. SmtpMessageSent(String), /// Emitted when an IMAP message has been marked as deleted ImapMessageDeleted(String), /// Emitted when an IMAP message has been moved ImapMessageMoved(String), /// Emitted before going into IDLE on the Inbox folder. ImapInboxIdle, /// Emitted when an new file in the $BLOBDIR was created NewBlobFile(String), /// Emitted when an file in the $BLOBDIR was deleted DeletedBlobFile(String), /// The library-user should write a warning string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Warning(String), /// The library-user should report an error to the end-user. /// /// As most things are asynchronous, things may go wrong at any time and the user /// should not be disturbed by a dialog or so. Instead, use a bubble or so. /// /// However, for ongoing processes (eg. configure()) /// or for functions that are expected to fail (eg. dc_continue_key_transfer()) /// it might be better to delay showing these events until the function has really /// failed (returned false). It should be sufficient to report only the *last* error /// in a messasge box then. Error(String), /// An action cannot be performed because the user is not in the group. /// Reported eg. after a call to /// dc_set_chat_name(), dc_set_chat_profile_image(), /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(), /// dc_send_text_msg() or another sending function. ErrorSelfNotInGroup(String), /// Messages or chats changed. One or more messages or chats changed for various /// reasons in the database: /// - Messages sent, received or removed /// - Chats created, deleted or archived /// - A draft has been set /// MsgsChanged { /// Set if only a single chat is affected by the changes, otherwise 0. chat_id: ChatId, /// Set if only a single message is affected by the changes, otherwise 0. msg_id: MsgId, }, /// Reactions for the message changed. ReactionsChanged { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message for which reactions were changed. msg_id: MsgId, /// ID of the contact whose reaction set is changed. contact_id: ContactId, }, /// There is a fresh message. Typically, the user will show an notification /// when receiving this message. /// /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event. IncomingMsg { /// ID of the chat where the message is assigned. chat_id: ChatId, /// ID of the message. msg_id: MsgId, }, /// Downloading a bunch of messages just finished. IncomingMsgBunch, /// Messages were seen or noticed. /// chat id is always set. MsgsNoticed(ChatId), /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state(). MsgDelivered { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was successfully sent. msg_id: MsgId, }, /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_FAILED, see dc_msg_get_state(). MsgFailed { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that could not be sent. msg_id: MsgId, }, /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state(). MsgRead { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was read. msg_id: MsgId, }, /// A single message was deleted. /// /// This event means that the message will no longer appear in the messagelist. /// UI should remove the message from the messagelist /// in response to this event if the message is currently displayed. /// /// The message may have been explicitly deleted by the user or expired. /// Internally the message may have been removed from the database, /// moved to the trash chat or hidden. /// /// This event does not indicate the message /// deletion from the server. MsgDeleted { /// ID of the chat where the message was prior to deletion. /// Never 0 or trash chat. chat_id: ChatId, /// ID of the deleted message. Never 0. msg_id: MsgId, }, /// Chat changed. The name or the image of a chat group was changed or members were added or removed. /// Or the verify state of a chat has changed. /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat() /// and dc_remove_contact_from_chat(). /// /// This event does not include ephemeral timer modification, which /// is a separate event. ChatModified(ChatId), /// Chat ephemeral timer changed. ChatEphemeralTimerModified { /// Chat ID. chat_id: ChatId, /// New ephemeral timer value. timer: EphemeralTimer, }, /// Contact(s) created, renamed, blocked, deleted or changed their "recently seen" status. /// /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected. ContactsChanged(Option<ContactId>), /// Location of one or more contact has changed. /// /// @param data1 (u32) contact_id of the contact for which the location has changed. /// If the locations of several contacts have been changed, /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`. LocationChanged(Option<ContactId>), /// Inform about the configuration progress started by configure(). ConfigureProgress { /// Progress. /// /// 0=error, 1-999=progress in permille, 1000=success and done progress: usize, /// Progress comment or error, something to display to the user. comment: Option<String>, }, /// Inform about the import/export progress started by imex(). /// /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done /// @param data2 0 ImexProgress(usize), /// A file has been exported. A file has been written by imex(). /// This event may be sent multiple times by a single call to imex(). /// /// A typical purpose for a handler of this event may be to make the file public to some system /// services. /// /// @param data2 0 ImexFileWritten(PathBuf), /// Progress information of a secure-join handshake from the view of the inviter /// (Alice, the person who shows the QR code). /// /// These events are typically sent after a joiner has scanned the QR code /// generated by dc_get_securejoin_qr(). SecurejoinInviterProgress { /// ID of the contact that wants to join. contact_id: ContactId, /// Progress as: /// 300=vg-/vc-request received, typically shown as "bob@addr joins". /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as "bob@addr verified". /// 800=contact added to chat, shown as "bob@addr securely joined GROUP". Only for the verified-group-protocol. /// 1000=Protocol finished for this contact. progress: usize, }, /// Progress information of a secure-join handshake from the view of the joiner /// (Bob, the person who scans the QR code). /// The events are typically sent while dc_join_securejoin(), which /// may take some time, is executed. SecurejoinJoinerProgress { /// ID of the inviting contact. contact_id: ContactId, /// Progress as: /// 400=vg-/vc-request-with-auth sent, typically shown as "alice@addr verified, introducing myself." /// (Bob has verified alice and waits until Alice does the same for him) /// 1000=vg-member-added/vc-contact-confirm received progress: usize, }, /// The connectivity to the server changed. /// This means that you should refresh the connectivity view /// and possibly the connectivtiy HTML; see dc_get_connectivity() and /// dc_get_connectivity_html() for details. ConnectivityChanged, /// The user's avatar changed. /// Deprecated by `ConfigSynced`. SelfavatarChanged, /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For /// uniformity this is emitted on the source device too. The value isn't here, otherwise it /// would be logged which might not be good for privacy. ConfigSynced { /// Configuration key. key: Config, }, /// Webxdc status update received. WebxdcStatusUpdate { /// Message ID. msg_id: MsgId, /// Status update ID. status_update_serial: StatusUpdateSerial, }, /// Data received over an ephemeral peer channel. WebxdcRealtimeData { /// Message ID. msg_id: MsgId, /// Realtime data. data: Vec<u8>, }, /// Inform that a message containing a webxdc instance has been deleted. WebxdcInstanceDeleted { /// ID of the deleted message. msg_id: MsgId, }, /// Tells that the Background fetch was completed (or timed out). /// This event acts as a marker, when you reach this event you can be sure /// that all events emitted during the background fetch were processed. /// /// This event is only emitted by the account manager AccountsBackgroundFetchDone, /// Inform that set of chats or the order of the chats in the chatlist has changed. /// /// Sometimes this is emitted together with `UIChatlistItemChanged`. ChatlistChanged, /// Inform that a single chat list item changed and needs to be rerendered. /// If `chat_id` is set to None, then all currently visible chats need to be rerendered, and all not-visible items need to be cleared from cache if the UI has a cache. ChatlistItemChanged { /// ID of the changed chat chat_id: Option<ChatId>, }, /// Event for using in tests, e.g. as a fence between normally generated events. #[cfg(test)] Test, /// Inform than some events have been skipped due to event channel overflow. EventChannelOverflow { /// Number of events skipped. n: u64, }, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__92.txt
pub unsafe extern "C" fn dc_set_msg_failed( mut context: *mut dc_context_t, mut msg_id: uint32_t, mut error: *const libc::c_char, ) { let mut msg: *mut dc_msg_t = dc_msg_new_untyped(context); let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(dc_msg_load_from_db(msg, context, msg_id) == 0) { if 18 as libc::c_int == (*msg).state || 20 as libc::c_int == (*msg).state || 26 as libc::c_int == (*msg).state { (*msg).state = 24 as libc::c_int; } if !error.is_null() { dc_param_set((*msg).param, 'L' as i32, error); dc_log_error( context, 0 as libc::c_int, b"%s\0" as *const u8 as *const libc::c_char, error, ); } stmt = dc_sqlite3_prepare( (*context).sql, b"UPDATE msgs SET state=?, param=? WHERE id=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, (*msg).state); sqlite3_bind_text( stmt, 2 as libc::c_int, (*(*msg).param).packed, -(1 as libc::c_int), None, ); sqlite3_bind_int(stmt, 3 as libc::c_int, msg_id as libc::c_int); sqlite3_step(stmt); ((*context).cb) .expect( "non-null function pointer", )( context, 2012 as libc::c_int, (*msg).chat_id as uintptr_t, msg_id as uintptr_t, ); } sqlite3_finalize(stmt); dc_msg_unref(msg); }
projects/deltachat-core/c/dc_chat.c
* using dc_set_chat_profile_image(). * For normal chats, this is the image set by each remote user on their own * using dc_set_config(context, "selfavatar", image). * * @memberof dc_chat_t * @param chat The chat object. * @return Path and file if the profile image, if any. * NULL otherwise. * Must be free()'d after usage. */ char* dc_chat_get_profile_image(const dc_chat_t* chat) { char* image_rel = NULL; char* image_abs = NULL; dc_array_t* contacts = NULL; dc_contact_t* contact = NULL; if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { goto cleanup; } image_rel = dc_param_get(chat->param, DC_PARAM_PROFILE_IMAGE, NULL); if (image_rel && image_rel[0]) { image_abs = dc_get_abs_path(chat->context, image_rel); } else if (chat-id == DC_CHAT_ID_ARCHIVED_LINK) { image_rel = dc_get_archive_icon(chat->context); if (image_rel){ image_abs = dc_get_abs_path(chat->context, image_rel); } } else if(chat->type==DC_CHAT_TYPE_SINGLE) { contacts = dc_get_chat_contacts(chat->context, chat->id); if (contacts->count >= 1) { contact = dc_get_contact(chat->context, contacts->array[0]); image_abs = dc_contact_get_profile_image(contact); } } else if(chat->type==DC_CHAT_TYPE_BROADCAST) { image_rel = dc_get_broadcast_icon(chat->context); if (image_rel){ image_abs = dc_get_abs_path(chat->context, image_rel); } } cleanup: free(image_rel); dc_array_unref(contacts); dc_contact_unref(contact); return image_abs; }
projects/deltachat-core/rust/chat.rs
pub async fn get_profile_image(&self, context: &Context) -> Result<Option<PathBuf>> { if let Some(image_rel) = self.param.get(Param::ProfileImage) { if !image_rel.is_empty() { return Ok(Some(get_abs_path(context, Path::new(&image_rel)))); } } else if self.id.is_archived_link() { if let Ok(image_rel) = get_archive_icon(context).await { return Ok(Some(get_abs_path(context, Path::new(&image_rel)))); } } else if self.typ == Chattype::Single { let contacts = get_chat_contacts(context, self.id).await?; if let Some(contact_id) = contacts.first() { if let Ok(contact) = Contact::get_by_id(context, *contact_id).await { return contact.get_profile_image(context).await; } } } else if self.typ == Chattype::Broadcast { if let Ok(image_rel) = get_broadcast_icon(context).await { return Ok(Some(get_abs_path(context, Path::new(&image_rel)))); } } Ok(None) }
pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> { // Normal chats do not include SELF. Group chats do (as it may happen that one is deleted from a // groupchat but the chats stays visible, moreover, this makes displaying lists easier) let list = context .sql .query_map( "SELECT cc.contact_id FROM chats_contacts cc LEFT JOIN contacts c ON c.id=cc.contact_id WHERE cc.chat_id=? ORDER BY c.id=1, c.last_seen DESC, c.id DESC;", (chat_id,), |row| row.get::<_, ContactId>(0), |ids| ids.collect::<Result<Vec<_>, _>>().map_err(Into::into), ) .await?; Ok(list) } pub(crate) async fn get_broadcast_icon(context: &Context) -> Result<String> { if let Some(icon) = context.sql.get_raw_config("icon-broadcast").await? { return Ok(icon); } let icon = include_bytes!("../assets/icon-broadcast.png"); let blob = BlobObject::create(context, "icon-broadcast.png", icon).await?; let icon = blob.as_name().to_string(); context .sql .set_raw_config("icon-broadcast", Some(&icon)) .await?; Ok(icon) } pub fn get(&self, key: Param) -> Option<&str> { self.inner.get(&key).map(|s| s.as_str()) } pub fn is_archived_link(self) -> bool { self == DC_CHAT_ID_ARCHIVED_LINK } pub(crate) async fn get_archive_icon(context: &Context) -> Result<String> { if let Some(icon) = context.sql.get_raw_config("icon-archive").await? { return Ok(icon); } let icon = include_bytes!("../assets/icon-archive.png"); let blob = BlobObject::create(context, "icon-archive.png", icon).await?; let icon = blob.as_name().to_string(); context .sql .set_raw_config("icon-archive", Some(&icon)) .await?; Ok(icon) } pub fn is_empty(&self) -> bool { self.inner.is_empty() } pub(crate) fn get_abs_path(context: &Context, path: &Path) -> PathBuf { if let Ok(p) = path.strip_prefix("$BLOBDIR") { context.get_blobdir().join(p) } else { path.into() } } pub async fn get_by_id(context: &Context, contact_id: ContactId) -> Result<Self> { let contact = Self::get_by_id_optional(context, contact_id) .await? .with_context(|| format!("contact {contact_id} not found"))?; Ok(contact) } pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path { unsafe { &*(s.as_ref() as *const OsStr as *const Path) } } pub struct Chat { /// Database ID. pub id: ChatId, /// Chat type, e.g. 1:1 chat, group chat, mailing list. pub typ: Chattype, /// Chat name. pub name: String, /// Whether the chat is archived or pinned. pub visibility: ChatVisibility, /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and /// ad-hoc groups. pub grpid: String, /// Whether the chat is blocked, unblocked or a contact request. pub blocked: Blocked, /// Additional chat parameters stored in the database. pub param: Params, /// If location streaming is enabled in the chat. is_sending_locations: bool, /// Duration of the chat being muted. pub mute_duration: MuteDuration, /// If the chat is protected (verified). pub(crate) protected: ProtectionStatus, } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub enum Chattype { /// 1:1 chat. Single = 100, /// Group chat. Group = 120, /// Mailing list. Mailinglist = 140, /// Broadcast list. Broadcast = 160, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__73.txt
pub unsafe extern "C" fn dc_set_chat_profile_image( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut new_image: *const libc::c_char, ) -> libc::c_int { let mut current_block: u64; let mut success: libc::c_int = 0 as libc::c_int; let mut chat: *mut dc_chat_t = dc_chat_new(context); let mut msg: *mut dc_msg_t = dc_msg_new_untyped(context); let mut new_image_rel: *mut libc::c_char = 0 as *mut libc::c_char; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || chat_id <= 9 as libc::c_int as libc::c_uint) { if !(0 as libc::c_int == real_group_exists(context, chat_id) || 0 as libc::c_int == dc_chat_load_from_db(chat, chat_id)) { if !(dc_is_contact_in_chat(context, chat_id, 1 as libc::c_int as uint32_t) == 1 as libc::c_int) { dc_log_event( context, 410 as libc::c_int, 0 as libc::c_int, b"Cannot set chat profile image; self not in group.\0" as *const u8 as *const libc::c_char, ); } else { if !new_image.is_null() { new_image_rel = dc_strdup(new_image); if dc_make_rel_and_copy(context, &mut new_image_rel) == 0 { current_block = 15699125285685737890; } else { current_block = 1394248824506584008; } } else { current_block = 1394248824506584008; } match current_block { 15699125285685737890 => {} _ => { dc_param_set((*chat).param, 'i' as i32, new_image_rel); if !(dc_chat_update_param(chat) == 0) { if dc_param_get_int( (*chat).param, 'U' as i32, 0 as libc::c_int, ) == 0 as libc::c_int { dc_param_set_int( (*msg).param, 'S' as i32, 3 as libc::c_int, ); dc_param_set((*msg).param, 'E' as i32, new_image_rel); (*msg).type_0 = 10 as libc::c_int; (*msg) .text = dc_stock_system_msg( context, if !new_image_rel.is_null() { 16 as libc::c_int } else { 33 as libc::c_int }, 0 as *const libc::c_char, 0 as *const libc::c_char, 1 as libc::c_int as uint32_t, ); (*msg).id = dc_send_msg(context, chat_id, msg); ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, chat_id as uintptr_t, (*msg).id as uintptr_t, ); } ((*context).cb) .expect( "non-null function pointer", )( context, 2020 as libc::c_int, chat_id as uintptr_t, 0 as libc::c_int as uintptr_t, ); success = 1 as libc::c_int; } } } } } } dc_chat_unref(chat); dc_msg_unref(msg); free(new_image_rel as *mut libc::c_void); return success; }
projects/deltachat-core/c/dc_location.c
dc_kml_t* dc_kml_parse(dc_context_t* context, const char* content, size_t content_bytes) { dc_kml_t* kml = calloc(1, sizeof(dc_kml_t)); char* content_nullterminated = NULL; dc_saxparser_t saxparser; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (content_bytes > 1*1024*1024) { dc_log_warning(context, 0, "A kml-files with %i bytes is larger than reasonably expected.", content_bytes); goto cleanup; } content_nullterminated = dc_null_terminate(content, content_bytes); if (content_nullterminated==NULL) { goto cleanup; } kml->locations = dc_array_new_typed(context, DC_ARRAY_LOCATIONS, 100); dc_saxparser_init (&saxparser, kml); dc_saxparser_set_tag_handler (&saxparser, kml_starttag_cb, kml_endtag_cb); dc_saxparser_set_text_handler(&saxparser, kml_text_cb); dc_saxparser_parse (&saxparser, content_nullterminated); cleanup: free(content_nullterminated); return kml; }
projects/deltachat-core/rust/location.rs
pub fn parse(to_parse: &[u8]) -> Result<Self> { ensure!(to_parse.len() <= 1024 * 1024, "kml-file is too large"); let mut reader = quick_xml::Reader::from_reader(to_parse); reader.trim_text(true); let mut kml = Kml::new(); kml.locations = Vec::with_capacity(100); let mut buf = Vec::new(); loop { match reader.read_event_into(&mut buf).with_context(|| { format!( "location parsing error at position {}", reader.buffer_position() ) })? { quick_xml::events::Event::Start(ref e) => kml.starttag_cb(e, &reader), quick_xml::events::Event::End(ref e) => kml.endtag_cb(e), quick_xml::events::Event::Text(ref e) => kml.text_cb(e), quick_xml::events::Event::Eof => break, _ => (), } buf.clear(); } Ok(kml) }
fn endtag_cb(&mut self, event: &BytesEnd) { let tag = String::from_utf8_lossy(event.name().as_ref()) .trim() .to_lowercase(); match self.tag { KmlTag::PlacemarkTimestampWhen => { if tag == "when" { self.tag = KmlTag::PlacemarkTimestamp } } KmlTag::PlacemarkTimestamp => { if tag == "timestamp" { self.tag = KmlTag::Placemark } } KmlTag::PlacemarkPointCoordinates => { if tag == "coordinates" { self.tag = KmlTag::PlacemarkPoint } } KmlTag::PlacemarkPoint => { if tag == "point" { self.tag = KmlTag::Placemark } } KmlTag::Placemark => { if tag == "placemark" { if 0 != self.curr.timestamp && 0. != self.curr.latitude && 0. != self.curr.longitude { self.locations .push(std::mem::replace(&mut self.curr, Location::new())); } self.tag = KmlTag::Undefined; } } KmlTag::Undefined => {} } } fn starttag_cb<B: std::io::BufRead>( &mut self, event: &BytesStart, reader: &quick_xml::Reader<B>, ) { let tag = String::from_utf8_lossy(event.name().as_ref()) .trim() .to_lowercase(); if tag == "document" { if let Some(addr) = event.attributes().filter_map(|a| a.ok()).find(|attr| { String::from_utf8_lossy(attr.key.as_ref()) .trim() .to_lowercase() == "addr" }) { self.addr = addr .decode_and_unescape_value(reader) .ok() .map(|a| a.into_owned()); } } else if tag == "placemark" { self.tag = KmlTag::Placemark; self.curr.timestamp = 0; self.curr.latitude = 0.0; self.curr.longitude = 0.0; self.curr.accuracy = 0.0 } else if tag == "timestamp" && self.tag == KmlTag::Placemark { self.tag = KmlTag::PlacemarkTimestamp; } else if tag == "when" && self.tag == KmlTag::PlacemarkTimestamp { self.tag = KmlTag::PlacemarkTimestampWhen; } else if tag == "point" && self.tag == KmlTag::Placemark { self.tag = KmlTag::PlacemarkPoint; } else if tag == "coordinates" && self.tag == KmlTag::PlacemarkPoint { self.tag = KmlTag::PlacemarkPointCoordinates; if let Some(acc) = event.attributes().find(|attr| { attr.as_ref() .map(|a| { String::from_utf8_lossy(a.key.as_ref()) .trim() .to_lowercase() == "accuracy" }) .unwrap_or_default() }) { let v = acc .unwrap() .decode_and_unescape_value(reader) .unwrap_or_default(); self.curr.accuracy = v.trim().parse().unwrap_or_default(); } } } fn text_cb(&mut self, event: &BytesText) { if self.tag == KmlTag::PlacemarkTimestampWhen || self.tag == KmlTag::PlacemarkPointCoordinates { let val = event.unescape().unwrap_or_default(); let val = val.replace(['\n', '\r', '\t', ' '], ""); if self.tag == KmlTag::PlacemarkTimestampWhen && val.len() >= 19 { // YYYY-MM-DDTHH:MM:SSZ // 0 4 7 10 13 16 19 match chrono::NaiveDateTime::parse_from_str(&val, "%Y-%m-%dT%H:%M:%SZ") { Ok(res) => { self.curr.timestamp = res.and_utc().timestamp(); let now = time(); if self.curr.timestamp > now { self.curr.timestamp = now; } } Err(_err) => { self.curr.timestamp = time(); } } } else if self.tag == KmlTag::PlacemarkPointCoordinates { let parts = val.splitn(2, ',').collect::<Vec<_>>(); if let [longitude, latitude] = &parts[..] { self.curr.longitude = longitude.parse().unwrap_or_default(); self.curr.latitude = latitude.parse().unwrap_or_default(); } } } } pub struct Kml { /// Nonstandard `addr` attribute of the `Document` tag storing the user email address. pub addr: Option<String>, /// Placemarks. pub locations: Vec<Location>, /// Currently parsed XML tag. tag: KmlTag, /// Currently parsed placemark. pub curr: Location, }
use std::time::Duration; use anyhow::{ensure, Context as _, Result}; use async_channel::Receiver; use quick_xml::events::{BytesEnd, BytesStart, BytesText}; use tokio::time::timeout; use crate::chat::{self, ChatId}; use crate::constants::DC_CHAT_ID_TRASH; use crate::contact::ContactId; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::tools::{duration_to_str, time}; use crate::{chatlist_events, stock_str}; use super::*; use crate::config::Config; use crate::message::MessageState; use crate::receive_imf::receive_imf; use crate::test_utils::{TestContext, TestContextManager}; use crate::tools::SystemTime;
projects__deltachat-core__rust__location__.rs__function__3.txt
pub unsafe extern "C" fn dc_kml_parse( mut context: *mut dc_context_t, mut content: *const libc::c_char, mut content_bytes: size_t, ) -> *mut dc_kml_t { let mut kml: *mut dc_kml_t = calloc( 1 as libc::c_int as libc::c_ulong, ::core::mem::size_of::<dc_kml_t>() as libc::c_ulong, ) as *mut dc_kml_t; let mut content_nullterminated: *mut libc::c_char = 0 as *mut libc::c_char; let mut saxparser: dc_saxparser_t = dc_saxparser_t { starttag_cb: None, endtag_cb: None, text_cb: None, userdata: 0 as *mut libc::c_void, }; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint) { if content_bytes > (1 as libc::c_int * 1024 as libc::c_int * 1024 as libc::c_int) as libc::c_ulong { dc_log_warning( context, 0 as libc::c_int, b"A kml-files with %i bytes is larger than reasonably expected.\0" as *const u8 as *const libc::c_char, content_bytes, ); } else { content_nullterminated = dc_null_terminate( content, content_bytes as libc::c_int, ); if !content_nullterminated.is_null() { (*kml) .locations = dc_array_new_typed( context, 1 as libc::c_int, 100 as libc::c_int as size_t, ); dc_saxparser_init(&mut saxparser, kml as *mut libc::c_void); dc_saxparser_set_tag_handler( &mut saxparser, Some( kml_starttag_cb as unsafe extern "C" fn( *mut libc::c_void, *const libc::c_char, *mut *mut libc::c_char, ) -> (), ), Some( kml_endtag_cb as unsafe extern "C" fn( *mut libc::c_void, *const libc::c_char, ) -> (), ), ); dc_saxparser_set_text_handler( &mut saxparser, Some( kml_text_cb as unsafe extern "C" fn( *mut libc::c_void, *const libc::c_char, libc::c_int, ) -> (), ), ); dc_saxparser_parse(&mut saxparser, content_nullterminated); } } } free(content_nullterminated as *mut libc::c_void); return kml; }
projects/deltachat-core/c/dc_oauth2.c
char* dc_get_oauth2_url(dc_context_t* context, const char* addr, const char* redirect_uri) { #define CLIENT_ID "959970109878-4mvtgf6feshskf7695nfln6002mom908.apps.googleusercontent.com" oauth2_t* oauth2 = NULL; char* oauth2_url = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || redirect_uri==NULL || redirect_uri[0]==0) { goto cleanup; } oauth2 = get_info(addr); if (oauth2==NULL) { goto cleanup; } dc_sqlite3_set_config(context->sql, "oauth2_pending_redirect_uri", redirect_uri); oauth2_url = dc_strdup(oauth2->get_code); replace_in_uri(&oauth2_url, "$CLIENT_ID", oauth2->client_id); replace_in_uri(&oauth2_url, "$REDIRECT_URI", redirect_uri); cleanup: free(oauth2); return oauth2_url; }
projects/deltachat-core/rust/oauth2.rs
pub async fn get_oauth2_url( context: &Context, addr: &str, redirect_uri: &str, ) -> Result<Option<String>> { let socks5_enabled = context.get_config_bool(Config::Socks5Enabled).await?; if let Some(oauth2) = Oauth2::from_address(context, addr, socks5_enabled).await { context .sql .set_raw_config("oauth2_pending_redirect_uri", Some(redirect_uri)) .await?; let oauth2_url = replace_in_uri(oauth2.get_code, "$CLIENT_ID", oauth2.client_id); let oauth2_url = replace_in_uri(&oauth2_url, "$REDIRECT_URI", redirect_uri); Ok(Some(oauth2_url)) } else { Ok(None) } }
pub async fn get_config_bool(&self, key: Config) -> Result<bool> { Ok(self.get_config_bool_opt(key).await?.unwrap_or_default()) } fn replace_in_uri(uri: &str, key: &str, value: &str) -> String { let value_urlencoded = utf8_percent_encode(value, NON_ALPHANUMERIC).to_string(); uri.replace(key, &value_urlencoded) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub async fn set_raw_config(&self, key: &str, value: Option<&str>) -> Result<()> { let mut lock = self.config_cache.write().await; if let Some(value) = value { self.execute( "INSERT OR REPLACE INTO config (keyname, value) VALUES (?, ?)", (key, value), ) .await?; } else { self.execute("DELETE FROM config WHERE keyname=?", (key,)) .await?; } lock.insert(key.to_string(), value.map(|s| s.to_string())); drop(lock); Ok(()) } async fn from_address(context: &Context, addr: &str, skip_mx: bool) -> Option<Self> { let addr_normalized = normalize_addr(addr); if let Some(domain) = addr_normalized .find('@') .map(|index| addr_normalized.split_at(index + 1).1) { if let Some(oauth2_authorizer) = provider::get_provider_info(context, domain, skip_mx) .await .and_then(|provider| provider.oauth2_authorizer.as_ref()) { return Some(match oauth2_authorizer { Oauth2Authorizer::Gmail => OAUTH2_GMAIL, Oauth2Authorizer::Yandex => OAUTH2_YANDEX, }); } } None } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub enum Config { /// Email address, used in the `From:` field. Addr, /// IMAP server hostname. MailServer, /// IMAP server username. MailUser, /// IMAP server password. MailPw, /// IMAP server port. MailPort, /// IMAP server security (e.g. TLS, STARTTLS). MailSecurity, /// How to check IMAP server TLS certificates. ImapCertificateChecks, /// SMTP server hostname. SendServer, /// SMTP server username. SendUser, /// SMTP server password. SendPw, /// SMTP server port. SendPort, /// SMTP server security (e.g. TLS, STARTTLS). SendSecurity, /// How to check SMTP server TLS certificates. SmtpCertificateChecks, /// Whether to use OAuth 2. /// /// Historically contained other bitflags, which are now deprecated. /// Should not be extended in the future, create new config keys instead. ServerFlags, /// True if SOCKS5 is enabled. /// /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration. Socks5Enabled, /// SOCKS5 proxy server hostname or address. Socks5Host, /// SOCKS5 proxy server port. Socks5Port, /// SOCKS5 proxy server username. Socks5User, /// SOCKS5 proxy server password. Socks5Password, /// Own name to use in the `From:` field when sending messages. Displayname, /// Own status to display, sent in message footer. Selfstatus, /// Own avatar filename. Selfavatar, /// Send BCC copy to self. /// /// Should be enabled for multidevice setups. #[strum(props(default = "1"))] BccSelf, /// True if encryption is preferred according to Autocrypt standard. #[strum(props(default = "1"))] E2eeEnabled, /// True if Message Delivery Notifications (read receipts) should /// be sent and requested. #[strum(props(default = "1"))] MdnsEnabled, /// True if "Sent" folder should be watched for changes. #[strum(props(default = "0"))] SentboxWatch, /// True if chat messages should be moved to a separate folder. #[strum(props(default = "1"))] MvboxMove, /// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only. /// /// This will not entirely disable other folders, e.g. the spam folder will also still /// be watched for new messages. #[strum(props(default = "0"))] OnlyFetchMvbox, /// Whether to show classic emails or only chat messages. #[strum(props(default = "2"))] // also change ShowEmails.default() on changes ShowEmails, /// Quality of the media files to send. #[strum(props(default = "0"))] // also change MediaQuality.default() on changes MediaQuality, /// If set to "1", on the first time `start_io()` is called after configuring, /// the newest existing messages are fetched. /// Existing recipients are added to the contact database regardless of this setting. #[strum(props(default = "0"))] FetchExistingMsgs, /// If set to "1", then existing messages are considered to be already fetched. /// This flag is reset after successful configuration. #[strum(props(default = "1"))] FetchedExistingMsgs, /// Type of the OpenPGP key to generate. #[strum(props(default = "0"))] KeyGenType, /// Timer in seconds after which the message is deleted from the /// server. /// /// Equals to 0 by default, which means the message is never /// deleted. /// /// Value 1 is treated as "delete at once": messages are deleted /// immediately, without moving to DeltaChat folder. #[strum(props(default = "0"))] DeleteServerAfter, /// Timer in seconds after which the message is deleted from the /// device. /// /// Equals to 0 by default, which means the message is never /// deleted. #[strum(props(default = "0"))] DeleteDeviceAfter, /// Move messages to the Trash folder instead of marking them "\Deleted". Overrides /// `ProviderOptions::delete_to_trash`. DeleteToTrash, /// Save raw MIME messages with headers in the database if true. SaveMimeHeaders, /// The primary email address. Also see `SecondaryAddrs`. ConfiguredAddr, /// Configured IMAP server hostname. ConfiguredMailServer, /// Configured IMAP server username. ConfiguredMailUser, /// Configured IMAP server password. ConfiguredMailPw, /// Configured IMAP server port. ConfiguredMailPort, /// Configured IMAP server security (e.g. TLS, STARTTLS). ConfiguredMailSecurity, /// How to check IMAP server TLS certificates. ConfiguredImapCertificateChecks, /// Configured SMTP server hostname. ConfiguredSendServer, /// Configured SMTP server username. ConfiguredSendUser, /// Configured SMTP server password. ConfiguredSendPw, /// Configured SMTP server port. ConfiguredSendPort, /// How to check SMTP server TLS certificates. ConfiguredSmtpCertificateChecks, /// Whether OAuth 2 is used with configured provider. ConfiguredServerFlags, /// Configured SMTP server security (e.g. TLS, STARTTLS). ConfiguredSendSecurity, /// Configured folder for incoming messages. ConfiguredInboxFolder, /// Configured folder for chat messages. ConfiguredMvboxFolder, /// Configured "Sent" folder. ConfiguredSentboxFolder, /// Configured "Trash" folder. ConfiguredTrashFolder, /// Unix timestamp of the last successful configuration. ConfiguredTimestamp, /// ID of the configured provider from the provider database. ConfiguredProvider, /// True if account is configured. Configured, /// True if account is a chatmail account. IsChatmail, /// All secondary self addresses separated by spaces /// (`[email protected] [email protected] [email protected]`) SecondaryAddrs, /// Read-only core version string. #[strum(serialize = "sys.version")] SysVersion, /// Maximal recommended attachment size in bytes. #[strum(serialize = "sys.msgsize_max_recommended")] SysMsgsizeMaxRecommended, /// Space separated list of all config keys available. #[strum(serialize = "sys.config_keys")] SysConfigKeys, /// True if it is a bot account. Bot, /// True when to skip initial start messages in groups. #[strum(props(default = "0"))] SkipStartMessages, /// Whether we send a warning if the password is wrong (set to false when we send a warning /// because we do not want to send a second warning) #[strum(props(default = "0"))] NotifyAboutWrongPw, /// If a warning about exceeding quota was shown recently, /// this is the percentage of quota at the time the warning was given. /// Unset, when quota falls below minimal warning threshold again. QuotaExceeding, /// address to webrtc instance to use for videochats WebrtcInstance, /// Timestamp of the last time housekeeping was run LastHousekeeping, /// Timestamp of the last `CantDecryptOutgoingMsgs` notification. LastCantDecryptOutgoingMsgs, /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely. #[strum(props(default = "60"))] ScanAllFoldersDebounceSecs, /// Whether to avoid using IMAP IDLE even if the server supports it. /// /// This is a developer option for testing "fake idle". #[strum(props(default = "0"))] DisableIdle, /// Defines the max. size (in bytes) of messages downloaded automatically. /// 0 = no limit. #[strum(props(default = "0"))] DownloadLimit, /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set. #[strum(props(default = "1"))] SyncMsgs, /// Space-separated list of all the authserv-ids which we believe /// may be the one of our email server. /// /// See `crate::authres::update_authservid_candidates`. AuthservIdCandidates, /// Make all outgoing messages with Autocrypt header "multipart/signed". SignUnencrypted, /// Let the core save all events to the database. /// This value is used internally to remember the MsgId of the logging xdc #[strum(props(default = "0"))] DebugLogging, /// Last message processed by the bot. LastMsgId, /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by /// default. /// /// This is not supposed to be changed by UIs and only used for testing. #[strum(props(default = "172800"))] GossipPeriod, /// Feature flag for verified 1:1 chats; the UI should set it /// to 1 if it supports verified 1:1 chats. /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified, /// and when the key changes, an info message is posted into the chat. /// 0=Nothing else happens when the key changes. /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true /// until `chat_id.accept()` is called. #[strum(props(default = "0"))] VerifiedOneOnOneChats, /// Row ID of the key in the `keypairs` table /// 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 /// without storing the email address SelfReportingId, /// MsgId of webxdc map integration. WebxdcIntegration, /// Iroh secret key. IrohSecretKey, }
use std::collections::HashMap; use anyhow::Result; use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC}; use serde::Deserialize; use crate::config::Config; use crate::context::Context; use crate::provider; use crate::provider::Oauth2Authorizer; use crate::socks::Socks5Config; use crate::tools::time; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__oauth2__.rs__function__1.txt
pub unsafe extern "C" fn dc_get_oauth2_url( mut context: *mut dc_context_t, mut addr: *const libc::c_char, mut redirect_uri: *const libc::c_char, ) -> *mut libc::c_char { let mut oauth2: *mut oauth2_t = 0 as *mut oauth2_t; let mut oauth2_url: *mut libc::c_char = 0 as *mut libc::c_char; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || redirect_uri.is_null() || *redirect_uri.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int) { oauth2 = get_info(addr); if !oauth2.is_null() { dc_sqlite3_set_config( (*context).sql, b"oauth2_pending_redirect_uri\0" as *const u8 as *const libc::c_char, redirect_uri, ); oauth2_url = dc_strdup((*oauth2).get_code); replace_in_uri( &mut oauth2_url, b"$CLIENT_ID\0" as *const u8 as *const libc::c_char, (*oauth2).client_id, ); replace_in_uri( &mut oauth2_url, b"$REDIRECT_URI\0" as *const u8 as *const libc::c_char, redirect_uri, ); } } free(oauth2 as *mut libc::c_void); return oauth2_url; }
projects/deltachat-core/c/dc_msg.c
time_t dc_msg_get_timestamp(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->timestamp_sent? msg->timestamp_sent : msg->timestamp_sort; }
projects/deltachat-core/rust/message.rs
pub fn get_timestamp(&self) -> i64 { if 0 != self.timestamp_sent { self.timestamp_sent } else { self.timestamp_sort } }
pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__29.txt
pub unsafe extern "C" fn dc_msg_get_timestamp(mut msg: *const dc_msg_t) -> time_t { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return 0 as libc::c_int as time_t; } return if (*msg).timestamp_sent != 0 { (*msg).timestamp_sent } else { (*msg).timestamp_sort }; }
projects/deltachat-core/c/dc_chat.c
* so you have to free it using dc_msg_unref() as usual. * @return The ID of the message that is being prepared. */ uint32_t dc_prepare_msg(dc_context_t* context, uint32_t chat_id, dc_msg_t* msg) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg==NULL || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { return 0; } uint32_t msg_id = prepare_msg_common(context, chat_id, msg); context->cb(context, DC_EVENT_MSGS_CHANGED, msg->chat_id, msg->id); if (dc_param_exists(msg->param, DC_PARAM_SET_LATITUDE)) { context->cb(context, DC_EVENT_LOCATION_CHANGED, DC_CONTACT_ID_SELF, 0); } return msg_id; }
projects/deltachat-core/rust/chat.rs
pub async fn prepare_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> { ensure!( !chat_id.is_special(), "Cannot prepare message for special chat" ); let msg_id = prepare_msg_common(context, chat_id, msg, MessageState::OutPreparing).await?; context.emit_msgs_changed(msg.chat_id, msg.id); Ok(msg_id) }
pub fn is_special(self) -> bool { (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0) } pub fn emit_msgs_changed(&self, chat_id: ChatId, msg_id: MsgId) { self.emit_event(EventType::MsgsChanged { chat_id, msg_id }); chatlist_events::emit_chatlist_changed(self); chatlist_events::emit_chatlist_item_changed(self, chat_id); } async fn prepare_msg_common( context: &Context, chat_id: ChatId, msg: &mut Message, change_state_to: MessageState, ) -> Result<MsgId> { let mut chat = Chat::load_from_db(context, chat_id).await?; // Check if the chat can be sent to. if let Some(reason) = chat.why_cant_send(context).await? { if matches!( reason, CantSendReason::ProtectionBroken | CantSendReason::ContactRequest | CantSendReason::SecurejoinWait ) && msg.param.get_cmd() == SystemMessage::SecurejoinMessage { // Send out the message, the securejoin message is supposed to repair the verification. // If the chat is a contact request, let the user accept it later. } else { bail!("cannot send to {chat_id}: {reason}"); } } // Check a quote reply is not leaking data from other chats. // This is meant as a last line of defence, the UI should check that before as well. // (We allow Chattype::Single in general for "Reply Privately"; // checking for exact contact_id will produce false positives when ppl just left the group) if chat.typ != Chattype::Single && !context.get_config_bool(Config::Bot).await? { if let Some(quoted_message) = msg.quoted_message(context).await? { if quoted_message.chat_id != chat_id { bail!("Bad quote reply"); } } } // check current MessageState for drafts (to keep msg_id) ... let update_msg_id = if msg.state == MessageState::OutDraft { msg.hidden = false; if !msg.id.is_special() && msg.chat_id == chat_id { Some(msg.id) } else { None } } else { None }; // ... then change the MessageState in the message object msg.state = change_state_to; prepare_msg_blob(context, msg).await?; if !msg.hidden { chat_id.unarchive_if_not_muted(context, msg.state).await?; } msg.id = chat .prepare_msg_raw( context, msg, update_msg_id, create_smeared_timestamp(context), ) .await?; msg.chat_id = chat_id; Ok(msg.id) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct MsgId(u32); pub struct ChatId(u32); pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum MessageState { /// Undefined message state. #[default] Undefined = 0, /// Incoming *fresh* message. Fresh messages are neither noticed /// nor seen and are typically shown in notifications. InFresh = 10, /// Incoming *noticed* message. E.g. chat opened but message not /// yet read - noticed messages are not counted as unread but did /// not marked as read nor resulted in MDNs. InNoticed = 13, /// Incoming message, really *seen* by the user. Marked as read on /// IMAP and MDN may be sent. InSeen = 16, /// For files which need time to be prepared before they can be /// sent, the message enters this state before /// OutPending. OutPreparing = 18, /// Message saved as draft. OutDraft = 19, /// The user has pressed the "send" button but the message is not /// yet sent and is pending in some way. Maybe we're offline (no /// checkmark). OutPending = 20, /// *Unrecoverable* error (*recoverable* errors result in pending /// messages). OutFailed = 24, /// Outgoing message successfully delivered to server (one /// checkmark). Note, that already delivered messages may get into /// the OutFailed state if we get such a hint from the server. OutDelivered = 26, /// Outgoing message read by the recipient (two checkmarks; this /// requires goodwill on the receiver's side) OutMdnRcvd = 28, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__100.txt
pub unsafe extern "C" fn dc_msg_unref(mut msg: *mut dc_msg_t) { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return; } dc_msg_empty(msg); dc_param_unref((*msg).param); (*msg).magic = 0 as libc::c_int as uint32_t; free(msg as *mut libc::c_void); }
projects/deltachat-core/c/dc_tools.c
time_t dc_create_smeared_timestamp(dc_context_t* context) { time_t now = time(NULL); time_t ret = now; SMEAR_LOCK context->last_smeared_timestamp = ret; SMEAR_UNLOCK return ret; }
projects/deltachat-core/rust/tools.rs
pub(crate) fn create_smeared_timestamp(context: &Context) -> i64 { let now = time(); context.smeared_timestamp.create(now) }
pub fn create(&self, now: i64) -> i64 { self.create_n(now, 1) } pub(crate) fn time() -> i64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap_or_default() .as_secs() as i64 } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, }
use std::borrow::Cow; use std::io::{Cursor, Write}; use std::mem; use std::path::{Path, PathBuf}; use std::str::from_utf8; use std::time::Duration; use std::time::SystemTime as Time; use std::time::SystemTime; use anyhow::{bail, Context as _, Result}; use base64::Engine as _; use chrono::{Local, NaiveDateTime, NaiveTime, TimeZone}; use deltachat_contact_tools::{strip_rtlo_characters, EmailAddress}; use deltachat_time::SystemTimeTools as SystemTime; use futures::{StreamExt, TryStreamExt}; use mailparse::dateparse; use mailparse::headers::Headers; use mailparse::MailHeaderMap; use rand::{thread_rng, Rng}; use tokio::{fs, io}; use url::Url; use crate::chat::{add_device_msg, add_device_msg_with_importance}; use crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS}; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, Viewtype}; use crate::stock_str; use chrono::NaiveDate; use proptest::prelude::*; use super::*; use crate::chatlist::Chatlist; use crate::{chat, test_utils}; use crate::{receive_imf::receive_imf, test_utils::TestContext}; use super::*;
projects__deltachat-core__rust__tools__.rs__function__7.txt
pub unsafe extern "C" fn dc_create_smeared_timestamp( mut context: *mut dc_context_t, ) -> time_t { let mut now: time_t = time(0 as *mut time_t); let mut ret: time_t = now; pthread_mutex_lock(&mut (*context).smear_critical); if ret <= (*context).last_smeared_timestamp { ret = (*context).last_smeared_timestamp + 1 as libc::c_int as libc::c_long; if ret - now > 5 as libc::c_int as libc::c_long { ret = now + 5 as libc::c_int as libc::c_long; } } (*context).last_smeared_timestamp = ret; pthread_mutex_unlock(&mut (*context).smear_critical); return ret; }
projects/deltachat-core/c/dc_imex.c
char* dc_initiate_key_transfer(dc_context_t* context) { int success = 0; char* setup_code = NULL; char* setup_file_content = NULL; char* setup_file_name = NULL; uint32_t chat_id = 0; dc_msg_t* msg = NULL; uint32_t msg_id = 0; if (!dc_alloc_ongoing(context)) { return 0; /* no cleanup as this would call dc_free_ongoing() */ } #define CHECK_EXIT if (context->shall_stop_ongoing) { goto cleanup; } if ((setup_code=dc_create_setup_code(context))==NULL) { /* this may require a keypair to be created. this may take a second ... */ goto cleanup; } CHECK_EXIT if ((setup_file_content=dc_render_setup_file(context, setup_code))==NULL) { /* encrypting may also take a while ... */ goto cleanup; } CHECK_EXIT if ((setup_file_name=dc_get_fine_pathNfilename(context, "$BLOBDIR", "autocrypt-setup-message.html"))==NULL || !dc_write_file(context, setup_file_name, setup_file_content, strlen(setup_file_content))) { goto cleanup; } if ((chat_id=dc_create_chat_by_contact_id(context, DC_CONTACT_ID_SELF))==0) { goto cleanup; } msg = dc_msg_new_untyped(context); msg->type = DC_MSG_FILE; dc_param_set (msg->param, DC_PARAM_FILE, setup_file_name); dc_param_set (msg->param, DC_PARAM_MIMETYPE, "application/autocrypt-setup"); dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_AUTOCRYPT_SETUP_MESSAGE); dc_param_set_int(msg->param, DC_PARAM_FORCE_PLAINTEXT, DC_FP_NO_AUTOCRYPT_HEADER); CHECK_EXIT if ((msg_id = dc_send_msg(context, chat_id, msg))==0) { goto cleanup; } dc_msg_unref(msg); msg = NULL; /* wait until the message is really sent */ dc_log_info(context, 0, "Wait for setup message being sent ..."); while (1) { CHECK_EXIT sleep(1); msg = dc_get_msg(context, msg_id); if (dc_msg_is_sent(msg)) { break; } dc_msg_unref(msg); msg = NULL; } dc_log_info(context, 0, "... setup message sent."); success = 1; cleanup: if (!success) { free(setup_code); setup_code = NULL; } free(setup_file_name); free(setup_file_content); dc_msg_unref(msg); dc_free_ongoing(context); return setup_code; }
projects/deltachat-core/rust/imex.rs
pub async fn initiate_key_transfer(context: &Context) -> Result<String> { let setup_code = create_setup_code(context); /* this may require a keypair to be created. this may take a second ... */ let setup_file_content = render_setup_file(context, &setup_code).await?; /* encrypting may also take a while ... */ let setup_file_blob = BlobObject::create( context, "autocrypt-setup-message.html", setup_file_content.as_bytes(), ) .await?; let chat_id = ChatId::create_for_contact(context, ContactId::SELF).await?; let mut msg = Message { viewtype: Viewtype::File, ..Default::default() }; msg.param.set(Param::File, setup_file_blob.as_name()); msg.subject = stock_str::ac_setup_msg_subject(context).await; msg.param .set(Param::MimeType, "application/autocrypt-setup"); msg.param.set_cmd(SystemMessage::AutocryptSetupMessage); msg.force_plaintext(); msg.param.set_int(Param::SkipAutocrypt, 1); chat::send_msg(context, chat_id, &mut msg).await?; // no maybe_add_bcc_self_device_msg() here. // the ui shows the dialog with the setup code on this device, // it would be too much noise to have two things popping up at the same time. // maybe_add_bcc_self_device_msg() is called on the other device // once the transfer is completed. Ok(setup_code) }
pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> { if chat_id.is_unset() { let forwards = msg.param.get(Param::PrepForwards); if let Some(forwards) = forwards { for forward in forwards.split(' ') { if let Ok(msg_id) = forward.parse::<u32>().map(MsgId::new) { if let Ok(mut msg) = Message::load_from_db(context, msg_id).await { send_msg_inner(context, chat_id, &mut msg).await?; }; } } msg.param.remove(Param::PrepForwards); msg.update_param(context).await?; } return send_msg_inner(context, chat_id, msg).await; } if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing { msg.param.remove(Param::GuaranteeE2ee); msg.param.remove(Param::ForcePlaintext); msg.update_param(context).await?; } send_msg_inner(context, chat_id, msg).await } pub fn as_name(&self) -> &str { &self.name } pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self { self.inner.insert(key, value.to_string()); self } pub fn set_int(&mut self, key: Param, value: i32) -> &mut Self { self.set(key, format!("{value}")); self } pub async fn render_setup_file(context: &Context, passphrase: &str) -> Result<String> { let passphrase_begin = if let Some(passphrase_begin) = passphrase.get(..2) { passphrase_begin } else { bail!("Passphrase must be at least 2 chars long."); }; let private_key = load_self_secret_key(context).await?; let ac_headers = match context.get_config_bool(Config::E2eeEnabled).await? { false => None, true => Some(("Autocrypt-Prefer-Encrypt", "mutual")), }; let private_key_asc = private_key.to_asc(ac_headers); let encr = pgp::symm_encrypt(passphrase, private_key_asc.as_bytes()) .await? .replace('\n', "\r\n"); let replacement = format!( concat!( "-----BEGIN PGP MESSAGE-----\r\n", "Passphrase-Format: numeric9x4\r\n", "Passphrase-Begin: {}" ), passphrase_begin ); let pgp_msg = encr.replace("-----BEGIN PGP MESSAGE-----", &replacement); let msg_subj = stock_str::ac_setup_msg_subject(context).await; let msg_body = stock_str::ac_setup_msg_body(context).await; let msg_body_html = msg_body.replace('\r', "").replace('\n', "<br>"); Ok(format!( concat!( "<!DOCTYPE html>\r\n", "<html>\r\n", " <head>\r\n", " <title>{}</title>\r\n", " </head>\r\n", " <body>\r\n", " <h1>{}</h1>\r\n", " <p>{}</p>\r\n", " <pre>\r\n{}\r\n</pre>\r\n", " </body>\r\n", "</html>\r\n" ), msg_subj, msg_subj, msg_body_html, pgp_msg )) } pub fn set_cmd(&mut self, value: SystemMessage) { self.set_int(Param::Cmd, value as i32); } pub fn force_plaintext(&mut self) { self.param.set_int(Param::ForcePlaintext, 1); } pub async fn create( context: &'a Context, suggested_name: &str, data: &[u8], ) -> Result<BlobObject<'a>> { let blobdir = context.get_blobdir(); let (stem, ext) = BlobObject::sanitise_name(suggested_name); let (name, mut file) = BlobObject::create_new_file(context, blobdir, &stem, &ext).await?; file.write_all(data).await.context("file write failure")?; // workaround a bug in async-std // (the executor does not handle blocking operation in Drop correctly, // see <https://github.com/async-rs/async-std/issues/900>) let _ = file.flush().await; let blob = BlobObject { blobdir, name: format!("$BLOBDIR/{name}"), }; context.emit_event(EventType::NewBlobFile(blob.as_name().to_string())); Ok(blob) } pub async fn create_for_contact(context: &Context, contact_id: ContactId) -> Result<Self> { ChatId::create_for_contact_with_blocked(context, contact_id, Blocked::Not).await } pub fn create_setup_code(_context: &Context) -> String { let mut random_val: u16; let mut rng = thread_rng(); let mut ret = String::new(); for i in 0..9 { loop { random_val = rng.gen(); if random_val as usize <= 60000 { break; } } random_val = (random_val as usize % 10000) as u16; ret += &format!( "{}{:04}", if 0 != i { "-" } else { "" }, random_val as usize ); } ret } pub fn new(viewtype: Viewtype) -> Self { Message { viewtype, ..Default::default() } } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub enum Viewtype { /// Unknown message type. #[default] Unknown = 0, /// Text message. /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text(). Text = 10, /// Image message. /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to /// `Gif` when sending the message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension(). Image = 20, /// Animated GIF message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension() /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height(). Gif = 21, /// Message containing a sticker, similar to image. /// If possible, the ui should display the image without borders in a transparent way. /// A click on a sticker will offer to install the sticker set in some future. Sticker = 23, /// Message containing an Audio file. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration(). Audio = 40, /// A voice message that was directly recorded by the user. /// For all other audio messages, the type #DC_MSG_AUDIO should be used. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration() Voice = 41, /// Video messages. /// File, width, height and durarion /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration() /// and retrieved via /// dc_msg_get_file(), dc_msg_get_width(), /// dc_msg_get_height(), dc_msg_get_duration(). Video = 50, /// Message containing any file, eg. a PDF. /// The file is set via dc_msg_set_file() /// and retrieved via dc_msg_get_file(). File = 60, /// Message is an invitation to a videochat. VideochatInvitation = 70, /// Message is an webxdc instance. Webxdc = 80, /// Message containing shared contacts represented as a vCard (virtual contact file) /// with email addresses and possibly other fields. /// Use `parse_vcard()` to retrieve them. Vcard = 90, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. } pub(crate) async fn ac_setup_msg_subject(context: &Context) -> String { translated(context, StockMessage::AcSetupMsgSubject).await } impl ContactId { /// Undefined contact. Used as a placeholder for trashed messages. pub const UNDEFINED: ContactId = ContactId::new(0); /// The owner of the account. /// /// The email-address is set by `set_config` using "addr". pub const SELF: ContactId = ContactId::new(1); /// ID of the contact for info messages. pub const INFO: ContactId = ContactId::new(2); /// ID of the contact for device messages. pub const DEVICE: ContactId = ContactId::new(5); pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9); /// Address to go with [`ContactId::DEVICE`]. /// /// This is used by APIs which need to return an email address for this contact. pub const DEVICE_ADDR: &'static str = "device@localhost"; } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum SystemMessage { /// Unknown type of system message. #[default] Unknown = 0, /// Group name changed. GroupNameChanged = 2, /// Group avatar changed. GroupImageChanged = 3, /// Member was added to the group. MemberAddedToGroup = 4, /// Member was removed from the group. MemberRemovedFromGroup = 5, /// Autocrypt Setup Message. AutocryptSetupMessage = 6, /// Secure-join message. SecurejoinMessage = 7, /// Location streaming is enabled. LocationStreamingEnabled = 8, /// Location-only message. LocationOnly = 9, /// Chat ephemeral message timer is changed. EphemeralTimerChanged = 10, /// "Messages are guaranteed to be end-to-end encrypted from now on." ChatProtectionEnabled = 11, /// "%1$s sent a message from another device." ChatProtectionDisabled = 12, /// Message can't be sent because of `Invalid unencrypted mail to <>` /// which is sent by chatmail servers. InvalidUnencryptedMail = 13, /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it /// to complete. SecurejoinWait = 14, /// 1:1 chats info message telling that SecureJoin is still running, but the user may already /// send messages. SecurejoinWaitTimeout = 15, /// Self-sent-message that contains only json used for multi-device-sync; /// if possible, we attach that to other messages as for locations. MultiDeviceSync = 20, /// Sync message that contains a json payload /// sent to the other webxdc instances /// These messages are not shown in the chat. WebxdcStatusUpdate = 30, /// Webxdc info added with `info` set in `send_webxdc_status_update()`. WebxdcInfoMessage = 32, /// This message contains a users iroh node address. IrohNodeAddr = 40, }
use std::any::Any; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use ::pgp::types::KeyTrait; use anyhow::{bail, ensure, format_err, Context as _, Result}; use deltachat_contact_tools::EmailAddress; use futures::StreamExt; use futures_lite::FutureExt; use rand::{thread_rng, Rng}; use tokio::fs::{self, File}; use tokio_tar::Archive; use crate::blob::{BlobDirContents, BlobObject}; use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId}; use crate::config::Config; use crate::contact::ContactId; use crate::context::Context; use crate::e2ee; use crate::events::EventType; use crate::key::{ self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey, }; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::pgp; use crate::sql; use crate::stock_str; use crate::tools::{ create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file, }; use transfer::{get_backup, BackupProvider}; use std::time::Duration; use ::pgp::armor::BlockType; use tokio::task; use super::*; use crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE}; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::{alice_keypair, TestContext, TestContextManager};
projects__deltachat-core__rust__imex__.rs__function__3.txt
pub unsafe extern "C" fn dc_initiate_key_transfer( mut context: *mut dc_context_t, ) -> *mut libc::c_char { let mut current_block: u64; let mut success: libc::c_int = 0 as libc::c_int; let mut setup_code: *mut libc::c_char = 0 as *mut libc::c_char; let mut setup_file_content: *mut libc::c_char = 0 as *mut libc::c_char; let mut setup_file_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut chat_id: uint32_t = 0 as libc::c_int as uint32_t; let mut msg: *mut dc_msg_t = 0 as *mut dc_msg_t; let mut msg_id: uint32_t = 0 as libc::c_int as uint32_t; if dc_alloc_ongoing(context) == 0 { return 0 as *mut libc::c_char; } setup_code = dc_create_setup_code(context); if !setup_code.is_null() { if !((*context).shall_stop_ongoing != 0) { setup_file_content = dc_render_setup_file(context, setup_code); if !setup_file_content.is_null() { if !((*context).shall_stop_ongoing != 0) { setup_file_name = dc_get_fine_pathNfilename( context, b"$BLOBDIR\0" as *const u8 as *const libc::c_char, b"autocrypt-setup-message.html\0" as *const u8 as *const libc::c_char, ); if !(setup_file_name.is_null() || dc_write_file( context, setup_file_name, setup_file_content as *const libc::c_void, strlen(setup_file_content), ) == 0) { chat_id = dc_create_chat_by_contact_id( context, 1 as libc::c_int as uint32_t, ); if !(chat_id == 0 as libc::c_int as libc::c_uint) { msg = dc_msg_new_untyped(context); (*msg).type_0 = 60 as libc::c_int; dc_param_set((*msg).param, 'f' as i32, setup_file_name); dc_param_set( (*msg).param, 'm' as i32, b"application/autocrypt-setup\0" as *const u8 as *const libc::c_char, ); dc_param_set_int((*msg).param, 'S' as i32, 6 as libc::c_int); dc_param_set_int((*msg).param, 'u' as i32, 2 as libc::c_int); if !((*context).shall_stop_ongoing != 0) { msg_id = dc_send_msg(context, chat_id, msg); if !(msg_id == 0 as libc::c_int as libc::c_uint) { dc_msg_unref(msg); msg = 0 as *mut dc_msg_t; dc_log_info( context, 0 as libc::c_int, b"Wait for setup message being sent ...\0" as *const u8 as *const libc::c_char, ); loop { if (*context).shall_stop_ongoing != 0 { current_block = 12992236231453723825; break; } sleep(1 as libc::c_int as libc::c_uint); msg = dc_get_msg(context, msg_id); if dc_msg_is_sent(msg) != 0 { current_block = 15345278821338558188; break; } dc_msg_unref(msg); msg = 0 as *mut dc_msg_t; } match current_block { 12992236231453723825 => {} _ => { dc_log_info( context, 0 as libc::c_int, b"... setup message sent.\0" as *const u8 as *const libc::c_char, ); success = 1 as libc::c_int; } } } } } } } } } } if success == 0 { free(setup_code as *mut libc::c_void); setup_code = 0 as *mut libc::c_char; } free(setup_file_name as *mut libc::c_void); free(setup_file_content as *mut libc::c_void); dc_msg_unref(msg); dc_free_ongoing(context); return setup_code; }
projects/deltachat-core/c/dc_chatlist.c
int dc_get_archived_cnt(dc_context_t* context) { int ret = 0; sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM chats WHERE blocked!=1 AND archived=1;"); if (sqlite3_step(stmt)==SQLITE_ROW) { ret = sqlite3_column_int(stmt, 0); } sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/rust/chatlist.rs
pub async fn get_archived_cnt(context: &Context) -> Result<usize> { let count = context .sql .count( "SELECT COUNT(*) FROM chats WHERE blocked!=? AND archived=?;", (Blocked::Yes, ChatVisibility::Archived), ) .await?; Ok(count) }
pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result<usize> { let count: isize = self.query_row(query, params, |row| row.get(0)).await?; Ok(usize::try_from(count)?) } pub enum Blocked { #[default] Not = 0, Yes = 1, Request = 2, } pub enum ChatVisibility { /// Chat is neither archived nor pinned. Normal = 0, /// Chat is archived. Archived = 1, /// Chat is pinned to the top of the chatlist. Pinned = 2, }
use anyhow::{ensure, Context as _, Result}; use once_cell::sync::Lazy; use crate::chat::{update_special_chat_names, Chat, ChatId, ChatVisibility}; use crate::constants::{ Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_GCL_ADD_ALLDONE_HINT, DC_GCL_ARCHIVED_ONLY, DC_GCL_FOR_FORWARDING, DC_GCL_NO_SPECIALS, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::message::{Message, MessageState, MsgId}; use crate::param::{Param, Params}; use crate::stock_str; use crate::summary::Summary; use crate::tools::IsNoneOrEmpty; use super::*; use crate::chat::{ add_contact_to_chat, create_group_chat, get_chat_contacts, remove_contact_from_chat, send_text_msg, ProtectionStatus, }; use crate::message::Viewtype; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::TestContext;
projects__deltachat-core__rust__chatlist__.rs__function__11.txt
pub unsafe extern "C" fn dc_get_archived_cnt( mut context: *mut dc_context_t, ) -> libc::c_int { let mut ret: libc::c_int = 0 as libc::c_int; let mut stmt: *mut sqlite3_stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT COUNT(*) FROM chats WHERE blocked=0 AND archived=1;\0" as *const u8 as *const libc::c_char, ); if sqlite3_step(stmt) == 100 as libc::c_int { ret = sqlite3_column_int(stmt, 0 as libc::c_int); } sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/c/dc_imex.c
static int export_key_to_asc_file(dc_context_t* context, const char* dir, int id, const dc_key_t* key, int is_default) { int success = 0; char* file_name = NULL; if (is_default) { file_name = dc_mprintf("%s/%s-key-default.asc", dir, key->type==DC_KEY_PUBLIC? "public" : "private"); } else { file_name = dc_mprintf("%s/%s-key-%i.asc", dir, key->type==DC_KEY_PUBLIC? "public" : "private", id); } dc_log_info(context, 0, "Exporting key %s", file_name); dc_delete_file(context, file_name); if (!dc_key_render_asc_to_file(key, file_name, context)) { dc_log_error(context, 0, "Cannot write key to %s", file_name); goto cleanup; } context->cb(context, DC_EVENT_IMEX_FILE_WRITTEN, (uintptr_t)file_name, 0); success = 1; cleanup: free(file_name); return success; }
projects/deltachat-core/rust/imex.rs
async fn export_key_to_asc_file<T>( context: &Context, dir: &Path, id: Option<i64>, key: &T, ) -> Result<()> where T: DcKey + Any, { let file_name = { let any_key = key as &dyn Any; let kind = if any_key.downcast_ref::<SignedPublicKey>().is_some() { "public" } else if any_key.downcast_ref::<SignedSecretKey>().is_some() { "private" } else { "unknown" }; let id = id.map_or("default".into(), |i| i.to_string()); dir.join(format!("{}-key-{}.asc", kind, &id)) }; info!( context, "Exporting key {:?} to {}", key.key_id(), file_name.display() ); // Delete the file if it already exists. delete_file(context, &file_name).await.ok(); let content = key.to_asc(None).into_bytes(); write_file(context, &file_name, &content) .await .with_context(|| format!("cannot write key to {}", file_name.display()))?; context.emit_event(EventType::ImexFileWritten(file_name)); Ok(()) }
pub(crate) async fn write_file( context: &Context, path: impl AsRef<Path>, buf: &[u8], ) -> Result<(), io::Error> { let path_abs = get_abs_path(context, path.as_ref()); fs::write(&path_abs, buf).await.map_err(|err| { warn!( context, "Cannot write {} bytes to \"{}\": {}", buf.len(), path.as_ref().display(), err ); err }) } pub fn emit_event(&self, event: EventType) { { let lock = self.debug_logging.read().expect("RwLock is poisoned"); if let Some(debug_logging) = &*lock { debug_logging.log_event(event.clone()); } } self.events.emit(Event { id: self.id, typ: event, }); } fn to_asc(&self, header: Option<(&str, &str)>) -> String { // Not using .to_armored_string() to make clear *why* it is // safe to do these unwraps. // Because we write to a Vec<u8> the io::Write impls never // fail and we can hide this error. The string is always ASCII. let headers = header.map(|(key, value)| { let mut m = BTreeMap::new(); m.insert(key.to_string(), value.to_string()); m }); let mut buf = Vec::new(); self.to_armored_writer(&mut buf, headers.as_ref()) .unwrap_or_default(); std::string::String::from_utf8(buf).unwrap_or_default() } macro_rules! info { ($ctx:expr, $msg:expr) => { info!($ctx, $msg,) }; ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{ let formatted = format!($msg, $($args),*); let full = format!("{file}:{line}: {msg}", file = file!(), line = line!(), msg = &formatted); $ctx.emit_event($crate::EventType::Info(full)); }}; } pub(crate) async fn delete_file(context: &Context, path: impl AsRef<Path>) -> Result<()> { let path = path.as_ref(); let path_abs = get_abs_path(context, path); if !path_abs.exists() { bail!("path {} does not exist", path_abs.display()); } if !path_abs.is_file() { warn!(context, "refusing to delete non-file {}.", path.display()); bail!("not a file: \"{}\"", path.display()); } let dpath = format!("{}", path.to_string_lossy()); fs::remove_file(path_abs) .await .with_context(|| format!("cannot delete {dpath:?}"))?; context.emit_event(EventType::DeletedBlobFile(dpath)); Ok(()) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub enum EventType { /// The library-user may write an informational string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Info(String), /// Emitted when SMTP connection is established and login was successful. SmtpConnected(String), /// Emitted when IMAP connection is established and login was successful. ImapConnected(String), /// Emitted when a message was successfully sent to the SMTP server. SmtpMessageSent(String), /// Emitted when an IMAP message has been marked as deleted ImapMessageDeleted(String), /// Emitted when an IMAP message has been moved ImapMessageMoved(String), /// Emitted before going into IDLE on the Inbox folder. ImapInboxIdle, /// Emitted when an new file in the $BLOBDIR was created NewBlobFile(String), /// Emitted when an file in the $BLOBDIR was deleted DeletedBlobFile(String), /// The library-user should write a warning string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Warning(String), /// The library-user should report an error to the end-user. /// /// As most things are asynchronous, things may go wrong at any time and the user /// should not be disturbed by a dialog or so. Instead, use a bubble or so. /// /// However, for ongoing processes (eg. configure()) /// or for functions that are expected to fail (eg. dc_continue_key_transfer()) /// it might be better to delay showing these events until the function has really /// failed (returned false). It should be sufficient to report only the *last* error /// in a messasge box then. Error(String), /// An action cannot be performed because the user is not in the group. /// Reported eg. after a call to /// dc_set_chat_name(), dc_set_chat_profile_image(), /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(), /// dc_send_text_msg() or another sending function. ErrorSelfNotInGroup(String), /// Messages or chats changed. One or more messages or chats changed for various /// reasons in the database: /// - Messages sent, received or removed /// - Chats created, deleted or archived /// - A draft has been set /// MsgsChanged { /// Set if only a single chat is affected by the changes, otherwise 0. chat_id: ChatId, /// Set if only a single message is affected by the changes, otherwise 0. msg_id: MsgId, }, /// Reactions for the message changed. ReactionsChanged { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message for which reactions were changed. msg_id: MsgId, /// ID of the contact whose reaction set is changed. contact_id: ContactId, }, /// There is a fresh message. Typically, the user will show an notification /// when receiving this message. /// /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event. IncomingMsg { /// ID of the chat where the message is assigned. chat_id: ChatId, /// ID of the message. msg_id: MsgId, }, /// Downloading a bunch of messages just finished. IncomingMsgBunch, /// Messages were seen or noticed. /// chat id is always set. MsgsNoticed(ChatId), /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state(). MsgDelivered { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was successfully sent. msg_id: MsgId, }, /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_FAILED, see dc_msg_get_state(). MsgFailed { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that could not be sent. msg_id: MsgId, }, /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state(). MsgRead { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was read. msg_id: MsgId, }, /// A single message was deleted. /// /// This event means that the message will no longer appear in the messagelist. /// UI should remove the message from the messagelist /// in response to this event if the message is currently displayed. /// /// The message may have been explicitly deleted by the user or expired. /// Internally the message may have been removed from the database, /// moved to the trash chat or hidden. /// /// This event does not indicate the message /// deletion from the server. MsgDeleted { /// ID of the chat where the message was prior to deletion. /// Never 0 or trash chat. chat_id: ChatId, /// ID of the deleted message. Never 0. msg_id: MsgId, }, /// Chat changed. The name or the image of a chat group was changed or members were added or removed. /// Or the verify state of a chat has changed. /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat() /// and dc_remove_contact_from_chat(). /// /// This event does not include ephemeral timer modification, which /// is a separate event. ChatModified(ChatId), /// Chat ephemeral timer changed. ChatEphemeralTimerModified { /// Chat ID. chat_id: ChatId, /// New ephemeral timer value. timer: EphemeralTimer, }, /// Contact(s) created, renamed, blocked, deleted or changed their "recently seen" status. /// /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected. ContactsChanged(Option<ContactId>), /// Location of one or more contact has changed. /// /// @param data1 (u32) contact_id of the contact for which the location has changed. /// If the locations of several contacts have been changed, /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`. LocationChanged(Option<ContactId>), /// Inform about the configuration progress started by configure(). ConfigureProgress { /// Progress. /// /// 0=error, 1-999=progress in permille, 1000=success and done progress: usize, /// Progress comment or error, something to display to the user. comment: Option<String>, }, /// Inform about the import/export progress started by imex(). /// /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done /// @param data2 0 ImexProgress(usize), /// A file has been exported. A file has been written by imex(). /// This event may be sent multiple times by a single call to imex(). /// /// A typical purpose for a handler of this event may be to make the file public to some system /// services. /// /// @param data2 0 ImexFileWritten(PathBuf), /// Progress information of a secure-join handshake from the view of the inviter /// (Alice, the person who shows the QR code). /// /// These events are typically sent after a joiner has scanned the QR code /// generated by dc_get_securejoin_qr(). SecurejoinInviterProgress { /// ID of the contact that wants to join. contact_id: ContactId, /// Progress as: /// 300=vg-/vc-request received, typically shown as "bob@addr joins". /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as "bob@addr verified". /// 800=contact added to chat, shown as "bob@addr securely joined GROUP". Only for the verified-group-protocol. /// 1000=Protocol finished for this contact. progress: usize, }, /// Progress information of a secure-join handshake from the view of the joiner /// (Bob, the person who scans the QR code). /// The events are typically sent while dc_join_securejoin(), which /// may take some time, is executed. SecurejoinJoinerProgress { /// ID of the inviting contact. contact_id: ContactId, /// Progress as: /// 400=vg-/vc-request-with-auth sent, typically shown as "alice@addr verified, introducing myself." /// (Bob has verified alice and waits until Alice does the same for him) /// 1000=vg-member-added/vc-contact-confirm received progress: usize, }, /// The connectivity to the server changed. /// This means that you should refresh the connectivity view /// and possibly the connectivtiy HTML; see dc_get_connectivity() and /// dc_get_connectivity_html() for details. ConnectivityChanged, /// The user's avatar changed. /// Deprecated by `ConfigSynced`. SelfavatarChanged, /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For /// uniformity this is emitted on the source device too. The value isn't here, otherwise it /// would be logged which might not be good for privacy. ConfigSynced { /// Configuration key. key: Config, }, /// Webxdc status update received. WebxdcStatusUpdate { /// Message ID. msg_id: MsgId, /// Status update ID. status_update_serial: StatusUpdateSerial, }, /// Data received over an ephemeral peer channel. WebxdcRealtimeData { /// Message ID. msg_id: MsgId, /// Realtime data. data: Vec<u8>, }, /// Inform that a message containing a webxdc instance has been deleted. WebxdcInstanceDeleted { /// ID of the deleted message. msg_id: MsgId, }, /// Tells that the Background fetch was completed (or timed out). /// This event acts as a marker, when you reach this event you can be sure /// that all events emitted during the background fetch were processed. /// /// This event is only emitted by the account manager AccountsBackgroundFetchDone, /// Inform that set of chats or the order of the chats in the chatlist has changed. /// /// Sometimes this is emitted together with `UIChatlistItemChanged`. ChatlistChanged, /// Inform that a single chat list item changed and needs to be rerendered. /// If `chat_id` is set to None, then all currently visible chats need to be rerendered, and all not-visible items need to be cleared from cache if the UI has a cache. ChatlistItemChanged { /// ID of the changed chat chat_id: Option<ChatId>, }, /// Event for using in tests, e.g. as a fence between normally generated events. #[cfg(test)] Test, /// Inform than some events have been skipped due to event channel overflow. EventChannelOverflow { /// Number of events skipped. n: u64, }, }
use std::any::Any; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use ::pgp::types::KeyTrait; use anyhow::{bail, ensure, format_err, Context as _, Result}; use deltachat_contact_tools::EmailAddress; use futures::StreamExt; use futures_lite::FutureExt; use rand::{thread_rng, Rng}; use tokio::fs::{self, File}; use tokio_tar::Archive; use crate::blob::{BlobDirContents, BlobObject}; use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId}; use crate::config::Config; use crate::contact::ContactId; use crate::context::Context; use crate::e2ee; use crate::events::EventType; use crate::key::{ self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey, }; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::pgp; use crate::sql; use crate::stock_str; use crate::tools::{ create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file, }; use transfer::{get_backup, BackupProvider}; use std::time::Duration; use ::pgp::armor::BlockType; use tokio::task; use super::*; use crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE}; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::{alice_keypair, TestContext, TestContextManager};
projects__deltachat-core__rust__imex__.rs__function__20.txt
unsafe extern "C" fn export_key_to_asc_file( mut context: *mut dc_context_t, mut dir: *const libc::c_char, mut id: libc::c_int, mut key: *const dc_key_t, mut is_default: libc::c_int, ) -> libc::c_int { let mut success: libc::c_int = 0 as libc::c_int; let mut file_name: *mut libc::c_char = 0 as *mut libc::c_char; if is_default != 0 { file_name = dc_mprintf( b"%s/%s-key-default.asc\0" as *const u8 as *const libc::c_char, dir, if (*key).type_0 == 0 as libc::c_int { b"public\0" as *const u8 as *const libc::c_char } else { b"private\0" as *const u8 as *const libc::c_char }, ); } else { file_name = dc_mprintf( b"%s/%s-key-%i.asc\0" as *const u8 as *const libc::c_char, dir, if (*key).type_0 == 0 as libc::c_int { b"public\0" as *const u8 as *const libc::c_char } else { b"private\0" as *const u8 as *const libc::c_char }, id, ); } dc_log_info( context, 0 as libc::c_int, b"Exporting key %s\0" as *const u8 as *const libc::c_char, file_name, ); dc_delete_file(context, file_name); if dc_key_render_asc_to_file(key, file_name, context) == 0 { dc_log_error( context, 0 as libc::c_int, b"Cannot write key to %s\0" as *const u8 as *const libc::c_char, file_name, ); } else { ((*context).cb) .expect( "non-null function pointer", )( context, 2052 as libc::c_int, file_name as uintptr_t, 0 as libc::c_int as uintptr_t, ); success = 1 as libc::c_int; } free(file_name as *mut libc::c_void); return success; }
projects/deltachat-core/c/dc_imex.c
char* dc_render_setup_file(dc_context_t* context, const char* passphrase) { sqlite3_stmt* stmt = NULL; char* self_addr = NULL; dc_key_t* curr_private_key = dc_key_new(); char passphrase_begin[8]; char* encr_string = NULL; char* ret_setupfilecontent = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || passphrase==NULL || strlen(passphrase)<2 || curr_private_key==NULL) { goto cleanup; } strncpy(passphrase_begin, passphrase, 2); passphrase_begin[2] = 0; /* create the payload */ if (!dc_ensure_secret_key_exists(context)) { goto cleanup; } { self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", NULL); dc_key_load_self_private(curr_private_key, self_addr, context->sql); int e2ee_enabled = dc_sqlite3_get_config_int(context->sql, "e2ee_enabled", DC_E2EE_DEFAULT_ENABLED); char* payload_key_asc = dc_key_render_asc(curr_private_key, e2ee_enabled? "Autocrypt-Prefer-Encrypt: mutual\r\n" : NULL); if (payload_key_asc==NULL) { goto cleanup; } if(!dc_pgp_symm_encrypt(context, passphrase, payload_key_asc, strlen(payload_key_asc), &encr_string)) { goto cleanup; } free(payload_key_asc); } /* add additional header to armored block */ #define LINEEND "\r\n" /* use the same lineends as the PGP armored data */ { char* replacement = dc_mprintf("-----BEGIN PGP MESSAGE-----" LINEEND "Passphrase-Format: numeric9x4" LINEEND "Passphrase-Begin: %s", passphrase_begin); dc_str_replace(&encr_string, "-----BEGIN PGP MESSAGE-----", replacement); free(replacement); } /* wrap HTML-commands with instructions around the encrypted payload */ { char* setup_message_title = dc_stock_str(context, DC_STR_AC_SETUP_MSG_SUBJECT); char* setup_message_body = dc_stock_str(context, DC_STR_AC_SETUP_MSG_BODY); dc_str_replace(&setup_message_body, "\r", NULL); dc_str_replace(&setup_message_body, "\n", "<br>"); ret_setupfilecontent = dc_mprintf( "<!DOCTYPE html>" LINEEND "<html>" LINEEND "<head>" LINEEND "<title>%s</title>" LINEEND "</head>" LINEEND "<body>" LINEEND "<h1>%s</h1>" LINEEND "<p>%s</p>" LINEEND "<pre>" LINEEND "%s" LINEEND "</pre>" LINEEND "</body>" LINEEND "</html>" LINEEND, setup_message_title, setup_message_title, setup_message_body, encr_string); free(setup_message_title); free(setup_message_body); } cleanup: sqlite3_finalize(stmt); dc_key_unref(curr_private_key); free(encr_string); free(self_addr); return ret_setupfilecontent; }
projects/deltachat-core/rust/imex.rs
pub async fn render_setup_file(context: &Context, passphrase: &str) -> Result<String> { let passphrase_begin = if let Some(passphrase_begin) = passphrase.get(..2) { passphrase_begin } else { bail!("Passphrase must be at least 2 chars long."); }; let private_key = load_self_secret_key(context).await?; let ac_headers = match context.get_config_bool(Config::E2eeEnabled).await? { false => None, true => Some(("Autocrypt-Prefer-Encrypt", "mutual")), }; let private_key_asc = private_key.to_asc(ac_headers); let encr = pgp::symm_encrypt(passphrase, private_key_asc.as_bytes()) .await? .replace('\n', "\r\n"); let replacement = format!( concat!( "-----BEGIN PGP MESSAGE-----\r\n", "Passphrase-Format: numeric9x4\r\n", "Passphrase-Begin: {}" ), passphrase_begin ); let pgp_msg = encr.replace("-----BEGIN PGP MESSAGE-----", &replacement); let msg_subj = stock_str::ac_setup_msg_subject(context).await; let msg_body = stock_str::ac_setup_msg_body(context).await; let msg_body_html = msg_body.replace('\r', "").replace('\n', "<br>"); Ok(format!( concat!( "<!DOCTYPE html>\r\n", "<html>\r\n", " <head>\r\n", " <title>{}</title>\r\n", " </head>\r\n", " <body>\r\n", " <h1>{}</h1>\r\n", " <p>{}</p>\r\n", " <pre>\r\n{}\r\n</pre>\r\n", " </body>\r\n", "</html>\r\n" ), msg_subj, msg_subj, msg_body_html, pgp_msg )) }
pub fn get(&self, key: Param) -> Option<&str> { self.inner.get(&key).map(|s| s.as_str()) } pub async fn get_config_bool(&self, key: Config) -> Result<bool> { Ok(self.get_config_bool_opt(key).await?.unwrap_or_default()) } pub(crate) async fn load_self_secret_key(context: &Context) -> Result<SignedSecretKey> { let private_key = context .sql .query_row_optional( "SELECT private_key FROM keypairs WHERE id=(SELECT value FROM config WHERE keyname='key_id')", (), |row| { let bytes: Vec<u8> = row.get(0)?; Ok(bytes) }, ) .await?; match private_key { Some(bytes) => SignedSecretKey::from_slice(&bytes), None => { let keypair = generate_keypair(context).await?; Ok(keypair.secret) } } } pub(crate) async fn ac_setup_msg_subject(context: &Context) -> String { translated(context, StockMessage::AcSetupMsgSubject).await } pub(crate) async fn ac_setup_msg_body(context: &Context) -> String { translated(context, StockMessage::AcSetupMsgBody).await } pub async fn symm_encrypt(passphrase: &str, plain: &[u8]) -> Result<String> { let lit_msg = Message::new_literal_bytes("", plain); let passphrase = passphrase.to_string(); tokio::task::spawn_blocking(move || { let mut rng = thread_rng(); let s2k = StringToKey::new_default(&mut rng); let msg = lit_msg.encrypt_with_password(&mut rng, s2k, SYMMETRIC_KEY_ALGORITHM, || passphrase)?; let encoded_msg = msg.to_armored_string(None)?; Ok(encoded_msg) }) .await? } fn to_asc(&self, header: Option<(&str, &str)>) -> String { // Not using .to_armored_string() to make clear *why* it is // safe to do these unwraps. // Because we write to a Vec<u8> the io::Write impls never // fail and we can hide this error. The string is always ASCII. let headers = header.map(|(key, value)| { let mut m = BTreeMap::new(); m.insert(key.to_string(), value.to_string()); m }); let mut buf = Vec::new(); self.to_armored_writer(&mut buf, headers.as_ref()) .unwrap_or_default(); std::string::String::from_utf8(buf).unwrap_or_default() } pub enum Config { /// Email address, used in the `From:` field. Addr, /// IMAP server hostname. MailServer, /// IMAP server username. MailUser, /// IMAP server password. MailPw, /// IMAP server port. MailPort, /// IMAP server security (e.g. TLS, STARTTLS). MailSecurity, /// How to check IMAP server TLS certificates. ImapCertificateChecks, /// SMTP server hostname. SendServer, /// SMTP server username. SendUser, /// SMTP server password. SendPw, /// SMTP server port. SendPort, /// SMTP server security (e.g. TLS, STARTTLS). SendSecurity, /// How to check SMTP server TLS certificates. SmtpCertificateChecks, /// Whether to use OAuth 2. /// /// Historically contained other bitflags, which are now deprecated. /// Should not be extended in the future, create new config keys instead. ServerFlags, /// True if SOCKS5 is enabled. /// /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration. Socks5Enabled, /// SOCKS5 proxy server hostname or address. Socks5Host, /// SOCKS5 proxy server port. Socks5Port, /// SOCKS5 proxy server username. Socks5User, /// SOCKS5 proxy server password. Socks5Password, /// Own name to use in the `From:` field when sending messages. Displayname, /// Own status to display, sent in message footer. Selfstatus, /// Own avatar filename. Selfavatar, /// Send BCC copy to self. /// /// Should be enabled for multidevice setups. #[strum(props(default = "1"))] BccSelf, /// True if encryption is preferred according to Autocrypt standard. #[strum(props(default = "1"))] E2eeEnabled, /// True if Message Delivery Notifications (read receipts) should /// be sent and requested. #[strum(props(default = "1"))] MdnsEnabled, /// True if "Sent" folder should be watched for changes. #[strum(props(default = "0"))] SentboxWatch, /// True if chat messages should be moved to a separate folder. #[strum(props(default = "1"))] MvboxMove, /// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only. /// /// This will not entirely disable other folders, e.g. the spam folder will also still /// be watched for new messages. #[strum(props(default = "0"))] OnlyFetchMvbox, /// Whether to show classic emails or only chat messages. #[strum(props(default = "2"))] // also change ShowEmails.default() on changes ShowEmails, /// Quality of the media files to send. #[strum(props(default = "0"))] // also change MediaQuality.default() on changes MediaQuality, /// If set to "1", on the first time `start_io()` is called after configuring, /// the newest existing messages are fetched. /// Existing recipients are added to the contact database regardless of this setting. #[strum(props(default = "0"))] FetchExistingMsgs, /// If set to "1", then existing messages are considered to be already fetched. /// This flag is reset after successful configuration. #[strum(props(default = "1"))] FetchedExistingMsgs, /// Type of the OpenPGP key to generate. #[strum(props(default = "0"))] KeyGenType, /// Timer in seconds after which the message is deleted from the /// server. /// /// Equals to 0 by default, which means the message is never /// deleted. /// /// Value 1 is treated as "delete at once": messages are deleted /// immediately, without moving to DeltaChat folder. #[strum(props(default = "0"))] DeleteServerAfter, /// Timer in seconds after which the message is deleted from the /// device. /// /// Equals to 0 by default, which means the message is never /// deleted. #[strum(props(default = "0"))] DeleteDeviceAfter, /// Move messages to the Trash folder instead of marking them "\Deleted". Overrides /// `ProviderOptions::delete_to_trash`. DeleteToTrash, /// Save raw MIME messages with headers in the database if true. SaveMimeHeaders, /// The primary email address. Also see `SecondaryAddrs`. ConfiguredAddr, /// Configured IMAP server hostname. ConfiguredMailServer, /// Configured IMAP server username. ConfiguredMailUser, /// Configured IMAP server password. ConfiguredMailPw, /// Configured IMAP server port. ConfiguredMailPort, /// Configured IMAP server security (e.g. TLS, STARTTLS). ConfiguredMailSecurity, /// How to check IMAP server TLS certificates. ConfiguredImapCertificateChecks, /// Configured SMTP server hostname. ConfiguredSendServer, /// Configured SMTP server username. ConfiguredSendUser, /// Configured SMTP server password. ConfiguredSendPw, /// Configured SMTP server port. ConfiguredSendPort, /// How to check SMTP server TLS certificates. ConfiguredSmtpCertificateChecks, /// Whether OAuth 2 is used with configured provider. ConfiguredServerFlags, /// Configured SMTP server security (e.g. TLS, STARTTLS). ConfiguredSendSecurity, /// Configured folder for incoming messages. ConfiguredInboxFolder, /// Configured folder for chat messages. ConfiguredMvboxFolder, /// Configured "Sent" folder. ConfiguredSentboxFolder, /// Configured "Trash" folder. ConfiguredTrashFolder, /// Unix timestamp of the last successful configuration. ConfiguredTimestamp, /// ID of the configured provider from the provider database. ConfiguredProvider, /// True if account is configured. Configured, /// True if account is a chatmail account. IsChatmail, /// All secondary self addresses separated by spaces /// (`[email protected] [email protected] [email protected]`) SecondaryAddrs, /// Read-only core version string. #[strum(serialize = "sys.version")] SysVersion, /// Maximal recommended attachment size in bytes. #[strum(serialize = "sys.msgsize_max_recommended")] SysMsgsizeMaxRecommended, /// Space separated list of all config keys available. #[strum(serialize = "sys.config_keys")] SysConfigKeys, /// True if it is a bot account. Bot, /// True when to skip initial start messages in groups. #[strum(props(default = "0"))] SkipStartMessages, /// Whether we send a warning if the password is wrong (set to false when we send a warning /// because we do not want to send a second warning) #[strum(props(default = "0"))] NotifyAboutWrongPw, /// If a warning about exceeding quota was shown recently, /// this is the percentage of quota at the time the warning was given. /// Unset, when quota falls below minimal warning threshold again. QuotaExceeding, /// address to webrtc instance to use for videochats WebrtcInstance, /// Timestamp of the last time housekeeping was run LastHousekeeping, /// Timestamp of the last `CantDecryptOutgoingMsgs` notification. LastCantDecryptOutgoingMsgs, /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely. #[strum(props(default = "60"))] ScanAllFoldersDebounceSecs, /// Whether to avoid using IMAP IDLE even if the server supports it. /// /// This is a developer option for testing "fake idle". #[strum(props(default = "0"))] DisableIdle, /// Defines the max. size (in bytes) of messages downloaded automatically. /// 0 = no limit. #[strum(props(default = "0"))] DownloadLimit, /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set. #[strum(props(default = "1"))] SyncMsgs, /// Space-separated list of all the authserv-ids which we believe /// may be the one of our email server. /// /// See `crate::authres::update_authservid_candidates`. AuthservIdCandidates, /// Make all outgoing messages with Autocrypt header "multipart/signed". SignUnencrypted, /// Let the core save all events to the database. /// This value is used internally to remember the MsgId of the logging xdc #[strum(props(default = "0"))] DebugLogging, /// Last message processed by the bot. LastMsgId, /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by /// default. /// /// This is not supposed to be changed by UIs and only used for testing. #[strum(props(default = "172800"))] GossipPeriod, /// Feature flag for verified 1:1 chats; the UI should set it /// to 1 if it supports verified 1:1 chats. /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified, /// and when the key changes, an info message is posted into the chat. /// 0=Nothing else happens when the key changes. /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true /// until `chat_id.accept()` is called. #[strum(props(default = "0"))] VerifiedOneOnOneChats, /// Row ID of the key in the `keypairs` table /// 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 /// without storing the email address SelfReportingId, /// MsgId of webxdc map integration. WebxdcIntegration, /// Iroh secret key. IrohSecretKey, } pub struct Context { pub(crate) inner: Arc<InnerContext>, }
use std::any::Any; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use ::pgp::types::KeyTrait; use anyhow::{bail, ensure, format_err, Context as _, Result}; use deltachat_contact_tools::EmailAddress; use futures::StreamExt; use futures_lite::FutureExt; use rand::{thread_rng, Rng}; use tokio::fs::{self, File}; use tokio_tar::Archive; use crate::blob::{BlobDirContents, BlobObject}; use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId}; use crate::config::Config; use crate::contact::ContactId; use crate::context::Context; use crate::e2ee; use crate::events::EventType; use crate::key::{ self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey, }; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::pgp; use crate::sql; use crate::stock_str; use crate::tools::{ create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file, }; use transfer::{get_backup, BackupProvider}; use std::time::Duration; use ::pgp::armor::BlockType; use tokio::task; use super::*; use crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE}; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::{alice_keypair, TestContext, TestContextManager};
projects__deltachat-core__rust__imex__.rs__function__4.txt
pub unsafe extern "C" fn dc_render_setup_file( mut context: *mut dc_context_t, mut passphrase: *const libc::c_char, ) -> *mut libc::c_char { let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; let mut self_addr: *mut libc::c_char = 0 as *mut libc::c_char; let mut curr_private_key: *mut dc_key_t = dc_key_new(); let mut passphrase_begin: [libc::c_char; 8] = [0; 8]; let mut encr_string: *mut libc::c_char = 0 as *mut libc::c_char; let mut ret_setupfilecontent: *mut libc::c_char = 0 as *mut libc::c_char; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || passphrase.is_null() || strlen(passphrase) < 2 as libc::c_int as libc::c_ulong || curr_private_key.is_null()) { strncpy( passphrase_begin.as_mut_ptr(), passphrase, 2 as libc::c_int as libc::c_ulong, ); passphrase_begin[2 as libc::c_int as usize] = 0 as libc::c_int as libc::c_char; if !(dc_ensure_secret_key_exists(context) == 0) { self_addr = dc_sqlite3_get_config( (*context).sql, b"configured_addr\0" as *const u8 as *const libc::c_char, 0 as *const libc::c_char, ); dc_key_load_self_private(curr_private_key, self_addr, (*context).sql); let mut e2ee_enabled: libc::c_int = dc_sqlite3_get_config_int( (*context).sql, b"e2ee_enabled\0" as *const u8 as *const libc::c_char, 1 as libc::c_int, ); let mut payload_key_asc: *mut libc::c_char = dc_key_render_asc( curr_private_key, if e2ee_enabled != 0 { b"Autocrypt-Prefer-Encrypt: mutual\r\n\0" as *const u8 as *const libc::c_char } else { 0 as *const libc::c_char }, ); if !payload_key_asc.is_null() { if !(dc_pgp_symm_encrypt( context, passphrase, payload_key_asc as *const libc::c_void, strlen(payload_key_asc), &mut encr_string, ) == 0) { free(payload_key_asc as *mut libc::c_void); let mut replacement: *mut libc::c_char = dc_mprintf( b"-----BEGIN PGP MESSAGE-----\r\nPassphrase-Format: numeric9x4\r\nPassphrase-Begin: %s\0" as *const u8 as *const libc::c_char, passphrase_begin.as_mut_ptr(), ); dc_str_replace( &mut encr_string, b"-----BEGIN PGP MESSAGE-----\0" as *const u8 as *const libc::c_char, replacement, ); free(replacement as *mut libc::c_void); let mut setup_message_title: *mut libc::c_char = dc_stock_str( context, 42 as libc::c_int, ); let mut setup_message_body: *mut libc::c_char = dc_stock_str( context, 43 as libc::c_int, ); dc_str_replace( &mut setup_message_body, b"\r\0" as *const u8 as *const libc::c_char, 0 as *const libc::c_char, ); dc_str_replace( &mut setup_message_body, b"\n\0" as *const u8 as *const libc::c_char, b"<br>\0" as *const u8 as *const libc::c_char, ); ret_setupfilecontent = dc_mprintf( b"<!DOCTYPE html>\r\n<html>\r\n<head>\r\n<title>%s</title>\r\n</head>\r\n<body>\r\n<h1>%s</h1>\r\n<p>%s</p>\r\n<pre>\r\n%s\r\n</pre>\r\n</body>\r\n</html>\r\n\0" as *const u8 as *const libc::c_char, setup_message_title, setup_message_title, setup_message_body, encr_string, ); free(setup_message_title as *mut libc::c_void); free(setup_message_body as *mut libc::c_void); } } } } sqlite3_finalize(stmt); dc_key_unref(curr_private_key); free(encr_string as *mut libc::c_void); free(self_addr as *mut libc::c_void); return ret_setupfilecontent; }
projects/deltachat-core/c/dc_chat.c
uint32_t dc_chat_get_color(const dc_chat_t* chat) { uint32_t color = 0; dc_array_t* contacts = NULL; dc_contact_t* contact = NULL; if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { goto cleanup; } if(chat->type==DC_CHAT_TYPE_SINGLE) { contacts = dc_get_chat_contacts(chat->context, chat->id); if (contacts->count >= 1) { contact = dc_get_contact(chat->context, contacts->array[0]); color = dc_str_to_color(contact->addr); } } else { color = dc_str_to_color(chat->name); } cleanup: dc_array_unref(contacts); dc_contact_unref(contact); return color; }
projects/deltachat-core/rust/chat.rs
pub async fn get_color(&self, context: &Context) -> Result<u32> { let mut color = 0; if self.typ == Chattype::Single { let contacts = get_chat_contacts(context, self.id).await?; if let Some(contact_id) = contacts.first() { if let Ok(contact) = Contact::get_by_id(context, *contact_id).await { color = contact.get_color(); } } } else { color = str_to_color(&self.name); } Ok(color) }
pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> { // Normal chats do not include SELF. Group chats do (as it may happen that one is deleted from a // groupchat but the chats stays visible, moreover, this makes displaying lists easier) let list = context .sql .query_map( "SELECT cc.contact_id FROM chats_contacts cc LEFT JOIN contacts c ON c.id=cc.contact_id WHERE cc.chat_id=? ORDER BY c.id=1, c.last_seen DESC, c.id DESC;", (chat_id,), |row| row.get::<_, ContactId>(0), |ids| ids.collect::<Result<Vec<_>, _>>().map_err(Into::into), ) .await?; Ok(list) } pub async fn get_by_id(context: &Context, contact_id: ContactId) -> Result<Self> { let contact = Self::get_by_id_optional(context, contact_id) .await? .with_context(|| format!("contact {contact_id} not found"))?; Ok(contact) } pub fn get_color(&self) -> u32 { str_to_color(&self.addr.to_lowercase()) } pub fn str_to_color(s: &str) -> u32 { rgb_to_u32(hsluv_to_rgb((str_to_angle(s), 100.0, 50.0))) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct Chat { /// Database ID. pub id: ChatId, /// Chat type, e.g. 1:1 chat, group chat, mailing list. pub typ: Chattype, /// Chat name. pub name: String, /// Whether the chat is archived or pinned. pub visibility: ChatVisibility, /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and /// ad-hoc groups. pub grpid: String, /// Whether the chat is blocked, unblocked or a contact request. pub blocked: Blocked, /// Additional chat parameters stored in the database. pub param: Params, /// If location streaming is enabled in the chat. is_sending_locations: bool, /// Duration of the chat being muted. pub mute_duration: MuteDuration, /// If the chat is protected (verified). pub(crate) protected: ProtectionStatus, } pub enum Chattype { /// 1:1 chat. Single = 100, /// Group chat. Group = 120, /// Mailing list. Mailinglist = 140, /// Broadcast list. Broadcast = 160, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__74.txt
pub unsafe extern "C" fn dc_chat_get_color(mut chat: *const dc_chat_t) -> uint32_t { let mut color: uint32_t = 0 as libc::c_int as uint32_t; let mut contacts: *mut dc_array_t = 0 as *mut dc_array_t; let mut contact: *mut dc_contact_t = 0 as *mut dc_contact_t; if !(chat.is_null() || (*chat).magic != 0xc4a7c4a7 as libc::c_uint) { if (*chat).type_0 == 100 as libc::c_int { contacts = dc_get_chat_contacts((*chat).context, (*chat).id); if (*contacts).count >= 1 as libc::c_int as libc::c_ulong { contact = dc_get_contact( (*chat).context, *((*contacts).array).offset(0 as libc::c_int as isize) as uint32_t, ); color = dc_str_to_color((*contact).addr) as uint32_t; } } else { color = dc_str_to_color((*chat).name) as uint32_t; } } dc_array_unref(contacts); dc_contact_unref(contact); return color; }
projects/deltachat-core/c/dc_qr.c
dc_lot_t* dc_check_qr(dc_context_t* context, const char* qr) { char* payload = NULL; char* addr = NULL; // must be normalized, if set char* fingerprint = NULL; // must be normalized, if set char* name = NULL; char* invitenumber = NULL; char* auth = NULL; dc_apeerstate_t* peerstate = dc_apeerstate_new(context); dc_lot_t* qr_parsed = dc_lot_new(); uint32_t chat_id = 0; char* device_msg = NULL; char* grpid = NULL; char* grpname = NULL; qr_parsed->state = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || qr==NULL) { goto cleanup; } dc_log_info(context, 0, "Scanned QR code: %s", qr); /* split parameters from the qr code*/ if (strncasecmp(qr, DC_OPENPGP4FPR_SCHEME, strlen(DC_OPENPGP4FPR_SCHEME))==0) { /* scheme: OPENPGP4FPR:FINGERPRINT#a=ADDR&n=NAME&i=INVITENUMBER&s=AUTH or: OPENPGP4FPR:FINGERPRINT#a=ADDR&g=GROUPNAME&x=GROUPID&i=INVITENUMBER&s=AUTH */ payload = dc_strdup(&qr[strlen(DC_OPENPGP4FPR_SCHEME)]); char* fragment = strchr(payload, '#'); /* must not be freed, only a pointer inside payload */ if (fragment) { *fragment = 0; fragment++; dc_param_t* param = dc_param_new(); dc_param_set_urlencoded(param, fragment); addr = dc_param_get(param, 'a', NULL); if (addr) { char* urlencoded = dc_param_get(param, 'n', NULL); if(urlencoded) { name = dc_urldecode(urlencoded); dc_normalize_name(name); free(urlencoded); } invitenumber = dc_param_get(param, 'i', NULL); auth = dc_param_get(param, 's', NULL); grpid = dc_param_get(param, 'x', NULL); if (grpid) { urlencoded = dc_param_get(param, 'g', NULL); if (urlencoded) { grpname = dc_urldecode(urlencoded); free(urlencoded); } } } dc_param_unref(param); } fingerprint = dc_normalize_fingerprint(payload); } else if (strncasecmp(qr, MAILTO_SCHEME, strlen(MAILTO_SCHEME))==0) { /* scheme: mailto:addr...?subject=...&body=... */ payload = dc_strdup(&qr[strlen(MAILTO_SCHEME)]); char* query = strchr(payload, '?'); /* must not be freed, only a pointer inside payload */ if (query) { *query = 0; } addr = dc_strdup(payload); } else if (strncasecmp(qr, SMTP_SCHEME, strlen(SMTP_SCHEME))==0) { /* scheme: `SMTP:addr...:subject...:body...` */ payload = dc_strdup(&qr[strlen(SMTP_SCHEME)]); char* colon = strchr(payload, ':'); /* must not be freed, only a pointer inside payload */ if (colon) { *colon = 0; } addr = dc_strdup(payload); } else if (strncasecmp(qr, MATMSG_SCHEME, strlen(MATMSG_SCHEME))==0) { /* scheme: `MATMSG:TO:addr...;SUB:subject...;BODY:body...;` - there may or may not be linebreaks after the fields */ char* to = strstr(qr, "TO:"); /* does not work when the text `TO:` is used in subject/body _and_ TO: is not the first field. we ignore this case. */ if (to) { addr = dc_strdup(&to[3]); char* semicolon = strchr(addr, ';'); if (semicolon) { *semicolon = 0; } } else { qr_parsed->state = DC_QR_ERROR; qr_parsed->text1 = dc_strdup("Bad e-mail address."); goto cleanup; } } else if (strncasecmp(qr, VCARD_BEGIN, strlen(VCARD_BEGIN))==0) { /* scheme: `VCARD:BEGIN\nN:last name;first name;...;\nEMAIL:addr...;` */ carray* lines = dc_split_into_lines(qr); for (int i = 0; i < carray_count(lines); i++) { char* key = (char*)carray_get(lines, i); dc_trim(key); char* value = strchr(key, ':'); if (value) { *value = 0; value++; char* semicolon = strchr(key, ';'); if (semicolon) { *semicolon = 0; } /* handle `EMAIL;type=work:` stuff */ if (strcasecmp(key, "EMAIL")==0) { semicolon = strchr(value, ';'); if (semicolon) { *semicolon = 0; } /* use the first EMAIL */ addr = dc_strdup(value); } else if (strcasecmp(key, "N")==0) { semicolon = strchr(value, ';'); if (semicolon) { semicolon = strchr(semicolon+1, ';'); if (semicolon) { *semicolon = 0; } } /* the N format is `lastname;prename;wtf;title` - skip everything after the second semicolon */ name = dc_strdup(value); dc_str_replace(&name, ";", ","); /* the format "lastname,prename" is handled by dc_normalize_name() */ dc_normalize_name(name); } } } dc_free_splitted_lines(lines); } /* check the paramters */ if (addr) { char* temp = dc_urldecode(addr); free(addr); addr = temp; /* urldecoding is needed at least for OPENPGP4FPR but should not hurt in the other cases */ temp = dc_addr_normalize(addr); free(addr); addr = temp; if (!dc_may_be_valid_addr(addr)) { qr_parsed->state = DC_QR_ERROR; qr_parsed->text1 = dc_strdup("Bad e-mail address."); goto cleanup; } } if (fingerprint) { if (strlen(fingerprint) != 40) { qr_parsed->state = DC_QR_ERROR; qr_parsed->text1 = dc_strdup("Bad fingerprint length in QR code."); goto cleanup; } } /* let's see what we can do with the parameters */ if (fingerprint) { /* fingerprint set ... */ if (addr==NULL || invitenumber==NULL || auth==NULL) { // _only_ fingerprint set ... // (we could also do this before/instead of a secure-join, however, this may require complicated questions in the ui) if (dc_apeerstate_load_by_fingerprint(peerstate, context->sql, fingerprint)) { qr_parsed->state = DC_QR_FPR_OK; qr_parsed->id = dc_add_or_lookup_contact(context, NULL, peerstate->addr, DC_ORIGIN_UNHANDLED_QR_SCAN, NULL); dc_create_or_lookup_nchat_by_contact_id(context, qr_parsed->id, DC_CHAT_DEADDROP_BLOCKED, &chat_id, NULL); device_msg = dc_mprintf("%s verified.", peerstate->addr); } else { qr_parsed->text1 = dc_format_fingerprint(fingerprint); qr_parsed->state = DC_QR_FPR_WITHOUT_ADDR; } } else { // fingerprint + addr set, secure-join requested // do not comapre the fingerprint already - it may have changed - errors are catched later more proberly. // (theroretically, there is also the state "addr=set, fingerprint=set, invitenumber=0", however, currently, we won't get into this state) if (grpid && grpname) { qr_parsed->state = DC_QR_ASK_VERIFYGROUP; qr_parsed->text1 = dc_strdup(grpname); qr_parsed->text2 = dc_strdup(grpid); } else { qr_parsed->state = DC_QR_ASK_VERIFYCONTACT; } qr_parsed->id = dc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_UNHANDLED_QR_SCAN, NULL); qr_parsed->fingerprint = dc_strdup(fingerprint); qr_parsed->invitenumber = dc_strdup(invitenumber); qr_parsed->auth = dc_strdup(auth); } } else if (addr) { qr_parsed->state = DC_QR_ADDR; qr_parsed->id = dc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_UNHANDLED_QR_SCAN, NULL); } else if (strstr(qr, "http://")==qr || strstr(qr, "https://")==qr) { qr_parsed->state = DC_QR_URL; qr_parsed->text1 = dc_strdup(qr); } else { qr_parsed->state = DC_QR_TEXT; qr_parsed->text1 = dc_strdup(qr); } if (device_msg) { dc_add_device_msg(context, chat_id, device_msg); } cleanup: free(addr); free(fingerprint); dc_apeerstate_unref(peerstate); free(payload); free(name); free(invitenumber); free(auth); free(device_msg); free(grpname); free(grpid); return qr_parsed; }
projects/deltachat-core/rust/qr.rs
pub async fn check_qr(context: &Context, qr: &str) -> Result<Qr> { let qrcode = if starts_with_ignore_case(qr, OPENPGP4FPR_SCHEME) { decode_openpgp(context, qr) .await .context("failed to decode OPENPGP4FPR QR code")? } else if qr.starts_with(IDELTACHAT_SCHEME) { decode_ideltachat(context, IDELTACHAT_SCHEME, qr).await? } else if qr.starts_with(IDELTACHAT_NOSLASH_SCHEME) { decode_ideltachat(context, IDELTACHAT_NOSLASH_SCHEME, qr).await? } else if starts_with_ignore_case(qr, DCACCOUNT_SCHEME) { decode_account(qr)? } else if starts_with_ignore_case(qr, DCLOGIN_SCHEME) { dclogin_scheme::decode_login(qr)? } else if starts_with_ignore_case(qr, DCWEBRTC_SCHEME) { decode_webrtc_instance(context, qr)? } else if starts_with_ignore_case(qr, DCBACKUP_SCHEME) { decode_backup(qr)? } else if qr.starts_with(MAILTO_SCHEME) { decode_mailto(context, qr).await? } else if qr.starts_with(SMTP_SCHEME) { decode_smtp(context, qr).await? } else if qr.starts_with(MATMSG_SCHEME) { decode_matmsg(context, qr).await? } else if qr.starts_with(VCARD_SCHEME) { decode_vcard(context, qr).await? } else if qr.starts_with(HTTP_SCHEME) || qr.starts_with(HTTPS_SCHEME) { Qr::Url { url: qr.to_string(), } } else { Qr::Text { text: qr.to_string(), } }; Ok(qrcode) }
async fn decode_mailto(context: &Context, qr: &str) -> Result<Qr> { let payload = &qr[MAILTO_SCHEME.len()..]; let (addr, query) = if let Some(query_index) = payload.find('?') { (&payload[..query_index], &payload[query_index + 1..]) } else { (payload, "") }; let param: BTreeMap<&str, &str> = query .split('&') .filter_map(|s| { if let [key, value] = s.splitn(2, '=').collect::<Vec<_>>()[..] { Some((key, value)) } else { None } }) .collect(); let subject = if let Some(subject) = param.get("subject") { subject.to_string() } else { "".to_string() }; let draft = if let Some(body) = param.get("body") { if subject.is_empty() { body.to_string() } else { subject + "\n" + body } } else { subject }; let draft = draft.replace('+', "%20"); // sometimes spaces are encoded as `+` let draft = match percent_decode_str(&draft).decode_utf8() { Ok(decoded_draft) => decoded_draft.to_string(), Err(_err) => draft, }; let addr = normalize_address(addr)?; let name = ""; Qr::from_address( context, name, &addr, if draft.is_empty() { None } else { Some(draft) }, ) .await } fn decode_backup(qr: &str) -> Result<Qr> { let payload = qr .strip_prefix(DCBACKUP_SCHEME) .ok_or_else(|| anyhow!("invalid DCBACKUP scheme"))?; let ticket: iroh::provider::Ticket = payload.parse().context("invalid DCBACKUP payload")?; Ok(Qr::Backup { ticket }) } async fn decode_matmsg(context: &Context, qr: &str) -> Result<Qr> { // Does not work when the text `TO:` is used in subject/body _and_ TO: is not the first field. // we ignore this case. let addr = if let Some(to_index) = qr.find("TO:") { let addr = qr[to_index + 3..].trim(); if let Some(semi_index) = addr.find(';') { addr[..semi_index].trim() } else { addr } } else { bail!("Invalid MATMSG found"); }; let addr = normalize_address(addr)?; let name = ""; Qr::from_address(context, name, &addr, None).await } async fn decode_smtp(context: &Context, qr: &str) -> Result<Qr> { let payload = &qr[SMTP_SCHEME.len()..]; let addr = if let Some(query_index) = payload.find(':') { &payload[..query_index] } else { bail!("Invalid SMTP found"); }; let addr = normalize_address(addr)?; let name = ""; Qr::from_address(context, name, &addr, None).await } async fn decode_vcard(context: &Context, qr: &str) -> Result<Qr> { let name = VCARD_NAME_RE .captures(qr) .and_then(|caps| { let last_name = caps.get(1)?.as_str().trim(); let first_name = caps.get(2)?.as_str().trim(); Some(format!("{first_name} {last_name}")) }) .unwrap_or_default(); let addr = if let Some(caps) = VCARD_EMAIL_RE.captures(qr) { normalize_address(caps[2].trim())? } else { bail!("Bad e-mail address"); }; Qr::from_address(context, &name, &addr, None).await } async fn decode_openpgp(context: &Context, qr: &str) -> Result<Qr> { let payload = &qr[OPENPGP4FPR_SCHEME.len()..]; // macOS and iOS sometimes replace the # with %23 (uri encode it), we should be able to parse this wrong format too. // see issue https://github.com/deltachat/deltachat-core-rust/issues/1969 for more info let (fingerprint, fragment) = match payload .split_once('#') .or_else(|| payload.split_once("%23")) { Some(pair) => pair, None => (payload, ""), }; let fingerprint: Fingerprint = fingerprint .parse() .context("Failed to parse fingerprint in the QR code")?; let param: BTreeMap<&str, &str> = fragment .split('&') .filter_map(|s| { if let [key, value] = s.splitn(2, '=').collect::<Vec<_>>()[..] { Some((key, value)) } else { None } }) .collect(); let addr = if let Some(addr) = param.get("a") { Some(normalize_address(addr)?) } else { None }; let name = if let Some(encoded_name) = param.get("n") { let encoded_name = encoded_name.replace('+', "%20"); // sometimes spaces are encoded as `+` match percent_decode_str(&encoded_name).decode_utf8() { Ok(name) => name.to_string(), Err(err) => bail!("Invalid name: {}", err), } } else { "".to_string() }; let invitenumber = param .get("i") .filter(|&s| validate_id(s)) .map(|s| s.to_string()); let authcode = param .get("s") .filter(|&s| validate_id(s)) .map(|s| s.to_string()); let grpid = param .get("x") .filter(|&s| validate_id(s)) .map(|s| s.to_string()); let grpname = if grpid.is_some() { if let Some(encoded_name) = param.get("g") { let encoded_name = encoded_name.replace('+', "%20"); // sometimes spaces are encoded as `+` match percent_decode_str(&encoded_name).decode_utf8() { Ok(name) => Some(name.to_string()), Err(err) => bail!("Invalid group name: {}", err), } } else { None } } else { None }; // retrieve known state for this fingerprint let peerstate = Peerstate::from_fingerprint(context, &fingerprint) .await .context("Can't load peerstate")?; if let (Some(addr), Some(invitenumber), Some(authcode)) = (&addr, invitenumber, authcode) { let addr = ContactAddress::new(addr)?; let (contact_id, _) = Contact::add_or_lookup(context, &name, &addr, Origin::UnhandledQrScan) .await .with_context(|| format!("failed to add or lookup contact for address {addr:?}"))?; if let (Some(grpid), Some(grpname)) = (grpid, grpname) { if context .is_self_addr(&addr) .await .with_context(|| format!("can't check if address {addr:?} is our address"))? { if token::exists(context, token::Namespace::InviteNumber, &invitenumber).await? { Ok(Qr::WithdrawVerifyGroup { grpname, grpid, contact_id, fingerprint, invitenumber, authcode, }) } else { Ok(Qr::ReviveVerifyGroup { grpname, grpid, contact_id, fingerprint, invitenumber, authcode, }) } } else { Ok(Qr::AskVerifyGroup { grpname, grpid, contact_id, fingerprint, invitenumber, authcode, }) } } else if context.is_self_addr(&addr).await? { if token::exists(context, token::Namespace::InviteNumber, &invitenumber).await? { Ok(Qr::WithdrawVerifyContact { contact_id, fingerprint, invitenumber, authcode, }) } else { Ok(Qr::ReviveVerifyContact { contact_id, fingerprint, invitenumber, authcode, }) } } else { Ok(Qr::AskVerifyContact { contact_id, fingerprint, invitenumber, authcode, }) } } else if let Some(addr) = addr { if let Some(peerstate) = peerstate { let peerstate_addr = ContactAddress::new(&peerstate.addr)?; let (contact_id, _) = Contact::add_or_lookup(context, &name, &peerstate_addr, Origin::UnhandledQrScan) .await .context("add_or_lookup")?; ChatIdBlocked::get_for_contact(context, contact_id, Blocked::Request) .await .context("Failed to create (new) chat for contact")?; Ok(Qr::FprOk { contact_id }) } else { let contact_id = Contact::lookup_id_by_addr(context, &addr, Origin::Unknown) .await .with_context(|| format!("Error looking up contact {addr:?}"))?; Ok(Qr::FprMismatch { contact_id }) } } else { Ok(Qr::FprWithoutAddr { fingerprint: fingerprint.to_string(), }) } } fn starts_with_ignore_case(string: &str, pattern: &str) -> bool { string.to_lowercase().starts_with(&pattern.to_lowercase()) } fn decode_account(qr: &str) -> Result<Qr> { let payload = qr .get(DCACCOUNT_SCHEME.len()..) .context("invalid DCACCOUNT payload")?; let url = url::Url::parse(payload).context("Invalid account URL")?; if url.scheme() == "http" || url.scheme() == "https" { Ok(Qr::Account { domain: url .host_str() .context("can't extract WebRTC instance domain")? .to_string(), }) } else { bail!("Bad scheme for account URL: {:?}.", url.scheme()); } } fn decode_webrtc_instance(_context: &Context, qr: &str) -> Result<Qr> { let payload = qr .get(DCWEBRTC_SCHEME.len()..) .context("invalid DCWEBRTC payload")?; let (_type, url) = Message::parse_webrtc_instance(payload); let url = url::Url::parse(&url).context("Invalid WebRTC instance")?; if url.scheme() == "http" || url.scheme() == "https" { Ok(Qr::WebrtcInstance { domain: url .host_str() .context("can't extract WebRTC instance domain")? .to_string(), instance_pattern: payload.to_string(), }) } else { bail!("Bad URL scheme for WebRTC instance: {:?}", url.scheme()); } } async fn decode_ideltachat(context: &Context, prefix: &str, qr: &str) -> Result<Qr> { let qr = qr.replacen(prefix, OPENPGP4FPR_SCHEME, 1); let qr = qr.replacen('&', "#", 1); decode_openpgp(context, &qr) .await .context("failed to decode {prefix} QR code") } pub struct Context { pub(crate) inner: Arc<InnerContext>, } const OPENPGP4FPR_SCHEME: &str = "OPENPGP4FPR:"; // yes: uppercase const IDELTACHAT_SCHEME: &str = "https://i.delta.chat/#"; const IDELTACHAT_NOSLASH_SCHEME: &str = "https://i.delta.chat#"; const DCACCOUNT_SCHEME: &str = "DCACCOUNT:"; pub(super) const DCLOGIN_SCHEME: &str = "DCLOGIN:"; const DCWEBRTC_SCHEME: &str = "DCWEBRTC:"; const MAILTO_SCHEME: &str = "mailto:"; const MATMSG_SCHEME: &str = "MATMSG:"; const VCARD_SCHEME: &str = "BEGIN:VCARD"; const SMTP_SCHEME: &str = "SMTP:"; const HTTP_SCHEME: &str = "http://"; const HTTPS_SCHEME: &str = "https://"; pub(crate) const DCBACKUP_SCHEME: &str = "DCBACKUP:";
use std::collections::BTreeMap; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use dclogin_scheme::LoginOptions; use deltachat_contact_tools::{addr_normalize, may_be_valid_addr, ContactAddress}; use once_cell::sync::Lazy; use percent_encoding::percent_decode_str; use serde::Deserialize; use self::dclogin_scheme::configure_from_login_qr; use crate::chat::{get_chat_id_by_grpid, ChatIdBlocked}; use crate::config::Config; use crate::constants::Blocked; use crate::contact::{Contact, ContactId, Origin}; use crate::context::Context; use crate::events::EventType; use crate::key::Fingerprint; use crate::message::Message; use crate::peerstate::Peerstate; use crate::socks::Socks5Config; use crate::token; use crate::tools::validate_id; use iroh_old as iroh; use super::*; use crate::aheader::EncryptPreference; use crate::chat::{create_group_chat, ProtectionStatus}; use crate::key::DcKey; use crate::securejoin::get_securejoin_qr; use crate::test_utils::{alice_keypair, TestContext};
projects__deltachat-core__rust__qr__.rs__function__2.txt
pub unsafe extern "C" fn dc_check_qr( mut context: *mut dc_context_t, mut qr: *const libc::c_char, ) -> *mut dc_lot_t { let mut current_block: u64; let mut payload: *mut libc::c_char = 0 as *mut libc::c_char; let mut addr: *mut libc::c_char = 0 as *mut libc::c_char; let mut fingerprint: *mut libc::c_char = 0 as *mut libc::c_char; let mut name: *mut libc::c_char = 0 as *mut libc::c_char; let mut invitenumber: *mut libc::c_char = 0 as *mut libc::c_char; let mut auth: *mut libc::c_char = 0 as *mut libc::c_char; let mut peerstate: *mut dc_apeerstate_t = dc_apeerstate_new(context); let mut qr_parsed: *mut dc_lot_t = dc_lot_new(); let mut chat_id: uint32_t = 0 as libc::c_int as uint32_t; let mut device_msg: *mut libc::c_char = 0 as *mut libc::c_char; let mut grpid: *mut libc::c_char = 0 as *mut libc::c_char; let mut grpname: *mut libc::c_char = 0 as *mut libc::c_char; (*qr_parsed).state = 0 as libc::c_int; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || qr.is_null()) { dc_log_info( context, 0 as libc::c_int, b"Scanned QR code: %s\0" as *const u8 as *const libc::c_char, qr, ); if strncasecmp( qr, b"OPENPGP4FPR:\0" as *const u8 as *const libc::c_char, strlen(b"OPENPGP4FPR:\0" as *const u8 as *const libc::c_char), ) == 0 as libc::c_int { payload = dc_strdup( &*qr .offset( (strlen as unsafe extern "C" fn( *const libc::c_char, ) -> libc::c_ulong)( b"OPENPGP4FPR:\0" as *const u8 as *const libc::c_char, ) as isize, ), ); let mut fragment: *mut libc::c_char = strchr(payload, '#' as i32); if !fragment.is_null() { *fragment = 0 as libc::c_int as libc::c_char; fragment = fragment.offset(1); fragment; let mut param: *mut dc_param_t = dc_param_new(); dc_param_set_urlencoded(param, fragment); addr = dc_param_get(param, 'a' as i32, 0 as *const libc::c_char); if !addr.is_null() { let mut urlencoded: *mut libc::c_char = dc_param_get( param, 'n' as i32, 0 as *const libc::c_char, ); if !urlencoded.is_null() { name = dc_urldecode(urlencoded); dc_normalize_name(name); free(urlencoded as *mut libc::c_void); } invitenumber = dc_param_get( param, 'i' as i32, 0 as *const libc::c_char, ); auth = dc_param_get(param, 's' as i32, 0 as *const libc::c_char); grpid = dc_param_get(param, 'x' as i32, 0 as *const libc::c_char); if !grpid.is_null() { urlencoded = dc_param_get( param, 'g' as i32, 0 as *const libc::c_char, ); if !urlencoded.is_null() { grpname = dc_urldecode(urlencoded); free(urlencoded as *mut libc::c_void); } } } dc_param_unref(param); } fingerprint = dc_normalize_fingerprint(payload); current_block = 10809827304263610514; } else if strncasecmp( qr, b"mailto:\0" as *const u8 as *const libc::c_char, strlen(b"mailto:\0" as *const u8 as *const libc::c_char), ) == 0 as libc::c_int { payload = dc_strdup( &*qr .offset( (strlen as unsafe extern "C" fn( *const libc::c_char, ) -> libc::c_ulong)( b"mailto:\0" as *const u8 as *const libc::c_char, ) as isize, ), ); let mut query: *mut libc::c_char = strchr(payload, '?' as i32); if !query.is_null() { *query = 0 as libc::c_int as libc::c_char; } addr = dc_strdup(payload); current_block = 10809827304263610514; } else if strncasecmp( qr, b"SMTP:\0" as *const u8 as *const libc::c_char, strlen(b"SMTP:\0" as *const u8 as *const libc::c_char), ) == 0 as libc::c_int { payload = dc_strdup( &*qr .offset( (strlen as unsafe extern "C" fn( *const libc::c_char, ) -> libc::c_ulong)( b"SMTP:\0" as *const u8 as *const libc::c_char, ) as isize, ), ); let mut colon: *mut libc::c_char = strchr(payload, ':' as i32); if !colon.is_null() { *colon = 0 as libc::c_int as libc::c_char; } addr = dc_strdup(payload); current_block = 10809827304263610514; } else if strncasecmp( qr, b"MATMSG:\0" as *const u8 as *const libc::c_char, strlen(b"MATMSG:\0" as *const u8 as *const libc::c_char), ) == 0 as libc::c_int { let mut to: *mut libc::c_char = strstr( qr, b"TO:\0" as *const u8 as *const libc::c_char, ); if !to.is_null() { addr = dc_strdup(&mut *to.offset(3 as libc::c_int as isize)); let mut semicolon: *mut libc::c_char = strchr(addr, ';' as i32); if !semicolon.is_null() { *semicolon = 0 as libc::c_int as libc::c_char; } current_block = 10809827304263610514; } else { (*qr_parsed).state = 400 as libc::c_int; (*qr_parsed) .text1 = dc_strdup( b"Bad e-mail address.\0" as *const u8 as *const libc::c_char, ); current_block = 2727351481511327683; } } else { if strncasecmp( qr, b"BEGIN:VCARD\0" as *const u8 as *const libc::c_char, strlen(b"BEGIN:VCARD\0" as *const u8 as *const libc::c_char), ) == 0 as libc::c_int { let mut lines: *mut carray = dc_split_into_lines(qr); let mut i: libc::c_int = 0 as libc::c_int; while (i as libc::c_uint) < carray_count(lines) { let mut key: *mut libc::c_char = carray_get(lines, i as libc::c_uint) as *mut libc::c_char; dc_trim(key); let mut value: *mut libc::c_char = strchr(key, ':' as i32); if !value.is_null() { *value = 0 as libc::c_int as libc::c_char; value = value.offset(1); value; let mut semicolon_0: *mut libc::c_char = strchr(key, ';' as i32); if !semicolon_0.is_null() { *semicolon_0 = 0 as libc::c_int as libc::c_char; } if strcasecmp( key, b"EMAIL\0" as *const u8 as *const libc::c_char, ) == 0 as libc::c_int { semicolon_0 = strchr(value, ';' as i32); if !semicolon_0.is_null() { *semicolon_0 = 0 as libc::c_int as libc::c_char; } addr = dc_strdup(value); } else if strcasecmp( key, b"N\0" as *const u8 as *const libc::c_char, ) == 0 as libc::c_int { semicolon_0 = strchr(value, ';' as i32); if !semicolon_0.is_null() { semicolon_0 = strchr( semicolon_0.offset(1 as libc::c_int as isize), ';' as i32, ); if !semicolon_0.is_null() { *semicolon_0 = 0 as libc::c_int as libc::c_char; } } name = dc_strdup(value); dc_str_replace( &mut name, b";\0" as *const u8 as *const libc::c_char, b",\0" as *const u8 as *const libc::c_char, ); dc_normalize_name(name); } } i += 1; i; } dc_free_splitted_lines(lines); } current_block = 10809827304263610514; } match current_block { 2727351481511327683 => {} _ => { if !addr.is_null() { let mut temp: *mut libc::c_char = dc_urldecode(addr); free(addr as *mut libc::c_void); addr = temp; temp = dc_addr_normalize(addr); free(addr as *mut libc::c_void); addr = temp; if dc_may_be_valid_addr(addr) == 0 { (*qr_parsed).state = 400 as libc::c_int; (*qr_parsed) .text1 = dc_strdup( b"Bad e-mail address.\0" as *const u8 as *const libc::c_char, ); current_block = 2727351481511327683; } else { current_block = 14294131666767243020; } } else { current_block = 14294131666767243020; } match current_block { 2727351481511327683 => {} _ => { if !fingerprint.is_null() { if strlen(fingerprint) != 40 as libc::c_int as libc::c_ulong { (*qr_parsed).state = 400 as libc::c_int; (*qr_parsed) .text1 = dc_strdup( b"Bad fingerprint length in QR code.\0" as *const u8 as *const libc::c_char, ); current_block = 2727351481511327683; } else { current_block = 1209030638129645089; } } else { current_block = 1209030638129645089; } match current_block { 2727351481511327683 => {} _ => { if !fingerprint.is_null() { if addr.is_null() || invitenumber.is_null() || auth.is_null() { if dc_apeerstate_load_by_fingerprint( peerstate, (*context).sql, fingerprint, ) != 0 { (*qr_parsed).state = 210 as libc::c_int; (*qr_parsed) .id = dc_add_or_lookup_contact( context, 0 as *const libc::c_char, (*peerstate).addr, 0x80 as libc::c_int, 0 as *mut libc::c_int, ); dc_create_or_lookup_nchat_by_contact_id( context, (*qr_parsed).id, 2 as libc::c_int, &mut chat_id, 0 as *mut libc::c_int, ); device_msg = dc_mprintf( b"%s verified.\0" as *const u8 as *const libc::c_char, (*peerstate).addr, ); } else { (*qr_parsed).text1 = dc_format_fingerprint(fingerprint); (*qr_parsed).state = 230 as libc::c_int; } } else { if !grpid.is_null() && !grpname.is_null() { (*qr_parsed).state = 202 as libc::c_int; (*qr_parsed).text1 = dc_strdup(grpname); (*qr_parsed).text2 = dc_strdup(grpid); } else { (*qr_parsed).state = 200 as libc::c_int; } (*qr_parsed) .id = dc_add_or_lookup_contact( context, name, addr, 0x80 as libc::c_int, 0 as *mut libc::c_int, ); (*qr_parsed).fingerprint = dc_strdup(fingerprint); (*qr_parsed).invitenumber = dc_strdup(invitenumber); (*qr_parsed).auth = dc_strdup(auth); } } else if !addr.is_null() { (*qr_parsed).state = 320 as libc::c_int; (*qr_parsed) .id = dc_add_or_lookup_contact( context, name, addr, 0x80 as libc::c_int, 0 as *mut libc::c_int, ); } else if strstr( qr, b"http://\0" as *const u8 as *const libc::c_char, ) == qr as *mut libc::c_char || strstr( qr, b"https://\0" as *const u8 as *const libc::c_char, ) == qr as *mut libc::c_char { (*qr_parsed).state = 332 as libc::c_int; (*qr_parsed).text1 = dc_strdup(qr); } else { (*qr_parsed).state = 330 as libc::c_int; (*qr_parsed).text1 = dc_strdup(qr); } if !device_msg.is_null() { dc_add_device_msg(context, chat_id, device_msg); } } } } } } } } free(addr as *mut libc::c_void); free(fingerprint as *mut libc::c_void); dc_apeerstate_unref(peerstate); free(payload as *mut libc::c_void); free(name as *mut libc::c_void); free(invitenumber as *mut libc::c_void); free(auth as *mut libc::c_void); free(device_msg as *mut libc::c_void); free(grpname as *mut libc::c_void); free(grpid as *mut libc::c_void); return qr_parsed; }
projects/deltachat-core/c/dc_chat.c
* If dc_prepare_msg() was called before, this parameter can be 0. * @param msg Message object to send to the chat defined by the chat ID. * On succcess, msg_id of the object is set up, * The function does not take ownership of the object, * so you have to free it using dc_msg_unref() as usual. * @return The ID of the message that is about to be sent. 0 in case of errors. */ uint32_t dc_send_msg(dc_context_t* context, uint32_t chat_id, dc_msg_t* msg) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg==NULL) { return 0; } // recursively send any forwarded copies if (!chat_id) { char* forwards = dc_param_get(msg->param, DC_PARAM_PREP_FORWARDS, NULL); if (forwards) { char* p = forwards; while (*p) { int32_t id = strtol(p, &p, 10); if (!id) break; // avoid hanging if user tampers with db dc_msg_t* copy = dc_get_msg(context, id); if (copy) { dc_send_msg(context, chat_id, copy); } dc_msg_unref(copy); } dc_param_set(msg->param, DC_PARAM_PREP_FORWARDS, NULL); dc_msg_save_param_to_disk(msg); } free(forwards); dc_send_msg(context, chat_id, msg); return msg->id; } // automatically prepare normal messages if (msg->state!=DC_STATE_OUT_PREPARING && msg-state!=DC_STATE_UNDEFINED) { dc_param_set(msg->param, DC_PARAM_GUARANTEE_E2EE, NULL); dc_param_set(msg->param, DC_PARAM_FORCE_PLAINTEXT, NULL); dc_msg_save_param_to_disk(msg); } dc_send_msg(context, chat_id, msg); return msg->id; }
projects/deltachat-core/rust/chat.rs
pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> { if chat_id.is_unset() { let forwards = msg.param.get(Param::PrepForwards); if let Some(forwards) = forwards { for forward in forwards.split(' ') { if let Ok(msg_id) = forward.parse::<u32>().map(MsgId::new) { if let Ok(mut msg) = Message::load_from_db(context, msg_id).await { send_msg_inner(context, chat_id, &mut msg).await?; }; } } msg.param.remove(Param::PrepForwards); msg.update_param(context).await?; } return send_msg_inner(context, chat_id, msg).await; } if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing { msg.param.remove(Param::GuaranteeE2ee); msg.param.remove(Param::ForcePlaintext); msg.update_param(context).await?; } send_msg_inner(context, chat_id, msg).await }
pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> { context .sql .execute( "UPDATE chats SET param=? WHERE id=?", (self.param.to_string(), self.id), ) .await?; Ok(()) } pub fn remove(&mut self, key: Param) -> &mut Self { self.inner.remove(&key); self } pub fn get(&self, key: Param) -> Option<&str> { self.inner.get(&key).map(|s| s.as_str()) } pub fn is_unset(self) -> bool { self.0 == 0 } async fn send_msg_inner(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> { // protect all system messages against RTLO attacks if msg.is_system_message() { msg.text = strip_rtlo_characters(&msg.text); } if !prepare_send_msg(context, chat_id, msg).await?.is_empty() { if !msg.hidden { context.emit_msgs_changed(msg.chat_id, msg.id); } if msg.param.exists(Param::SetLatitude) { context.emit_location_changed(Some(ContactId::SELF)).await?; } context.scheduler.interrupt_smtp().await; } Ok(msg.id) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct MsgId(u32); pub struct ChatId(u32); pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } impl Message { /// Loads message with given ID from the database. /// /// Returns an error if the message does not exist. pub async fn load_from_db(context: &Context, id: MsgId) -> Result<Message> { let message = Self::load_from_db_optional(context, id) .await? .with_context(|| format!("Message {id} does not exist"))?; Ok(message) } } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. } impl MsgId { /// Create a new [MsgId]. pub fn new(id: u32) -> MsgId { MsgId(id) } } pub enum MessageState { /// Undefined message state. #[default] Undefined = 0, /// Incoming *fresh* message. Fresh messages are neither noticed /// nor seen and are typically shown in notifications. InFresh = 10, /// Incoming *noticed* message. E.g. chat opened but message not /// yet read - noticed messages are not counted as unread but did /// not marked as read nor resulted in MDNs. InNoticed = 13, /// Incoming message, really *seen* by the user. Marked as read on /// IMAP and MDN may be sent. InSeen = 16, /// For files which need time to be prepared before they can be /// sent, the message enters this state before /// OutPending. OutPreparing = 18, /// Message saved as draft. OutDraft = 19, /// The user has pressed the "send" button but the message is not /// yet sent and is pending in some way. Maybe we're offline (no /// checkmark). OutPending = 20, /// *Unrecoverable* error (*recoverable* errors result in pending /// messages). OutFailed = 24, /// Outgoing message successfully delivered to server (one /// checkmark). Note, that already delivered messages may get into /// the OutFailed state if we get such a hint from the server. OutDelivered = 26, /// Outgoing message read by the recipient (two checkmarks; this /// requires goodwill on the receiver's side) OutMdnRcvd = 28, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__104.txt
pub unsafe extern "C" fn dc_prepare_msg( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut msg: *mut dc_msg_t, ) -> uint32_t { if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || msg.is_null() || chat_id <= 9 as libc::c_int as libc::c_uint { return 0 as libc::c_int as uint32_t; } (*msg).state = 18 as libc::c_int; let mut msg_id: uint32_t = prepare_msg_common(context, chat_id, msg); ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, (*msg).chat_id as uintptr_t, (*msg).id as uintptr_t, ); if dc_param_exists((*msg).param, 'l' as i32) != 0 { ((*context).cb) .expect( "non-null function pointer", )( context, 2035 as libc::c_int, 1 as libc::c_int as uintptr_t, 0 as libc::c_int as uintptr_t, ); } return msg_id; }
projects/deltachat-core/c/dc_chat.c
int dc_add_contact_to_chat_ex(dc_context_t* context, uint32_t chat_id, uint32_t contact_id, int flags) { int success = 0; dc_contact_t* contact = dc_get_contact(context, contact_id); dc_chat_t* chat = dc_chat_new(context); dc_msg_t* msg = dc_msg_new_untyped(context); char* self_addr = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || contact==NULL || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } dc_reset_gossiped_timestamp(context, chat_id); if (0==real_group_exists(context, chat_id) /*this also makes sure, not contacts are added to special or normal chats*/ || (0==dc_real_contact_exists(context, contact_id) && contact_id!=DC_CONTACT_ID_SELF) || 0==dc_chat_load_from_db(chat, chat_id)) { goto cleanup; } if (!IS_SELF_IN_GROUP) { dc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0, "Cannot add contact to group; self not in group."); goto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */ } if ((flags&DC_FROM_HANDSHAKE) && dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0)==1) { // after a handshake, force sending the `Chat-Group-Member-Added` message dc_param_set(chat->param, DC_PARAM_UNPROMOTED, NULL); dc_chat_update_param(chat); } self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", ""); if (strcasecmp(contact->addr, self_addr)==0) { goto cleanup; /* ourself is added using DC_CONTACT_ID_SELF, do not add it explicitly. if SELF is not in the group, members cannot be added at all. */ } if (dc_is_contact_in_chat(context, chat_id, contact_id)) { if (!(flags&DC_FROM_HANDSHAKE)) { success = 1; goto cleanup; } // else continue and send status mail } else { if (dc_chat_is_protected() && dc_contact_is_verified(contact)!=DC_BIDIRECT_VERIFIED) { dc_log_error(context, 0, "Only bidirectional verified contacts can be added to verified groups."); goto cleanup; } if (dc_is_contact_in_chat(context, chat_id, contact_id)){ goto cleanup; } if (0==dc_add_to_chat_contacts_table(context, chat_id, contact_id)) { goto cleanup; } } /* send a status mail to all group members */ if (chat->type==DC_CHAT_TYPE_GROUP && dc_chat_is_unpromoted() == 0) { msg->type = DC_MSG_TEXT; msg->text = dc_stock_system_msg(context, DC_STR_MSGADDMEMBER, contact->addr, NULL, DC_CONTACT_ID_SELF); dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_MEMBER_ADDED_TO_GROUP); dc_param_set (msg->param, DC_PARAM_CMD_ARG, contact->addr); dc_param_set_int(msg->param, DC_PARAM_CMD_ARG2, flags); // combine the Secure-Join protocol headers with the Chat-Group-Member-Added header msg->id = dc_send_msg(context, chat_id, msg); } context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); success = 1; cleanup: dc_chat_unref(chat); dc_contact_unref(contact); dc_msg_unref(msg); free(self_addr); return success; }
projects/deltachat-core/rust/chat.rs
pub(crate) async fn add_contact_to_chat_ex( context: &Context, mut sync: sync::Sync, chat_id: ChatId, contact_id: ContactId, from_handshake: bool, ) -> Result<bool> { ensure!(!chat_id.is_special(), "can not add member to special chats"); let contact = Contact::get_by_id(context, contact_id).await?; let mut msg = Message::default(); chat_id.reset_gossiped_timestamp(context).await?; // this also makes sure, no contacts are added to special or normal chats let mut chat = Chat::load_from_db(context, chat_id).await?; ensure!( chat.typ == Chattype::Group || chat.typ == Chattype::Broadcast, "{} is not a group/broadcast where one can add members", chat_id ); ensure!( Contact::real_exists_by_id(context, contact_id).await? || contact_id == ContactId::SELF, "invalid contact_id {} for adding to group", contact_id ); ensure!(!chat.is_mailing_list(), "Mailing lists can't be changed"); ensure!( chat.typ != Chattype::Broadcast || contact_id != ContactId::SELF, "Cannot add SELF to broadcast." ); if !chat.is_self_in_chat(context).await? { context.emit_event(EventType::ErrorSelfNotInGroup( "Cannot add contact to group; self not in group.".into(), )); bail!("can not add contact because the account is not part of the group/broadcast"); } if from_handshake && chat.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 { chat.param.remove(Param::Unpromoted); chat.update_param(context).await?; let _ = context .sync_qr_code_tokens(Some(chat_id)) .await .log_err(context) .is_ok() && context.send_sync_msg().await.log_err(context).is_ok(); } if context.is_self_addr(contact.get_addr()).await? { // ourself is added using ContactId::SELF, do not add this address explicitly. // if SELF is not in the group, members cannot be added at all. warn!( context, "Invalid attempt to add self e-mail address to group." ); return Ok(false); } if is_contact_in_chat(context, chat_id, contact_id).await? { if !from_handshake { return Ok(true); } } else { // else continue and send status mail if chat.is_protected() && !contact.is_verified(context).await? { error!( context, "Cannot add non-bidirectionally verified contact {contact_id} to protected chat {chat_id}." ); return Ok(false); } if is_contact_in_chat(context, chat_id, contact_id).await? { return Ok(false); } add_to_chat_contacts_table(context, chat_id, &[contact_id]).await?; } if chat.typ == Chattype::Group && chat.is_promoted() { msg.viewtype = Viewtype::Text; let contact_addr = contact.get_addr().to_lowercase(); msg.text = stock_str::msg_add_member_local(context, &contact_addr, ContactId::SELF).await; msg.param.set_cmd(SystemMessage::MemberAddedToGroup); msg.param.set(Param::Arg, contact_addr); msg.param.set_int(Param::Arg2, from_handshake.into()); msg.id = send_msg(context, chat_id, &mut msg).await?; sync = Nosync; } context.emit_event(EventType::ChatModified(chat_id)); if sync.into() { chat.sync_contacts(context).await.log_err(context).ok(); } Ok(true) }
pub fn is_special(self) -> bool { (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0) } pub async fn get_by_id(context: &Context, contact_id: ContactId) -> Result<Self> { let contact = Self::get_by_id_optional(context, contact_id) .await? .with_context(|| format!("contact {contact_id} not found"))?; Ok(contact) } pub(crate) async fn msg_add_member_local( context: &Context, added_member_addr: &str, by_contact: ContactId, ) -> String { let addr = added_member_addr; let whom = &match Contact::lookup_id_by_addr(context, addr, Origin::Unknown).await { Ok(Some(contact_id)) => Contact::get_by_id(context, contact_id) .await .map(|contact| contact.get_name_n_addr()) .unwrap_or_else(|_| addr.to_string()), _ => addr.to_string(), }; if by_contact == ContactId::UNDEFINED { translated(context, StockMessage::MsgAddMember) .await .replace1(whom) } else if by_contact == ContactId::SELF { translated(context, StockMessage::MsgYouAddMember) .await .replace1(whom) } else { translated(context, StockMessage::MsgAddMemberBy) .await .replace1(whom) .replace2(&by_contact.get_stock_name_n_addr(context).await) } } pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> { let mut chat = context .sql .query_row( "SELECT c.type, c.name, c.grpid, c.param, c.archived, c.blocked, c.locations_send_until, c.muted_until, c.protected FROM chats c WHERE c.id=?;", (chat_id,), |row| { let c = Chat { id: chat_id, typ: row.get(0)?, name: row.get::<_, String>(1)?, grpid: row.get::<_, String>(2)?, param: row.get::<_, String>(3)?.parse().unwrap_or_default(), visibility: row.get(4)?, blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(), is_sending_locations: row.get(6)?, mute_duration: row.get(7)?, protected: row.get(8)?, }; Ok(c) }, ) .await .context(format!("Failed loading chat {chat_id} from database"))?; if chat.id.is_archived_link() { chat.name = stock_str::archived_chats(context).await; } else { if chat.typ == Chattype::Single && chat.name.is_empty() { // chat.name is set to contact.display_name on changes, // however, if things went wrong somehow, we do this here explicitly. let mut chat_name = "Err [Name not found]".to_owned(); match get_chat_contacts(context, chat.id).await { Ok(contacts) => { if let Some(contact_id) = contacts.first() { if let Ok(contact) = Contact::get_by_id(context, *contact_id).await { contact.get_display_name().clone_into(&mut chat_name); } } } Err(err) => { error!( context, "Failed to load contacts for {}: {:#}.", chat.id, err ); } } chat.name = chat_name; } if chat.param.exists(Param::Selftalk) { chat.name = stock_str::saved_messages(context).await; } else if chat.param.exists(Param::Devicetalk) { chat.name = stock_str::device_messages(context).await; } } Ok(chat) } pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> { context .sql .execute( "UPDATE chats SET param=? WHERE id=?", (self.param.to_string(), self.id), ) .await?; Ok(()) } pub fn set_int(&mut self, key: Param, value: i32) -> &mut Self { self.set(key, format!("{value}")); self } pub fn is_protected(&self) -> bool { self.protected == ProtectionStatus::Protected } pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> { if chat_id.is_unset() { let forwards = msg.param.get(Param::PrepForwards); if let Some(forwards) = forwards { for forward in forwards.split(' ') { if let Ok(msg_id) = forward.parse::<u32>().map(MsgId::new) { if let Ok(mut msg) = Message::load_from_db(context, msg_id).await { send_msg_inner(context, chat_id, &mut msg).await?; }; } } msg.param.remove(Param::PrepForwards); msg.update_param(context).await?; } return send_msg_inner(context, chat_id, msg).await; } if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing { msg.param.remove(Param::GuaranteeE2ee); msg.param.remove(Param::ForcePlaintext); msg.update_param(context).await?; } send_msg_inner(context, chat_id, msg).await } pub async fn is_contact_in_chat( context: &Context, chat_id: ChatId, contact_id: ContactId, ) -> Result<bool> { // this function works for group and for normal chats, however, it is more useful // for group chats. // ContactId::SELF may be used to check, if the user itself is in a group // chat (ContactId::SELF is not added to normal chats) let exists = context .sql .exists( "SELECT COUNT(*) FROM chats_contacts WHERE chat_id=? AND contact_id=?;", (chat_id, contact_id), ) .await?; Ok(exists) } pub(crate) async fn sync_contacts(&self, context: &Context) -> Result<()> { let addrs = context .sql .query_map( "SELECT c.addr \ FROM contacts c INNER JOIN chats_contacts cc \ ON c.id=cc.contact_id \ WHERE cc.chat_id=?", (self.id,), |row| row.get::<_, String>(0), |addrs| addrs.collect::<Result<Vec<_>, _>>().map_err(Into::into), ) .await?; self.sync(context, SyncAction::SetContacts(addrs)).await } pub(crate) async fn sync_qr_code_tokens(&self, chat_id: Option<ChatId>) -> Result<()> { if !self.get_config_bool(Config::SyncMsgs).await? { return Ok(()); } if let (Some(invitenumber), Some(auth)) = ( token::lookup(self, Namespace::InviteNumber, chat_id).await?, token::lookup(self, Namespace::Auth, chat_id).await?, ) { let grpid = if let Some(chat_id) = chat_id { let chat = Chat::load_from_db(self, chat_id).await?; if !chat.is_promoted() { info!( self, "group '{}' not yet promoted, do not sync tokens yet.", chat.grpid ); return Ok(()); } Some(chat.grpid) } else { None }; self.add_sync_item(SyncData::AddQrToken(QrTokenData { invitenumber, auth, grpid, })) .await?; } Ok(()) } pub fn remove(&mut self, key: Param) -> &mut Self { self.inner.remove(&key); self } pub fn set_cmd(&mut self, value: SystemMessage) { self.set_int(Param::Cmd, value as i32); } pub fn is_promoted(&self) -> bool { !self.is_unpromoted() } pub fn get_int(&self, key: Param) -> Option<i32> { self.get(key).and_then(|s| s.parse().ok()) } pub(crate) async fn add_to_chat_contacts_table( context: &Context, chat_id: ChatId, contact_ids: &[ContactId], ) -> Result<()> { context .sql .transaction(move |transaction| { for contact_id in contact_ids { transaction.execute( "INSERT OR IGNORE INTO chats_contacts (chat_id, contact_id) VALUES(?, ?)", (chat_id, contact_id), )?; } Ok(()) }) .await?; Ok(()) } pub(crate) async fn reset_gossiped_timestamp(self, context: &Context) -> Result<()> { self.set_gossiped_timestamp(context, 0).await } pub(crate) async fn is_self_in_chat(&self, context: &Context) -> Result<bool> { match self.typ { Chattype::Single | Chattype::Broadcast | Chattype::Mailinglist => Ok(true), Chattype::Group => is_contact_in_chat(context, self.id, ContactId::SELF).await, } } pub(crate) async fn is_self_addr(&self, addr: &str) -> Result<bool> { Ok(self .get_config(Config::ConfiguredAddr) .await? .iter() .any(|a| addr_cmp(addr, a)) || self .get_secondary_self_addrs() .await? .iter() .any(|a| addr_cmp(addr, a))) } pub async fn is_verified(&self, context: &Context) -> Result<bool> { // We're always sort of secured-verified as we could verify the key on this device any time with the key // on this device if self.id == ContactId::SELF { return Ok(true); } let Some(peerstate) = Peerstate::from_addr(context, &self.addr).await? else { return Ok(false); }; let forward_verified = peerstate.is_using_verified_key(); let backward_verified = peerstate.is_backward_verified(context).await?; Ok(forward_verified && backward_verified) } fn log_err(self, context: &Context) -> Result<T, E> { if let Err(e) = &self { let location = std::panic::Location::caller(); // We are using Anyhow's .context() and to show the inner error, too, we need the {:#}: let full = format!( "{file}:{line}: {e:#}", file = location.file(), line = location.line(), e = e ); // We can't use the warn!() macro here as the file!() and line!() macros // don't work with #[track_caller] context.emit_event(crate::EventType::Warning(full)); }; self } pub async fn send_sync_msg(&self) -> Result<Option<MsgId>> { if let Some((json, ids)) = self.build_sync_json().await? { let chat_id = ChatId::create_for_contact_with_blocked(self, ContactId::SELF, Blocked::Yes) .await?; let mut msg = Message { chat_id, viewtype: Viewtype::Text, text: stock_str::sync_msg_body(self).await, hidden: true, subject: stock_str::sync_msg_subject(self).await, ..Default::default() }; msg.param.set_cmd(SystemMessage::MultiDeviceSync); msg.param.set(Param::Arg, json); msg.param.set(Param::Arg2, ids); msg.param.set_int(Param::GuaranteeE2ee, 1); Ok(Some(chat::send_msg(self, chat_id, &mut msg).await?)) } else { Ok(None) } } pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self { self.inner.insert(key, value.to_string()); self } pub fn emit_event(&self, event: EventType) { { let lock = self.debug_logging.read().expect("RwLock is poisoned"); if let Some(debug_logging) = &*lock { debug_logging.log_event(event.clone()); } } self.events.emit(Event { id: self.id, typ: event, }); } macro_rules! warn { ($ctx:expr, $msg:expr) => { warn!($ctx, $msg,) }; ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{ let formatted = format!($msg, $($args),*); let full = format!("{file}:{line}: {msg}", file = file!(), line = line!(), msg = &formatted); $ctx.emit_event($crate::EventType::Warning(full)); }}; } pub fn get_addr(&self) -> &str { &self.addr } pub fn error(&self) -> Option<String> { self.error.clone() } pub async fn real_exists_by_id(context: &Context, contact_id: ContactId) -> Result<bool> { if contact_id.is_special() { return Ok(false); } let exists = context .sql .exists("SELECT COUNT(*) FROM contacts WHERE id=?;", (contact_id,)) .await?; Ok(exists) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct ChatId(u32); pub struct ContactId(u32); pub enum Chattype { /// 1:1 chat. Single = 100, /// Group chat. Group = 120, /// Mailing list. Mailinglist = 140, /// Broadcast list. Broadcast = 160, } impl ContactId { /// The owner of the account. /// /// The email-address is set by `set_config` using "addr". pub const SELF: ContactId = ContactId::new(1); } pub enum EventType { /// The library-user may write an informational string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Info(String), /// Emitted when SMTP connection is established and login was successful. SmtpConnected(String), /// Emitted when IMAP connection is established and login was successful. ImapConnected(String), /// Emitted when a message was successfully sent to the SMTP server. SmtpMessageSent(String), /// Emitted when an IMAP message has been marked as deleted ImapMessageDeleted(String), /// Emitted when an IMAP message has been moved ImapMessageMoved(String), /// Emitted before going into IDLE on the Inbox folder. ImapInboxIdle, /// Emitted when an new file in the $BLOBDIR was created NewBlobFile(String), /// Emitted when an file in the $BLOBDIR was deleted DeletedBlobFile(String), /// The library-user should write a warning string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Warning(String), /// The library-user should report an error to the end-user. /// /// As most things are asynchronous, things may go wrong at any time and the user /// should not be disturbed by a dialog or so. Instead, use a bubble or so. /// /// However, for ongoing processes (eg. configure()) /// or for functions that are expected to fail (eg. dc_continue_key_transfer()) /// it might be better to delay showing these events until the function has really /// failed (returned false). It should be sufficient to report only the *last* error /// in a messasge box then. Error(String), /// An action cannot be performed because the user is not in the group. /// Reported eg. after a call to /// dc_set_chat_name(), dc_set_chat_profile_image(), /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(), /// dc_send_text_msg() or another sending function. ErrorSelfNotInGroup(String), /// Messages or chats changed. One or more messages or chats changed for various /// reasons in the database: /// - Messages sent, received or removed /// - Chats created, deleted or archived /// - A draft has been set /// MsgsChanged { /// Set if only a single chat is affected by the changes, otherwise 0. chat_id: ChatId, /// Set if only a single message is affected by the changes, otherwise 0. msg_id: MsgId, }, /// Reactions for the message changed. ReactionsChanged { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message for which reactions were changed. msg_id: MsgId, /// ID of the contact whose reaction set is changed. contact_id: ContactId, }, /// There is a fresh message. Typically, the user will show an notification /// when receiving this message. /// /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event. IncomingMsg { /// ID of the chat where the message is assigned. chat_id: ChatId, /// ID of the message. msg_id: MsgId, }, /// Downloading a bunch of messages just finished. IncomingMsgBunch, /// Messages were seen or noticed. /// chat id is always set. MsgsNoticed(ChatId), /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state(). MsgDelivered { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was successfully sent. msg_id: MsgId, }, /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_FAILED, see dc_msg_get_state(). MsgFailed { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that could not be sent. msg_id: MsgId, }, /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state(). MsgRead { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was read. msg_id: MsgId, }, /// A single message was deleted. /// /// This event means that the message will no longer appear in the messagelist. /// UI should remove the message from the messagelist /// in response to this event if the message is currently displayed. /// /// The message may have been explicitly deleted by the user or expired. /// Internally the message may have been removed from the database, /// moved to the trash chat or hidden. /// /// This event does not indicate the message /// deletion from the server. MsgDeleted { /// ID of the chat where the message was prior to deletion. /// Never 0 or trash chat. chat_id: ChatId, /// ID of the deleted message. Never 0. msg_id: MsgId, }, /// Chat changed. The name or the image of a chat group was changed or members were added or removed. /// Or the verify state of a chat has changed. /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat() /// and dc_remove_contact_from_chat(). /// /// This event does not include ephemeral timer modification, which /// is a separate event. ChatModified(ChatId), /// Chat ephemeral timer changed. ChatEphemeralTimerModified { /// Chat ID. chat_id: ChatId, /// New ephemeral timer value. timer: EphemeralTimer, }, /// Contact(s) created, renamed, blocked, deleted or changed their "recently seen" status. /// /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected. ContactsChanged(Option<ContactId>), /// Location of one or more contact has changed. /// /// @param data1 (u32) contact_id of the contact for which the location has changed. /// If the locations of several contacts have been changed, /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`. LocationChanged(Option<ContactId>), /// Inform about the configuration progress started by configure(). ConfigureProgress { /// Progress. /// /// 0=error, 1-999=progress in permille, 1000=success and done progress: usize, /// Progress comment or error, something to display to the user. comment: Option<String>, }, /// Inform about the import/export progress started by imex(). /// /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done /// @param data2 0 ImexProgress(usize), /// A file has been exported. A file has been written by imex(). /// This event may be sent multiple times by a single call to imex(). /// /// A typical purpose for a handler of this event may be to make the file public to some system /// services. /// /// @param data2 0 ImexFileWritten(PathBuf), /// Progress information of a secure-join handshake from the view of the inviter /// (Alice, the person who shows the QR code). /// /// These events are typically sent after a joiner has scanned the QR code /// generated by dc_get_securejoin_qr(). SecurejoinInviterProgress { /// ID of the contact that wants to join. contact_id: ContactId, /// Progress as: /// 300=vg-/vc-request received, typically shown as "bob@addr joins". /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as "bob@addr verified". /// 800=contact added to chat, shown as "bob@addr securely joined GROUP". Only for the verified-group-protocol. /// 1000=Protocol finished for this contact. progress: usize, }, /// Progress information of a secure-join handshake from the view of the joiner /// (Bob, the person who scans the QR code). /// The events are typically sent while dc_join_securejoin(), which /// may take some time, is executed. SecurejoinJoinerProgress { /// ID of the inviting contact. contact_id: ContactId, /// Progress as: /// 400=vg-/vc-request-with-auth sent, typically shown as "alice@addr verified, introducing myself." /// (Bob has verified alice and waits until Alice does the same for him) /// 1000=vg-member-added/vc-contact-confirm received progress: usize, }, /// The connectivity to the server changed. /// This means that you should refresh the connectivity view /// and possibly the connectivtiy HTML; see dc_get_connectivity() and /// dc_get_connectivity_html() for details. ConnectivityChanged, /// The user's avatar changed. /// Deprecated by `ConfigSynced`. SelfavatarChanged, /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For /// uniformity this is emitted on the source device too. The value isn't here, otherwise it /// would be logged which might not be good for privacy. ConfigSynced { /// Configuration key. key: Config, }, /// Webxdc status update received. WebxdcStatusUpdate { /// Message ID. msg_id: MsgId, /// Status update ID. status_update_serial: StatusUpdateSerial, }, /// Data received over an ephemeral peer channel. WebxdcRealtimeData { /// Message ID. msg_id: MsgId, /// Realtime data. data: Vec<u8>, }, /// Inform that a message containing a webxdc instance has been deleted. WebxdcInstanceDeleted { /// ID of the deleted message. msg_id: MsgId, }, /// Tells that the Background fetch was completed (or timed out). /// This event acts as a marker, when you reach this event you can be sure /// that all events emitted during the background fetch were processed. /// /// This event is only emitted by the account manager AccountsBackgroundFetchDone, /// Inform that set of chats or the order of the chats in the chatlist has changed. /// /// Sometimes this is emitted together with `UIChatlistItemChanged`. ChatlistChanged, /// Inform that a single chat list item changed and needs to be rerendered. /// If `chat_id` is set to None, then all currently visible chats need to be rerendered, and all not-visible items need to be cleared from cache if the UI has a cache. ChatlistItemChanged { /// ID of the changed chat chat_id: Option<ChatId>, }, /// Event for using in tests, e.g. as a fence between normally generated events. #[cfg(test)] Test, /// Inform than some events have been skipped due to event channel overflow. EventChannelOverflow { /// Number of events skipped. n: u64, }, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. } pub enum SystemMessage { /// Unknown type of system message. #[default] Unknown = 0, /// Group name changed. GroupNameChanged = 2, /// Group avatar changed. GroupImageChanged = 3, /// Member was added to the group. MemberAddedToGroup = 4, /// Member was removed from the group. MemberRemovedFromGroup = 5, /// Autocrypt Setup Message. AutocryptSetupMessage = 6, /// Secure-join message. SecurejoinMessage = 7, /// Location streaming is enabled. LocationStreamingEnabled = 8, /// Location-only message. LocationOnly = 9, /// Chat ephemeral message timer is changed. EphemeralTimerChanged = 10, /// "Messages are guaranteed to be end-to-end encrypted from now on." ChatProtectionEnabled = 11, /// "%1$s sent a message from another device." ChatProtectionDisabled = 12, /// Message can't be sent because of `Invalid unencrypted mail to <>` /// which is sent by chatmail servers. InvalidUnencryptedMail = 13, /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it /// to complete. SecurejoinWait = 14, /// 1:1 chats info message telling that SecureJoin is still running, but the user may already /// send messages. SecurejoinWaitTimeout = 15, /// Self-sent-message that contains only json used for multi-device-sync; /// if possible, we attach that to other messages as for locations. MultiDeviceSync = 20, /// Sync message that contains a json payload /// sent to the other webxdc instances /// These messages are not shown in the chat. WebxdcStatusUpdate = 30, /// Webxdc info added with `info` set in `send_webxdc_status_update()`. WebxdcInfoMessage = 32, /// This message contains a users iroh node address. IrohNodeAddr = 40, } pub enum Viewtype { /// Unknown message type. #[default] Unknown = 0, /// Text message. /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text(). Text = 10, /// Image message. /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to /// `Gif` when sending the message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension(). Image = 20, /// Animated GIF message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension() /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height(). Gif = 21, /// Message containing a sticker, similar to image. /// If possible, the ui should display the image without borders in a transparent way. /// A click on a sticker will offer to install the sticker set in some future. Sticker = 23, /// Message containing an Audio file. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration(). Audio = 40, /// A voice message that was directly recorded by the user. /// For all other audio messages, the type #DC_MSG_AUDIO should be used. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration() Voice = 41, /// Video messages. /// File, width, height and durarion /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration() /// and retrieved via /// dc_msg_get_file(), dc_msg_get_width(), /// dc_msg_get_height(), dc_msg_get_duration(). Video = 50, /// Message containing any file, eg. a PDF. /// The file is set via dc_msg_set_file() /// and retrieved via dc_msg_get_file(). File = 60, /// Message is an invitation to a videochat. VideochatInvitation = 70, /// Message is an webxdc instance. Webxdc = 80, /// Message containing shared contacts represented as a vCard (virtual contact file) /// with email addresses and possibly other fields. /// Use `parse_vcard()` to retrieve them. Vcard = 90, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__127.txt
pub unsafe extern "C" fn dc_add_contact_to_chat_ex( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut contact_id: uint32_t, mut flags: libc::c_int, ) -> libc::c_int { let mut current_block: u64; let mut success: libc::c_int = 0 as libc::c_int; let mut contact: *mut dc_contact_t = dc_get_contact(context, contact_id); let mut chat: *mut dc_chat_t = dc_chat_new(context); let mut msg: *mut dc_msg_t = dc_msg_new_untyped(context); let mut self_addr: *mut libc::c_char = 0 as *mut libc::c_char; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || contact.is_null() || chat_id <= 9 as libc::c_int as libc::c_uint) { dc_reset_gossiped_timestamp(context, chat_id); if !(0 as libc::c_int == real_group_exists(context, chat_id) || 0 as libc::c_int == dc_real_contact_exists(context, contact_id) && contact_id != 1 as libc::c_int as libc::c_uint || 0 as libc::c_int == dc_chat_load_from_db(chat, chat_id)) { if !(dc_is_contact_in_chat(context, chat_id, 1 as libc::c_int as uint32_t) == 1 as libc::c_int) { dc_log_event( context, 410 as libc::c_int, 0 as libc::c_int, b"Cannot add contact to group; self not in group.\0" as *const u8 as *const libc::c_char, ); } else { if flags & 0x1 as libc::c_int != 0 && dc_param_get_int((*chat).param, 'U' as i32, 0 as libc::c_int) == 1 as libc::c_int { dc_param_set((*chat).param, 'U' as i32, 0 as *const libc::c_char); dc_chat_update_param(chat); } self_addr = dc_sqlite3_get_config( (*context).sql, b"configured_addr\0" as *const u8 as *const libc::c_char, b"\0" as *const u8 as *const libc::c_char, ); if !(strcasecmp((*contact).addr, self_addr) == 0 as libc::c_int) { if dc_is_contact_in_chat(context, chat_id, contact_id) != 0 { if flags & 0x1 as libc::c_int == 0 { success = 1 as libc::c_int; current_block = 9909809848178435643; } else { current_block = 5601891728916014340; } } else { if (*chat).type_0 == 130 as libc::c_int { if dc_contact_is_verified(contact) != 2 as libc::c_int { dc_log_error( context, 0 as libc::c_int, b"Only bidirectional verified contacts can be added to verified groups.\0" as *const u8 as *const libc::c_char, ); current_block = 9909809848178435643; } else { current_block = 2370887241019905314; } } else { current_block = 2370887241019905314; } match current_block { 9909809848178435643 => {} _ => { if 0 as libc::c_int == dc_add_to_chat_contacts_table( context, chat_id, contact_id, ) { current_block = 9909809848178435643; } else { current_block = 5601891728916014340; } } } } match current_block { 9909809848178435643 => {} _ => { if dc_param_get_int( (*chat).param, 'U' as i32, 0 as libc::c_int, ) == 0 as libc::c_int { (*msg).type_0 = 10 as libc::c_int; (*msg) .text = dc_stock_system_msg( context, 17 as libc::c_int, (*contact).addr, 0 as *const libc::c_char, 1 as libc::c_int as uint32_t, ); dc_param_set_int( (*msg).param, 'S' as i32, 4 as libc::c_int, ); dc_param_set((*msg).param, 'E' as i32, (*contact).addr); dc_param_set_int((*msg).param, 'F' as i32, flags); (*msg).id = dc_send_msg(context, chat_id, msg); ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, chat_id as uintptr_t, (*msg).id as uintptr_t, ); } ((*context).cb) .expect( "non-null function pointer", )( context, 2020 as libc::c_int, chat_id as uintptr_t, 0 as libc::c_int as uintptr_t, ); success = 1 as libc::c_int; } } } } } } dc_chat_unref(chat); dc_contact_unref(contact); dc_msg_unref(msg); free(self_addr as *mut libc::c_void); return success; }
projects/deltachat-core/c/dc_securejoin.c
uint32_t dc_join_securejoin(dc_context_t* context, const char* qr) { /* ========================================================== ==== Bob - the joiner's side ===== ==== Step 2 in "Setup verified contact" protocol ===== ========================================================== */ int ret_chat_id = 0; int ongoing_allocated = 0; uint32_t contact_chat_id = 0; int join_vg = 0; dc_lot_t* qr_scan = NULL; int qr_locked = 0; #define LOCK_QR { pthread_mutex_lock(&context->bobs_qr_critical); qr_locked = 1; } #define UNLOCK_QR if (qr_locked) { pthread_mutex_unlock(&context->bobs_qr_critical); qr_locked = 0; } #define CHECK_EXIT if (context->shall_stop_ongoing) { goto cleanup; } dc_log_info(context, 0, "Requesting secure-join ..."); dc_ensure_secret_key_exists(context); if ((ongoing_allocated=dc_alloc_ongoing(context))==0) { goto cleanup; } if (((qr_scan=dc_check_qr(context, qr))==NULL) || (qr_scan->state!=DC_QR_ASK_VERIFYCONTACT && qr_scan->state!=DC_QR_ASK_VERIFYGROUP)) { dc_log_error(context, 0, "Unknown QR code."); goto cleanup; } if ((contact_chat_id=dc_create_chat_by_contact_id(context, qr_scan->id))==0) { dc_log_error(context, 0, "Unknown contact."); goto cleanup; } CHECK_EXIT join_vg = (qr_scan->state==DC_QR_ASK_VERIFYGROUP); context->bobs_status = 0; LOCK_QR context->bobs_qr_scan = qr_scan; UNLOCK_QR if (fingerprint_equals_sender(context, qr_scan->fingerprint, contact_chat_id)) { // the scanned fingerprint matches Alice's key, we can proceed to step 4b) directly and save two mails dc_log_info(context, 0, "Taking protocol shortcut."); context->bob_expects = DC_VC_CONTACT_CONFIRM; context->cb(context, DC_EVENT_SECUREJOIN_JOINER_PROGRESS, chat_id_2_contact_id(context, contact_chat_id), 400); char* own_fingerprint = get_self_fingerprint(context); send_handshake_msg(context, contact_chat_id, join_vg? "vg-request-with-auth" : "vc-request-with-auth", qr_scan->auth, own_fingerprint, join_vg? qr_scan->text2 : NULL); // Bob -> Alice free(own_fingerprint); } else { context->bob_expects = DC_VC_AUTH_REQUIRED; send_handshake_msg(context, contact_chat_id, join_vg? "vg-request" : "vc-request", qr_scan->invitenumber, NULL, NULL); // Bob -> Alice } while (1) { CHECK_EXIT usleep(300*1000); // 0.3 seconds } cleanup: context->bob_expects = 0; if (context->bobs_status==DC_BOB_SUCCESS) { if (join_vg) { ret_chat_id = dc_get_chat_id_by_grpid(context, qr_scan->text2, NULL, NULL); } else { ret_chat_id = contact_chat_id; } } LOCK_QR context->bobs_qr_scan = NULL; UNLOCK_QR dc_lot_unref(qr_scan); if (ongoing_allocated) { dc_free_ongoing(context); } return ret_chat_id; }
projects/deltachat-core/rust/securejoin.rs
pub async fn join_securejoin(context: &Context, qr: &str) -> Result<ChatId> { 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 }) }
pub fn error(&self) -> Option<String> { self.error.clone() } async fn securejoin(context: &Context, qr: &str) -> Result<ChatId> { /*======================================================== ==== Bob - the joiner's side ===== ==== Step 2 in "Setup verified contact" protocol ===== ========================================================*/ info!(context, "Requesting secure-join ...",); let qr_scan = check_qr(context, qr).await?; let invite = QrInvite::try_from(qr_scan)?; bob::start_protocol(context, invite).await } pub struct Context { pub(crate) inner: Arc<InnerContext>, }
use anyhow::{bail, Context as _, Error, Result}; use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC}; use crate::aheader::EncryptPreference; use crate::chat::{self, Chat, ChatId, ChatIdBlocked, ProtectionStatus}; use crate::chatlist_events; use crate::config::Config; use crate::constants::Blocked; use crate::contact::{Contact, ContactId, Origin}; use crate::context::Context; use crate::e2ee::ensure_secret_key_exists; use crate::events::EventType; use crate::headerdef::HeaderDef; use crate::key::{load_self_public_key, DcKey, Fingerprint}; use crate::message::{Message, Viewtype}; use crate::mimeparser::{MimeMessage, SystemMessage}; use crate::param::Param; use crate::peerstate::Peerstate; use crate::qr::check_qr; use crate::securejoin::bob::JoinerProgress; use crate::stock_str; use crate::sync::Sync::*; use crate::token; use crate::tools::time; use bobstate::BobState; use qrinvite::QrInvite; use crate::token::Namespace; use deltachat_contact_tools::{ContactAddress, EmailAddress}; use super::*; use crate::chat::{remove_contact_from_chat, CantSendReason}; use crate::chatlist::Chatlist; use crate::constants::{self, Chattype}; use crate::imex::{imex, ImexMode}; use crate::receive_imf::receive_imf; use crate::stock_str::{self, chat_protection_enabled}; use crate::test_utils::get_chat_msg; use crate::test_utils::{TestContext, TestContextManager}; use crate::tools::SystemTime; use std::collections::HashSet; use std::time::Duration;
projects__deltachat-core__rust__securejoin__.rs__function__4.txt
pub unsafe extern "C" fn dc_join_securejoin( mut context: *mut dc_context_t, mut qr: *const libc::c_char, ) -> uint32_t { let mut ret_chat_id: libc::c_int = 0 as libc::c_int; let mut ongoing_allocated: libc::c_int = 0 as libc::c_int; let mut contact_chat_id: uint32_t = 0 as libc::c_int as uint32_t; let mut join_vg: libc::c_int = 0 as libc::c_int; let mut qr_scan: *mut dc_lot_t = 0 as *mut dc_lot_t; let mut qr_locked: libc::c_int = 0 as libc::c_int; dc_log_info( context, 0 as libc::c_int, b"Requesting secure-join ...\0" as *const u8 as *const libc::c_char, ); dc_ensure_secret_key_exists(context); ongoing_allocated = dc_alloc_ongoing(context); if !(ongoing_allocated == 0 as libc::c_int) { qr_scan = dc_check_qr(context, qr); if qr_scan.is_null() || (*qr_scan).state != 200 as libc::c_int && (*qr_scan).state != 202 as libc::c_int { dc_log_error( context, 0 as libc::c_int, b"Unknown QR code.\0" as *const u8 as *const libc::c_char, ); } else { contact_chat_id = dc_create_chat_by_contact_id(context, (*qr_scan).id); if contact_chat_id == 0 as libc::c_int as libc::c_uint { dc_log_error( context, 0 as libc::c_int, b"Unknown contact.\0" as *const u8 as *const libc::c_char, ); } else if !((*context).shall_stop_ongoing != 0) { join_vg = ((*qr_scan).state == 202 as libc::c_int) as libc::c_int; (*context).bobs_status = 0 as libc::c_int; pthread_mutex_lock(&mut (*context).bobs_qr_critical); qr_locked = 1 as libc::c_int; (*context).bobs_qr_scan = qr_scan; if qr_locked != 0 { pthread_mutex_unlock(&mut (*context).bobs_qr_critical); qr_locked = 0 as libc::c_int; } if fingerprint_equals_sender( context, (*qr_scan).fingerprint, contact_chat_id, ) != 0 { dc_log_info( context, 0 as libc::c_int, b"Taking protocol shortcut.\0" as *const u8 as *const libc::c_char, ); (*context).bob_expects = 6 as libc::c_int; ((*context).cb) .expect( "non-null function pointer", )( context, 2061 as libc::c_int, chat_id_2_contact_id(context, contact_chat_id) as uintptr_t, 400 as libc::c_int as uintptr_t, ); let mut own_fingerprint: *mut libc::c_char = get_self_fingerprint( context, ); send_handshake_msg( context, contact_chat_id, if join_vg != 0 { b"vg-request-with-auth\0" as *const u8 as *const libc::c_char } else { b"vc-request-with-auth\0" as *const u8 as *const libc::c_char }, (*qr_scan).auth, own_fingerprint, if join_vg != 0 { (*qr_scan).text2 } else { 0 as *mut libc::c_char }, ); free(own_fingerprint as *mut libc::c_void); } else { (*context).bob_expects = 2 as libc::c_int; send_handshake_msg( context, contact_chat_id, if join_vg != 0 { b"vg-request\0" as *const u8 as *const libc::c_char } else { b"vc-request\0" as *const u8 as *const libc::c_char }, (*qr_scan).invitenumber, 0 as *const libc::c_char, 0 as *const libc::c_char, ); } while !((*context).shall_stop_ongoing != 0) { usleep((300 as libc::c_int * 1000 as libc::c_int) as __useconds_t); } } } } (*context).bob_expects = 0 as libc::c_int; if (*context).bobs_status == 1 as libc::c_int { if join_vg != 0 { ret_chat_id = dc_get_chat_id_by_grpid( context, (*qr_scan).text2, 0 as *mut libc::c_int, 0 as *mut libc::c_int, ) as libc::c_int; } else { ret_chat_id = contact_chat_id as libc::c_int; } } pthread_mutex_lock(&mut (*context).bobs_qr_critical); qr_locked = 1 as libc::c_int; (*context).bobs_qr_scan = 0 as *mut dc_lot_t; if qr_locked != 0 { pthread_mutex_unlock(&mut (*context).bobs_qr_critical); qr_locked = 0 as libc::c_int; } dc_lot_unref(qr_scan); if ongoing_allocated != 0 { dc_free_ongoing(context); } return ret_chat_id as uint32_t; }
projects/deltachat-core/c/dc_contact.c
uint32_t dc_contact_get_color(const dc_contact_t* contact) { if (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) { return 0x000000; } return dc_str_to_color(contact->addr); }
projects/deltachat-core/rust/contact.rs
pub fn get_color(&self) -> u32 { str_to_color(&self.addr.to_lowercase()) }
pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, } pub fn str_to_color(s: &str) -> u32 { rgb_to_u32(hsluv_to_rgb((str_to_angle(s), 100.0, 50.0))) }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__44.txt
pub unsafe extern "C" fn dc_contact_get_color( mut contact: *const dc_contact_t, ) -> uint32_t { if contact.is_null() || (*contact).magic != 0xc047ac7 as libc::c_int as libc::c_uint { return 0 as libc::c_int as uint32_t; } return dc_str_to_color((*contact).addr) as uint32_t; }
projects/deltachat-core/c/dc_chat.c
* If the group is already _promoted_ (any message was sent to the group), * all group members are informed by a special status message that is sent automatically by this function. * * If the group is a verified group, only verified contacts can be added to the group. * * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param chat_id The chat ID to add the contact to. Must be a group chat. * @param contact_id The contact ID to add to the chat. * @return 1=member added to group, 0=error */ int dc_add_contact_to_chat(dc_context_t* context, uint32_t chat_id, uint32_t contact_id /*may be DC_CONTACT_ID_SELF*/) { return dc_add_contact_to_chat_ex(context, chat_id, contact_id, 0); }
projects/deltachat-core/rust/chat.rs
pub async fn add_contact_to_chat( context: &Context, chat_id: ChatId, contact_id: ContactId, ) -> Result<()> { add_contact_to_chat_ex(context, Sync, chat_id, contact_id, false).await?; Ok(()) }
pub(crate) async fn add_contact_to_chat_ex( context: &Context, mut sync: sync::Sync, chat_id: ChatId, contact_id: ContactId, from_handshake: bool, ) -> Result<bool> { ensure!(!chat_id.is_special(), "can not add member to special chats"); let contact = Contact::get_by_id(context, contact_id).await?; let mut msg = Message::default(); chat_id.reset_gossiped_timestamp(context).await?; // this also makes sure, no contacts are added to special or normal chats let mut chat = Chat::load_from_db(context, chat_id).await?; ensure!( chat.typ == Chattype::Group || chat.typ == Chattype::Broadcast, "{} is not a group/broadcast where one can add members", chat_id ); ensure!( Contact::real_exists_by_id(context, contact_id).await? || contact_id == ContactId::SELF, "invalid contact_id {} for adding to group", contact_id ); ensure!(!chat.is_mailing_list(), "Mailing lists can't be changed"); ensure!( chat.typ != Chattype::Broadcast || contact_id != ContactId::SELF, "Cannot add SELF to broadcast." ); if !chat.is_self_in_chat(context).await? { context.emit_event(EventType::ErrorSelfNotInGroup( "Cannot add contact to group; self not in group.".into(), )); bail!("can not add contact because the account is not part of the group/broadcast"); } if from_handshake && chat.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 { chat.param.remove(Param::Unpromoted); chat.update_param(context).await?; let _ = context .sync_qr_code_tokens(Some(chat_id)) .await .log_err(context) .is_ok() && context.send_sync_msg().await.log_err(context).is_ok(); } if context.is_self_addr(contact.get_addr()).await? { // ourself is added using ContactId::SELF, do not add this address explicitly. // if SELF is not in the group, members cannot be added at all. warn!( context, "Invalid attempt to add self e-mail address to group." ); return Ok(false); } if is_contact_in_chat(context, chat_id, contact_id).await? { if !from_handshake { return Ok(true); } } else { // else continue and send status mail if chat.is_protected() && !contact.is_verified(context).await? { error!( context, "Cannot add non-bidirectionally verified contact {contact_id} to protected chat {chat_id}." ); return Ok(false); } if is_contact_in_chat(context, chat_id, contact_id).await? { return Ok(false); } add_to_chat_contacts_table(context, chat_id, &[contact_id]).await?; } if chat.typ == Chattype::Group && chat.is_promoted() { msg.viewtype = Viewtype::Text; let contact_addr = contact.get_addr().to_lowercase(); msg.text = stock_str::msg_add_member_local(context, &contact_addr, ContactId::SELF).await; msg.param.set_cmd(SystemMessage::MemberAddedToGroup); msg.param.set(Param::Arg, contact_addr); msg.param.set_int(Param::Arg2, from_handshake.into()); msg.id = send_msg(context, chat_id, &mut msg).await?; sync = Nosync; } context.emit_event(EventType::ChatModified(chat_id)); if sync.into() { chat.sync_contacts(context).await.log_err(context).ok(); } Ok(true) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct ContactId(u32); pub struct ChatId(u32);
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__126.txt
pub unsafe extern "C" fn dc_add_contact_to_chat_ex( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut contact_id: uint32_t, mut flags: libc::c_int, ) -> libc::c_int { let mut current_block: u64; let mut success: libc::c_int = 0 as libc::c_int; let mut contact: *mut dc_contact_t = dc_get_contact(context, contact_id); let mut chat: *mut dc_chat_t = dc_chat_new(context); let mut msg: *mut dc_msg_t = dc_msg_new_untyped(context); let mut self_addr: *mut libc::c_char = 0 as *mut libc::c_char; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || contact.is_null() || chat_id <= 9 as libc::c_int as libc::c_uint) { dc_reset_gossiped_timestamp(context, chat_id); if !(0 as libc::c_int == real_group_exists(context, chat_id) || 0 as libc::c_int == dc_real_contact_exists(context, contact_id) && contact_id != 1 as libc::c_int as libc::c_uint || 0 as libc::c_int == dc_chat_load_from_db(chat, chat_id)) { if !(dc_is_contact_in_chat(context, chat_id, 1 as libc::c_int as uint32_t) == 1 as libc::c_int) { dc_log_event( context, 410 as libc::c_int, 0 as libc::c_int, b"Cannot add contact to group; self not in group.\0" as *const u8 as *const libc::c_char, ); } else { if flags & 0x1 as libc::c_int != 0 && dc_param_get_int((*chat).param, 'U' as i32, 0 as libc::c_int) == 1 as libc::c_int { dc_param_set((*chat).param, 'U' as i32, 0 as *const libc::c_char); dc_chat_update_param(chat); } self_addr = dc_sqlite3_get_config( (*context).sql, b"configured_addr\0" as *const u8 as *const libc::c_char, b"\0" as *const u8 as *const libc::c_char, ); if !(strcasecmp((*contact).addr, self_addr) == 0 as libc::c_int) { if dc_is_contact_in_chat(context, chat_id, contact_id) != 0 { if flags & 0x1 as libc::c_int == 0 { success = 1 as libc::c_int; current_block = 9909809848178435643; } else { current_block = 5601891728916014340; } } else { if (*chat).type_0 == 130 as libc::c_int { if dc_contact_is_verified(contact) != 2 as libc::c_int { dc_log_error( context, 0 as libc::c_int, b"Only bidirectional verified contacts can be added to verified groups.\0" as *const u8 as *const libc::c_char, ); current_block = 9909809848178435643; } else { current_block = 2370887241019905314; } } else { current_block = 2370887241019905314; } match current_block { 9909809848178435643 => {} _ => { if 0 as libc::c_int == dc_add_to_chat_contacts_table( context, chat_id, contact_id, ) { current_block = 9909809848178435643; } else { current_block = 5601891728916014340; } } } } match current_block { 9909809848178435643 => {} _ => { if dc_param_get_int( (*chat).param, 'U' as i32, 0 as libc::c_int, ) == 0 as libc::c_int { (*msg).type_0 = 10 as libc::c_int; (*msg) .text = dc_stock_system_msg( context, 17 as libc::c_int, (*contact).addr, 0 as *const libc::c_char, 1 as libc::c_int as uint32_t, ); dc_param_set_int( (*msg).param, 'S' as i32, 4 as libc::c_int, ); dc_param_set((*msg).param, 'E' as i32, (*contact).addr); dc_param_set_int((*msg).param, 'F' as i32, flags); (*msg).id = dc_send_msg(context, chat_id, msg); ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, chat_id as uintptr_t, (*msg).id as uintptr_t, ); } ((*context).cb) .expect( "non-null function pointer", )( context, 2020 as libc::c_int, chat_id as uintptr_t, 0 as libc::c_int as uintptr_t, ); success = 1 as libc::c_int; } } } } } } dc_chat_unref(chat); dc_contact_unref(contact); dc_msg_unref(msg); free(self_addr as *mut libc::c_void); return success; }
projects/deltachat-core/c/dc_param.c
void dc_param_set_int(dc_param_t* param, int key, int32_t value) { if (param==NULL || key==0) { return; } char* value_str = dc_mprintf("%i", (int)value); if (value_str==NULL) { return; } dc_param_set(param, key, value_str); free(value_str); }
projects/deltachat-core/rust/param.rs
pub fn set_int(&mut self, key: Param, value: i32) -> &mut Self { self.set(key, format!("{value}")); self }
pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self { self.inner.insert(key, value.to_string()); self } pub struct Params { inner: BTreeMap<Param, String>, }
use std::collections::BTreeMap; use std::fmt; use std::path::PathBuf; use std::str; use anyhow::{bail, Error, Result}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use crate::blob::BlobObject; use crate::context::Context; use crate::mimeparser::SystemMessage; use std::path::Path; use std::str::FromStr; use tokio::fs; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__param__.rs__function__20.txt
pub unsafe extern "C" fn dc_param_set_int( mut param: *mut dc_param_t, mut key: libc::c_int, mut value: int32_t, ) { if param.is_null() || key == 0 as libc::c_int { return; } let mut value_str: *mut libc::c_char = dc_mprintf( b"%i\0" as *const u8 as *const libc::c_char, value, ); if value_str.is_null() { return; } dc_param_set(param, key, value_str); free(value_str as *mut libc::c_void); }
projects/deltachat-core/c/dc_param.c
char* dc_param_get(const dc_param_t* param, int key, const char* def) { char* p1 = NULL; char* p2 = NULL; char bak = 0; char* ret = NULL; if (param==NULL || key==0) { return def? dc_strdup(def) : NULL; } p1 = find_param(param->packed, key, &p2); if (p1==NULL) { return def? dc_strdup(def) : NULL; } p1 += 2; /* skip key and "=" (safe as find_param checks for its existance) */ bak = *p2; *p2 = 0; ret = dc_strdup(p1); dc_rtrim(ret); /* to be safe with '\r' characters ... */ *p2 = bak; return ret; }
projects/deltachat-core/rust/param.rs
pub fn get(&self, key: Param) -> Option<&str> { self.inner.get(&key).map(|s| s.as_str()) }
pub struct Params { inner: BTreeMap<Param, String>, }
use std::collections::BTreeMap; use std::fmt; use std::path::PathBuf; use std::str; use anyhow::{bail, Error, Result}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use crate::blob::BlobObject; use crate::context::Context; use crate::mimeparser::SystemMessage; use std::path::Path; use std::str::FromStr; use tokio::fs; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__param__.rs__function__4.txt
pub unsafe extern "C" fn dc_param_get( mut param: *const dc_param_t, mut key: libc::c_int, mut def: *const libc::c_char, ) -> *mut libc::c_char { let mut p1: *mut libc::c_char = 0 as *mut libc::c_char; let mut p2: *mut libc::c_char = 0 as *mut libc::c_char; let mut bak: libc::c_char = 0 as libc::c_int as libc::c_char; let mut ret: *mut libc::c_char = 0 as *mut libc::c_char; if param.is_null() || key == 0 as libc::c_int { return if !def.is_null() { dc_strdup(def) } else { 0 as *mut libc::c_char }; } p1 = find_param((*param).packed, key, &mut p2); if p1.is_null() { return if !def.is_null() { dc_strdup(def) } else { 0 as *mut libc::c_char }; } p1 = p1.offset(2 as libc::c_int as isize); bak = *p2; *p2 = 0 as libc::c_int as libc::c_char; ret = dc_strdup(p1); dc_rtrim(ret); *p2 = bak; return ret; }
projects/deltachat-core/c/dc_oauth2.c
static void replace_in_uri(char** uri, const char* key, const char* value) { if (uri && key && value) { char* value_urlencoded = dc_urlencode(value); dc_str_replace(uri, key, value_urlencoded); free(value_urlencoded); } }
projects/deltachat-core/rust/oauth2.rs
fn replace_in_uri(uri: &str, key: &str, value: &str) -> String { let value_urlencoded = utf8_percent_encode(value, NON_ALPHANUMERIC).to_string(); uri.replace(key, &value_urlencoded) }
use std::collections::HashMap; use anyhow::Result; use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC}; use serde::Deserialize; use crate::config::Config; use crate::context::Context; use crate::provider; use crate::provider::Oauth2Authorizer; use crate::socks::Socks5Config; use crate::tools::time; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__oauth2__.rs__function__7.txt
unsafe extern "C" fn replace_in_uri( mut uri: *mut *mut libc::c_char, mut key: *const libc::c_char, mut value: *const libc::c_char, ) { if !uri.is_null() && !key.is_null() && !value.is_null() { let mut value_urlencoded: *mut libc::c_char = dc_urlencode(value); dc_str_replace(uri, key, value_urlencoded); free(value_urlencoded as *mut libc::c_void); } }
projects/deltachat-core/c/dc_msg.c
uint32_t dc_msg_get_id(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->id; }
projects/deltachat-core/rust/message.rs
pub fn get_id(&self) -> MsgId { self.id }
pub struct MsgId(u32); pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__30.txt
pub unsafe extern "C" fn dc_msg_get_id(mut msg: *const dc_msg_t) -> uint32_t { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return 0 as libc::c_int as uint32_t; } return (*msg).id; }
projects/deltachat-core/c/dc_chat.c
int dc_get_msg_cnt(dc_context_t* context, uint32_t chat_id) { int ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM msgs WHERE chat_id=?;"); sqlite3_bind_int(stmt, 1, chat_id); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/rust/chat.rs
pub async fn get_msg_cnt(self, context: &Context) -> Result<usize> { let count = context .sql .count( "SELECT COUNT(*) FROM msgs WHERE hidden=0 AND chat_id=?", (self,), ) .await?; Ok(count) }
pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result<usize> { let count: isize = self.query_row(query, params, |row| row.get(0)).await?; Ok(usize::try_from(count)?) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result<usize> { let count: isize = self.query_row(query, params, |row| row.get(0)).await?; Ok(usize::try_from(count)?) } pub struct ChatId(u32);
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__36.txt
pub unsafe extern "C" fn dc_get_msg_cnt( mut context: *mut dc_context_t, mut chat_id: uint32_t, ) -> libc::c_int { let mut ret: libc::c_int = 0 as libc::c_int; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint) { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT COUNT(*) FROM msgs WHERE chat_id=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, chat_id as libc::c_int); if !(sqlite3_step(stmt) != 100 as libc::c_int) { ret = sqlite3_column_int(stmt, 0 as libc::c_int); } } sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/c/dc_configure.c
static int get_folder_meaning_by_name(const char* folder_name) { // try to get the folder meaning by the name of the folder. // only used if the server does not support XLIST. int ret_meaning = MEANING_UNKNOWN; // TODO: lots languages missing - maybe there is a list somewhere on other MUAs? // however, if we fail to find out the sent-folder, // only watching this folder is not working. at least, this is no show stopper. // CAVE: if possible, take care not to add a name here that is "sent" in one language // but sth. different in others - a hard job. static const char* sent_names = "sent,sentmail,sent objects,gesendet,Sent Mail,Sendte e-mails,Enviados," "Messages envoyés,Messages envoyes,Posta inviata,Verzonden berichten," "Wyslane,E-mails enviados,Correio enviado,Enviada,Enviado,Gönderildi," "Inviati,Odeslaná pošta,Sendt,Skickat,Verzonden,Wysłane,Éléments envoyés," "Απεσταλμένα,Отправленные,寄件備份,已发送邮件,送信済み,보낸편지함"; static const char* spam_names = "spam,junk,Correio electrónico não solicitado,Correo basura,Lixo,Nettsøppel," "Nevyžádaná pošta,No solicitado,Ongewenst,Posta indesiderata,Skräp," "Wiadomości-śmieci,Önemsiz,Ανεπιθύμητα,Спам,垃圾邮件,垃圾郵件,迷惑メール,스팸"; static const char* draft_names = "Drafts,Kladder,Entw?rfe,Borradores,Brouillons,Bozze,Concepten," "Wersje robocze,Rascunhos,Entwürfe,Koncepty,Kopie robocze,Taslaklar," "Utkast,Πρόχειρα,Черновики,下書き,草稿,임시보관함"; static const char* trash_names = "Trash,Bin,Caixote do lixo,Cestino,Corbeille,Papelera,Papierkorb," "Papirkurv,Papperskorgen,Prullenbak,Rubujo,Κάδος απορριμμάτων,Корзина," "Кошик,ゴミ箱,垃圾桶,已删除邮件,휴지통"; char* lower = dc_mprintf(",%s,", folder_name); dc_strlower_in_place(lower); if (strstr(sent_names, lower)!=NULL) { ret_meaning = MEANING_SENT_OBJECTS; } else if (strstr(spam_names, lower)!=NULL) { ret_meaning = MEANING_SPAM; } else if (strstr(draft_names, lower)!=NULL) { ret_meaning = MEANING_DRAFT; } else if (strstr(trash_names, lower)!=NULL) { ret_meaning = MEANING_TRASH; } free(lower); return ret_meaning; }
projects/deltachat-core/rust/imap.rs
fn get_folder_meaning_by_name(folder_name: &str) -> FolderMeaning { // source: <https://stackoverflow.com/questions/2185391/localized-gmail-imap-folders> const SENT_NAMES: &[&str] = &[ "sent", "sentmail", "sent objects", "gesendet", "Sent Mail", "Sendte e-mails", "Enviados", "Messages envoyés", "Messages envoyes", "Posta inviata", "Verzonden berichten", "Wyslane", "E-mails enviados", "Correio enviado", "Enviada", "Enviado", "Gönderildi", "Inviati", "Odeslaná pošta", "Sendt", "Skickat", "Verzonden", "Wysłane", "Éléments envoyés", "Απεσταλμένα", "Отправленные", "寄件備份", "已发送邮件", "送信済み", "보낸편지함", ]; const SPAM_NAMES: &[&str] = &[ "spam", "junk", "Correio electrónico não solicitado", "Correo basura", "Lixo", "Nettsøppel", "Nevyžádaná pošta", "No solicitado", "Ongewenst", "Posta indesiderata", "Skräp", "Wiadomości-śmieci", "Önemsiz", "Ανεπιθύμητα", "Спам", "垃圾邮件", "垃圾郵件", "迷惑メール", "스팸", ]; const DRAFT_NAMES: &[&str] = &[ "Drafts", "Kladder", "Entw?rfe", "Borradores", "Brouillons", "Bozze", "Concepten", "Wersje robocze", "Rascunhos", "Entwürfe", "Koncepty", "Kopie robocze", "Taslaklar", "Utkast", "Πρόχειρα", "Черновики", "下書き", "草稿", "임시보관함", ]; const TRASH_NAMES: &[&str] = &[ "Trash", "Bin", "Caixote do lixo", "Cestino", "Corbeille", "Papelera", "Papierkorb", "Papirkurv", "Papperskorgen", "Prullenbak", "Rubujo", "Κάδος απορριμμάτων", "Корзина", "Кошик", "ゴミ箱", "垃圾桶", "已删除邮件", "휴지통", ]; let lower = folder_name.to_lowercase(); if SENT_NAMES.iter().any(|s| s.to_lowercase() == lower) { FolderMeaning::Sent } else if SPAM_NAMES.iter().any(|s| s.to_lowercase() == lower) { FolderMeaning::Spam } else if DRAFT_NAMES.iter().any(|s| s.to_lowercase() == lower) { FolderMeaning::Drafts } else if TRASH_NAMES.iter().any(|s| s.to_lowercase() == lower) { FolderMeaning::Trash } else { FolderMeaning::Unknown } }
pub enum FolderMeaning { Unknown, /// Spam folder. Spam, Inbox, Mvbox, Sent, Trash, Drafts, /// Virtual folders. /// /// On Gmail there are virtual folders marked as \\All, \\Important and \\Flagged. /// Delta Chat ignores these folders because the same messages can be fetched /// from the real folder and the result of moving and deleting messages via /// virtual folder is unclear. Virtual, }
use std::{ cmp::max, cmp::min, collections::{BTreeMap, BTreeSet, HashMap}, iter::Peekable, mem::take, sync::atomic::Ordering, time::{Duration, UNIX_EPOCH}, }; use anyhow::{bail, format_err, Context as _, Result}; use async_channel::Receiver; use async_imap::types::{Fetch, Flag, Name, NameAttribute, UnsolicitedResponse}; use deltachat_contact_tools::{normalize_name, ContactAddress}; use futures::{FutureExt as _, StreamExt, TryStreamExt}; use futures_lite::FutureExt; use num_traits::FromPrimitive; use rand::Rng; use ratelimit::Ratelimit; use url::Url; use crate::chat::{self, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{self, Blocked, Chattype, ShowEmails}; use crate::contact::{Contact, ContactId, Modifier, Origin}; use crate::context::Context; use crate::events::EventType; use crate::headerdef::{HeaderDef, HeaderDefMap}; use crate::login_param::{CertificateChecks, LoginParam, ServerLoginParam}; use crate::message::{self, Message, MessageState, MessengerMessage, MsgId, Viewtype}; use crate::mimeparser; use crate::oauth2::get_oauth2_access_token; use crate::provider::Socket; use crate::receive_imf::{ from_field_to_contact_id, get_prefetch_parent_message, receive_imf_inner, ReceivedMsg, }; use crate::scheduler::connectivity::ConnectivityStore; use crate::socks::Socks5Config; use crate::sql; use crate::stock_str; use crate::tools::{self, create_id, duration_to_str}; use client::Client; use mailparse::SingleInfo; use session::Session; use async_imap::imap_proto::Response; use async_imap::imap_proto::ResponseCode; use UnsolicitedResponse::*; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__imap__.rs__function__32.txt
unsafe extern "C" fn get_folder_meaning_by_name( mut folder_name: *const libc::c_char, ) -> libc::c_int { let mut ret_meaning: libc::c_int = 0 as libc::c_int; static mut sent_names: *const libc::c_char = b",sent,sent objects,gesendet,\0" as *const u8 as *const libc::c_char; let mut lower: *mut libc::c_char = dc_mprintf( b",%s,\0" as *const u8 as *const libc::c_char, folder_name, ); dc_strlower_in_place(lower); if !(strstr(sent_names, lower)).is_null() { ret_meaning = 1 as libc::c_int; } free(lower as *mut libc::c_void); return ret_meaning; }
projects/deltachat-core/c/dc_chat.c
char* dc_chat_get_name(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return dc_strdup("Err"); } return dc_strdup(chat->name); }
projects/deltachat-core/rust/chat.rs
pub fn get_name(&self) -> &str { &self.name }
pub struct Chat { /// Database ID. pub id: ChatId, /// Chat type, e.g. 1:1 chat, group chat, mailing list. pub typ: Chattype, /// Chat name. pub name: String, /// Whether the chat is archived or pinned. pub visibility: ChatVisibility, /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and /// ad-hoc groups. pub grpid: String, /// Whether the chat is blocked, unblocked or a contact request. pub blocked: Blocked, /// Additional chat parameters stored in the database. pub param: Params, /// If location streaming is enabled in the chat. is_sending_locations: bool, /// Duration of the chat being muted. pub mute_duration: MuteDuration, /// If the chat is protected (verified). pub(crate) protected: ProtectionStatus, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__71.txt
pub unsafe extern "C" fn dc_chat_get_name( mut chat: *const dc_chat_t, ) -> *mut libc::c_char { if chat.is_null() || (*chat).magic != 0xc4a7c4a7 as libc::c_uint { return dc_strdup(b"Err\0" as *const u8 as *const libc::c_char); } return dc_strdup((*chat).name); }
projects/deltachat-core/c/dc_chat.c
int dc_get_fresh_msg_cnt(dc_context_t* context, uint32_t chat_id) { int ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (chat_id == DC_CHAT_ID_ARCHIVED_LINK){ stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(DISTINCT(m.chat_id))" "FROM msgs m" "LEFT JOIN chats c ON m.chat_id=c.id" "WHERE m.state=10" "and m.hidden=0" "AND m.chat_id>9" "AND c.blocked=0" "AND c.archived=1;"); } else{ stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM msgs " " WHERE state=" DC_STRINGIFY(DC_STATE_IN_FRESH) " AND hidden=0 " " AND chat_id=?;"); /* we have an index over the state-column, this should be sufficient as there are typically only few fresh messages */ sqlite3_bind_int(stmt, 1, chat_id); } if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/rust/chat.rs
pub async fn get_fresh_msg_cnt(self, context: &Context) -> Result<usize> { // this function is typically used to show a badge counter beside _each_ chatlist item. // to make this as fast as possible, esp. on older devices, we added an combined index over the rows used for querying. // so if you alter the query here, you may want to alter the index over `(state, hidden, chat_id)` in `sql.rs`. // // the impact of the index is significant once the database grows: // - on an older android4 with 18k messages, query-time decreased from 110ms to 2ms // - on an mid-class moto-g or iphone7 with 50k messages, query-time decreased from 26ms or 6ms to 0-1ms // the times are average, no matter if there are fresh messages or not - // and have to be multiplied by the number of items shown at once on the chatlist, // so savings up to 2 seconds are possible on older devices - newer ones will feel "snappier" :) let count = if self.is_archived_link() { context .sql .count( "SELECT COUNT(DISTINCT(m.chat_id)) FROM msgs m LEFT JOIN chats c ON m.chat_id=c.id WHERE m.state=10 and m.hidden=0 AND m.chat_id>9 AND c.blocked=0 AND c.archived=1 ", (), ) .await? } else { context .sql .count( "SELECT COUNT(*) FROM msgs WHERE state=? AND hidden=0 AND chat_id=?;", (MessageState::InFresh, self), ) .await? }; Ok(count) }
pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result<usize> { let count: isize = self.query_row(query, params, |row| row.get(0)).await?; Ok(usize::try_from(count)?) } pub fn is_archived_link(self) -> bool { self == DC_CHAT_ID_ARCHIVED_LINK } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result<usize> { let count: isize = self.query_row(query, params, |row| row.get(0)).await?; Ok(usize::try_from(count)?) } pub struct ChatId(u32); pub enum MessageState { /// Undefined message state. #[default] Undefined = 0, /// Incoming *fresh* message. Fresh messages are neither noticed /// nor seen and are typically shown in notifications. InFresh = 10, /// Incoming *noticed* message. E.g. chat opened but message not /// yet read - noticed messages are not counted as unread but did /// not marked as read nor resulted in MDNs. InNoticed = 13, /// Incoming message, really *seen* by the user. Marked as read on /// IMAP and MDN may be sent. InSeen = 16, /// For files which need time to be prepared before they can be /// sent, the message enters this state before /// OutPending. OutPreparing = 18, /// Message saved as draft. OutDraft = 19, /// The user has pressed the "send" button but the message is not /// yet sent and is pending in some way. Maybe we're offline (no /// checkmark). OutPending = 20, /// *Unrecoverable* error (*recoverable* errors result in pending /// messages). OutFailed = 24, /// Outgoing message successfully delivered to server (one /// checkmark). Note, that already delivered messages may get into /// the OutFailed state if we get such a hint from the server. OutDelivered = 26, /// Outgoing message read by the recipient (two checkmarks; this /// requires goodwill on the receiver's side) OutMdnRcvd = 28, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__37.txt
pub unsafe extern "C" fn dc_get_fresh_msg_cnt( mut context: *mut dc_context_t, mut chat_id: uint32_t, ) -> libc::c_int { let mut ret: libc::c_int = 0 as libc::c_int; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint) { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT COUNT(*) FROM msgs WHERE state=10 AND hidden=0 AND chat_id=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, chat_id as libc::c_int); if !(sqlite3_step(stmt) != 100 as libc::c_int) { ret = sqlite3_column_int(stmt, 0 as libc::c_int); } } sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/c/dc_apeerstate.c
void dc_apeerstate_apply_header(dc_apeerstate_t* peerstate, const dc_aheader_t* header, time_t message_time) { if (peerstate==NULL || header==NULL || peerstate->addr==NULL || header->addr==NULL || header->public_key->binary==NULL || strcasecmp(peerstate->addr, header->addr)!=0) { return; } if (message_time > peerstate->last_seen_autocrypt) { peerstate->last_seen = message_time; peerstate->last_seen_autocrypt = message_time; if ((header->prefer_encrypt==DC_PE_MUTUAL || header->prefer_encrypt==DC_PE_NOPREFERENCE) /*this also switches from DC_PE_RESET to DC_PE_NOPREFERENCE, which is just fine as the function is only called _if_ the Autocrypt:-header is preset at all */ && header->prefer_encrypt!=peerstate->prefer_encrypt) { peerstate->prefer_encrypt = header->prefer_encrypt; } if (peerstate->public_key==NULL) { peerstate->public_key = dc_key_new(); } if (!dc_key_equals(peerstate->public_key, header->public_key)) { dc_key_set_from_key(peerstate->public_key, header->public_key); dc_apeerstate_recalc_fingerprint(peerstate); } } }
projects/deltachat-core/rust/peerstate.rs
pub fn apply_header(&mut self, header: &Aheader, message_time: i64) { if !addr_cmp(&self.addr, &header.addr) { return; } if message_time >= self.last_seen { self.last_seen = message_time; self.last_seen_autocrypt = message_time; if (header.prefer_encrypt == EncryptPreference::Mutual || header.prefer_encrypt == EncryptPreference::NoPreference) && header.prefer_encrypt != self.prefer_encrypt { self.prefer_encrypt = header.prefer_encrypt; } if self.public_key.as_ref() != Some(&header.public_key) { self.public_key = Some(header.public_key.clone()); self.recalc_fingerprint(); } } }
pub fn recalc_fingerprint(&mut self) { if let Some(ref public_key) = self.public_key { let old_public_fingerprint = self.public_key_fingerprint.take(); self.public_key_fingerprint = Some(public_key.fingerprint()); if old_public_fingerprint.is_some() && old_public_fingerprint != self.public_key_fingerprint { self.fingerprint_changed = true; } } if let Some(ref gossip_key) = self.gossip_key { let old_gossip_fingerprint = self.gossip_key_fingerprint.take(); self.gossip_key_fingerprint = Some(gossip_key.fingerprint()); if old_gossip_fingerprint.is_none() || self.gossip_key_fingerprint.is_none() || old_gossip_fingerprint != self.gossip_key_fingerprint { // Warn about gossip key change only if there is no public key obtained from // Autocrypt header, which overrides gossip key. if old_gossip_fingerprint.is_some() && self.public_key_fingerprint.is_none() { self.fingerprint_changed = true; } } } } pub struct Aheader { pub addr: String, pub public_key: SignedPublicKey, pub prefer_encrypt: EncryptPreference, } pub enum EncryptPreference { #[default] NoPreference = 0, Mutual = 1, Reset = 20, } pub struct Peerstate { /// E-mail address of the contact. pub addr: String, /// Timestamp of the latest peerstate update. /// /// Updated when a message is received from a contact, /// either with or without `Autocrypt` header. pub last_seen: i64, /// Timestamp of the latest `Autocrypt` header reception. pub last_seen_autocrypt: i64, /// Encryption preference of the contact. pub prefer_encrypt: EncryptPreference, /// Public key of the contact received in `Autocrypt` header. pub public_key: Option<SignedPublicKey>, /// Fingerprint of the contact public key. pub public_key_fingerprint: Option<Fingerprint>, /// Public key of the contact received in `Autocrypt-Gossip` header. pub gossip_key: Option<SignedPublicKey>, /// Timestamp of the latest `Autocrypt-Gossip` header reception. /// /// It is stored to avoid applying outdated gossiped key /// from delayed or reordered messages. pub gossip_timestamp: i64, /// Fingerprint of the contact gossip key. pub gossip_key_fingerprint: Option<Fingerprint>, /// Public key of the contact at the time it was verified, /// either directly or via gossip from the verified contact. pub verified_key: Option<SignedPublicKey>, /// Fingerprint of the verified public key. pub verified_key_fingerprint: Option<Fingerprint>, /// The address that introduced this verified key. pub verifier: Option<String>, /// Secondary public verified key of the contact. /// It could be a contact gossiped by another verified contact in a shared group /// or a key that was previously used as a verified key. pub secondary_verified_key: Option<SignedPublicKey>, /// Fingerprint of the secondary verified public key. pub secondary_verified_key_fingerprint: Option<Fingerprint>, /// The address that introduced secondary verified key. pub secondary_verifier: Option<String>, /// Row ID of the key in the `keypairs` table /// that we think the peer knows as verified. pub backward_verified_key_id: Option<i64>, /// True if it was detected /// that the fingerprint of the key used in chats with /// opportunistic encryption was changed after Peerstate creation. pub fingerprint_changed: bool, }
use std::mem; use anyhow::{Context as _, Error, Result}; use deltachat_contact_tools::{addr_cmp, ContactAddress}; use num_traits::FromPrimitive; use crate::aheader::{Aheader, EncryptPreference}; use crate::chat::{self, Chat}; use crate::chatlist::Chatlist; use crate::config::Config; use crate::constants::Chattype; use crate::contact::{Contact, Origin}; use crate::context::Context; use crate::events::EventType; use crate::key::{DcKey, Fingerprint, SignedPublicKey}; use crate::message::Message; use crate::mimeparser::SystemMessage; use crate::sql::Sql; use crate::{chatlist_events, stock_str}; use super::*; use crate::test_utils::alice_keypair;
projects__deltachat-core__rust__peerstate__.rs__function__10.txt
pub unsafe extern "C" fn dc_apeerstate_apply_header( mut peerstate: *mut dc_apeerstate_t, mut header: *const dc_aheader_t, mut message_time: time_t, ) { if peerstate.is_null() || header.is_null() || ((*peerstate).addr).is_null() || ((*header).addr).is_null() || ((*(*header).public_key).binary).is_null() || strcasecmp((*peerstate).addr, (*header).addr) != 0 as libc::c_int { return; } if message_time > (*peerstate).last_seen_autocrypt { (*peerstate).last_seen = message_time; (*peerstate).last_seen_autocrypt = message_time; (*peerstate).to_save |= 0x1 as libc::c_int; if ((*header).prefer_encrypt == 1 as libc::c_int || (*header).prefer_encrypt == 0 as libc::c_int) && (*header).prefer_encrypt != (*peerstate).prefer_encrypt { if (*peerstate).prefer_encrypt == 1 as libc::c_int && (*header).prefer_encrypt != 1 as libc::c_int { (*peerstate).degrade_event |= 0x1 as libc::c_int; } (*peerstate).prefer_encrypt = (*header).prefer_encrypt; (*peerstate).to_save |= 0x2 as libc::c_int; } if ((*peerstate).public_key).is_null() { (*peerstate).public_key = dc_key_new(); } if dc_key_equals((*peerstate).public_key, (*header).public_key) == 0 { dc_key_set_from_key((*peerstate).public_key, (*header).public_key); dc_apeerstate_recalc_fingerprint(peerstate); (*peerstate).to_save |= 0x2 as libc::c_int; } } }
projects/deltachat-core/c/dc_param.c
void dc_param_set(dc_param_t* param, int key, const char* value) { char* old1 = NULL; char* old2 = NULL; char* new1 = NULL; if (param==NULL || key==0) { return; } old1 = param->packed; old2 = NULL; /* remove existing parameter from packed string, if any */ if (old1) { char *p1, *p2; p1 = find_param(old1, key, &p2); if (p1 != NULL) { *p1 = 0; old2 = p2; } else if (value==NULL) { return; /* parameter does not exist and should be cleared -> done. */ } } dc_rtrim(old1); /* trim functions are null-pointer-safe */ dc_ltrim(old2); if (old1 && old1[0]==0) { old1 = NULL; } if (old2 && old2[0]==0) { old2 = NULL; } /* create new string */ if (value) { new1 = dc_mprintf("%s%s%c=%s%s%s", old1? old1 : "", old1? "\n" : "", key, value, old2? "\n" : "", old2? old2 : ""); } else { new1 = dc_mprintf("%s%s%s", old1? old1 : "", (old1&&old2)? "\n" : "", old2? old2 : ""); } free(param->packed); param->packed = new1; }
projects/deltachat-core/rust/param.rs
pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self { self.inner.insert(key, value.to_string()); self }
pub struct Params { inner: BTreeMap<Param, String>, }
use std::collections::BTreeMap; use std::fmt; use std::path::PathBuf; use std::str; use anyhow::{bail, Error, Result}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use crate::blob::BlobObject; use crate::context::Context; use crate::mimeparser::SystemMessage; use std::path::Path; use std::str::FromStr; use tokio::fs; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__param__.rs__function__6.txt
pub unsafe extern "C" fn dc_param_set( mut param: *mut dc_param_t, mut key: libc::c_int, mut value: *const libc::c_char, ) { let mut old1: *mut libc::c_char = 0 as *mut libc::c_char; let mut old2: *mut libc::c_char = 0 as *mut libc::c_char; let mut new1: *mut libc::c_char = 0 as *mut libc::c_char; if param.is_null() || key == 0 as libc::c_int { return; } old1 = (*param).packed; old2 = 0 as *mut libc::c_char; if !old1.is_null() { let mut p1: *mut libc::c_char = 0 as *mut libc::c_char; let mut p2: *mut libc::c_char = 0 as *mut libc::c_char; p1 = find_param(old1, key, &mut p2); if !p1.is_null() { *p1 = 0 as libc::c_int as libc::c_char; old2 = p2; } else if value.is_null() { return } } dc_rtrim(old1); dc_ltrim(old2); if !old1.is_null() && *old1.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int { old1 = 0 as *mut libc::c_char; } if !old2.is_null() && *old2.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int { old2 = 0 as *mut libc::c_char; } if !value.is_null() { new1 = dc_mprintf( b"%s%s%c=%s%s%s\0" as *const u8 as *const libc::c_char, if !old1.is_null() { old1 as *const libc::c_char } else { b"\0" as *const u8 as *const libc::c_char }, if !old1.is_null() { b"\n\0" as *const u8 as *const libc::c_char } else { b"\0" as *const u8 as *const libc::c_char }, key, value, if !old2.is_null() { b"\n\0" as *const u8 as *const libc::c_char } else { b"\0" as *const u8 as *const libc::c_char }, if !old2.is_null() { old2 as *const libc::c_char } else { b"\0" as *const u8 as *const libc::c_char }, ); } else { new1 = dc_mprintf( b"%s%s%s\0" as *const u8 as *const libc::c_char, if !old1.is_null() { old1 as *const libc::c_char } else { b"\0" as *const u8 as *const libc::c_char }, if !old1.is_null() && !old2.is_null() { b"\n\0" as *const u8 as *const libc::c_char } else { b"\0" as *const u8 as *const libc::c_char }, if !old2.is_null() { old2 as *const libc::c_char } else { b"\0" as *const u8 as *const libc::c_char }, ); } free((*param).packed as *mut libc::c_void); (*param).packed = new1; }
projects/deltachat-core/c/dc_sqlite3.c
int dc_sqlite3_table_exists(dc_sqlite3_t* sql, const char* name) { int ret = 0; char* querystr = NULL; sqlite3_stmt* stmt = NULL; int sqlState = 0; if ((querystr=sqlite3_mprintf("PRAGMA table_info(%s)", name))==NULL) { /* this statement cannot be used with binded variables */ dc_log_error(sql->context, 0, "dc_sqlite3_table_exists_(): Out of memory."); goto cleanup; } if ((stmt=dc_sqlite3_prepare(sql, querystr))==NULL) { goto cleanup; } sqlState = sqlite3_step(stmt); if (sqlState==SQLITE_ROW) { ret = 1; /* the table exists. Other states are SQLITE_DONE or SQLITE_ERROR in both cases we return 0. */ } /* success - fall through to free allocated objects */ ; /* error/cleanup */ cleanup: if (stmt) { sqlite3_finalize(stmt); } if (querystr) { sqlite3_free(querystr); } return ret; }
projects/deltachat-core/rust/sql.rs
pub async fn table_exists(&self, name: &str) -> Result<bool> { self.call(move |conn| { let mut exists = false; conn.pragma(None, "table_info", name.to_string(), |_row| { // will only be executed if the info was found exists = true; Ok(()) })?; Ok(exists) }) .await }
async fn call<'a, F, R>(&'a self, function: F) -> Result<R> where F: 'a + FnOnce(&mut Connection) -> Result<R> + Send, R: Send + 'static, { let lock = self.pool.read().await; let pool = lock.as_ref().context("no SQL connection")?; let mut conn = pool.get().await?; let res = tokio::task::block_in_place(move || function(&mut conn))?; Ok(res) } pub struct Sql { /// Database file path pub(crate) dbfile: PathBuf, /// Write transactions mutex. /// /// See [`Self::write_lock`]. write_mtx: Mutex<()>, /// SQL connection pool. pool: RwLock<Option<Pool>>, /// None if the database is not open, true if it is open with passphrase and false if it is /// open without a passphrase. is_encrypted: RwLock<Option<bool>>, /// Cache of `config` table. pub(crate) config_cache: RwLock<HashMap<String, Option<String>>>, }
use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use anyhow::{bail, Context as _, Result}; use rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row}; use tokio::sync::{Mutex, MutexGuard, RwLock}; use crate::blob::BlobObject; use crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon}; use crate::config::Config; use crate::constants::DC_CHAT_ID_TRASH; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::ephemeral::start_ephemeral_timers; use crate::imex::BLOBS_BACKUP_NAME; use crate::location::delete_orphaned_poi_locations; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::stock_str; use crate::tools::{delete_file, time, SystemTime}; use pool::Pool; use super::*; use crate::{test_utils::TestContext, EventType}; use tempfile::tempdir; use tempfile::tempdir; use tempfile::tempdir;
projects__deltachat-core__rust__sql__.rs__function__23.txt
pub unsafe extern "C" fn dc_sqlite3_table_exists( mut sql: *mut dc_sqlite3_t, mut name: *const libc::c_char, ) -> libc::c_int { let mut ret: libc::c_int = 0 as libc::c_int; let mut querystr: *mut libc::c_char = 0 as *mut libc::c_char; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; let mut sqlState: libc::c_int = 0 as libc::c_int; querystr = sqlite3_mprintf( b"PRAGMA table_info(%s)\0" as *const u8 as *const libc::c_char, name, ); if querystr.is_null() { dc_log_error( (*sql).context, 0 as libc::c_int, b"dc_sqlite3_table_exists_(): Out of memory.\0" as *const u8 as *const libc::c_char, ); } else { stmt = dc_sqlite3_prepare(sql, querystr); if !stmt.is_null() { sqlState = sqlite3_step(stmt); if sqlState == 100 as libc::c_int { ret = 1 as libc::c_int; } } } if !stmt.is_null() { sqlite3_finalize(stmt); } if !querystr.is_null() { sqlite3_free(querystr as *mut libc::c_void); } return ret; }
projects/deltachat-core/c/dc_chat.c
void dc_forward_msgs(dc_context_t* context, const uint32_t* msg_ids, int msg_cnt, uint32_t chat_id) { dc_msg_t* msg = dc_msg_new_untyped(context); dc_chat_t* chat = dc_chat_new(context); dc_contact_t* contact = dc_contact_new(context); int transaction_pending = 0; carray* created_db_entries = carray_new(16); char* idsstr = NULL; char* q3 = NULL; sqlite3_stmt* stmt = NULL; time_t curr_timestamp = 0; dc_param_t* original_param = dc_param_new(); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_ids==NULL || msg_cnt<=0 || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } dc_sqlite3_begin_transaction(context->sql); transaction_pending = 1; dc_unarchive_chat(context, chat_id); context->smtp->log_connect_errors = 1; if (!dc_chat_load_from_db(chat, chat_id)) { goto cleanup; } curr_timestamp = dc_create_smeared_timestamps(context, msg_cnt); idsstr = dc_arr_to_string(msg_ids, msg_cnt); q3 = sqlite3_mprintf("SELECT id FROM msgs WHERE id IN(%s) ORDER BY timestamp,id", idsstr); stmt = dc_sqlite3_prepare(context->sql, q3); while (sqlite3_step(stmt)==SQLITE_ROW) { int src_msg_id = sqlite3_column_int(stmt, 0); if (!dc_msg_load_from_db(msg, context, src_msg_id)) { goto cleanup; } dc_param_set_packed(original_param, msg->param->packed); // do not mark own messages as being forwarded. // this allows sort of broadcasting // by just forwarding messages to other chats. if (msg->from_id!=DC_CONTACT_ID_SELF) { dc_param_set_int(msg->param, DC_PARAM_FORWARDED, 1); } dc_param_set(msg->param, DC_PARAM_GUARANTEE_E2EE, NULL); dc_param_set(msg->param, DC_PARAM_FORCE_PLAINTEXT, NULL); dc_param_set(msg->param, DC_PARAM_CMD, NULL); uint32_t new_msg_id; // PREPARING messages can't be forwarded immediately if (msg->state==DC_STATE_OUT_PREPARING) { new_msg_id = prepare_msg_raw(context, chat, msg, curr_timestamp++); // to update the original message, perform in-place surgery // on msg to avoid copying the entire structure, text, etc. dc_param_t* save_param = msg->param; msg->param = original_param; msg->id = src_msg_id; { // append new id to the original's param. char* old_fwd = dc_param_get(msg->param, DC_PARAM_PREP_FORWARDS, ""); char* new_fwd = dc_mprintf("%s %d", old_fwd, new_msg_id); dc_param_set(msg->param, DC_PARAM_PREP_FORWARDS, new_fwd); dc_msg_save_param_to_disk(msg); free(new_fwd); free(old_fwd); } msg->param = save_param; } else { msg->state = DC_STATE_OUT_PENDING; new_msg_id = prepare_msg_raw(context, chat, msg, curr_timestamp++); dc_job_send_msg(context, new_msg_id); } carray_add(created_db_entries, (void*)(uintptr_t)chat_id, NULL); carray_add(created_db_entries, (void*)(uintptr_t)new_msg_id, NULL); } dc_sqlite3_commit(context->sql); transaction_pending = 0; cleanup: if (transaction_pending) { dc_sqlite3_rollback(context->sql); } if (created_db_entries) { size_t i, icnt = carray_count(created_db_entries); for (i = 0; i < icnt; i += 2) { context->cb(context, DC_EVENT_MSGS_CHANGED, (uintptr_t)carray_get(created_db_entries, i), (uintptr_t)carray_get(created_db_entries, i+1)); } carray_free(created_db_entries); } dc_contact_unref(contact); dc_msg_unref(msg); dc_chat_unref(chat); sqlite3_finalize(stmt); free(idsstr); sqlite3_free(q3); dc_param_unref(original_param); }
projects/deltachat-core/rust/chat.rs
pub async fn forward_msgs(context: &Context, msg_ids: &[MsgId], chat_id: ChatId) -> Result<()> { ensure!(!msg_ids.is_empty(), "empty msgs_ids: nothing to forward"); ensure!(!chat_id.is_special(), "can not forward to special chat"); let mut created_chats: Vec<ChatId> = Vec::new(); let mut created_msgs: Vec<MsgId> = Vec::new(); let mut curr_timestamp: i64; chat_id .unarchive_if_not_muted(context, MessageState::Undefined) .await?; let mut chat = Chat::load_from_db(context, chat_id).await?; if let Some(reason) = chat.why_cant_send(context).await? { bail!("cannot send to {}: {}", chat_id, reason); } curr_timestamp = create_smeared_timestamps(context, msg_ids.len()); let ids = context .sql .query_map( &format!( "SELECT id FROM msgs WHERE id IN({}) ORDER BY timestamp,id", sql::repeat_vars(msg_ids.len()) ), rusqlite::params_from_iter(msg_ids), |row| row.get::<_, MsgId>(0), |ids| ids.collect::<Result<Vec<_>, _>>().map_err(Into::into), ) .await?; for id in ids { let src_msg_id: MsgId = id; let mut msg = Message::load_from_db(context, src_msg_id).await?; if msg.state == MessageState::OutDraft { bail!("cannot forward drafts."); } let original_param = msg.param.clone(); // we tested a sort of broadcast // by not marking own forwarded messages as such, // however, this turned out to be to confusing and unclear. if msg.get_viewtype() != Viewtype::Sticker { msg.param .set_int(Param::Forwarded, src_msg_id.to_u32() as i32); } msg.param.remove(Param::GuaranteeE2ee); msg.param.remove(Param::ForcePlaintext); msg.param.remove(Param::Cmd); msg.param.remove(Param::OverrideSenderDisplayname); msg.param.remove(Param::WebxdcDocument); msg.param.remove(Param::WebxdcDocumentTimestamp); msg.param.remove(Param::WebxdcSummary); msg.param.remove(Param::WebxdcSummaryTimestamp); msg.in_reply_to = None; // do not leak data as group names; a default subject is generated by mimefactory msg.subject = "".to_string(); let new_msg_id: MsgId; if msg.state == MessageState::OutPreparing { new_msg_id = chat .prepare_msg_raw(context, &mut msg, None, curr_timestamp) .await?; curr_timestamp += 1; msg.param = original_param; msg.id = src_msg_id; if let Some(old_fwd) = msg.param.get(Param::PrepForwards) { let new_fwd = format!("{} {}", old_fwd, new_msg_id.to_u32()); msg.param.set(Param::PrepForwards, new_fwd); } else { msg.param .set(Param::PrepForwards, new_msg_id.to_u32().to_string()); } msg.update_param(context).await?; } else { msg.state = MessageState::OutPending; new_msg_id = chat .prepare_msg_raw(context, &mut msg, None, curr_timestamp) .await?; curr_timestamp += 1; if !create_send_msg_jobs(context, &mut msg).await?.is_empty() { context.scheduler.interrupt_smtp().await; } } created_chats.push(chat_id); created_msgs.push(new_msg_id); } for (chat_id, msg_id) in created_chats.iter().zip(created_msgs.iter()) { context.emit_msgs_changed(*chat_id, *msg_id); } Ok(()) }
pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> { context .sql .execute( "UPDATE chats SET param=? WHERE id=?", (self.param.to_string(), self.id), ) .await?; Ok(()) } pub fn get_viewtype(&self) -> Viewtype { self.viewtype } pub(crate) async fn create_send_msg_jobs(context: &Context, msg: &mut Message) -> Result<Vec<i64>> { let needs_encryption = msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default(); let mimefactory = MimeFactory::from_msg(context, msg).await?; let attach_selfavatar = mimefactory.attach_selfavatar; let mut recipients = mimefactory.recipients(); let from = context.get_primary_self_addr().await?; let lowercase_from = from.to_lowercase(); // Send BCC to self if it is enabled. // // Previous versions of Delta Chat did not send BCC self // if DeleteServerAfter was set to immediately delete messages // from the server. This is not the case anymore // because BCC-self messages are also used to detect // that message was sent if SMTP server is slow to respond // and connection is frequently lost // before receiving status line. // // `from` must be the last addr, see `receive_imf_inner()` why. if context.get_config_bool(Config::BccSelf).await? && !recipients .iter() .any(|x| x.to_lowercase() == lowercase_from) { recipients.push(from); } // Webxdc integrations are messages, however, shipped with main app and must not be sent out if msg.param.get_int(Param::WebxdcIntegration).is_some() { recipients.clear(); } if recipients.is_empty() { // may happen eg. for groups with only SELF and bcc_self disabled info!( context, "Message {} has no recipient, skipping smtp-send.", msg.id ); msg.id.set_delivered(context).await?; msg.state = MessageState::OutDelivered; return Ok(Vec::new()); } let rendered_msg = match mimefactory.render(context).await { Ok(res) => Ok(res), Err(err) => { message::set_msg_failed(context, msg, &err.to_string()).await?; Err(err) } }?; if needs_encryption && !rendered_msg.is_encrypted { /* unrecoverable */ message::set_msg_failed( context, msg, "End-to-end-encryption unavailable unexpectedly.", ) .await?; bail!( "e2e encryption unavailable {} - {:?}", msg.id, needs_encryption ); } let now = smeared_time(context); if rendered_msg.is_gossiped { msg.chat_id.set_gossiped_timestamp(context, now).await?; } if msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup { // Reject member list synchronisation from older messages. See also // `receive_imf::apply_group_changes()`. msg.chat_id .update_timestamp( context, Param::MemberListTimestamp, now.saturating_add(constants::TIMESTAMP_SENT_TOLERANCE), ) .await?; } if rendered_msg.last_added_location_id.is_some() { if let Err(err) = location::set_kml_sent_timestamp(context, msg.chat_id, now).await { error!(context, "Failed to set kml sent_timestamp: {err:#}."); } } if let Some(sync_ids) = rendered_msg.sync_ids_to_delete { if let Err(err) = context.delete_sync_ids(sync_ids).await { error!(context, "Failed to delete sync ids: {err:#}."); } } if attach_selfavatar { if let Err(err) = msg.chat_id.set_selfavatar_timestamp(context, now).await { error!(context, "Failed to set selfavatar timestamp: {err:#}."); } } if rendered_msg.is_encrypted && !needs_encryption { msg.param.set_int(Param::GuaranteeE2ee, 1); msg.update_param(context).await?; } msg.subject.clone_from(&rendered_msg.subject); msg.update_subject(context).await?; let chunk_size = context.get_max_smtp_rcpt_to().await?; let trans_fn = |t: &mut rusqlite::Transaction| { let mut row_ids = Vec::<i64>::new(); for recipients_chunk in recipients.chunks(chunk_size) { let recipients_chunk = recipients_chunk.join(" "); let row_id = t.execute( "INSERT INTO smtp (rfc724_mid, recipients, mime, msg_id) \ VALUES (?1, ?2, ?3, ?4)", ( &rendered_msg.rfc724_mid, recipients_chunk, &rendered_msg.message, msg.id, ), )?; row_ids.push(row_id.try_into()?); } Ok(row_ids) }; context.sql.transaction(trans_fn).await } async fn prepare_msg_raw( &mut self, context: &Context, msg: &mut Message, update_msg_id: Option<MsgId>, timestamp: i64, ) -> Result<MsgId> { let mut to_id = 0; let mut location_id = 0; let new_rfc724_mid = create_outgoing_rfc724_mid(); if self.typ == Chattype::Single { if let Some(id) = context .sql .query_get_value( "SELECT contact_id FROM chats_contacts WHERE chat_id=?;", (self.id,), ) .await? { to_id = id; } else { error!( context, "Cannot send message, contact for {} not found.", self.id, ); bail!("Cannot set message, contact for {} not found.", self.id); } } else if self.typ == Chattype::Group && self.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 { msg.param.set_int(Param::AttachGroupImage, 1); self.param.remove(Param::Unpromoted); self.update_param(context).await?; // send_sync_msg() is called (usually) a moment later at send_msg_to_smtp() // when the group-creation message is actually sent though SMTP - // this makes sure, the other devices are aware of grpid that is used in the sync-message. context .sync_qr_code_tokens(Some(self.id)) .await .log_err(context) .ok(); } // reset encrypt error state eg. for forwarding msg.param.remove(Param::ErroneousE2ee); let is_bot = context.get_config_bool(Config::Bot).await?; msg.param .set_optional(Param::Bot, Some("1").filter(|_| is_bot)); // Set "In-Reply-To:" to identify the message to which the composed message is a reply. // Set "References:" to identify the "thread" of the conversation. // Both according to [RFC 5322 3.6.4, page 25](https://www.rfc-editor.org/rfc/rfc5322#section-3.6.4). let new_references; if self.is_self_talk() { // As self-talks are mainly used to transfer data between devices, // we do not set In-Reply-To/References in this case. new_references = String::new(); } else if let Some((parent_rfc724_mid, parent_in_reply_to, parent_references)) = // We don't filter `OutPending` and `OutFailed` messages because the new message for // which `parent_query()` is done may assume that it will be received in a context // affected by those messages, e.g. they could add new members to a group and the // new message will contain them in "To:". Anyway recipients must be prepared to // orphaned references. self .id .get_parent_mime_headers(context, MessageState::OutPending) .await? { // "In-Reply-To:" is not changed if it is set manually. // This does not affect "References:" header, it will contain "default parent" (the // latest message in the thread) anyway. if msg.in_reply_to.is_none() && !parent_rfc724_mid.is_empty() { msg.in_reply_to = Some(parent_rfc724_mid.clone()); } // Use parent `In-Reply-To` as a fallback // in case parent message has no `References` header // as specified in RFC 5322: // > If the parent message does not contain // > a "References:" field but does have an "In-Reply-To:" field // > containing a single message identifier, then the "References:" field // > will contain the contents of the parent's "In-Reply-To:" field // > followed by the contents of the parent's "Message-ID:" field (if // > any). let parent_references = if parent_references.is_empty() { parent_in_reply_to } else { parent_references }; // The whole list of messages referenced may be huge. // Only take 2 recent references and add third from `In-Reply-To`. let mut references_vec: Vec<&str> = parent_references.rsplit(' ').take(2).collect(); references_vec.reverse(); if !parent_rfc724_mid.is_empty() && !references_vec.contains(&parent_rfc724_mid.as_str()) { references_vec.push(&parent_rfc724_mid) } if references_vec.is_empty() { // As a fallback, use our Message-ID, // same as in the case of top-level message. new_references = new_rfc724_mid.clone(); } else { new_references = references_vec.join(" "); } } else { // This is a top-level message. // Add our Message-ID as first references. // This allows us to identify replies to our message even if // email server such as Outlook changes `Message-ID:` header. // MUAs usually keep the first Message-ID in `References:` header unchanged. new_references = new_rfc724_mid.clone(); } // add independent location to database if msg.param.exists(Param::SetLatitude) { if let Ok(row_id) = context .sql .insert( "INSERT INTO locations \ (timestamp,from_id,chat_id, latitude,longitude,independent)\ VALUES (?,?,?, ?,?,1);", ( timestamp, ContactId::SELF, self.id, msg.param.get_float(Param::SetLatitude).unwrap_or_default(), msg.param.get_float(Param::SetLongitude).unwrap_or_default(), ), ) .await { location_id = row_id; } } let ephemeral_timer = if msg.param.get_cmd() == SystemMessage::EphemeralTimerChanged { EphemeralTimer::Disabled } else { self.id.get_ephemeral_timer(context).await? }; let ephemeral_timestamp = match ephemeral_timer { EphemeralTimer::Disabled => 0, EphemeralTimer::Enabled { duration } => time().saturating_add(duration.into()), }; let new_mime_headers = if msg.has_html() { let html = if msg.param.exists(Param::Forwarded) { msg.get_id().get_html(context).await? } else { msg.param.get(Param::SendHtml).map(|s| s.to_string()) }; match html { Some(html) => Some(tokio::task::block_in_place(move || { buf_compress(new_html_mimepart(html).build().as_string().as_bytes()) })?), None => None, } } else { None }; msg.chat_id = self.id; msg.from_id = ContactId::SELF; msg.rfc724_mid = new_rfc724_mid; msg.timestamp_sort = timestamp; // add message to the database if let Some(update_msg_id) = update_msg_id { context .sql .execute( "UPDATE msgs SET rfc724_mid=?, chat_id=?, from_id=?, to_id=?, timestamp=?, type=?, state=?, txt=?, subject=?, param=?, hidden=?, mime_in_reply_to=?, mime_references=?, mime_modified=?, mime_headers=?, mime_compressed=1, location_id=?, ephemeral_timer=?, ephemeral_timestamp=? WHERE id=?;", params_slice![ msg.rfc724_mid, msg.chat_id, msg.from_id, to_id, msg.timestamp_sort, msg.viewtype, msg.state, msg.text, &msg.subject, msg.param.to_string(), msg.hidden, msg.in_reply_to.as_deref().unwrap_or_default(), new_references, new_mime_headers.is_some(), new_mime_headers.unwrap_or_default(), location_id as i32, ephemeral_timer, ephemeral_timestamp, update_msg_id ], ) .await?; msg.id = update_msg_id; } else { let raw_id = context .sql .insert( "INSERT INTO msgs ( rfc724_mid, chat_id, from_id, to_id, timestamp, type, state, txt, subject, param, hidden, mime_in_reply_to, mime_references, mime_modified, mime_headers, mime_compressed, location_id, ephemeral_timer, ephemeral_timestamp) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?,?);", params_slice![ msg.rfc724_mid, msg.chat_id, msg.from_id, to_id, msg.timestamp_sort, msg.viewtype, msg.state, msg.text, &msg.subject, msg.param.to_string(), msg.hidden, msg.in_reply_to.as_deref().unwrap_or_default(), new_references, new_mime_headers.is_some(), new_mime_headers.unwrap_or_default(), location_id as i32, ephemeral_timer, ephemeral_timestamp ], ) .await?; context.new_msgs_notify.notify_one(); msg.id = MsgId::new(u32::try_from(raw_id)?); maybe_set_logging_xdc(context, msg, self.id).await?; context.update_webxdc_integration_database(msg).await?; } context.scheduler.interrupt_ephemeral_task().await; Ok(msg.id) } pub fn emit_msgs_changed(&self, chat_id: ChatId, msg_id: MsgId) { self.emit_event(EventType::MsgsChanged { chat_id, msg_id }); chatlist_events::emit_chatlist_changed(self); chatlist_events::emit_chatlist_item_changed(self, chat_id); } pub fn set_int(&mut self, key: Param, value: i32) -> &mut Self { self.set(key, format!("{value}")); self } pub async fn query_map<T, F, G, H>( &self, sql: &str, params: impl rusqlite::Params + Send, f: F, mut g: G, ) -> Result<H> where F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>, G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>, H: Send + 'static, { self.call(move |conn| { let mut stmt = conn.prepare(sql)?; let res = stmt.query_map(params, f)?; g(res) }) .await } pub(crate) fn iter(&self) -> BlobDirIter<'_> { BlobDirIter::new(self.context, self.inner.iter()) } pub fn remove(&mut self, key: Param) -> &mut Self { self.inner.remove(&key); self } pub fn is_empty(&self) -> bool { self.inner.is_empty() } pub fn is_special(self) -> bool { (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0) } pub fn to_u32(self) -> u32 { self.0 } pub(crate) async fn why_cant_send(&self, context: &Context) -> Result<Option<CantSendReason>> { use CantSendReason::*; // NB: Don't forget to update Chatlist::try_load() when changing this function! let reason = if self.id.is_special() { Some(SpecialChat) } else if self.is_device_talk() { Some(DeviceChat) } else if self.is_contact_request() { Some(ContactRequest) } else if self.is_protection_broken() { Some(ProtectionBroken) } else if self.is_mailing_list() && self.get_mailinglist_addr().is_none_or_empty() { Some(ReadOnlyMailingList) } else if !self.is_self_in_chat(context).await? { Some(NotAMember) } else if self .check_securejoin_wait(context, constants::SECUREJOIN_WAIT_TIMEOUT) .await? > 0 { Some(SecurejoinWait) } else { None }; Ok(reason) } pub async fn unarchive_if_not_muted( self, context: &Context, msg_state: MessageState, ) -> Result<()> { if msg_state != MessageState::InFresh { context .sql .execute( "UPDATE chats SET archived=0 WHERE id=? AND archived=1 \ AND NOT(muted_until=-1 OR muted_until>?)", (self, time()), ) .await?; return Ok(()); } let chat = Chat::load_from_db(context, self).await?; if chat.visibility != ChatVisibility::Archived { return Ok(()); } if chat.is_muted() { let unread_cnt = context .sql .count( "SELECT COUNT(*) FROM msgs WHERE state=? AND hidden=0 AND chat_id=?", (MessageState::InFresh, self), ) .await?; if unread_cnt == 1 { // Added the first unread message in the chat. context.emit_msgs_changed(DC_CHAT_ID_ARCHIVED_LINK, MsgId::new(0)); } return Ok(()); } context .sql .execute("UPDATE chats SET archived=0 WHERE id=?", (self,)) .await?; Ok(()) } pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> { let mut chat = context .sql .query_row( "SELECT c.type, c.name, c.grpid, c.param, c.archived, c.blocked, c.locations_send_until, c.muted_until, c.protected FROM chats c WHERE c.id=?;", (chat_id,), |row| { let c = Chat { id: chat_id, typ: row.get(0)?, name: row.get::<_, String>(1)?, grpid: row.get::<_, String>(2)?, param: row.get::<_, String>(3)?.parse().unwrap_or_default(), visibility: row.get(4)?, blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(), is_sending_locations: row.get(6)?, mute_duration: row.get(7)?, protected: row.get(8)?, }; Ok(c) }, ) .await .context(format!("Failed loading chat {chat_id} from database"))?; if chat.id.is_archived_link() { chat.name = stock_str::archived_chats(context).await; } else { if chat.typ == Chattype::Single && chat.name.is_empty() { // chat.name is set to contact.display_name on changes, // however, if things went wrong somehow, we do this here explicitly. let mut chat_name = "Err [Name not found]".to_owned(); match get_chat_contacts(context, chat.id).await { Ok(contacts) => { if let Some(contact_id) = contacts.first() { if let Ok(contact) = Contact::get_by_id(context, *contact_id).await { contact.get_display_name().clone_into(&mut chat_name); } } } Err(err) => { error!( context, "Failed to load contacts for {}: {:#}.", chat.id, err ); } } chat.name = chat_name; } if chat.param.exists(Param::Selftalk) { chat.name = stock_str::saved_messages(context).await; } else if chat.param.exists(Param::Devicetalk) { chat.name = stock_str::device_messages(context).await; } } Ok(chat) } pub async fn query_map<T, F, G, H>( &self, sql: &str, params: impl rusqlite::Params + Send, f: F, mut g: G, ) -> Result<H> where F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>, G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>, H: Send + 'static, { self.call(move |conn| { let mut stmt = conn.prepare(sql)?; let res = stmt.query_map(params, f)?; g(res) }) .await } pub fn params_from_iter<I>(iter: I) -> ParamsFromIter<I> where I: IntoIterator, I::Item: ToSql, { ParamsFromIter(iter) } pub(crate) fn create_smeared_timestamps(context: &Context, count: usize) -> i64 { let now = time(); context.smeared_timestamp.create_n(now, count as i64) } pub fn repeat_vars(count: usize) -> String { let mut s = "?,".repeat(count); s.pop(); // Remove trailing comma s } pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self { self.inner.insert(key, value.to_string()); self } pub fn len(&self) -> usize { self.inner.len() } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct MsgId(u32); pub struct ChatId(u32); pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. } pub enum Viewtype { /// Unknown message type. #[default] Unknown = 0, /// Text message. /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text(). Text = 10, /// Image message. /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to /// `Gif` when sending the message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension(). Image = 20, /// Animated GIF message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension() /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height(). Gif = 21, /// Message containing a sticker, similar to image. /// If possible, the ui should display the image without borders in a transparent way. /// A click on a sticker will offer to install the sticker set in some future. Sticker = 23, /// Message containing an Audio file. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration(). Audio = 40, /// A voice message that was directly recorded by the user. /// For all other audio messages, the type #DC_MSG_AUDIO should be used. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration() Voice = 41, /// Video messages. /// File, width, height and durarion /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration() /// and retrieved via /// dc_msg_get_file(), dc_msg_get_width(), /// dc_msg_get_height(), dc_msg_get_duration(). Video = 50, /// Message containing any file, eg. a PDF. /// The file is set via dc_msg_set_file() /// and retrieved via dc_msg_get_file(). File = 60, /// Message is an invitation to a videochat. VideochatInvitation = 70, /// Message is an webxdc instance. Webxdc = 80, /// Message containing shared contacts represented as a vCard (virtual contact file) /// with email addresses and possibly other fields. /// Use `parse_vcard()` to retrieve them. Vcard = 90, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub enum MessageState { /// Undefined message state. #[default] Undefined = 0, /// Incoming *fresh* message. Fresh messages are neither noticed /// nor seen and are typically shown in notifications. InFresh = 10, /// Incoming *noticed* message. E.g. chat opened but message not /// yet read - noticed messages are not counted as unread but did /// not marked as read nor resulted in MDNs. InNoticed = 13, /// Incoming message, really *seen* by the user. Marked as read on /// IMAP and MDN may be sent. InSeen = 16, /// For files which need time to be prepared before they can be /// sent, the message enters this state before /// OutPending. OutPreparing = 18, /// Message saved as draft. OutDraft = 19, /// The user has pressed the "send" button but the message is not /// yet sent and is pending in some way. Maybe we're offline (no /// checkmark). OutPending = 20, /// *Unrecoverable* error (*recoverable* errors result in pending /// messages). OutFailed = 24, /// Outgoing message successfully delivered to server (one /// checkmark). Note, that already delivered messages may get into /// the OutFailed state if we get such a hint from the server. OutDelivered = 26, /// Outgoing message read by the recipient (two checkmarks; this /// requires goodwill on the receiver's side) OutMdnRcvd = 28, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__139.txt
pub unsafe extern "C" fn dc_forward_msgs( mut context: *mut dc_context_t, mut msg_ids: *const uint32_t, mut msg_cnt: libc::c_int, mut chat_id: uint32_t, ) { let mut current_block: u64; let mut msg: *mut dc_msg_t = dc_msg_new_untyped(context); let mut chat: *mut dc_chat_t = dc_chat_new(context); let mut contact: *mut dc_contact_t = dc_contact_new(context); let mut transaction_pending: libc::c_int = 0 as libc::c_int; let mut created_db_entries: *mut carray = carray_new( 16 as libc::c_int as libc::c_uint, ); let mut idsstr: *mut libc::c_char = 0 as *mut libc::c_char; let mut q3: *mut libc::c_char = 0 as *mut libc::c_char; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; let mut curr_timestamp: time_t = 0 as libc::c_int as time_t; let mut original_param: *mut dc_param_t = dc_param_new(); if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || msg_ids.is_null() || msg_cnt <= 0 as libc::c_int || chat_id <= 9 as libc::c_int as libc::c_uint) { dc_sqlite3_begin_transaction((*context).sql); transaction_pending = 1 as libc::c_int; dc_unarchive_chat(context, chat_id); (*(*context).smtp).log_connect_errors = 1 as libc::c_int; if !(dc_chat_load_from_db(chat, chat_id) == 0) { curr_timestamp = dc_create_smeared_timestamps(context, msg_cnt); idsstr = dc_arr_to_string(msg_ids, msg_cnt); q3 = sqlite3_mprintf( b"SELECT id FROM msgs WHERE id IN(%s) ORDER BY timestamp,id\0" as *const u8 as *const libc::c_char, idsstr, ); stmt = dc_sqlite3_prepare((*context).sql, q3); loop { if !(sqlite3_step(stmt) == 100 as libc::c_int) { current_block = 18377268871191777778; break; } let mut src_msg_id: libc::c_int = sqlite3_column_int( stmt, 0 as libc::c_int, ); if dc_msg_load_from_db(msg, context, src_msg_id as uint32_t) == 0 { current_block = 3343462040619382785; break; } dc_param_set_packed(original_param, (*(*msg).param).packed); if (*msg).from_id != 1 as libc::c_int as libc::c_uint { dc_param_set_int((*msg).param, 'a' as i32, 1 as libc::c_int); } dc_param_set((*msg).param, 'c' as i32, 0 as *const libc::c_char); dc_param_set((*msg).param, 'u' as i32, 0 as *const libc::c_char); dc_param_set((*msg).param, 'S' as i32, 0 as *const libc::c_char); let mut new_msg_id: uint32_t = 0; if (*msg).state == 18 as libc::c_int { let fresh9 = curr_timestamp; curr_timestamp = curr_timestamp + 1; new_msg_id = prepare_msg_raw(context, chat, msg, fresh9); let mut save_param: *mut dc_param_t = (*msg).param; (*msg).param = original_param; (*msg).id = src_msg_id as uint32_t; let mut old_fwd: *mut libc::c_char = dc_param_get( (*msg).param, 'P' as i32, b"\0" as *const u8 as *const libc::c_char, ); let mut new_fwd: *mut libc::c_char = dc_mprintf( b"%s %d\0" as *const u8 as *const libc::c_char, old_fwd, new_msg_id, ); dc_param_set((*msg).param, 'P' as i32, new_fwd); dc_msg_save_param_to_disk(msg); free(new_fwd as *mut libc::c_void); free(old_fwd as *mut libc::c_void); (*msg).param = save_param; } else { (*msg).state = 20 as libc::c_int; let fresh10 = curr_timestamp; curr_timestamp = curr_timestamp + 1; new_msg_id = prepare_msg_raw(context, chat, msg, fresh10); dc_job_send_msg(context, new_msg_id); } carray_add( created_db_entries, chat_id as uintptr_t as *mut libc::c_void, 0 as *mut libc::c_uint, ); carray_add( created_db_entries, new_msg_id as uintptr_t as *mut libc::c_void, 0 as *mut libc::c_uint, ); } match current_block { 3343462040619382785 => {} _ => { dc_sqlite3_commit((*context).sql); transaction_pending = 0 as libc::c_int; } } } } if transaction_pending != 0 { dc_sqlite3_rollback((*context).sql); } if !created_db_entries.is_null() { let mut i: size_t = 0; let mut icnt: size_t = carray_count(created_db_entries) as size_t; i = 0 as libc::c_int as size_t; while i < icnt { ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, carray_get(created_db_entries, i as libc::c_uint) as uintptr_t, carray_get( created_db_entries, i.wrapping_add(1 as libc::c_int as libc::c_ulong) as libc::c_uint, ) as uintptr_t, ); i = (i as libc::c_ulong).wrapping_add(2 as libc::c_int as libc::c_ulong) as size_t as size_t; } carray_free(created_db_entries); } dc_contact_unref(contact); dc_msg_unref(msg); dc_chat_unref(chat); sqlite3_finalize(stmt); free(idsstr as *mut libc::c_void); sqlite3_free(q3 as *mut libc::c_void); dc_param_unref(original_param); }
projects/deltachat-core/c/dc_contact.c
int dc_delete_contact(dc_context_t* context, uint32_t contact_id) { int success = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || contact_id<=DC_CONTACT_ID_LAST_SPECIAL) { goto cleanup; } /* we can only delete contacts that are not in use anywhere; this function is mainly for the user who has just created an contact manually and wants to delete it a moment later */ stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM chats_contacts WHERE contact_id=?;"); sqlite3_bind_int(stmt, 1, contact_id); if (sqlite3_step(stmt)!=SQLITE_ROW || sqlite3_column_int(stmt, 0) >= 1) { goto cleanup; } sqlite3_finalize(stmt); stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM msgs WHERE from_id=? OR to_id=?;"); sqlite3_bind_int(stmt, 1, contact_id); sqlite3_bind_int(stmt, 2, contact_id); if (sqlite3_step(stmt)!=SQLITE_ROW || sqlite3_column_int(stmt, 0) >= 1) { goto cleanup; } sqlite3_finalize(stmt); stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "DELETE FROM contacts WHERE id=?;"); sqlite3_bind_int(stmt, 1, contact_id); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } context->cb(context, DC_EVENT_CONTACTS_CHANGED, 0, 0); success = 1; cleanup: sqlite3_finalize(stmt); return success; }
projects/deltachat-core/rust/contact.rs
pub async fn delete(context: &Context, contact_id: ContactId) -> Result<()> { ensure!(!contact_id.is_special(), "Can not delete special contact"); context .sql .transaction(move |transaction| { // make sure, the transaction starts with a write command and becomes EXCLUSIVE by that - // upgrading later may be impossible by races. let deleted_contacts = transaction.execute( "DELETE FROM contacts WHERE id=? AND (SELECT COUNT(*) FROM chats_contacts WHERE contact_id=?)=0;", (contact_id, contact_id), )?; if deleted_contacts == 0 { transaction.execute( "UPDATE contacts SET origin=? WHERE id=?;", (Origin::Hidden, contact_id), )?; } Ok(()) }) .await?; context.emit_event(EventType::ContactsChanged(None)); Ok(()) }
pub fn emit_event(&self, event: EventType) { { let lock = self.debug_logging.read().expect("RwLock is poisoned"); if let Some(debug_logging) = &*lock { debug_logging.log_event(event.clone()); } } self.events.emit(Event { id: self.id, typ: event, }); } pub fn is_special(&self) -> bool { self.0 <= Self::LAST_SPECIAL.0 } pub async fn transaction<G, H>(&self, callback: G) -> Result<H> where H: Send + 'static, G: Send + FnOnce(&mut rusqlite::Transaction<'_>) -> Result<H>, { self.call_write(move |conn| { let mut transaction = conn.transaction()?; let ret = callback(&mut transaction); match ret { Ok(ret) => { transaction.commit()?; Ok(ret) } Err(err) => { transaction.rollback()?; Err(err) } } }) .await } pub struct ContactId(u32); pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub enum Origin { /// Unknown origin. Can be used as a minimum origin to specify that the caller does not care /// about origin of the contact. #[default] Unknown = 0, /// The contact is a mailing list address, needed to unblock mailing lists MailinglistAddress = 0x2, /// Hidden on purpose, e.g. addresses with the word "noreply" in it Hidden = 0x8, /// From: of incoming messages of unknown sender IncomingUnknownFrom = 0x10, /// Cc: of incoming messages of unknown sender IncomingUnknownCc = 0x20, /// To: of incoming messages of unknown sender IncomingUnknownTo = 0x40, /// address scanned but not verified UnhandledQrScan = 0x80, /// Reply-To: of incoming message of known sender /// Contacts with at least this origin value are shown in the contact list. IncomingReplyTo = 0x100, /// Cc: of incoming message of known sender IncomingCc = 0x200, /// additional To:'s of incoming message of known sender IncomingTo = 0x400, /// a chat was manually created for this user, but no message yet sent CreateChat = 0x800, /// message sent by us OutgoingBcc = 0x1000, /// message sent by us OutgoingCc = 0x2000, /// message sent by us OutgoingTo = 0x4000, /// internal use Internal = 0x40000, /// address is in our address book AddressBook = 0x80000, /// set on Alice's side for contacts like Bob that have scanned the QR code offered by her. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling contact_is_verified() ! SecurejoinInvited = 0x0100_0000, /// set on Bob's side for contacts scanned and verified from a QR code. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling contact_is_verified() ! SecurejoinJoined = 0x0200_0000, /// contact added manually by create_contact(), this should be the largest origin as otherwise the user cannot modify the names ManuallyCreated = 0x0400_0000, } pub enum EventType { /// The library-user may write an informational string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Info(String), /// Emitted when SMTP connection is established and login was successful. SmtpConnected(String), /// Emitted when IMAP connection is established and login was successful. ImapConnected(String), /// Emitted when a message was successfully sent to the SMTP server. SmtpMessageSent(String), /// Emitted when an IMAP message has been marked as deleted ImapMessageDeleted(String), /// Emitted when an IMAP message has been moved ImapMessageMoved(String), /// Emitted before going into IDLE on the Inbox folder. ImapInboxIdle, /// Emitted when an new file in the $BLOBDIR was created NewBlobFile(String), /// Emitted when an file in the $BLOBDIR was deleted DeletedBlobFile(String), /// The library-user should write a warning string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Warning(String), /// The library-user should report an error to the end-user. /// /// As most things are asynchronous, things may go wrong at any time and the user /// should not be disturbed by a dialog or so. Instead, use a bubble or so. /// /// However, for ongoing processes (eg. configure()) /// or for functions that are expected to fail (eg. dc_continue_key_transfer()) /// it might be better to delay showing these events until the function has really /// failed (returned false). It should be sufficient to report only the *last* error /// in a messasge box then. Error(String), /// An action cannot be performed because the user is not in the group. /// Reported eg. after a call to /// dc_set_chat_name(), dc_set_chat_profile_image(), /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(), /// dc_send_text_msg() or another sending function. ErrorSelfNotInGroup(String), /// Messages or chats changed. One or more messages or chats changed for various /// reasons in the database: /// - Messages sent, received or removed /// - Chats created, deleted or archived /// - A draft has been set /// MsgsChanged { /// Set if only a single chat is affected by the changes, otherwise 0. chat_id: ChatId, /// Set if only a single message is affected by the changes, otherwise 0. msg_id: MsgId, }, /// Reactions for the message changed. ReactionsChanged { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message for which reactions were changed. msg_id: MsgId, /// ID of the contact whose reaction set is changed. contact_id: ContactId, }, /// There is a fresh message. Typically, the user will show an notification /// when receiving this message. /// /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event. IncomingMsg { /// ID of the chat where the message is assigned. chat_id: ChatId, /// ID of the message. msg_id: MsgId, }, /// Downloading a bunch of messages just finished. IncomingMsgBunch, /// Messages were seen or noticed. /// chat id is always set. MsgsNoticed(ChatId), /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state(). MsgDelivered { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was successfully sent. msg_id: MsgId, }, /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_FAILED, see dc_msg_get_state(). MsgFailed { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that could not be sent. msg_id: MsgId, }, /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state(). MsgRead { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was read. msg_id: MsgId, }, /// A single message was deleted. /// /// This event means that the message will no longer appear in the messagelist. /// UI should remove the message from the messagelist /// in response to this event if the message is currently displayed. /// /// The message may have been explicitly deleted by the user or expired. /// Internally the message may have been removed from the database, /// moved to the trash chat or hidden. /// /// This event does not indicate the message /// deletion from the server. MsgDeleted { /// ID of the chat where the message was prior to deletion. /// Never 0 or trash chat. chat_id: ChatId, /// ID of the deleted message. Never 0. msg_id: MsgId, }, /// Chat changed. The name or the image of a chat group was changed or members were added or removed. /// Or the verify state of a chat has changed. /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat() /// and dc_remove_contact_from_chat(). /// /// This event does not include ephemeral timer modification, which /// is a separate event. ChatModified(ChatId), /// Chat ephemeral timer changed. ChatEphemeralTimerModified { /// Chat ID. chat_id: ChatId, /// New ephemeral timer value. timer: EphemeralTimer, }, /// Contact(s) created, renamed, blocked, deleted or changed their "recently seen" status. /// /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected. ContactsChanged(Option<ContactId>), /// Location of one or more contact has changed. /// /// @param data1 (u32) contact_id of the contact for which the location has changed. /// If the locations of several contacts have been changed, /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`. LocationChanged(Option<ContactId>), /// Inform about the configuration progress started by configure(). ConfigureProgress { /// Progress. /// /// 0=error, 1-999=progress in permille, 1000=success and done progress: usize, /// Progress comment or error, something to display to the user. comment: Option<String>, }, /// Inform about the import/export progress started by imex(). /// /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done /// @param data2 0 ImexProgress(usize), /// A file has been exported. A file has been written by imex(). /// This event may be sent multiple times by a single call to imex(). /// /// A typical purpose for a handler of this event may be to make the file public to some system /// services. /// /// @param data2 0 ImexFileWritten(PathBuf), /// Progress information of a secure-join handshake from the view of the inviter /// (Alice, the person who shows the QR code). /// /// These events are typically sent after a joiner has scanned the QR code /// generated by dc_get_securejoin_qr(). SecurejoinInviterProgress { /// ID of the contact that wants to join. contact_id: ContactId, /// Progress as: /// 300=vg-/vc-request received, typically shown as "bob@addr joins". /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as "bob@addr verified". /// 800=contact added to chat, shown as "bob@addr securely joined GROUP". Only for the verified-group-protocol. /// 1000=Protocol finished for this contact. progress: usize, }, /// Progress information of a secure-join handshake from the view of the joiner /// (Bob, the person who scans the QR code). /// The events are typically sent while dc_join_securejoin(), which /// may take some time, is executed. SecurejoinJoinerProgress { /// ID of the inviting contact. contact_id: ContactId, /// Progress as: /// 400=vg-/vc-request-with-auth sent, typically shown as "alice@addr verified, introducing myself." /// (Bob has verified alice and waits until Alice does the same for him) /// 1000=vg-member-added/vc-contact-confirm received progress: usize, }, /// The connectivity to the server changed. /// This means that you should refresh the connectivity view /// and possibly the connectivtiy HTML; see dc_get_connectivity() and /// dc_get_connectivity_html() for details. ConnectivityChanged, /// The user's avatar changed. /// Deprecated by `ConfigSynced`. SelfavatarChanged, /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For /// uniformity this is emitted on the source device too. The value isn't here, otherwise it /// would be logged which might not be good for privacy. ConfigSynced { /// Configuration key. key: Config, }, /// Webxdc status update received. WebxdcStatusUpdate { /// Message ID. msg_id: MsgId, /// Status update ID. status_update_serial: StatusUpdateSerial, }, /// Data received over an ephemeral peer channel. WebxdcRealtimeData { /// Message ID. msg_id: MsgId, /// Realtime data. data: Vec<u8>, }, /// Inform that a message containing a webxdc instance has been deleted. WebxdcInstanceDeleted { /// ID of the deleted message. msg_id: MsgId, }, /// Tells that the Background fetch was completed (or timed out). /// This event acts as a marker, when you reach this event you can be sure /// that all events emitted during the background fetch were processed. /// /// This event is only emitted by the account manager AccountsBackgroundFetchDone, /// Inform that set of chats or the order of the chats in the chatlist has changed. /// /// Sometimes this is emitted together with `UIChatlistItemChanged`. ChatlistChanged, /// Inform that a single chat list item changed and needs to be rerendered. /// If `chat_id` is set to None, then all currently visible chats need to be rerendered, and all not-visible items need to be cleared from cache if the UI has a cache. ChatlistItemChanged { /// ID of the changed chat chat_id: Option<ChatId>, }, /// Event for using in tests, e.g. as a fence between normally generated events. #[cfg(test)] Test, /// Inform than some events have been skipped due to event channel overflow. EventChannelOverflow { /// Number of events skipped. n: u64, }, } pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__33.txt
pub unsafe extern "C" fn dc_delete_contact( mut context: *mut dc_context_t, mut contact_id: uint32_t, ) -> libc::c_int { let mut success: libc::c_int = 0 as libc::c_int; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || contact_id <= 9 as libc::c_int as libc::c_uint) { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT COUNT(*) FROM chats_contacts WHERE contact_id=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, contact_id as libc::c_int); if !(sqlite3_step(stmt) != 100 as libc::c_int || sqlite3_column_int(stmt, 0 as libc::c_int) >= 1 as libc::c_int) { sqlite3_finalize(stmt); stmt = 0 as *mut sqlite3_stmt; stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT COUNT(*) FROM msgs WHERE from_id=? OR to_id=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, contact_id as libc::c_int); sqlite3_bind_int(stmt, 2 as libc::c_int, contact_id as libc::c_int); if !(sqlite3_step(stmt) != 100 as libc::c_int || sqlite3_column_int(stmt, 0 as libc::c_int) >= 1 as libc::c_int) { sqlite3_finalize(stmt); stmt = 0 as *mut sqlite3_stmt; stmt = dc_sqlite3_prepare( (*context).sql, b"DELETE FROM contacts WHERE id=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, contact_id as libc::c_int); if !(sqlite3_step(stmt) != 101 as libc::c_int) { ((*context).cb) .expect( "non-null function pointer", )( context, 2030 as libc::c_int, 0 as libc::c_int as uintptr_t, 0 as libc::c_int as uintptr_t, ); success = 1 as libc::c_int; } } } } sqlite3_finalize(stmt); return success; }
projects/deltachat-core/c/dc_chat.c
* After the creation with dc_create_group_chat() the chat is usually unpromoted * until the first call to dc_send_text_msg() or another sending function. * * With unpromoted chats, members can be added * and settings can be modified without the need of special status messages being sent. * * While the core takes care of the unpromoted state on its own, * checking the state from the UI side may be useful to decide whether a hint as * "Send the first message to allow others to reply within the group" * should be shown to the user or not. * * @memberof dc_chat_t * @param chat The chat object. * @return 1=chat is still unpromoted, no message was ever send to the chat, * 0=chat is not unpromoted, messages were send and/or received * or the chat is not group chat. */ int dc_chat_is_unpromoted(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0); }
projects/deltachat-core/rust/chat.rs
pub(crate) async fn is_unpromoted(self, context: &Context) -> Result<bool> { let param = self.get_param(context).await?; let unpromoted = param.get_bool(Param::Unpromoted).unwrap_or_default(); Ok(unpromoted) }
pub fn get_bool(&self, key: Param) -> Option<bool> { self.get_int(key).map(|v| v != 0) } pub(crate) async fn get_param(self, context: &Context) -> Result<Params> { let res: Option<String> = context .sql .query_get_value("SELECT param FROM chats WHERE id=?", (self,)) .await?; Ok(res .map(|s| s.parse().unwrap_or_default()) .unwrap_or_default()) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct Chat { /// Database ID. pub id: ChatId, /// Chat type, e.g. 1:1 chat, group chat, mailing list. pub typ: Chattype, /// Chat name. pub name: String, /// Whether the chat is archived or pinned. pub visibility: ChatVisibility, /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and /// ad-hoc groups. pub grpid: String, /// Whether the chat is blocked, unblocked or a contact request. pub blocked: Blocked, /// Additional chat parameters stored in the database. pub param: Params, /// If location streaming is enabled in the chat. is_sending_locations: bool, /// Duration of the chat being muted. pub mute_duration: MuteDuration, /// If the chat is protected (verified). pub(crate) protected: ProtectionStatus, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. } pub struct ChatId(u32);
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__42.txt
pub unsafe extern "C" fn dc_create_group_chat( mut context: *mut dc_context_t, mut verified: libc::c_int, mut chat_name: *const libc::c_char, ) -> uint32_t { let mut chat_id: uint32_t = 0 as libc::c_int as uint32_t; let mut draft_txt: *mut libc::c_char = 0 as *mut libc::c_char; let mut draft_msg: *mut dc_msg_t = 0 as *mut dc_msg_t; let mut grpid: *mut libc::c_char = 0 as *mut libc::c_char; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || chat_name.is_null() || *chat_name.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int { return 0 as libc::c_int as uint32_t; } draft_txt = dc_stock_str_repl_string(context, 14 as libc::c_int, chat_name); grpid = dc_create_id(); stmt = dc_sqlite3_prepare( (*context).sql, b"INSERT INTO chats (type, name, grpid, param) VALUES(?, ?, ?, 'U=1');\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int( stmt, 1 as libc::c_int, if verified != 0 { 130 as libc::c_int } else { 120 as libc::c_int }, ); sqlite3_bind_text(stmt, 2 as libc::c_int, chat_name, -(1 as libc::c_int), None); sqlite3_bind_text(stmt, 3 as libc::c_int, grpid, -(1 as libc::c_int), None); if !(sqlite3_step(stmt) != 101 as libc::c_int) { chat_id = dc_sqlite3_get_rowid( (*context).sql, b"chats\0" as *const u8 as *const libc::c_char, b"grpid\0" as *const u8 as *const libc::c_char, grpid, ); if !(chat_id == 0 as libc::c_int as libc::c_uint) { if !(dc_add_to_chat_contacts_table( context, chat_id, 1 as libc::c_int as uint32_t, ) == 0) { draft_msg = dc_msg_new(context, 10 as libc::c_int); dc_msg_set_text(draft_msg, draft_txt); set_draft_raw(context, chat_id, draft_msg); } } } sqlite3_finalize(stmt); free(draft_txt as *mut libc::c_void); dc_msg_unref(draft_msg); free(grpid as *mut libc::c_void); if chat_id != 0 { ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, 0 as libc::c_int as uintptr_t, 0 as libc::c_int as uintptr_t, ); } return chat_id; }
projects/deltachat-core/c/dc_chat.c
* If the group is already _promoted_ (any message was sent to the group), * all group members are informed by a special status message that is sent automatically by this function. * * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent. * * @memberof dc_context_t * @param chat_id The chat ID to set the name for. Must be a group chat. * @param new_name New name of the group. * @param context The context as created by dc_context_new(). * @return 1=success, 0=error */ int dc_set_chat_name(dc_context_t* context, uint32_t chat_id, const char* new_name) { /* the function only sets the names of group chats; normal chats get their names from the contacts */ int success = 0; dc_chat_t* chat = dc_chat_new(context); dc_msg_t* msg = dc_msg_new_untyped(context); char* q3 = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || new_name==NULL || new_name[0]==0 || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } if (0==real_group_exists(context, chat_id) || 0==dc_chat_load_from_db(chat, chat_id)) { goto cleanup; } if (strcmp(chat->name, new_name)==0) { success = 1; goto cleanup; /* name not modified */ } if (!IS_SELF_IN_GROUP) { dc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0, "Cannot set chat name; self not in group"); goto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */ } q3 = sqlite3_mprintf("UPDATE chats SET name=%Q WHERE id=%i;", new_name, chat_id); if (!dc_sqlite3_execute(context->sql, q3)) { goto cleanup; } /* send a status mail to all group members, also needed for outself to allow multi-client */ if (DO_SEND_STATUS_MAILS) { msg->type = DC_MSG_TEXT; msg->text = dc_stock_system_msg(context, DC_STR_MSGGRPNAME, chat->name, new_name, DC_CONTACT_ID_SELF); dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_GROUPNAME_CHANGED); dc_param_set (msg->param, DC_PARAM_CMD_ARG, chat->name); msg->id = dc_send_msg(context, chat_id, msg); context->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, msg->id); } context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); success = 1; cleanup: sqlite3_free(q3); dc_chat_unref(chat); dc_msg_unref(msg); return success; }
projects/deltachat-core/rust/chat.rs
pub async fn set_chat_name(context: &Context, chat_id: ChatId, new_name: &str) -> Result<()> { rename_ex(context, Sync, chat_id, new_name).await }
async fn rename_ex( context: &Context, mut sync: sync::Sync, chat_id: ChatId, new_name: &str, ) -> Result<()> { let new_name = improve_single_line_input(new_name); /* the function only sets the names of group chats; normal chats get their names from the contacts */ let mut success = false; ensure!(!new_name.is_empty(), "Invalid name"); ensure!(!chat_id.is_special(), "Invalid chat ID"); let chat = Chat::load_from_db(context, chat_id).await?; let mut msg = Message::default(); if chat.typ == Chattype::Group || chat.typ == Chattype::Mailinglist || chat.typ == Chattype::Broadcast { if chat.name == new_name { success = true; } else if !chat.is_self_in_chat(context).await? { context.emit_event(EventType::ErrorSelfNotInGroup( "Cannot set chat name; self not in group".into(), )); } else { context .sql .execute( "UPDATE chats SET name=? WHERE id=?;", (new_name.to_string(), chat_id), ) .await?; if chat.is_promoted() && !chat.is_mailing_list() && chat.typ != Chattype::Broadcast && improve_single_line_input(&chat.name) != new_name { msg.viewtype = Viewtype::Text; msg.text = stock_str::msg_grp_name(context, &chat.name, &new_name, ContactId::SELF).await; msg.param.set_cmd(SystemMessage::GroupNameChanged); if !chat.name.is_empty() { msg.param.set(Param::Arg, &chat.name); } msg.id = send_msg(context, chat_id, &mut msg).await?; context.emit_msgs_changed(chat_id, msg.id); sync = Nosync; } context.emit_event(EventType::ChatModified(chat_id)); chatlist_events::emit_chatlist_item_changed(context, chat_id); success = true; } } if !success { bail!("Failed to set name"); } if sync.into() && chat.name != new_name { let sync_name = new_name.to_string(); chat.sync(context, SyncAction::Rename(sync_name)) .await .log_err(context) .ok(); } Ok(()) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct ChatId(u32);
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__136.txt
pub unsafe extern "C" fn dc_set_chat_name( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut new_name: *const libc::c_char, ) -> libc::c_int { let mut success: libc::c_int = 0 as libc::c_int; let mut chat: *mut dc_chat_t = dc_chat_new(context); let mut msg: *mut dc_msg_t = dc_msg_new_untyped(context); let mut q3: *mut libc::c_char = 0 as *mut libc::c_char; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || new_name.is_null() || *new_name.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int || chat_id <= 9 as libc::c_int as libc::c_uint) { if !(0 as libc::c_int == real_group_exists(context, chat_id) || 0 as libc::c_int == dc_chat_load_from_db(chat, chat_id)) { if strcmp((*chat).name, new_name) == 0 as libc::c_int { success = 1 as libc::c_int; } else if !(dc_is_contact_in_chat( context, chat_id, 1 as libc::c_int as uint32_t, ) == 1 as libc::c_int) { dc_log_event( context, 410 as libc::c_int, 0 as libc::c_int, b"Cannot set chat name; self not in group\0" as *const u8 as *const libc::c_char, ); } else { q3 = sqlite3_mprintf( b"UPDATE chats SET name=%Q WHERE id=%i;\0" as *const u8 as *const libc::c_char, new_name, chat_id, ); if !(dc_sqlite3_execute((*context).sql, q3) == 0) { if dc_param_get_int((*chat).param, 'U' as i32, 0 as libc::c_int) == 0 as libc::c_int { (*msg).type_0 = 10 as libc::c_int; (*msg) .text = dc_stock_system_msg( context, 15 as libc::c_int, (*chat).name, new_name, 1 as libc::c_int as uint32_t, ); dc_param_set_int((*msg).param, 'S' as i32, 2 as libc::c_int); dc_param_set((*msg).param, 'E' as i32, (*chat).name); (*msg).id = dc_send_msg(context, chat_id, msg); ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, chat_id as uintptr_t, (*msg).id as uintptr_t, ); } ((*context).cb) .expect( "non-null function pointer", )( context, 2020 as libc::c_int, chat_id as uintptr_t, 0 as libc::c_int as uintptr_t, ); success = 1 as libc::c_int; } } } } sqlite3_free(q3 as *mut libc::c_void); dc_chat_unref(chat); dc_msg_unref(msg); return success; }
projects/deltachat-core/c/dc_chat.c
* See dc_set_draft() for more details about drafts. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param chat_id The chat ID to get the draft for. * @return Message object. * Can be passed directly to dc_send_msg(). * Must be freed using dc_msg_unref() after usage. * If there is no draft, NULL is returned. */ dc_msg_t* dc_get_draft(dc_context_t* context, uint32_t chat_id) { uint32_t draft_msg_id = 0; dc_msg_t* draft_msg = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { return NULL; } draft_msg_id = get_draft_msg_id(context, chat_id); if (draft_msg_id==0) { return NULL; } draft_msg = dc_msg_new_untyped(context); if (!dc_msg_load_from_db(draft_msg, context, draft_msg_id)) { dc_msg_unref(draft_msg); return NULL; } return draft_msg; }
projects/deltachat-core/rust/chat.rs
pub async fn get_draft(self, context: &Context) -> Result<Option<Message>> { if self.is_special() { return Ok(None); } match self.get_draft_msg_id(context).await? { Some(draft_msg_id) => { let msg = Message::load_from_db(context, draft_msg_id).await?; Ok(Some(msg)) } None => Ok(None), } }
async fn get_draft_msg_id(self, context: &Context) -> Result<Option<MsgId>> { let msg_id: Option<MsgId> = context .sql .query_get_value( "SELECT id FROM msgs WHERE chat_id=? AND state=?;", (self, MessageState::OutDraft), ) .await?; Ok(msg_id) } pub fn is_special(self) -> bool { (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct ChatId(u32); pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub async fn load_from_db(context: &Context, id: MsgId) -> Result<Message> { let message = Self::load_from_db_optional(context, id) .await? .with_context(|| format!("Message {id} does not exist"))?; Ok(message) }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__33.txt
pub unsafe extern "C" fn dc_set_draft( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut msg: *mut dc_msg_t, ) { if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || chat_id <= 9 as libc::c_int as libc::c_uint { return; } if set_draft_raw(context, chat_id, msg) != 0 { ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, chat_id as uintptr_t, 0 as libc::c_int as uintptr_t, ); } }
projects/deltachat-core/c/dc_contact.c
* using dc_set_config(context, "selfavatar", image). * * @memberof dc_contact_t * @param contact The contact object. * @return Path and file if the profile image, if any. * NULL otherwise. * Must be free()'d after usage. */ char* dc_contact_get_profile_image(const dc_contact_t* contact) { char* selfavatar = NULL; char* image_abs = NULL; if (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) { goto cleanup; } if (contact->id==DC_CONTACT_ID_SELF) { selfavatar = dc_get_config(contact->context, "selfavatar"); if (selfavatar && selfavatar[0]) { image_abs = dc_strdup(selfavatar); } } else { image_rel = dc_param_get(chat->param, DC_PARAM_PROFILE_IMAGE, NULL); if (image_rel && image_rel[0]) { image_abs = dc_get_abs_path(chat->context, image_rel); } } cleanup: free(selfavatar); return image_abs; }
projects/deltachat-core/rust/contact.rs
pub async fn get_profile_image(&self, context: &Context) -> Result<Option<PathBuf>> { if self.id == ContactId::SELF { if let Some(p) = context.get_config(Config::Selfavatar).await? { return Ok(Some(PathBuf::from(p))); } } else if let Some(image_rel) = self.param.get(Param::ProfileImage) { if !image_rel.is_empty() { return Ok(Some(get_abs_path(context, Path::new(image_rel)))); } } Ok(None) }
pub fn get(&self, key: Param) -> Option<&str> { self.inner.get(&key).map(|s| s.as_str()) } pub async fn get_config(&self, key: Config) -> Result<Option<String>> { let env_key = format!("DELTACHAT_{}", key.as_ref().to_uppercase()); if let Ok(value) = env::var(env_key) { return Ok(Some(value)); } let value = match key { Config::Selfavatar => { let rel_path = self.sql.get_raw_config(key.as_ref()).await?; rel_path.map(|p| { get_abs_path(self, Path::new(&p)) .to_string_lossy() .into_owned() }) } Config::SysVersion => Some((*DC_VERSION_STR).clone()), Config::SysMsgsizeMaxRecommended => Some(format!("{RECOMMENDED_FILE_SIZE}")), Config::SysConfigKeys => Some(get_config_keys_string()), _ => self.sql.get_raw_config(key.as_ref()).await?, }; if value.is_some() { return Ok(value); } // Default values match key { Config::ConfiguredInboxFolder => Ok(Some("INBOX".to_owned())), _ => Ok(key.get_str("default").map(|s| s.to_string())), } } pub fn is_empty(&self) -> bool { self.inner.is_empty() } pub(crate) fn get_abs_path(context: &Context, path: &Path) -> PathBuf { if let Ok(p) = path.strip_prefix("$BLOBDIR") { context.get_blobdir().join(p) } else { path.into() } } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct ContactId(u32); impl ContactId { /// Undefined contact. Used as a placeholder for trashed messages. pub const UNDEFINED: ContactId = ContactId::new(0); /// The owner of the account. /// /// The email-address is set by `set_config` using "addr". pub const SELF: ContactId = ContactId::new(1); /// ID of the contact for info messages. pub const INFO: ContactId = ContactId::new(2); /// ID of the contact for device messages. pub const DEVICE: ContactId = ContactId::new(5); pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9); /// Address to go with [`ContactId::DEVICE`]. /// /// This is used by APIs which need to return an email address for this contact. pub const DEVICE_ADDR: &'static str = "device@localhost"; } pub enum Config { /// Email address, used in the `From:` field. Addr, /// IMAP server hostname. MailServer, /// IMAP server username. MailUser, /// IMAP server password. MailPw, /// IMAP server port. MailPort, /// IMAP server security (e.g. TLS, STARTTLS). MailSecurity, /// How to check IMAP server TLS certificates. ImapCertificateChecks, /// SMTP server hostname. SendServer, /// SMTP server username. SendUser, /// SMTP server password. SendPw, /// SMTP server port. SendPort, /// SMTP server security (e.g. TLS, STARTTLS). SendSecurity, /// How to check SMTP server TLS certificates. SmtpCertificateChecks, /// Whether to use OAuth 2. /// /// Historically contained other bitflags, which are now deprecated. /// Should not be extended in the future, create new config keys instead. ServerFlags, /// True if SOCKS5 is enabled. /// /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration. Socks5Enabled, /// SOCKS5 proxy server hostname or address. Socks5Host, /// SOCKS5 proxy server port. Socks5Port, /// SOCKS5 proxy server username. Socks5User, /// SOCKS5 proxy server password. Socks5Password, /// Own name to use in the `From:` field when sending messages. Displayname, /// Own status to display, sent in message footer. Selfstatus, /// Own avatar filename. Selfavatar, /// Send BCC copy to self. /// /// Should be enabled for multidevice setups. #[strum(props(default = "1"))] BccSelf, /// True if encryption is preferred according to Autocrypt standard. #[strum(props(default = "1"))] E2eeEnabled, /// True if Message Delivery Notifications (read receipts) should /// be sent and requested. #[strum(props(default = "1"))] MdnsEnabled, /// True if "Sent" folder should be watched for changes. #[strum(props(default = "0"))] SentboxWatch, /// True if chat messages should be moved to a separate folder. #[strum(props(default = "1"))] MvboxMove, /// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only. /// /// This will not entirely disable other folders, e.g. the spam folder will also still /// be watched for new messages. #[strum(props(default = "0"))] OnlyFetchMvbox, /// Whether to show classic emails or only chat messages. #[strum(props(default = "2"))] // also change ShowEmails.default() on changes ShowEmails, /// Quality of the media files to send. #[strum(props(default = "0"))] // also change MediaQuality.default() on changes MediaQuality, /// If set to "1", on the first time `start_io()` is called after configuring, /// the newest existing messages are fetched. /// Existing recipients are added to the contact database regardless of this setting. #[strum(props(default = "0"))] FetchExistingMsgs, /// If set to "1", then existing messages are considered to be already fetched. /// This flag is reset after successful configuration. #[strum(props(default = "1"))] FetchedExistingMsgs, /// Type of the OpenPGP key to generate. #[strum(props(default = "0"))] KeyGenType, /// Timer in seconds after which the message is deleted from the /// server. /// /// Equals to 0 by default, which means the message is never /// deleted. /// /// Value 1 is treated as "delete at once": messages are deleted /// immediately, without moving to DeltaChat folder. #[strum(props(default = "0"))] DeleteServerAfter, /// Timer in seconds after which the message is deleted from the /// device. /// /// Equals to 0 by default, which means the message is never /// deleted. #[strum(props(default = "0"))] DeleteDeviceAfter, /// Move messages to the Trash folder instead of marking them "\Deleted". Overrides /// `ProviderOptions::delete_to_trash`. DeleteToTrash, /// Save raw MIME messages with headers in the database if true. SaveMimeHeaders, /// The primary email address. Also see `SecondaryAddrs`. ConfiguredAddr, /// Configured IMAP server hostname. ConfiguredMailServer, /// Configured IMAP server username. ConfiguredMailUser, /// Configured IMAP server password. ConfiguredMailPw, /// Configured IMAP server port. ConfiguredMailPort, /// Configured IMAP server security (e.g. TLS, STARTTLS). ConfiguredMailSecurity, /// How to check IMAP server TLS certificates. ConfiguredImapCertificateChecks, /// Configured SMTP server hostname. ConfiguredSendServer, /// Configured SMTP server username. ConfiguredSendUser, /// Configured SMTP server password. ConfiguredSendPw, /// Configured SMTP server port. ConfiguredSendPort, /// How to check SMTP server TLS certificates. ConfiguredSmtpCertificateChecks, /// Whether OAuth 2 is used with configured provider. ConfiguredServerFlags, /// Configured SMTP server security (e.g. TLS, STARTTLS). ConfiguredSendSecurity, /// Configured folder for incoming messages. ConfiguredInboxFolder, /// Configured folder for chat messages. ConfiguredMvboxFolder, /// Configured "Sent" folder. ConfiguredSentboxFolder, /// Configured "Trash" folder. ConfiguredTrashFolder, /// Unix timestamp of the last successful configuration. ConfiguredTimestamp, /// ID of the configured provider from the provider database. ConfiguredProvider, /// True if account is configured. Configured, /// True if account is a chatmail account. IsChatmail, /// All secondary self addresses separated by spaces /// (`[email protected] [email protected] [email protected]`) SecondaryAddrs, /// Read-only core version string. #[strum(serialize = "sys.version")] SysVersion, /// Maximal recommended attachment size in bytes. #[strum(serialize = "sys.msgsize_max_recommended")] SysMsgsizeMaxRecommended, /// Space separated list of all config keys available. #[strum(serialize = "sys.config_keys")] SysConfigKeys, /// True if it is a bot account. Bot, /// True when to skip initial start messages in groups. #[strum(props(default = "0"))] SkipStartMessages, /// Whether we send a warning if the password is wrong (set to false when we send a warning /// because we do not want to send a second warning) #[strum(props(default = "0"))] NotifyAboutWrongPw, /// If a warning about exceeding quota was shown recently, /// this is the percentage of quota at the time the warning was given. /// Unset, when quota falls below minimal warning threshold again. QuotaExceeding, /// address to webrtc instance to use for videochats WebrtcInstance, /// Timestamp of the last time housekeeping was run LastHousekeeping, /// Timestamp of the last `CantDecryptOutgoingMsgs` notification. LastCantDecryptOutgoingMsgs, /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely. #[strum(props(default = "60"))] ScanAllFoldersDebounceSecs, /// Whether to avoid using IMAP IDLE even if the server supports it. /// /// This is a developer option for testing "fake idle". #[strum(props(default = "0"))] DisableIdle, /// Defines the max. size (in bytes) of messages downloaded automatically. /// 0 = no limit. #[strum(props(default = "0"))] DownloadLimit, /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set. #[strum(props(default = "1"))] SyncMsgs, /// Space-separated list of all the authserv-ids which we believe /// may be the one of our email server. /// /// See `crate::authres::update_authservid_candidates`. AuthservIdCandidates, /// Make all outgoing messages with Autocrypt header "multipart/signed". SignUnencrypted, /// Let the core save all events to the database. /// This value is used internally to remember the MsgId of the logging xdc #[strum(props(default = "0"))] DebugLogging, /// Last message processed by the bot. LastMsgId, /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by /// default. /// /// This is not supposed to be changed by UIs and only used for testing. #[strum(props(default = "172800"))] GossipPeriod, /// Feature flag for verified 1:1 chats; the UI should set it /// to 1 if it supports verified 1:1 chats. /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified, /// and when the key changes, an info message is posted into the chat. /// 0=Nothing else happens when the key changes. /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true /// until `chat_id.accept()` is called. #[strum(props(default = "0"))] VerifiedOneOnOneChats, /// Row ID of the key in the `keypairs` table /// 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 /// without storing the email address SelfReportingId, /// MsgId of webxdc map integration. WebxdcIntegration, /// Iroh secret key. IrohSecretKey, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. } pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__43.txt
pub unsafe extern "C" fn dc_set_config( mut context: *mut dc_context_t, mut key: *const libc::c_char, mut value: *const libc::c_char, ) -> libc::c_int { let mut ret: libc::c_int = 0 as libc::c_int; let mut rel_path: *mut libc::c_char = 0 as *mut libc::c_char; if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || key.is_null() || is_settable_config_key(key) == 0 { return 0 as libc::c_int; } if strcmp(key, b"selfavatar\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int && !value.is_null() { rel_path = dc_strdup(value); if !(dc_make_rel_and_copy(context, &mut rel_path) == 0) { ret = dc_sqlite3_set_config((*context).sql, key, rel_path); } } else if strcmp(key, b"inbox_watch\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { ret = dc_sqlite3_set_config((*context).sql, key, value); dc_interrupt_imap_idle(context); } else if strcmp(key, b"sentbox_watch\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { ret = dc_sqlite3_set_config((*context).sql, key, value); dc_interrupt_sentbox_idle(context); } else if strcmp(key, b"mvbox_watch\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { ret = dc_sqlite3_set_config((*context).sql, key, value); dc_interrupt_mvbox_idle(context); } else if strcmp(key, b"selfstatus\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { let mut def: *mut libc::c_char = dc_stock_str(context, 13 as libc::c_int); ret = dc_sqlite3_set_config( (*context).sql, key, if value.is_null() || strcmp(value, def) == 0 as libc::c_int { 0 as *const libc::c_char } else { value }, ); free(def as *mut libc::c_void); } else { ret = dc_sqlite3_set_config((*context).sql, key, value); } free(rel_path as *mut libc::c_void); return ret; }
projects/deltachat-core/c/dc_msg.c
int dc_msg_is_increation(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->context==NULL) { return 0; } return DC_MSG_NEEDS_ATTACHMENT(msg->type) && msg->state==DC_STATE_OUT_PREPARING; }
projects/deltachat-core/rust/message.rs
pub fn is_increation(&self) -> bool { self.viewtype.has_file() && self.state == MessageState::OutPreparing }
pub fn has_file(&self) -> bool { match self { Viewtype::Unknown => false, Viewtype::Text => false, Viewtype::Image => true, Viewtype::Gif => true, Viewtype::Sticker => true, Viewtype::Audio => true, Viewtype::Voice => true, Viewtype::Video => true, Viewtype::File => true, Viewtype::VideochatInvitation => false, Viewtype::Webxdc => true, Viewtype::Vcard => true, } } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum MessageState { /// Undefined message state. #[default] Undefined = 0, /// Incoming *fresh* message. Fresh messages are neither noticed /// nor seen and are typically shown in notifications. InFresh = 10, /// Incoming *noticed* message. E.g. chat opened but message not /// yet read - noticed messages are not counted as unread but did /// not marked as read nor resulted in MDNs. InNoticed = 13, /// Incoming message, really *seen* by the user. Marked as read on /// IMAP and MDN may be sent. InSeen = 16, /// For files which need time to be prepared before they can be /// sent, the message enters this state before /// OutPending. OutPreparing = 18, /// Message saved as draft. OutDraft = 19, /// The user has pressed the "send" button but the message is not /// yet sent and is pending in some way. Maybe we're offline (no /// checkmark). OutPending = 20, /// *Unrecoverable* error (*recoverable* errors result in pending /// messages). OutFailed = 24, /// Outgoing message successfully delivered to server (one /// checkmark). Note, that already delivered messages may get into /// the OutFailed state if we get such a hint from the server. OutDelivered = 26, /// Outgoing message read by the recipient (two checkmarks; this /// requires goodwill on the receiver's side) OutMdnRcvd = 28, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__59.txt
pub unsafe extern "C" fn dc_msg_is_increation(mut msg: *const dc_msg_t) -> libc::c_int { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint || ((*msg).context).is_null() { return 0 as libc::c_int; } return (((*msg).type_0 == 20 as libc::c_int || (*msg).type_0 == 21 as libc::c_int || (*msg).type_0 == 40 as libc::c_int || (*msg).type_0 == 41 as libc::c_int || (*msg).type_0 == 50 as libc::c_int || (*msg).type_0 == 60 as libc::c_int) && (*msg).state == 18 as libc::c_int) as libc::c_int; }
projects/deltachat-core/c/dc_location.c
char* dc_get_message_kml(dc_context_t* context, time_t timestamp, double latitude, double longitude) { char* timestamp_str = NULL; char* latitude_str = NULL; char* longitude_str = NULL; char* ret = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } timestamp_str = get_kml_timestamp(timestamp); latitude_str = dc_ftoa(latitude); longitude_str = dc_ftoa(longitude); ret = dc_mprintf( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n" "<Document>\n" "<Placemark>" "<Timestamp><when>%s</when></Timestamp>" "<Point><coordinates>%s,%s</coordinates></Point>" "</Placemark>\n" "</Document>\n" "</kml>", timestamp_str, longitude_str, // reverse order! latitude_str); cleanup: free(latitude_str); free(longitude_str); free(timestamp_str); return ret; }
projects/deltachat-core/rust/location.rs
pub fn get_message_kml(timestamp: i64, latitude: f64, longitude: f64) -> String { format!( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\ <kml xmlns=\"http://www.opengis.net/kml/2.2\">\n\ <Document>\n\ <Placemark>\ <Timestamp><when>{}</when></Timestamp>\ <Point><coordinates>{},{}</coordinates></Point>\ </Placemark>\n\ </Document>\n\ </kml>", get_kml_timestamp(timestamp), longitude, latitude, ) }
use std::time::Duration; use anyhow::{ensure, Context as _, Result}; use async_channel::Receiver; use quick_xml::events::{BytesEnd, BytesStart, BytesText}; use tokio::time::timeout; use crate::chat::{self, ChatId}; use crate::constants::DC_CHAT_ID_TRASH; use crate::contact::ContactId; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::tools::{duration_to_str, time}; use crate::{chatlist_events, stock_str}; use super::*; use crate::config::Config; use crate::message::MessageState; use crate::receive_imf::receive_imf; use crate::test_utils::{TestContext, TestContextManager}; use crate::tools::SystemTime;
projects__deltachat-core__rust__location__.rs__function__18.txt
pub unsafe extern "C" fn dc_get_message_kml( mut context: *mut dc_context_t, mut timestamp: time_t, mut latitude: libc::c_double, mut longitude: libc::c_double, ) -> *mut libc::c_char { let mut timestamp_str: *mut libc::c_char = 0 as *mut libc::c_char; let mut latitude_str: *mut libc::c_char = 0 as *mut libc::c_char; let mut longitude_str: *mut libc::c_char = 0 as *mut libc::c_char; let mut ret: *mut libc::c_char = 0 as *mut libc::c_char; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint) { timestamp_str = get_kml_timestamp(timestamp); latitude_str = dc_ftoa(latitude); longitude_str = dc_ftoa(longitude); ret = dc_mprintf( b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n<Document>\n<Placemark><Timestamp><when>%s</when></Timestamp><Point><coordinates>%s,%s</coordinates></Point></Placemark>\n</Document>\n</kml>\0" as *const u8 as *const libc::c_char, timestamp_str, longitude_str, latitude_str, ); } free(latitude_str as *mut libc::c_void); free(longitude_str as *mut libc::c_void); free(timestamp_str as *mut libc::c_void); return ret; }
projects/deltachat-core/c/dc_location.c
void dc_send_locations_to_chat(dc_context_t* context, uint32_t chat_id, int seconds) { sqlite3_stmt* stmt = NULL; time_t now = time(NULL); dc_msg_t* msg = NULL; char* stock_str = NULL; int is_sending_locations_before = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || seconds<0 || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } is_sending_locations_before = dc_is_sending_locations_to_chat(context, chat_id); stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats " " SET locations_send_begin=?, " " locations_send_until=? " " WHERE id=?"); sqlite3_bind_int64(stmt, 1, seconds? now : 0); sqlite3_bind_int64(stmt, 2, seconds? now+seconds : 0); sqlite3_bind_int (stmt, 3, chat_id); sqlite3_step(stmt); // add/sent status message. // as disable also happens after a timeout, this is not sent explicitly. if (seconds && !is_sending_locations_before) { msg = dc_msg_new(context, DC_MSG_TEXT); msg->text = dc_stock_system_msg(context, DC_STR_MSGLOCATIONENABLED, NULL, NULL, 0); dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_LOCATION_STREAMING_ENABLED); dc_send_msg(context, chat_id, msg); } else if(!seconds && is_sending_locations_before) { stock_str = dc_stock_system_msg(context, DC_STR_MSGLOCATIONDISABLED, NULL, NULL, 0); dc_add_device_msg(context, chat_id, stock_str); } // update eg. the "location-sending"-icon context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); if (seconds) { schedule_MAYBE_SEND_LOCATIONS(context, 0); dc_job_add(context, DC_JOB_MAYBE_SEND_LOC_ENDED, chat_id, NULL, seconds+1); } cleanup: free(stock_str); dc_msg_unref(msg); sqlite3_finalize(stmt); }
projects/deltachat-core/rust/location.rs
pub async fn send_locations_to_chat( context: &Context, chat_id: ChatId, seconds: i64, ) -> Result<()> { ensure!(seconds >= 0); ensure!(!chat_id.is_special()); let now = time(); let is_sending_locations_before = is_sending_locations_to_chat(context, Some(chat_id)).await?; context .sql .execute( "UPDATE chats \ SET locations_send_begin=?, \ locations_send_until=? \ WHERE id=?", ( if 0 != seconds { now } else { 0 }, if 0 != seconds { now + seconds } else { 0 }, chat_id, ), ) .await?; if 0 != seconds && !is_sending_locations_before { let mut msg = Message::new(Viewtype::Text); msg.text = stock_str::msg_location_enabled(context).await; msg.param.set_cmd(SystemMessage::LocationStreamingEnabled); chat::send_msg(context, chat_id, &mut msg) .await .unwrap_or_default(); } else if 0 == seconds && is_sending_locations_before { let stock_str = stock_str::msg_location_disabled(context).await; chat::add_info_msg(context, chat_id, &stock_str, now).await?; } context.emit_event(EventType::ChatModified(chat_id)); chatlist_events::emit_chatlist_item_changed(context, chat_id); if 0 != seconds { context.scheduler.interrupt_location().await; } Ok(()) }
pub fn emit_event(&self, event: EventType) { { let lock = self.debug_logging.read().expect("RwLock is poisoned"); if let Some(debug_logging) = &*lock { debug_logging.log_event(event.clone()); } } self.events.emit(Event { id: self.id, typ: event, }); } pub fn is_special(self) -> bool { (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0) } pub async fn is_sending_locations_to_chat( context: &Context, chat_id: Option<ChatId>, ) -> Result<bool> { let exists = match chat_id { Some(chat_id) => { context .sql .exists( "SELECT COUNT(id) FROM chats WHERE id=? AND locations_send_until>?;", (chat_id, time()), ) .await? } None => { context .sql .exists( "SELECT COUNT(id) FROM chats WHERE locations_send_until>?;", (time(),), ) .await? } }; Ok(exists) } pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> { if chat_id.is_unset() { let forwards = msg.param.get(Param::PrepForwards); if let Some(forwards) = forwards { for forward in forwards.split(' ') { if let Ok(msg_id) = forward.parse::<u32>().map(MsgId::new) { if let Ok(mut msg) = Message::load_from_db(context, msg_id).await { send_msg_inner(context, chat_id, &mut msg).await?; }; } } msg.param.remove(Param::PrepForwards); msg.update_param(context).await?; } return send_msg_inner(context, chat_id, msg).await; } if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing { msg.param.remove(Param::GuaranteeE2ee); msg.param.remove(Param::ForcePlaintext); msg.update_param(context).await?; } send_msg_inner(context, chat_id, msg).await } pub async fn execute( &self, query: &str, params: impl rusqlite::Params + Send, ) -> Result<usize> { self.call_write(move |conn| { let res = conn.execute(query, params)?; Ok(res) }) .await } pub(crate) fn time() -> i64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap_or_default() .as_secs() as i64 } pub struct Context { pub(crate) inner: Arc<InnerContext>, } impl Message { /// Creates a new message with given view type. pub fn new(viewtype: Viewtype) -> Self { Message { viewtype, ..Default::default() } } } pub enum Viewtype { /// Unknown message type. #[default] Unknown = 0, /// Text message. /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text(). Text = 10, /// Image message. /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to /// `Gif` when sending the message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension(). Image = 20, /// Animated GIF message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension() /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height(). Gif = 21, /// Message containing a sticker, similar to image. /// If possible, the ui should display the image without borders in a transparent way. /// A click on a sticker will offer to install the sticker set in some future. Sticker = 23, /// Message containing an Audio file. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration(). Audio = 40, /// A voice message that was directly recorded by the user. /// For all other audio messages, the type #DC_MSG_AUDIO should be used. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration() Voice = 41, /// Video messages. /// File, width, height and durarion /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration() /// and retrieved via /// dc_msg_get_file(), dc_msg_get_width(), /// dc_msg_get_height(), dc_msg_get_duration(). Video = 50, /// Message containing any file, eg. a PDF. /// The file is set via dc_msg_set_file() /// and retrieved via dc_msg_get_file(). File = 60, /// Message is an invitation to a videochat. VideochatInvitation = 70, /// Message is an webxdc instance. Webxdc = 80, /// Message containing shared contacts represented as a vCard (virtual contact file) /// with email addresses and possibly other fields. /// Use `parse_vcard()` to retrieve them. Vcard = 90, } pub(crate) async fn msg_location_enabled(context: &Context) -> String { translated(context, StockMessage::MsgLocationEnabled).await } pub enum EventType { /// The library-user may write an informational string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Info(String), /// Emitted when SMTP connection is established and login was successful. SmtpConnected(String), /// Emitted when IMAP connection is established and login was successful. ImapConnected(String), /// Emitted when a message was successfully sent to the SMTP server. SmtpMessageSent(String), /// Emitted when an IMAP message has been marked as deleted ImapMessageDeleted(String), /// Emitted when an IMAP message has been moved ImapMessageMoved(String), /// Emitted before going into IDLE on the Inbox folder. ImapInboxIdle, /// Emitted when an new file in the $BLOBDIR was created NewBlobFile(String), /// Emitted when an file in the $BLOBDIR was deleted DeletedBlobFile(String), /// The library-user should write a warning string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Warning(String), /// The library-user should report an error to the end-user. /// /// As most things are asynchronous, things may go wrong at any time and the user /// should not be disturbed by a dialog or so. Instead, use a bubble or so. /// /// However, for ongoing processes (eg. configure()) /// or for functions that are expected to fail (eg. dc_continue_key_transfer()) /// it might be better to delay showing these events until the function has really /// failed (returned false). It should be sufficient to report only the *last* error /// in a messasge box then. Error(String), /// An action cannot be performed because the user is not in the group. /// Reported eg. after a call to /// dc_set_chat_name(), dc_set_chat_profile_image(), /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(), /// dc_send_text_msg() or another sending function. ErrorSelfNotInGroup(String), /// Messages or chats changed. One or more messages or chats changed for various /// reasons in the database: /// - Messages sent, received or removed /// - Chats created, deleted or archived /// - A draft has been set /// MsgsChanged { /// Set if only a single chat is affected by the changes, otherwise 0. chat_id: ChatId, /// Set if only a single message is affected by the changes, otherwise 0. msg_id: MsgId, }, /// Reactions for the message changed. ReactionsChanged { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message for which reactions were changed. msg_id: MsgId, /// ID of the contact whose reaction set is changed. contact_id: ContactId, }, /// There is a fresh message. Typically, the user will show an notification /// when receiving this message. /// /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event. IncomingMsg { /// ID of the chat where the message is assigned. chat_id: ChatId, /// ID of the message. msg_id: MsgId, }, /// Downloading a bunch of messages just finished. IncomingMsgBunch, /// Messages were seen or noticed. /// chat id is always set. MsgsNoticed(ChatId), /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state(). MsgDelivered { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was successfully sent. msg_id: MsgId, }, /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_FAILED, see dc_msg_get_state(). MsgFailed { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that could not be sent. msg_id: MsgId, }, /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state(). MsgRead { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was read. msg_id: MsgId, }, /// A single message was deleted. /// /// This event means that the message will no longer appear in the messagelist. /// UI should remove the message from the messagelist /// in response to this event if the message is currently displayed. /// /// The message may have been explicitly deleted by the user or expired. /// Internally the message may have been removed from the database, /// moved to the trash chat or hidden. /// /// This event does not indicate the message /// deletion from the server. MsgDeleted { /// ID of the chat where the message was prior to deletion. /// Never 0 or trash chat. chat_id: ChatId, /// ID of the deleted message. Never 0. msg_id: MsgId, }, /// Chat changed. The name or the image of a chat group was changed or members were added or removed. /// Or the verify state of a chat has changed. /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat() /// and dc_remove_contact_from_chat(). /// /// This event does not include ephemeral timer modification, which /// is a separate event. ChatModified(ChatId), /// Chat ephemeral timer changed. ChatEphemeralTimerModified { /// Chat ID. chat_id: ChatId, /// New ephemeral timer value. timer: EphemeralTimer, }, /// Contact(s) created, renamed, blocked, deleted or changed their "recently seen" status. /// /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected. ContactsChanged(Option<ContactId>), /// Location of one or more contact has changed. /// /// @param data1 (u32) contact_id of the contact for which the location has changed. /// If the locations of several contacts have been changed, /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`. LocationChanged(Option<ContactId>), /// Inform about the configuration progress started by configure(). ConfigureProgress { /// Progress. /// /// 0=error, 1-999=progress in permille, 1000=success and done progress: usize, /// Progress comment or error, something to display to the user. comment: Option<String>, }, /// Inform about the import/export progress started by imex(). /// /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done /// @param data2 0 ImexProgress(usize), /// A file has been exported. A file has been written by imex(). /// This event may be sent multiple times by a single call to imex(). /// /// A typical purpose for a handler of this event may be to make the file public to some system /// services. /// /// @param data2 0 ImexFileWritten(PathBuf), /// Progress information of a secure-join handshake from the view of the inviter /// (Alice, the person who shows the QR code). /// /// These events are typically sent after a joiner has scanned the QR code /// generated by dc_get_securejoin_qr(). SecurejoinInviterProgress { /// ID of the contact that wants to join. contact_id: ContactId, /// Progress as: /// 300=vg-/vc-request received, typically shown as "bob@addr joins". /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as "bob@addr verified". /// 800=contact added to chat, shown as "bob@addr securely joined GROUP". Only for the verified-group-protocol. /// 1000=Protocol finished for this contact. progress: usize, }, /// Progress information of a secure-join handshake from the view of the joiner /// (Bob, the person who scans the QR code). /// The events are typically sent while dc_join_securejoin(), which /// may take some time, is executed. SecurejoinJoinerProgress { /// ID of the inviting contact. contact_id: ContactId, /// Progress as: /// 400=vg-/vc-request-with-auth sent, typically shown as "alice@addr verified, introducing myself." /// (Bob has verified alice and waits until Alice does the same for him) /// 1000=vg-member-added/vc-contact-confirm received progress: usize, }, /// The connectivity to the server changed. /// This means that you should refresh the connectivity view /// and possibly the connectivtiy HTML; see dc_get_connectivity() and /// dc_get_connectivity_html() for details. ConnectivityChanged, /// The user's avatar changed. /// Deprecated by `ConfigSynced`. SelfavatarChanged, /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For /// uniformity this is emitted on the source device too. The value isn't here, otherwise it /// would be logged which might not be good for privacy. ConfigSynced { /// Configuration key. key: Config, }, /// Webxdc status update received. WebxdcStatusUpdate { /// Message ID. msg_id: MsgId, /// Status update ID. status_update_serial: StatusUpdateSerial, }, /// Data received over an ephemeral peer channel. WebxdcRealtimeData { /// Message ID. msg_id: MsgId, /// Realtime data. data: Vec<u8>, }, /// Inform that a message containing a webxdc instance has been deleted. WebxdcInstanceDeleted { /// ID of the deleted message. msg_id: MsgId, }, /// Tells that the Background fetch was completed (or timed out). /// This event acts as a marker, when you reach this event you can be sure /// that all events emitted during the background fetch were processed. /// /// This event is only emitted by the account manager AccountsBackgroundFetchDone, /// Inform that set of chats or the order of the chats in the chatlist has changed. /// /// Sometimes this is emitted together with `UIChatlistItemChanged`. ChatlistChanged, /// Inform that a single chat list item changed and needs to be rerendered. /// If `chat_id` is set to None, then all currently visible chats need to be rerendered, and all not-visible items need to be cleared from cache if the UI has a cache. ChatlistItemChanged { /// ID of the changed chat chat_id: Option<ChatId>, }, /// Event for using in tests, e.g. as a fence between normally generated events. #[cfg(test)] Test, /// Inform than some events have been skipped due to event channel overflow. EventChannelOverflow { /// Number of events skipped. n: u64, }, } pub(crate) fn emit_chatlist_item_changed(context: &Context, chat_id: ChatId) { context.emit_event(EventType::ChatlistItemChanged { chat_id: Some(chat_id), }); } pub(crate) async fn interrupt_location(&self) { let inner = self.inner.read().await; if let InnerSchedulerState::Started(ref scheduler) = *inner { scheduler.interrupt_location(); } } pub(crate) async fn add_info_msg( context: &Context, chat_id: ChatId, text: &str, timestamp: i64, ) -> Result<MsgId> { add_info_msg_with_cmd( context, chat_id, text, SystemMessage::Unknown, timestamp, None, None, None, ) .await } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, }
use std::time::Duration; use anyhow::{ensure, Context as _, Result}; use async_channel::Receiver; use quick_xml::events::{BytesEnd, BytesStart, BytesText}; use tokio::time::timeout; use crate::chat::{self, ChatId}; use crate::constants::DC_CHAT_ID_TRASH; use crate::contact::ContactId; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::tools::{duration_to_str, time}; use crate::{chatlist_events, stock_str}; use super::*; use crate::config::Config; use crate::message::MessageState; use crate::receive_imf::receive_imf; use crate::test_utils::{TestContext, TestContextManager}; use crate::tools::SystemTime;
projects__deltachat-core__rust__location__.rs__function__7.txt
pub unsafe extern "C" fn dc_send_locations_to_chat( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut seconds: libc::c_int, ) { let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; let mut now: time_t = time(0 as *mut time_t); let mut msg: *mut dc_msg_t = 0 as *mut dc_msg_t; let mut stock_str: *mut libc::c_char = 0 as *mut libc::c_char; let mut is_sending_locations_before: libc::c_int = 0 as libc::c_int; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || seconds < 0 as libc::c_int || chat_id <= 9 as libc::c_int as libc::c_uint) { is_sending_locations_before = dc_is_sending_locations_to_chat(context, chat_id); stmt = dc_sqlite3_prepare( (*context).sql, b"UPDATE chats SET locations_send_begin=?, locations_send_until=? WHERE id=?\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int64( stmt, 1 as libc::c_int, (if seconds != 0 { now } else { 0 as libc::c_int as libc::c_long }) as sqlite3_int64, ); sqlite3_bind_int64( stmt, 2 as libc::c_int, (if seconds != 0 { now + seconds as libc::c_long } else { 0 as libc::c_int as libc::c_long }) as sqlite3_int64, ); sqlite3_bind_int(stmt, 3 as libc::c_int, chat_id as libc::c_int); sqlite3_step(stmt); if seconds != 0 && is_sending_locations_before == 0 { msg = dc_msg_new(context, 10 as libc::c_int); (*msg) .text = dc_stock_system_msg( context, 64 as libc::c_int, 0 as *const libc::c_char, 0 as *const libc::c_char, 0 as libc::c_int as uint32_t, ); dc_param_set_int((*msg).param, 'S' as i32, 8 as libc::c_int); dc_send_msg(context, chat_id, msg); } else if seconds == 0 && is_sending_locations_before != 0 { stock_str = dc_stock_system_msg( context, 65 as libc::c_int, 0 as *const libc::c_char, 0 as *const libc::c_char, 0 as libc::c_int as uint32_t, ); dc_add_device_msg(context, chat_id, stock_str); } ((*context).cb) .expect( "non-null function pointer", )( context, 2020 as libc::c_int, chat_id as uintptr_t, 0 as libc::c_int as uintptr_t, ); if seconds != 0 { schedule_MAYBE_SEND_LOCATIONS(context, 0 as libc::c_int); dc_job_add( context, 5007 as libc::c_int, chat_id as libc::c_int, 0 as *const libc::c_char, seconds + 1 as libc::c_int, ); } } free(stock_str as *mut libc::c_void); dc_msg_unref(msg); sqlite3_finalize(stmt); }
projects/deltachat-core/c/dc_location.c
dc_array_t* dc_get_locations(dc_context_t* context, uint32_t chat_id, uint32_t contact_id, time_t timestamp_from, time_t timestamp_to) { dc_array_t* ret = dc_array_new_typed(context, DC_ARRAY_LOCATIONS, 500); sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (timestamp_to==0) { timestamp_to = time(NULL) + 10/*messages may be inserted by another thread just now*/; } stmt = dc_sqlite3_prepare(context->sql, "SELECT l.id, l.latitude, l.longitude, l.accuracy, l.timestamp, l.independent, " " m.id, l.from_id, l.chat_id, m.txt " " FROM locations l " " LEFT JOIN msgs m ON l.id=m.location_id " " WHERE (? OR l.chat_id=?) " " AND (? OR l.from_id=?) " " AND (l.independent=1 OR (l.timestamp>=? AND l.timestamp<=?)) " " ORDER BY l.timestamp DESC, l.id DESC, m.id DESC;"); sqlite3_bind_int(stmt, 1, chat_id==0? 1 : 0); sqlite3_bind_int(stmt, 2, chat_id); sqlite3_bind_int(stmt, 3, contact_id==0? 1 : 0); sqlite3_bind_int(stmt, 4, contact_id); sqlite3_bind_int(stmt, 5, timestamp_from); sqlite3_bind_int(stmt, 6, timestamp_to); while (sqlite3_step(stmt)==SQLITE_ROW) { struct _dc_location* loc = calloc(1, sizeof(struct _dc_location)); if (loc==NULL) { goto cleanup; } loc->location_id = sqlite3_column_double(stmt, 0); loc->latitude = sqlite3_column_double(stmt, 1); loc->longitude = sqlite3_column_double(stmt, 2); loc->accuracy = sqlite3_column_double(stmt, 3); loc->timestamp = sqlite3_column_int64 (stmt, 4); loc->independent = sqlite3_column_int (stmt, 5); loc->msg_id = sqlite3_column_int (stmt, 6); loc->contact_id = sqlite3_column_int (stmt, 7); loc->chat_id = sqlite3_column_int (stmt, 8); if (loc->msg_id) { const char* txt = (const char*)sqlite3_column_text(stmt, 9); if (is_marker(txt)) { loc->marker = strdup(txt); } } dc_array_add_ptr(ret, loc); } cleanup: sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/rust/location.rs
pub async fn get_range( context: &Context, chat_id: Option<ChatId>, contact_id: Option<u32>, timestamp_from: i64, mut timestamp_to: i64, ) -> Result<Vec<Location>> { if timestamp_to == 0 { timestamp_to = time() + 10; } let (disable_chat_id, chat_id) = match chat_id { Some(chat_id) => (0, chat_id), None => (1, ChatId::new(0)), // this ChatId is unused }; let (disable_contact_id, contact_id) = match contact_id { Some(contact_id) => (0, contact_id), None => (1, 0), // this contact_id is unused }; let list = context .sql .query_map( "SELECT l.id, l.latitude, l.longitude, l.accuracy, l.timestamp, l.independent, \ COALESCE(m.id, 0) AS msg_id, l.from_id, l.chat_id, COALESCE(m.txt, '') AS txt \ FROM locations l LEFT JOIN msgs m ON l.id=m.location_id WHERE (? OR l.chat_id=?) \ AND (? OR l.from_id=?) \ AND (l.independent=1 OR (l.timestamp>=? AND l.timestamp<=?)) \ ORDER BY l.timestamp DESC, l.id DESC, msg_id DESC;", ( disable_chat_id, chat_id, disable_contact_id, contact_id as i32, timestamp_from, timestamp_to, ), |row| { let msg_id = row.get(6)?; let txt: String = row.get(9)?; let marker = if msg_id != 0 && is_marker(&txt) { Some(txt) } else { None }; let loc = Location { location_id: row.get(0)?, latitude: row.get(1)?, longitude: row.get(2)?, accuracy: row.get(3)?, timestamp: row.get(4)?, independent: row.get(5)?, msg_id, contact_id: row.get(7)?, chat_id: row.get(8)?, marker, }; Ok(loc) }, |locations| { let mut ret = Vec::new(); for location in locations { ret.push(location?); } Ok(ret) }, ) .await?; Ok(list) }
fn is_marker(txt: &str) -> bool { let mut chars = txt.chars(); if let Some(c) = chars.next() { !c.is_whitespace() && chars.next().is_none() } else { false } } pub(crate) fn time() -> i64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap_or_default() .as_secs() as i64 } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub async fn query_map<T, F, G, H>( &self, sql: &str, params: impl rusqlite::Params + Send, f: F, mut g: G, ) -> Result<H> where F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>, G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>, H: Send + 'static, { self.call(move |conn| { let mut stmt = conn.prepare(sql)?; let res = stmt.query_map(params, f)?; g(res) }) .await } pub const fn new(id: u32) -> ChatId { ChatId(id) } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub struct Location { /// Row ID of the location. pub location_id: u32, /// Location latitude. pub latitude: f64, /// Location longitude. pub longitude: f64, /// Nonstandard `accuracy` attribute of the `coordinates` tag. pub accuracy: f64, /// Location timestamp in seconds. pub timestamp: i64, /// Contact ID. pub contact_id: ContactId, /// Message ID. pub msg_id: u32, /// Chat ID. pub chat_id: ChatId, /// A marker string, such as an emoji, to be displayed on top of the location. pub marker: Option<String>, /// Whether location is independent, i.e. not part of the path. pub independent: u32, }
use std::time::Duration; use anyhow::{ensure, Context as _, Result}; use async_channel::Receiver; use quick_xml::events::{BytesEnd, BytesStart, BytesText}; use tokio::time::timeout; use crate::chat::{self, ChatId}; use crate::constants::DC_CHAT_ID_TRASH; use crate::contact::ContactId; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::tools::{duration_to_str, time}; use crate::{chatlist_events, stock_str}; use super::*; use crate::config::Config; use crate::message::MessageState; use crate::receive_imf::receive_imf; use crate::test_utils::{TestContext, TestContextManager}; use crate::tools::SystemTime;
projects__deltachat-core__rust__location__.rs__function__10.txt
pub unsafe extern "C" fn dc_get_locations( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut contact_id: uint32_t, mut timestamp_from: time_t, mut timestamp_to: time_t, ) -> *mut dc_array_t { let mut ret: *mut dc_array_t = dc_array_new_typed( context, 1 as libc::c_int, 500 as libc::c_int as size_t, ); let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint) { if timestamp_to == 0 as libc::c_int as libc::c_long { timestamp_to = time(0 as *mut time_t) + 10 as libc::c_int as libc::c_long; } stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT l.id, l.latitude, l.longitude, l.accuracy, l.timestamp, l.independent, m.id, l.from_id, l.chat_id, m.txt FROM locations l LEFT JOIN msgs m ON l.id=m.location_id WHERE (? OR l.chat_id=?) AND (? OR l.from_id=?) AND (l.independent=1 OR (l.timestamp>=? AND l.timestamp<=?)) ORDER BY l.timestamp DESC, l.id DESC, m.id DESC;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int( stmt, 1 as libc::c_int, if chat_id == 0 as libc::c_int as libc::c_uint { 1 as libc::c_int } else { 0 as libc::c_int }, ); sqlite3_bind_int(stmt, 2 as libc::c_int, chat_id as libc::c_int); sqlite3_bind_int( stmt, 3 as libc::c_int, if contact_id == 0 as libc::c_int as libc::c_uint { 1 as libc::c_int } else { 0 as libc::c_int }, ); sqlite3_bind_int(stmt, 4 as libc::c_int, contact_id as libc::c_int); sqlite3_bind_int(stmt, 5 as libc::c_int, timestamp_from as libc::c_int); sqlite3_bind_int(stmt, 6 as libc::c_int, timestamp_to as libc::c_int); while sqlite3_step(stmt) == 100 as libc::c_int { let mut loc: *mut _dc_location = calloc( 1 as libc::c_int as libc::c_ulong, ::core::mem::size_of::<_dc_location>() as libc::c_ulong, ) as *mut _dc_location; if loc.is_null() { break; } (*loc) .location_id = sqlite3_column_double(stmt, 0 as libc::c_int) as uint32_t; (*loc).latitude = sqlite3_column_double(stmt, 1 as libc::c_int); (*loc).longitude = sqlite3_column_double(stmt, 2 as libc::c_int); (*loc).accuracy = sqlite3_column_double(stmt, 3 as libc::c_int); (*loc).timestamp = sqlite3_column_int64(stmt, 4 as libc::c_int) as time_t; (*loc).independent = sqlite3_column_int(stmt, 5 as libc::c_int); (*loc).msg_id = sqlite3_column_int(stmt, 6 as libc::c_int) as uint32_t; (*loc).contact_id = sqlite3_column_int(stmt, 7 as libc::c_int) as uint32_t; (*loc).chat_id = sqlite3_column_int(stmt, 8 as libc::c_int) as uint32_t; if (*loc).msg_id != 0 { let mut txt: *const libc::c_char = sqlite3_column_text( stmt, 9 as libc::c_int, ) as *const libc::c_char; if is_marker(txt) != 0 { (*loc).marker = strdup(txt); } } dc_array_add_ptr(ret, loc as *mut libc::c_void); } } sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/c/dc_location.c
static int is_marker(const char* txt) { if (txt) { int len = dc_utf8_strlen(txt); if (len==1 && !isspace(txt[0])) { return 1; } } return 0; }
projects/deltachat-core/rust/location.rs
fn is_marker(txt: &str) -> bool { let mut chars = txt.chars(); if let Some(c) = chars.next() { !c.is_whitespace() && chars.next().is_none() } else { false } }
use std::time::Duration; use anyhow::{ensure, Context as _, Result}; use async_channel::Receiver; use quick_xml::events::{BytesEnd, BytesStart, BytesText}; use tokio::time::timeout; use crate::chat::{self, ChatId}; use crate::constants::DC_CHAT_ID_TRASH; use crate::contact::ContactId; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::tools::{duration_to_str, time}; use crate::{chatlist_events, stock_str}; use super::*; use crate::config::Config; use crate::message::MessageState; use crate::receive_imf::receive_imf; use crate::test_utils::{TestContext, TestContextManager}; use crate::tools::SystemTime;
projects__deltachat-core__rust__location__.rs__function__11.txt
unsafe extern "C" fn is_marker(mut txt: *const libc::c_char) -> libc::c_int { if !txt.is_null() { let mut len: libc::c_int = dc_utf8_strlen(txt) as libc::c_int; if len == 1 as libc::c_int && *txt.offset(0 as libc::c_int as isize) as libc::c_int != ' ' as i32 { return 1 as libc::c_int; } } return 0 as libc::c_int; }
projects/deltachat-core/c/dc_configure.c
* function not under the control of the core (eg. #DC_EVENT_HTTP_GET). Another * reason for dc_stop_ongoing_process() not to wait is that otherwise it * would be GUI-blocking and should be started in another thread then; this * would make things even more complicated. * * Typical ongoing processes are started by dc_configure(), * dc_initiate_key_transfer() or dc_imex(). As there is always at most only * one onging process at the same time, there is no need to define _which_ process to exit. * * @memberof dc_context_t * @param context The context object. * @return None. */ void dc_stop_ongoing_process(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } if (context->ongoing_running && context->shall_stop_ongoing==0) { dc_log_info(context, 0, "Signaling the ongoing process to stop ASAP."); context->shall_stop_ongoing = 1; } else { dc_log_info(context, 0, "No ongoing process to stop."); } }
projects/deltachat-core/rust/context.rs
pub async fn stop_ongoing(&self) { let mut s = self.running_state.write().await; match &*s { RunningState::Running { cancel_sender } => { if let Err(err) = cancel_sender.send(()).await { warn!(self, "could not cancel ongoing: {:#}", err); } info!(self, "Signaling the ongoing process to stop ASAP.",); *s = RunningState::ShallStop { request: tools::Time::now(), }; } RunningState::ShallStop { .. } | RunningState::Stopped => { info!(self, "No ongoing process to stop.",); } } }
macro_rules! info { ($ctx:expr, $msg:expr) => { info!($ctx, $msg,) }; ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{ let formatted = format!($msg, $($args),*); let full = format!("{file}:{line}: {msg}", file = file!(), line = line!(), msg = &formatted); $ctx.emit_event($crate::EventType::Info(full)); }}; } macro_rules! warn { ($ctx:expr, $msg:expr) => { warn!($ctx, $msg,) }; ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{ let formatted = format!($msg, $($args),*); let full = format!("{file}:{line}: {msg}", file = file!(), line = line!(), msg = &formatted); $ctx.emit_event($crate::EventType::Warning(full)); }}; } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } enum RunningState { /// Ongoing process is allocated. Running { cancel_sender: Sender<()> }, /// Cancel signal has been sent, waiting for ongoing process to be freed. ShallStop { request: tools::Time }, /// There is no ongoing process, a new one can be allocated. Stopped, }
use std::collections::{BTreeMap, HashMap}; use std::ffi::OsString; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use pgp::SignedPublicKey; use ratelimit::Ratelimit; use tokio::sync::{Mutex, Notify, OnceCell, RwLock}; use crate::aheader::EncryptPreference; use crate::chat::{get_chat_cnt, ChatId, ProtectionStatus}; use crate::chatlist_events; 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}; 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_public_key, load_self_secret_key, DcKey as _}; use crate::login_param::LoginParam; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::param::{Param, Params}; use crate::peer_channels::Iroh; use crate::peerstate::Peerstate; use crate::push::PushSubscriber; use crate::quota::QuotaInfo; use crate::scheduler::{convert_folder_meaning, SchedulerState}; 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 anyhow::Context as _; use strum::IntoEnumIterator; use tempfile::tempdir; use super::*; use crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration}; use crate::chatlist::Chatlist; use crate::constants::Chattype; use crate::mimeparser::SystemMessage; use crate::receive_imf::receive_imf; use crate::test_utils::{get_chat_msg, TestContext}; use crate::tools::{create_outgoing_rfc724_mid, SystemTime};
projects__deltachat-core__rust__context__.rs__function__39.txt
pub unsafe extern "C" fn dc_stop_ongoing_process(mut context: *mut dc_context_t) { if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint { return; } if (*context).ongoing_running != 0 && (*context).shall_stop_ongoing == 0 as libc::c_int { dc_log_info( context, 0 as libc::c_int, b"Signaling the ongoing process to stop ASAP.\0" as *const u8 as *const libc::c_char, ); (*context).shall_stop_ongoing = 1 as libc::c_int; } else { dc_log_info( context, 0 as libc::c_int, b"No ongoing process to stop.\0" as *const u8 as *const libc::c_char, ); }; }
projects/deltachat-core/c/dc_msg.c
void dc_msg_set_location(dc_msg_t* msg, double latitude, double longitude) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC || (latitude==0.0 && longitude==0.0)) { return; } dc_param_set_float(msg->param, DC_PARAM_SET_LATITUDE, latitude); dc_param_set_float(msg->param, DC_PARAM_SET_LONGITUDE, longitude); }
projects/deltachat-core/rust/message.rs
pub fn set_location(&mut self, latitude: f64, longitude: f64) { if latitude == 0.0 && longitude == 0.0 { return; } self.param.set_float(Param::SetLatitude, latitude); self.param.set_float(Param::SetLongitude, longitude); }
pub fn set_float(&mut self, key: Param, value: f64) -> &mut Self { self.set(key, format!("{value}")); self } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__28.txt
pub unsafe extern "C" fn dc_msg_set_location( mut msg: *mut dc_msg_t, mut latitude: libc::c_double, mut longitude: libc::c_double, ) { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint || latitude == 0.0f64 && longitude == 0.0f64 { return; } dc_param_set_float((*msg).param, 'l' as i32, latitude); dc_param_set_float((*msg).param, 'n' as i32, longitude); }
projects/deltachat-core/c/dc_contact.c
void dc_block_contact(dc_context_t* context, uint32_t contact_id, int new_blocking) { int send_event = 0; dc_contact_t* contact = dc_contact_new(context); sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || contact_id<=DC_CONTACT_ID_LAST_SPECIAL) { goto cleanup; } if (dc_contact_load_from_db(contact, context->sql, contact_id) && contact->blocked!=new_blocking) { stmt = dc_sqlite3_prepare(context->sql, "UPDATE contacts SET blocked=? WHERE id=?;"); sqlite3_bind_int(stmt, 1, new_blocking); sqlite3_bind_int(stmt, 2, contact_id); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } sqlite3_finalize(stmt); stmt = NULL; /* also (un)block all chats with _only_ this contact - we do not delete them to allow a non-destructive blocking->unblocking. (Maybe, beside normal chats (type=100) we should also block group chats with only this user. However, I'm not sure about this point; it may be confusing if the user wants to add other people; this would result in recreating the same group...) */ stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats SET blocked=? WHERE type=? AND id IN (SELECT chat_id FROM chats_contacts WHERE contact_id=?);"); sqlite3_bind_int(stmt, 1, new_blocking); sqlite3_bind_int(stmt, 2, DC_CHAT_TYPE_SINGLE); sqlite3_bind_int(stmt, 3, contact_id); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } /* mark all messages from the blocked contact as being noticed (this is to remove the deaddrop popup) */ dc_marknoticed_contact(context, contact_id); send_event = 1; } if (send_event) { context->cb(context, DC_EVENT_CONTACTS_CHANGED, 0, 0); } cleanup: sqlite3_finalize(stmt); dc_contact_unref(contact); }
projects/deltachat-core/rust/contact.rs
pub async fn block(context: &Context, id: ContactId) -> Result<()> { set_blocked(context, Sync, id, true).await }
pub(crate) async fn set_blocked( context: &Context, sync: sync::Sync, contact_id: ContactId, new_blocking: bool, ) -> Result<()> { ensure!( !contact_id.is_special(), "Can't block special contact {}", contact_id ); let contact = Contact::get_by_id(context, contact_id).await?; if contact.blocked != new_blocking { context .sql .execute( "UPDATE contacts SET blocked=? WHERE id=?;", (i32::from(new_blocking), contact_id), ) .await?; // also (un)block all chats with _only_ this contact - we do not delete them to allow a // non-destructive blocking->unblocking. // (Maybe, beside normal chats (type=100) we should also block group chats with only this user. // However, I'm not sure about this point; it may be confusing if the user wants to add other people; // this would result in recreating the same group...) if context .sql .execute( r#" UPDATE chats SET blocked=? WHERE type=? AND id IN ( SELECT chat_id FROM chats_contacts WHERE contact_id=? ); "#, (new_blocking, Chattype::Single, contact_id), ) .await .is_ok() { Contact::mark_noticed(context, contact_id).await?; context.emit_event(EventType::ContactsChanged(Some(contact_id))); } // also unblock mailinglist // if the contact is a mailinglist address explicitly created to allow unblocking if !new_blocking && contact.origin == Origin::MailinglistAddress { if let Some((chat_id, _, _)) = chat::get_chat_id_by_grpid(context, &contact.addr).await? { chat_id.unblock_ex(context, Nosync).await?; } } if sync.into() { let action = match new_blocking { true => chat::SyncAction::Block, false => chat::SyncAction::Unblock, }; chat::sync( context, chat::SyncId::ContactAddr(contact.addr.clone()), action, ) .await .log_err(context) .ok(); } } chatlist_events::emit_chatlist_changed(context); Ok(()) } pub struct ContactId(u32); pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__18.txt
pub unsafe extern "C" fn dc_block_contact( mut context: *mut dc_context_t, mut contact_id: uint32_t, mut new_blocking: libc::c_int, ) { let mut current_block: u64; let mut send_event: libc::c_int = 0 as libc::c_int; let mut contact: *mut dc_contact_t = dc_contact_new(context); let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || contact_id <= 9 as libc::c_int as libc::c_uint) { if dc_contact_load_from_db(contact, (*context).sql, contact_id) != 0 && (*contact).blocked != new_blocking { stmt = dc_sqlite3_prepare( (*context).sql, b"UPDATE contacts SET blocked=? WHERE id=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, new_blocking); sqlite3_bind_int(stmt, 2 as libc::c_int, contact_id as libc::c_int); if sqlite3_step(stmt) != 101 as libc::c_int { current_block = 9158202047307229657; } else { sqlite3_finalize(stmt); stmt = 0 as *mut sqlite3_stmt; stmt = dc_sqlite3_prepare( (*context).sql, b"UPDATE chats SET blocked=? WHERE type=? AND id IN (SELECT chat_id FROM chats_contacts WHERE contact_id=?);\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, new_blocking); sqlite3_bind_int(stmt, 2 as libc::c_int, 100 as libc::c_int); sqlite3_bind_int(stmt, 3 as libc::c_int, contact_id as libc::c_int); if sqlite3_step(stmt) != 101 as libc::c_int { current_block = 9158202047307229657; } else { dc_marknoticed_contact(context, contact_id); send_event = 1 as libc::c_int; current_block = 13586036798005543211; } } } else { current_block = 13586036798005543211; } match current_block { 9158202047307229657 => {} _ => { if send_event != 0 { ((*context).cb) .expect( "non-null function pointer", )( context, 2030 as libc::c_int, 0 as libc::c_int as uintptr_t, 0 as libc::c_int as uintptr_t, ); } } } } sqlite3_finalize(stmt); dc_contact_unref(contact); }
projects/deltachat-core/c/dc_msg.c
int dc_msg_get_showpadlock(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->context==NULL) { return 0; } if (dc_param_get_int(msg->param, DC_PARAM_GUARANTEE_E2EE, 0)!=0) { return 1; } return 0; }
projects/deltachat-core/rust/message.rs
pub fn get_showpadlock(&self) -> bool { self.param.get_int(Param::GuaranteeE2ee).unwrap_or_default() != 0 }
pub fn get_int(&self, key: Param) -> Option<i32> { self.get(key).and_then(|s| s.parse().ok()) } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__46.txt
pub unsafe extern "C" fn dc_msg_get_showpadlock( mut msg: *const dc_msg_t, ) -> libc::c_int { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint || ((*msg).context).is_null() { return 0 as libc::c_int; } if dc_param_get_int((*msg).param, 'c' as i32, 0 as libc::c_int) != 0 as libc::c_int { return 1 as libc::c_int; } return 0 as libc::c_int; }
projects/deltachat-core/c/dc_location.c
int dc_set_location(dc_context_t* context, double latitude, double longitude, double accuracy) { sqlite3_stmt* stmt_chats = NULL; sqlite3_stmt* stmt_insert = NULL; int continue_streaming = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || (latitude==0.0 && longitude==0.0)) { continue_streaming = 1; goto cleanup; } stmt_chats = dc_sqlite3_prepare(context->sql, "SELECT id FROM chats WHERE locations_send_until>?;"); sqlite3_bind_int64(stmt_chats, 1, time(NULL)); while (sqlite3_step(stmt_chats)==SQLITE_ROW) { uint32_t chat_id = sqlite3_column_int(stmt_chats, 0); stmt_insert = dc_sqlite3_prepare(context->sql, "INSERT INTO locations " " (latitude, longitude, accuracy, timestamp, chat_id, from_id)" " VALUES (?,?,?,?,?,?);"); sqlite3_bind_double(stmt_insert, 1, latitude); sqlite3_bind_double(stmt_insert, 2, longitude); sqlite3_bind_double(stmt_insert, 3, accuracy); sqlite3_bind_int64 (stmt_insert, 4, time(NULL)); sqlite3_bind_int (stmt_insert, 5, chat_id); sqlite3_bind_int (stmt_insert, 6, DC_CONTACT_ID_SELF); sqlite3_step(stmt_insert); continue_streaming = 1; } if (continue_streaming) { context->cb(context, DC_EVENT_LOCATION_CHANGED, DC_CONTACT_ID_SELF, 0); schedule_MAYBE_SEND_LOCATIONS(context, 0); } cleanup: sqlite3_finalize(stmt_chats); sqlite3_finalize(stmt_insert); return continue_streaming; }
projects/deltachat-core/rust/location.rs
pub async fn set(context: &Context, latitude: f64, longitude: f64, accuracy: f64) -> Result<bool> { if latitude == 0.0 && longitude == 0.0 { return Ok(true); } let mut continue_streaming = false; let now = time(); let chats = context .sql .query_map( "SELECT id FROM chats WHERE locations_send_until>?;", (now,), |row| row.get::<_, i32>(0), |chats| { chats .collect::<std::result::Result<Vec<_>, _>>() .map_err(Into::into) }, ) .await?; let mut stored_location = false; for chat_id in chats { context.sql.execute( "INSERT INTO locations \ (latitude, longitude, accuracy, timestamp, chat_id, from_id) VALUES (?,?,?,?,?,?);", ( latitude, longitude, accuracy, now, chat_id, ContactId::SELF, )).await.context("Failed to store location")?; stored_location = true; info!(context, "Stored location for chat {chat_id}."); continue_streaming = true; } if continue_streaming { context.emit_location_changed(Some(ContactId::SELF)).await?; }; if stored_location { // Interrupt location loop so it may send a location-only message. context.scheduler.interrupt_location().await; } Ok(continue_streaming) }
pub(crate) fn time() -> i64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap_or_default() .as_secs() as i64 } pub async fn query_map<T, F, G, H>( &self, sql: &str, params: impl rusqlite::Params + Send, f: F, mut g: G, ) -> Result<H> where F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>, G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>, H: Send + 'static, { self.call(move |conn| { let mut stmt = conn.prepare(sql)?; let res = stmt.query_map(params, f)?; g(res) }) .await } pub async fn execute( &self, query: &str, params: impl rusqlite::Params + Send, ) -> Result<usize> { self.call_write(move |conn| { let res = conn.execute(query, params)?; Ok(res) }) .await } pub async fn emit_location_changed(&self, contact_id: Option<ContactId>) -> Result<()> { self.emit_event(EventType::LocationChanged(contact_id)); if let Some(msg_id) = self .get_config_parsed::<u32>(Config::WebxdcIntegration) .await? { self.emit_event(EventType::WebxdcStatusUpdate { msg_id: MsgId::new(msg_id), status_update_serial: Default::default(), }) } Ok(()) } pub(crate) async fn interrupt_location(&self) { let inner = self.inner.read().await; if let InnerSchedulerState::Started(ref scheduler) = *inner { scheduler.interrupt_location(); } } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub struct ContactId(u32); impl ContactId { /// Undefined contact. Used as a placeholder for trashed messages. pub const UNDEFINED: ContactId = ContactId::new(0); /// The owner of the account. /// /// The email-address is set by `set_config` using "addr". pub const SELF: ContactId = ContactId::new(1); /// ID of the contact for info messages. pub const INFO: ContactId = ContactId::new(2); /// ID of the contact for device messages. pub const DEVICE: ContactId = ContactId::new(5); pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9); /// Address to go with [`ContactId::DEVICE`]. /// /// This is used by APIs which need to return an email address for this contact. pub const DEVICE_ADDR: &'static str = "device@localhost"; }
use std::time::Duration; use anyhow::{ensure, Context as _, Result}; use async_channel::Receiver; use quick_xml::events::{BytesEnd, BytesStart, BytesText}; use tokio::time::timeout; use crate::chat::{self, ChatId}; use crate::constants::DC_CHAT_ID_TRASH; use crate::contact::ContactId; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::tools::{duration_to_str, time}; use crate::{chatlist_events, stock_str}; use super::*; use crate::config::Config; use crate::message::MessageState; use crate::receive_imf::receive_imf; use crate::test_utils::{TestContext, TestContextManager}; use crate::tools::SystemTime;
projects__deltachat-core__rust__location__.rs__function__9.txt
pub unsafe extern "C" fn dc_set_location( mut context: *mut dc_context_t, mut latitude: libc::c_double, mut longitude: libc::c_double, mut accuracy: libc::c_double, ) -> libc::c_int { let mut stmt_chats: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; let mut stmt_insert: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; let mut continue_streaming: libc::c_int = 0 as libc::c_int; if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || latitude == 0.0f64 && longitude == 0.0f64 { continue_streaming = 1 as libc::c_int; } else { stmt_chats = dc_sqlite3_prepare( (*context).sql, b"SELECT id FROM chats WHERE locations_send_until>?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int64( stmt_chats, 1 as libc::c_int, time(0 as *mut time_t) as sqlite3_int64, ); while sqlite3_step(stmt_chats) == 100 as libc::c_int { let mut chat_id: uint32_t = sqlite3_column_int(stmt_chats, 0 as libc::c_int) as uint32_t; stmt_insert = dc_sqlite3_prepare( (*context).sql, b"INSERT INTO locations (latitude, longitude, accuracy, timestamp, chat_id, from_id) VALUES (?,?,?,?,?,?);\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_double(stmt_insert, 1 as libc::c_int, latitude); sqlite3_bind_double(stmt_insert, 2 as libc::c_int, longitude); sqlite3_bind_double(stmt_insert, 3 as libc::c_int, accuracy); sqlite3_bind_int64( stmt_insert, 4 as libc::c_int, time(0 as *mut time_t) as sqlite3_int64, ); sqlite3_bind_int(stmt_insert, 5 as libc::c_int, chat_id as libc::c_int); sqlite3_bind_int(stmt_insert, 6 as libc::c_int, 1 as libc::c_int); sqlite3_step(stmt_insert); continue_streaming = 1 as libc::c_int; } if continue_streaming != 0 { ((*context).cb) .expect( "non-null function pointer", )( context, 2035 as libc::c_int, 1 as libc::c_int as uintptr_t, 0 as libc::c_int as uintptr_t, ); schedule_MAYBE_SEND_LOCATIONS(context, 0 as libc::c_int); } } sqlite3_finalize(stmt_chats); sqlite3_finalize(stmt_insert); return continue_streaming; }
projects/deltachat-core/c/dc_msg.c
void dc_msg_guess_msgtype_from_suffix(const char* pathNfilename, int* ret_msgtype, char** ret_mime) { char* suffix = NULL; int dummy_msgtype = 0; char* dummy_buf = NULL; if (pathNfilename==NULL) { goto cleanup; } if (ret_msgtype==NULL) { ret_msgtype = &dummy_msgtype; } if (ret_mime==NULL) { ret_mime = &dummy_buf; } *ret_msgtype = 0; *ret_mime = NULL; suffix = dc_get_filesuffix_lc(pathNfilename); if (suffix==NULL) { goto cleanup; } if (strcmp(suffix, "mp3")==0) { *ret_msgtype = DC_MSG_AUDIO; *ret_mime = dc_strdup("audio/mpeg"); } else if (strcmp(suffix, "aac")==0) { *ret_msgtype = DC_MSG_AUDIO; *ret_mime = dc_strdup("audio/aac"); } else if (strcmp(suffix, "mp4")==0) { *ret_msgtype = DC_MSG_VIDEO; *ret_mime = dc_strdup("video/mp4"); } else if (strcmp(suffix, "jpg")==0 || strcmp(suffix, "jpeg")==0) { *ret_msgtype = DC_MSG_IMAGE; *ret_mime = dc_strdup("image/jpeg"); } else if (strcmp(suffix, "png")==0) { *ret_msgtype = DC_MSG_IMAGE; *ret_mime = dc_strdup("image/png"); } else if (strcmp(suffix, "webp")==0) { *ret_msgtype = DC_MSG_IMAGE; *ret_mime = dc_strdup("image/webp"); } else if (strcmp(suffix, "gif")==0) { *ret_msgtype = DC_MSG_GIF; *ret_mime = dc_strdup("image/gif"); } else if (strcmp(suffix, "vcf")==0 || strcmp(suffix, "vcard")==0) { *ret_msgtype = DC_MSG_FILE; *ret_mime = dc_strdup("text/vcard"); } cleanup: free(suffix); free(dummy_buf); }
projects/deltachat-core/rust/message.rs
pub(crate) fn guess_msgtype_from_suffix(path: &Path) -> Option<(Viewtype, &str)> { let extension: &str = &path.extension()?.to_str()?.to_lowercase(); let info = match extension { // before using viewtype other than Viewtype::File, // make sure, all target UIs support that type in the context of the used viewer/player. // if in doubt, it is better to default to Viewtype::File that passes handing to an external app. // (cmp. <https://developer.android.com/guide/topics/media/media-formats>) "3gp" => (Viewtype::Video, "video/3gpp"), "aac" => (Viewtype::Audio, "audio/aac"), "avi" => (Viewtype::Video, "video/x-msvideo"), "avif" => (Viewtype::File, "image/avif"), // supported since Android 12 / iOS 16 "doc" => (Viewtype::File, "application/msword"), "docx" => ( Viewtype::File, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ), "epub" => (Viewtype::File, "application/epub+zip"), "flac" => (Viewtype::Audio, "audio/flac"), "gif" => (Viewtype::Gif, "image/gif"), "heic" => (Viewtype::File, "image/heic"), // supported since Android 10 / iOS 11 "heif" => (Viewtype::File, "image/heif"), // supported since Android 10 / iOS 11 "html" => (Viewtype::File, "text/html"), "htm" => (Viewtype::File, "text/html"), "ico" => (Viewtype::File, "image/vnd.microsoft.icon"), "jar" => (Viewtype::File, "application/java-archive"), "jpeg" => (Viewtype::Image, "image/jpeg"), "jpe" => (Viewtype::Image, "image/jpeg"), "jpg" => (Viewtype::Image, "image/jpeg"), "json" => (Viewtype::File, "application/json"), "mov" => (Viewtype::Video, "video/quicktime"), "m4a" => (Viewtype::Audio, "audio/m4a"), "mp3" => (Viewtype::Audio, "audio/mpeg"), "mp4" => (Viewtype::Video, "video/mp4"), "odp" => ( Viewtype::File, "application/vnd.oasis.opendocument.presentation", ), "ods" => ( Viewtype::File, "application/vnd.oasis.opendocument.spreadsheet", ), "odt" => (Viewtype::File, "application/vnd.oasis.opendocument.text"), "oga" => (Viewtype::Audio, "audio/ogg"), "ogg" => (Viewtype::Audio, "audio/ogg"), "ogv" => (Viewtype::File, "video/ogg"), "opus" => (Viewtype::File, "audio/ogg"), // supported since Android 10 "otf" => (Viewtype::File, "font/otf"), "pdf" => (Viewtype::File, "application/pdf"), "png" => (Viewtype::Image, "image/png"), "ppt" => (Viewtype::File, "application/vnd.ms-powerpoint"), "pptx" => ( Viewtype::File, "application/vnd.openxmlformats-officedocument.presentationml.presentation", ), "rar" => (Viewtype::File, "application/vnd.rar"), "rtf" => (Viewtype::File, "application/rtf"), "spx" => (Viewtype::File, "audio/ogg"), // Ogg Speex Profile "svg" => (Viewtype::File, "image/svg+xml"), "tgs" => (Viewtype::Sticker, "application/x-tgsticker"), "tiff" => (Viewtype::File, "image/tiff"), "tif" => (Viewtype::File, "image/tiff"), "ttf" => (Viewtype::File, "font/ttf"), "txt" => (Viewtype::File, "text/plain"), "vcard" => (Viewtype::Vcard, "text/vcard"), "vcf" => (Viewtype::Vcard, "text/vcard"), "wav" => (Viewtype::Audio, "audio/wav"), "weba" => (Viewtype::File, "audio/webm"), "webm" => (Viewtype::Video, "video/webm"), "webp" => (Viewtype::Image, "image/webp"), // iOS via SDWebImage, Android since 4.0 "wmv" => (Viewtype::Video, "video/x-ms-wmv"), "xdc" => (Viewtype::Webxdc, "application/webxdc+zip"), "xhtml" => (Viewtype::File, "application/xhtml+xml"), "xls" => (Viewtype::File, "application/vnd.ms-excel"), "xlsx" => ( Viewtype::File, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ), "xml" => (Viewtype::File, "application/xml"), "zip" => (Viewtype::File, "application/zip"), _ => { return None; } }; Some(info) }
pub enum Viewtype { /// Unknown message type. #[default] Unknown = 0, /// Text message. /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text(). Text = 10, /// Image message. /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to /// `Gif` when sending the message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension(). Image = 20, /// Animated GIF message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension() /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height(). Gif = 21, /// Message containing a sticker, similar to image. /// If possible, the ui should display the image without borders in a transparent way. /// A click on a sticker will offer to install the sticker set in some future. Sticker = 23, /// Message containing an Audio file. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration(). Audio = 40, /// A voice message that was directly recorded by the user. /// For all other audio messages, the type #DC_MSG_AUDIO should be used. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration() Voice = 41, /// Video messages. /// File, width, height and durarion /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration() /// and retrieved via /// dc_msg_get_file(), dc_msg_get_width(), /// dc_msg_get_height(), dc_msg_get_duration(). Video = 50, /// Message containing any file, eg. a PDF. /// The file is set via dc_msg_set_file() /// and retrieved via dc_msg_get_file(). File = 60, /// Message is an invitation to a videochat. VideochatInvitation = 70, /// Message is an webxdc instance. Webxdc = 80, /// Message containing shared contacts represented as a vCard (virtual contact file) /// with email addresses and possibly other fields. /// Use `parse_vcard()` to retrieve them. Vcard = 90, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__87.txt
pub unsafe extern "C" fn dc_msg_guess_msgtype_from_suffix( mut pathNfilename: *const libc::c_char, mut ret_msgtype: *mut libc::c_int, mut ret_mime: *mut *mut libc::c_char, ) { let mut suffix: *mut libc::c_char = 0 as *mut libc::c_char; let mut dummy_msgtype: libc::c_int = 0 as libc::c_int; let mut dummy_buf: *mut libc::c_char = 0 as *mut libc::c_char; if !pathNfilename.is_null() { if ret_msgtype.is_null() { ret_msgtype = &mut dummy_msgtype; } if ret_mime.is_null() { ret_mime = &mut dummy_buf; } *ret_msgtype = 0 as libc::c_int; *ret_mime = 0 as *mut libc::c_char; suffix = dc_get_filesuffix_lc(pathNfilename); if !suffix.is_null() { if strcmp(suffix, b"mp3\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { *ret_msgtype = 40 as libc::c_int; *ret_mime = dc_strdup( b"audio/mpeg\0" as *const u8 as *const libc::c_char, ); } else if strcmp(suffix, b"aac\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { *ret_msgtype = 40 as libc::c_int; *ret_mime = dc_strdup( b"audio/aac\0" as *const u8 as *const libc::c_char, ); } else if strcmp(suffix, b"mp4\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { *ret_msgtype = 50 as libc::c_int; *ret_mime = dc_strdup( b"video/mp4\0" as *const u8 as *const libc::c_char, ); } else if strcmp(suffix, b"jpg\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int || strcmp(suffix, b"jpeg\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { *ret_msgtype = 20 as libc::c_int; *ret_mime = dc_strdup( b"image/jpeg\0" as *const u8 as *const libc::c_char, ); } else if strcmp(suffix, b"png\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { *ret_msgtype = 20 as libc::c_int; *ret_mime = dc_strdup( b"image/png\0" as *const u8 as *const libc::c_char, ); } else if strcmp(suffix, b"webp\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { *ret_msgtype = 20 as libc::c_int; *ret_mime = dc_strdup( b"image/webp\0" as *const u8 as *const libc::c_char, ); } else if strcmp(suffix, b"gif\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { *ret_msgtype = 21 as libc::c_int; *ret_mime = dc_strdup( b"image/gif\0" as *const u8 as *const libc::c_char, ); } else if strcmp(suffix, b"vcf\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int || strcmp(suffix, b"vcard\0" as *const u8 as *const libc::c_char) == 0 as libc::c_int { *ret_msgtype = 60 as libc::c_int; *ret_mime = dc_strdup( b"text/vcard\0" as *const u8 as *const libc::c_char, ); } } } free(suffix as *mut libc::c_void); free(dummy_buf as *mut libc::c_void); }
projects/deltachat-core/c/dc_msg.c
int dc_msg_is_forwarded(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return dc_param_get_int(msg->param, DC_PARAM_FORWARDED, 0)? 1 : 0; }
projects/deltachat-core/rust/message.rs
pub fn is_forwarded(&self) -> bool { 0 != self.param.get_int(Param::Forwarded).unwrap_or_default() }
pub fn get_int(&self, key: Param) -> Option<i32> { self.get(key).and_then(|s| s.parse().ok()) } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__55.txt
pub unsafe extern "C" fn dc_msg_is_forwarded(mut msg: *const dc_msg_t) -> libc::c_int { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return 0 as libc::c_int; } return if dc_param_get_int((*msg).param, 'a' as i32, 0 as libc::c_int) != 0 { 1 as libc::c_int } else { 0 as libc::c_int }; }
projects/deltachat-core/c/dc_sqlite3.c
static void maybe_add_file(dc_hash_t* files_in_use, const char* file) { #define PREFIX "$BLOBDIR/" #define PREFIX_LEN 9 if (strncmp(file, PREFIX, PREFIX_LEN)!=0) { return; } const char* raw_name = &file[PREFIX_LEN]; dc_hash_insert_str(files_in_use, raw_name, (void*)1); }
projects/deltachat-core/rust/sql.rs
fn maybe_add_file(files_in_use: &mut HashSet<String>, file: &str) { if let Some(file) = file.strip_prefix("$BLOBDIR/") { files_in_use.insert(file.to_string()); } }
use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use anyhow::{bail, Context as _, Result}; use rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row}; use tokio::sync::{Mutex, MutexGuard, RwLock}; use crate::blob::BlobObject; use crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon}; use crate::config::Config; use crate::constants::DC_CHAT_ID_TRASH; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::ephemeral::start_ephemeral_timers; use crate::imex::BLOBS_BACKUP_NAME; use crate::location::delete_orphaned_poi_locations; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::stock_str; use crate::tools::{delete_file, time, SystemTime}; use pool::Pool; use super::*; use crate::{test_utils::TestContext, EventType}; use tempfile::tempdir; use tempfile::tempdir; use tempfile::tempdir;
projects__deltachat-core__rust__sql__.rs__function__42.txt
unsafe extern "C" fn maybe_add_file( mut files_in_use: *mut dc_hash_t, mut file: *const libc::c_char, ) { if strncmp( file, b"$BLOBDIR/\0" as *const u8 as *const libc::c_char, 9 as libc::c_int as libc::c_ulong, ) != 0 as libc::c_int { return; } let mut raw_name: *const libc::c_char = &*file.offset(9 as libc::c_int as isize) as *const libc::c_char; dc_hash_insert( files_in_use, raw_name as *const libc::c_void, strlen(raw_name) as libc::c_int, 1 as libc::c_int as *mut libc::c_void, ); }
projects/deltachat-core/c/dc_tools.c
time_t dc_smeared_time(dc_context_t* context) { /* function returns a corrected time(NULL) */ time_t now = time(NULL); SMEAR_LOCK if (context->last_smeared_timestamp >= now) { now = context->last_smeared_timestamp+1; } SMEAR_UNLOCK return now; }
projects/deltachat-core/rust/tools.rs
pub(crate) fn smeared_time(context: &Context) -> i64 { let now = time(); let ts = context.smeared_timestamp.current(); std::cmp::max(ts, now) }
pub(crate) fn time() -> i64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap_or_default() .as_secs() as i64 } pub fn current(&self) -> i64 { self.smeared_timestamp.load(Ordering::Relaxed) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, }
use std::borrow::Cow; use std::io::{Cursor, Write}; use std::mem; use std::path::{Path, PathBuf}; use std::str::from_utf8; use std::time::Duration; use std::time::SystemTime as Time; use std::time::SystemTime; use anyhow::{bail, Context as _, Result}; use base64::Engine as _; use chrono::{Local, NaiveDateTime, NaiveTime, TimeZone}; use deltachat_contact_tools::{strip_rtlo_characters, EmailAddress}; use deltachat_time::SystemTimeTools as SystemTime; use futures::{StreamExt, TryStreamExt}; use mailparse::dateparse; use mailparse::headers::Headers; use mailparse::MailHeaderMap; use rand::{thread_rng, Rng}; use tokio::{fs, io}; use url::Url; use crate::chat::{add_device_msg, add_device_msg_with_importance}; use crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS}; use crate::context::Context; use crate::events::EventType; use crate::message::{Message, Viewtype}; use crate::stock_str; use chrono::NaiveDate; use proptest::prelude::*; use super::*; use crate::chatlist::Chatlist; use crate::{chat, test_utils}; use crate::{receive_imf::receive_imf, test_utils::TestContext}; use super::*;
projects__deltachat-core__rust__tools__.rs__function__6.txt
pub unsafe extern "C" fn dc_smeared_time(mut context: *mut dc_context_t) -> time_t { let mut now: time_t = time(0 as *mut time_t); pthread_mutex_lock(&mut (*context).smear_critical); if (*context).last_smeared_timestamp >= now { now = (*context).last_smeared_timestamp + 1 as libc::c_int as libc::c_long; } pthread_mutex_unlock(&mut (*context).smear_critical); return now; }
projects/deltachat-core/c/dc_oauth2.c
char* dc_get_oauth2_access_token(dc_context_t* context, const char* addr, const char* code, int flags) { oauth2_t* oauth2 = NULL; char* access_token = NULL; char* refresh_token = NULL; char* refresh_token_for = NULL; char* redirect_uri = NULL; int update_redirect_uri_on_success = 0; char* token_url = NULL; time_t expires_in = 0; char* error = NULL; char* error_description = NULL; char* json = NULL; jsmn_parser parser; jsmntok_t tok[128]; // we do not expect nor read more tokens int tok_cnt = 0; int locked = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || code==NULL || code[0]==0) { dc_log_warning(context, 0, "Internal OAuth2 error"); goto cleanup; } if ((oauth2=get_info(addr))==NULL) { dc_log_warning(context, 0, "Internal OAuth2 error: 2"); goto cleanup; } pthread_mutex_lock(&context->oauth2_critical); locked = 1; // read generated token if ( !(flags&DC_REGENERATE) && !is_expired(context) ) { access_token = dc_sqlite3_get_config(context->sql, "oauth2_access_token", NULL); if (access_token!=NULL) { goto cleanup; // success } } // generate new token: build & call auth url refresh_token = dc_sqlite3_get_config(context->sql, "oauth2_refresh_token", NULL); refresh_token_for = dc_sqlite3_get_config(context->sql, "oauth2_refresh_token_for", "unset"); if (refresh_token==NULL || strcmp(refresh_token_for, code)!=0) { dc_log_info(context, 0, "Generate OAuth2 refresh_token and access_token..."); redirect_uri = dc_sqlite3_get_config(context->sql, "oauth2_pending_redirect_uri", "unset"); update_redirect_uri_on_success = 1; token_url = dc_strdup(oauth2->init_token); } else { dc_log_info(context, 0, "Regenerate OAuth2 access_token by refresh_token..."); redirect_uri = dc_sqlite3_get_config(context->sql, "oauth2_redirect_uri", "unset"); token_url = dc_strdup(oauth2->refresh_token); } replace_in_uri(&token_url, "$CLIENT_ID", oauth2->client_id); replace_in_uri(&token_url, "$REDIRECT_URI", redirect_uri); replace_in_uri(&token_url, "$CODE", code); replace_in_uri(&token_url, "$REFRESH_TOKEN", refresh_token); json = (char*)context->cb(context, DC_EVENT_HTTP_POST, (uintptr_t)token_url, 0); if (json==NULL) { dc_log_warning(context, 0, "Error calling OAuth2 at %s", token_url); goto cleanup; } // generate new token: parse returned json jsmn_init(&parser); tok_cnt = jsmn_parse(&parser, json, strlen(json), tok, sizeof(tok)/sizeof(tok[0])); if (tok_cnt<2 || tok[0].type!=JSMN_OBJECT) { dc_log_warning(context, 0, "Failed to parse OAuth2 json from %s", token_url); goto cleanup; } for (int i = 1; i < tok_cnt; i++) { if (access_token==NULL && jsoneq(json, &tok[i], "access_token")==0) { access_token = jsondup(json, &tok[i+1]); } else if (refresh_token==NULL && jsoneq(json, &tok[i], "refresh_token")==0) { refresh_token = jsondup(json, &tok[i+1]); } else if (jsoneq(json, &tok[i], "expires_in")==0) { char* expires_in_str = jsondup(json, &tok[i+1]); if (expires_in_str) { time_t val = atol(expires_in_str); // val should be reasonable, maybe between 20 seconds and 5 years. // if out of range, we re-create when the token gets invalid, // which may create some additional load and requests wrt threads. if (val>20 && val<(60*60*24*365*5)) { expires_in = val; } free(expires_in_str); } } else if (error==NULL && jsoneq(json, &tok[i], "error")==0) { error = jsondup(json, &tok[i+1]); } else if (error_description==NULL && jsoneq(json, &tok[i], "error_description")==0) { error_description = jsondup(json, &tok[i+1]); } } if (error || error_description) { dc_log_warning(context, 0, "OAuth error: %s: %s", error? error : "unknown", error_description? error_description : "no details"); // continue, errors do not imply everything went wrong } // update refresh_token if given, typically on the first round, but we update it later as well. if (refresh_token && refresh_token[0]) { dc_sqlite3_set_config(context->sql, "oauth2_refresh_token", refresh_token); dc_sqlite3_set_config(context->sql, "oauth2_refresh_token_for", code); } // after that, save the access token. // if it's unset, we may get it in the next round as we have the refresh_token now. if (access_token==NULL || access_token[0]==0) { dc_log_warning(context, 0, "Failed to find OAuth2 access token"); goto cleanup; } dc_sqlite3_set_config(context->sql, "oauth2_access_token", access_token); dc_sqlite3_set_config_int64(context->sql, "oauth2_timestamp_expires", expires_in? time(NULL)+expires_in-5/*refresh a bet before*/ : 0); if (update_redirect_uri_on_success) { dc_sqlite3_set_config(context->sql, "oauth2_redirect_uri", redirect_uri); } cleanup: if (locked) { pthread_mutex_unlock(&context->oauth2_critical); } free(refresh_token); free(refresh_token_for); free(redirect_uri); free(token_url); free(json); free(error); free(error_description); free(oauth2); return access_token? access_token : dc_strdup(NULL); }
projects/deltachat-core/rust/oauth2.rs
pub(crate) async fn get_oauth2_access_token( context: &Context, addr: &str, code: &str, regenerate: bool, ) -> Result<Option<String>> { let socks5_enabled = context.get_config_bool(Config::Socks5Enabled).await?; if let Some(oauth2) = Oauth2::from_address(context, addr, socks5_enabled).await { let lock = context.oauth2_mutex.lock().await; // read generated token if !regenerate && !is_expired(context).await? { let access_token = context.sql.get_raw_config("oauth2_access_token").await?; if access_token.is_some() { // success return Ok(access_token); } } // generate new token: build & call auth url let refresh_token = context.sql.get_raw_config("oauth2_refresh_token").await?; let refresh_token_for = context .sql .get_raw_config("oauth2_refresh_token_for") .await? .unwrap_or_else(|| "unset".into()); let (redirect_uri, token_url, update_redirect_uri_on_success) = if refresh_token.is_none() || refresh_token_for != code { info!(context, "Generate OAuth2 refresh_token and access_token...",); ( context .sql .get_raw_config("oauth2_pending_redirect_uri") .await? .unwrap_or_else(|| "unset".into()), oauth2.init_token, true, ) } else { info!( context, "Regenerate OAuth2 access_token by refresh_token...", ); ( context .sql .get_raw_config("oauth2_redirect_uri") .await? .unwrap_or_else(|| "unset".into()), oauth2.refresh_token, false, ) }; // to allow easier specification of different configurations, // token_url is in GET-method-format, sth. as <https://domain?param1=val1&param2=val2> - // convert this to POST-format ... let mut parts = token_url.splitn(2, '?'); let post_url = parts.next().unwrap_or_default(); let post_args = parts.next().unwrap_or_default(); let mut post_param = HashMap::new(); for key_value_pair in post_args.split('&') { let mut parts = key_value_pair.splitn(2, '='); let key = parts.next().unwrap_or_default(); let mut value = parts.next().unwrap_or_default(); if value == "$CLIENT_ID" { value = oauth2.client_id; } else if value == "$REDIRECT_URI" { value = &redirect_uri; } else if value == "$CODE" { value = code; } else if value == "$REFRESH_TOKEN" { if let Some(refresh_token) = refresh_token.as_ref() { value = refresh_token; } } post_param.insert(key, value); } // ... and POST let socks5_config = Socks5Config::from_database(&context.sql).await?; let client = crate::net::http::get_client(socks5_config)?; let response: Response = match client.post(post_url).form(&post_param).send().await { Ok(resp) => match resp.json().await { Ok(response) => response, Err(err) => { warn!( context, "Failed to parse OAuth2 JSON response from {}: error: {}", token_url, err ); return Ok(None); } }, Err(err) => { warn!(context, "Error calling OAuth2 at {}: {:?}", token_url, err); return Ok(None); } }; // update refresh_token if given, typically on the first round, but we update it later as well. if let Some(ref token) = response.refresh_token { context .sql .set_raw_config("oauth2_refresh_token", Some(token)) .await?; context .sql .set_raw_config("oauth2_refresh_token_for", Some(code)) .await?; } // after that, save the access token. // if it's unset, we may get it in the next round as we have the refresh_token now. if let Some(ref token) = response.access_token { context .sql .set_raw_config("oauth2_access_token", Some(token)) .await?; let expires_in = response .expires_in // refresh a bit before .map(|t| time() + t as i64 - 5) .unwrap_or_else(|| 0); context .sql .set_raw_config_int64("oauth2_timestamp_expires", expires_in) .await?; if update_redirect_uri_on_success { context .sql .set_raw_config("oauth2_redirect_uri", Some(redirect_uri.as_ref())) .await?; } } else { warn!(context, "Failed to find OAuth2 access token"); } drop(lock); Ok(response.access_token) } else { warn!(context, "Internal OAuth2 error: 2"); Ok(None) } }
pub async fn get_config_bool(&self, key: Config) -> Result<bool> { Ok(self.get_config_bool_opt(key).await?.unwrap_or_default()) } pub(crate) fn time() -> i64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap_or_default() .as_secs() as i64 } pub async fn get_raw_config(&self, key: &str) -> Result<Option<String>> { let lock = self.config_cache.read().await; let cached = lock.get(key).cloned(); drop(lock); if let Some(c) = cached { return Ok(c); } let mut lock = self.config_cache.write().await; let value = self .query_get_value("SELECT value FROM config WHERE keyname=?", (key,)) .await .context(format!("failed to fetch raw config: {key}"))?; lock.insert(key.to_string(), value.clone()); drop(lock); Ok(value) } pub(crate) fn get_client(socks5_config: Option<Socks5Config>) -> Result<reqwest::Client> { let builder = reqwest::ClientBuilder::new() .timeout(HTTP_TIMEOUT) .add_root_certificate(LETSENCRYPT_ROOT.clone()); let builder = if let Some(socks5_config) = socks5_config { let proxy = reqwest::Proxy::all(socks5_config.to_url())?; builder.proxy(proxy) } else { // Disable usage of "system" proxy configured via environment variables. // It is enabled by default in `reqwest`, see // <https://docs.rs/reqwest/0.11.14/reqwest/struct.ClientBuilder.html#method.no_proxy> // for documentation. builder.no_proxy() }; Ok(builder.build()?) } pub async fn from_database(sql: &Sql) -> Result<Option<Self>> { let enabled = sql.get_raw_config_bool("socks5_enabled").await?; if enabled { let host = sql.get_raw_config("socks5_host").await?.unwrap_or_default(); let port: u16 = sql .get_raw_config_int("socks5_port") .await? .unwrap_or_default() as u16; let user = sql.get_raw_config("socks5_user").await?.unwrap_or_default(); let password = sql .get_raw_config("socks5_password") .await? .unwrap_or_default(); let socks5_config = Self { host, port, user_password: if !user.is_empty() { Some((user, password)) } else { None }, }; Ok(Some(socks5_config)) } else { Ok(None) } } async fn is_expired(context: &Context) -> Result<bool> { let expire_timestamp = context .sql .get_raw_config_int64("oauth2_timestamp_expires") .await? .unwrap_or_default(); if expire_timestamp <= 0 { return Ok(false); } if expire_timestamp > time() { return Ok(false); } Ok(true) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } struct Response { // Should always be there according to: <https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/> // but previous code handled its abscense. access_token: Option<String>, token_type: String, /// Duration of time the token is granted for, in seconds expires_in: Option<u64>, refresh_token: Option<String>, scope: Option<String>, } async fn from_address(context: &Context, addr: &str, skip_mx: bool) -> Option<Self> { let addr_normalized = normalize_addr(addr); if let Some(domain) = addr_normalized .find('@') .map(|index| addr_normalized.split_at(index + 1).1) { if let Some(oauth2_authorizer) = provider::get_provider_info(context, domain, skip_mx) .await .and_then(|provider| provider.oauth2_authorizer.as_ref()) { return Some(match oauth2_authorizer { Oauth2Authorizer::Gmail => OAUTH2_GMAIL, Oauth2Authorizer::Yandex => OAUTH2_YANDEX, }); } } None } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub enum Config { /// Email address, used in the `From:` field. Addr, /// IMAP server hostname. MailServer, /// IMAP server username. MailUser, /// IMAP server password. MailPw, /// IMAP server port. MailPort, /// IMAP server security (e.g. TLS, STARTTLS). MailSecurity, /// How to check IMAP server TLS certificates. ImapCertificateChecks, /// SMTP server hostname. SendServer, /// SMTP server username. SendUser, /// SMTP server password. SendPw, /// SMTP server port. SendPort, /// SMTP server security (e.g. TLS, STARTTLS). SendSecurity, /// How to check SMTP server TLS certificates. SmtpCertificateChecks, /// Whether to use OAuth 2. /// /// Historically contained other bitflags, which are now deprecated. /// Should not be extended in the future, create new config keys instead. ServerFlags, /// True if SOCKS5 is enabled. /// /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration. Socks5Enabled, /// SOCKS5 proxy server hostname or address. Socks5Host, /// SOCKS5 proxy server port. Socks5Port, /// SOCKS5 proxy server username. Socks5User, /// SOCKS5 proxy server password. Socks5Password, /// Own name to use in the `From:` field when sending messages. Displayname, /// Own status to display, sent in message footer. Selfstatus, /// Own avatar filename. Selfavatar, /// Send BCC copy to self. /// /// Should be enabled for multidevice setups. #[strum(props(default = "1"))] BccSelf, /// True if encryption is preferred according to Autocrypt standard. #[strum(props(default = "1"))] E2eeEnabled, /// True if Message Delivery Notifications (read receipts) should /// be sent and requested. #[strum(props(default = "1"))] MdnsEnabled, /// True if "Sent" folder should be watched for changes. #[strum(props(default = "0"))] SentboxWatch, /// True if chat messages should be moved to a separate folder. #[strum(props(default = "1"))] MvboxMove, /// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only. /// /// This will not entirely disable other folders, e.g. the spam folder will also still /// be watched for new messages. #[strum(props(default = "0"))] OnlyFetchMvbox, /// Whether to show classic emails or only chat messages. #[strum(props(default = "2"))] // also change ShowEmails.default() on changes ShowEmails, /// Quality of the media files to send. #[strum(props(default = "0"))] // also change MediaQuality.default() on changes MediaQuality, /// If set to "1", on the first time `start_io()` is called after configuring, /// the newest existing messages are fetched. /// Existing recipients are added to the contact database regardless of this setting. #[strum(props(default = "0"))] FetchExistingMsgs, /// If set to "1", then existing messages are considered to be already fetched. /// This flag is reset after successful configuration. #[strum(props(default = "1"))] FetchedExistingMsgs, /// Type of the OpenPGP key to generate. #[strum(props(default = "0"))] KeyGenType, /// Timer in seconds after which the message is deleted from the /// server. /// /// Equals to 0 by default, which means the message is never /// deleted. /// /// Value 1 is treated as "delete at once": messages are deleted /// immediately, without moving to DeltaChat folder. #[strum(props(default = "0"))] DeleteServerAfter, /// Timer in seconds after which the message is deleted from the /// device. /// /// Equals to 0 by default, which means the message is never /// deleted. #[strum(props(default = "0"))] DeleteDeviceAfter, /// Move messages to the Trash folder instead of marking them "\Deleted". Overrides /// `ProviderOptions::delete_to_trash`. DeleteToTrash, /// Save raw MIME messages with headers in the database if true. SaveMimeHeaders, /// The primary email address. Also see `SecondaryAddrs`. ConfiguredAddr, /// Configured IMAP server hostname. ConfiguredMailServer, /// Configured IMAP server username. ConfiguredMailUser, /// Configured IMAP server password. ConfiguredMailPw, /// Configured IMAP server port. ConfiguredMailPort, /// Configured IMAP server security (e.g. TLS, STARTTLS). ConfiguredMailSecurity, /// How to check IMAP server TLS certificates. ConfiguredImapCertificateChecks, /// Configured SMTP server hostname. ConfiguredSendServer, /// Configured SMTP server username. ConfiguredSendUser, /// Configured SMTP server password. ConfiguredSendPw, /// Configured SMTP server port. ConfiguredSendPort, /// How to check SMTP server TLS certificates. ConfiguredSmtpCertificateChecks, /// Whether OAuth 2 is used with configured provider. ConfiguredServerFlags, /// Configured SMTP server security (e.g. TLS, STARTTLS). ConfiguredSendSecurity, /// Configured folder for incoming messages. ConfiguredInboxFolder, /// Configured folder for chat messages. ConfiguredMvboxFolder, /// Configured "Sent" folder. ConfiguredSentboxFolder, /// Configured "Trash" folder. ConfiguredTrashFolder, /// Unix timestamp of the last successful configuration. ConfiguredTimestamp, /// ID of the configured provider from the provider database. ConfiguredProvider, /// True if account is configured. Configured, /// True if account is a chatmail account. IsChatmail, /// All secondary self addresses separated by spaces /// (`[email protected] [email protected] [email protected]`) SecondaryAddrs, /// Read-only core version string. #[strum(serialize = "sys.version")] SysVersion, /// Maximal recommended attachment size in bytes. #[strum(serialize = "sys.msgsize_max_recommended")] SysMsgsizeMaxRecommended, /// Space separated list of all config keys available. #[strum(serialize = "sys.config_keys")] SysConfigKeys, /// True if it is a bot account. Bot, /// True when to skip initial start messages in groups. #[strum(props(default = "0"))] SkipStartMessages, /// Whether we send a warning if the password is wrong (set to false when we send a warning /// because we do not want to send a second warning) #[strum(props(default = "0"))] NotifyAboutWrongPw, /// If a warning about exceeding quota was shown recently, /// this is the percentage of quota at the time the warning was given. /// Unset, when quota falls below minimal warning threshold again. QuotaExceeding, /// address to webrtc instance to use for videochats WebrtcInstance, /// Timestamp of the last time housekeeping was run LastHousekeeping, /// Timestamp of the last `CantDecryptOutgoingMsgs` notification. LastCantDecryptOutgoingMsgs, /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely. #[strum(props(default = "60"))] ScanAllFoldersDebounceSecs, /// Whether to avoid using IMAP IDLE even if the server supports it. /// /// This is a developer option for testing "fake idle". #[strum(props(default = "0"))] DisableIdle, /// Defines the max. size (in bytes) of messages downloaded automatically. /// 0 = no limit. #[strum(props(default = "0"))] DownloadLimit, /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set. #[strum(props(default = "1"))] SyncMsgs, /// Space-separated list of all the authserv-ids which we believe /// may be the one of our email server. /// /// See `crate::authres::update_authservid_candidates`. AuthservIdCandidates, /// Make all outgoing messages with Autocrypt header "multipart/signed". SignUnencrypted, /// Let the core save all events to the database. /// This value is used internally to remember the MsgId of the logging xdc #[strum(props(default = "0"))] DebugLogging, /// Last message processed by the bot. LastMsgId, /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by /// default. /// /// This is not supposed to be changed by UIs and only used for testing. #[strum(props(default = "172800"))] GossipPeriod, /// Feature flag for verified 1:1 chats; the UI should set it /// to 1 if it supports verified 1:1 chats. /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified, /// and when the key changes, an info message is posted into the chat. /// 0=Nothing else happens when the key changes. /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true /// until `chat_id.accept()` is called. #[strum(props(default = "0"))] VerifiedOneOnOneChats, /// Row ID of the key in the `keypairs` table /// 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 /// without storing the email address SelfReportingId, /// MsgId of webxdc map integration. WebxdcIntegration, /// Iroh secret key. IrohSecretKey, }
use std::collections::HashMap; use anyhow::Result; use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC}; use serde::Deserialize; use crate::config::Config; use crate::context::Context; use crate::provider; use crate::provider::Oauth2Authorizer; use crate::socks::Socks5Config; use crate::tools::time; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__oauth2__.rs__function__2.txt
pub unsafe extern "C" fn dc_get_oauth2_access_token( mut context: *mut dc_context_t, mut addr: *const libc::c_char, mut code: *const libc::c_char, mut flags: libc::c_int, ) -> *mut libc::c_char { let mut current_block: u64; let mut oauth2: *mut oauth2_t = 0 as *mut oauth2_t; let mut access_token: *mut libc::c_char = 0 as *mut libc::c_char; let mut refresh_token: *mut libc::c_char = 0 as *mut libc::c_char; let mut refresh_token_for: *mut libc::c_char = 0 as *mut libc::c_char; let mut redirect_uri: *mut libc::c_char = 0 as *mut libc::c_char; let mut update_redirect_uri_on_success: libc::c_int = 0 as libc::c_int; let mut token_url: *mut libc::c_char = 0 as *mut libc::c_char; let mut expires_in: time_t = 0 as libc::c_int as time_t; let mut error: *mut libc::c_char = 0 as *mut libc::c_char; let mut error_description: *mut libc::c_char = 0 as *mut libc::c_char; let mut json: *mut libc::c_char = 0 as *mut libc::c_char; let mut parser: jsmn_parser = jsmn_parser { pos: 0, toknext: 0, toksuper: 0, }; let mut tok: [jsmntok_t; 128] = [jsmntok_t { type_0: JSMN_UNDEFINED, start: 0, end: 0, size: 0, }; 128]; let mut tok_cnt: libc::c_int = 0 as libc::c_int; let mut locked: libc::c_int = 0 as libc::c_int; if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || code.is_null() || *code.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int { dc_log_warning( context, 0 as libc::c_int, b"Internal OAuth2 error\0" as *const u8 as *const libc::c_char, ); } else { oauth2 = get_info(addr); if oauth2.is_null() { dc_log_warning( context, 0 as libc::c_int, b"Internal OAuth2 error: 2\0" as *const u8 as *const libc::c_char, ); } else { pthread_mutex_lock(&mut (*context).oauth2_critical); locked = 1 as libc::c_int; if flags & 0x1 as libc::c_int == 0 && is_expired(context) == 0 { access_token = dc_sqlite3_get_config( (*context).sql, b"oauth2_access_token\0" as *const u8 as *const libc::c_char, 0 as *const libc::c_char, ); if !access_token.is_null() { current_block = 7489901148814943651; } else { current_block = 12349973810996921269; } } else { current_block = 12349973810996921269; } match current_block { 7489901148814943651 => {} _ => { refresh_token = dc_sqlite3_get_config( (*context).sql, b"oauth2_refresh_token\0" as *const u8 as *const libc::c_char, 0 as *const libc::c_char, ); refresh_token_for = dc_sqlite3_get_config( (*context).sql, b"oauth2_refresh_token_for\0" as *const u8 as *const libc::c_char, b"unset\0" as *const u8 as *const libc::c_char, ); if refresh_token.is_null() || strcmp(refresh_token_for, code) != 0 as libc::c_int { dc_log_info( context, 0 as libc::c_int, b"Generate OAuth2 refresh_token and access_token...\0" as *const u8 as *const libc::c_char, ); redirect_uri = dc_sqlite3_get_config( (*context).sql, b"oauth2_pending_redirect_uri\0" as *const u8 as *const libc::c_char, b"unset\0" as *const u8 as *const libc::c_char, ); update_redirect_uri_on_success = 1 as libc::c_int; token_url = dc_strdup((*oauth2).init_token); } else { dc_log_info( context, 0 as libc::c_int, b"Regenerate OAuth2 access_token by refresh_token...\0" as *const u8 as *const libc::c_char, ); redirect_uri = dc_sqlite3_get_config( (*context).sql, b"oauth2_redirect_uri\0" as *const u8 as *const libc::c_char, b"unset\0" as *const u8 as *const libc::c_char, ); token_url = dc_strdup((*oauth2).refresh_token); } replace_in_uri( &mut token_url, b"$CLIENT_ID\0" as *const u8 as *const libc::c_char, (*oauth2).client_id, ); replace_in_uri( &mut token_url, b"$REDIRECT_URI\0" as *const u8 as *const libc::c_char, redirect_uri, ); replace_in_uri( &mut token_url, b"$CODE\0" as *const u8 as *const libc::c_char, code, ); replace_in_uri( &mut token_url, b"$REFRESH_TOKEN\0" as *const u8 as *const libc::c_char, refresh_token, ); json = ((*context).cb) .expect( "non-null function pointer", )( context, 2110 as libc::c_int, token_url as uintptr_t, 0 as libc::c_int as uintptr_t, ) as *mut libc::c_char; if json.is_null() { dc_log_warning( context, 0 as libc::c_int, b"Error calling OAuth2 at %s\0" as *const u8 as *const libc::c_char, token_url, ); } else { jsmn_init(&mut parser); tok_cnt = jsmn_parse( &mut parser, json, strlen(json), tok.as_mut_ptr(), (::core::mem::size_of::<[jsmntok_t; 128]>() as libc::c_ulong) .wrapping_div( ::core::mem::size_of::<jsmntok_t>() as libc::c_ulong, ) as libc::c_uint, ); if tok_cnt < 2 as libc::c_int || tok[0 as libc::c_int as usize].type_0 as libc::c_uint != JSMN_OBJECT as libc::c_int as libc::c_uint { dc_log_warning( context, 0 as libc::c_int, b"Failed to parse OAuth2 json from %s\0" as *const u8 as *const libc::c_char, token_url, ); } else { let mut i: libc::c_int = 1 as libc::c_int; while i < tok_cnt { if access_token.is_null() && jsoneq( json, &mut *tok.as_mut_ptr().offset(i as isize), b"access_token\0" as *const u8 as *const libc::c_char, ) == 0 as libc::c_int { access_token = jsondup( json, &mut *tok .as_mut_ptr() .offset((i + 1 as libc::c_int) as isize), ); } else if refresh_token.is_null() && jsoneq( json, &mut *tok.as_mut_ptr().offset(i as isize), b"refresh_token\0" as *const u8 as *const libc::c_char, ) == 0 as libc::c_int { refresh_token = jsondup( json, &mut *tok .as_mut_ptr() .offset((i + 1 as libc::c_int) as isize), ); } else if jsoneq( json, &mut *tok.as_mut_ptr().offset(i as isize), b"expires_in\0" as *const u8 as *const libc::c_char, ) == 0 as libc::c_int { let mut expires_in_str: *mut libc::c_char = jsondup( json, &mut *tok .as_mut_ptr() .offset((i + 1 as libc::c_int) as isize), ); if !expires_in_str.is_null() { let mut val: time_t = atol(expires_in_str); if val > 20 as libc::c_int as libc::c_long && val < (60 as libc::c_int * 60 as libc::c_int * 24 as libc::c_int * 365 as libc::c_int * 5 as libc::c_int) as libc::c_long { expires_in = val; } free(expires_in_str as *mut libc::c_void); } } else if error.is_null() && jsoneq( json, &mut *tok.as_mut_ptr().offset(i as isize), b"error\0" as *const u8 as *const libc::c_char, ) == 0 as libc::c_int { error = jsondup( json, &mut *tok .as_mut_ptr() .offset((i + 1 as libc::c_int) as isize), ); } else if error_description.is_null() && jsoneq( json, &mut *tok.as_mut_ptr().offset(i as isize), b"error_description\0" as *const u8 as *const libc::c_char, ) == 0 as libc::c_int { error_description = jsondup( json, &mut *tok .as_mut_ptr() .offset((i + 1 as libc::c_int) as isize), ); } i += 1; i; } if !error.is_null() || !error_description.is_null() { dc_log_warning( context, 0 as libc::c_int, b"OAuth error: %s: %s\0" as *const u8 as *const libc::c_char, if !error.is_null() { error as *const libc::c_char } else { b"unknown\0" as *const u8 as *const libc::c_char }, if !error_description.is_null() { error_description as *const libc::c_char } else { b"no details\0" as *const u8 as *const libc::c_char }, ); } if !refresh_token.is_null() && *refresh_token.offset(0 as libc::c_int as isize) as libc::c_int != 0 { dc_sqlite3_set_config( (*context).sql, b"oauth2_refresh_token\0" as *const u8 as *const libc::c_char, refresh_token, ); dc_sqlite3_set_config( (*context).sql, b"oauth2_refresh_token_for\0" as *const u8 as *const libc::c_char, code, ); } if access_token.is_null() || *access_token.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int { dc_log_warning( context, 0 as libc::c_int, b"Failed to find OAuth2 access token\0" as *const u8 as *const libc::c_char, ); } else { dc_sqlite3_set_config( (*context).sql, b"oauth2_access_token\0" as *const u8 as *const libc::c_char, access_token, ); dc_sqlite3_set_config_int64( (*context).sql, b"oauth2_timestamp_expires\0" as *const u8 as *const libc::c_char, if expires_in != 0 { time(0 as *mut time_t) + expires_in - 5 as libc::c_int as libc::c_long } else { 0 as libc::c_int as libc::c_long }, ); if update_redirect_uri_on_success != 0 { dc_sqlite3_set_config( (*context).sql, b"oauth2_redirect_uri\0" as *const u8 as *const libc::c_char, redirect_uri, ); } } } } } } } } if locked != 0 { pthread_mutex_unlock(&mut (*context).oauth2_critical); } free(refresh_token as *mut libc::c_void); free(refresh_token_for as *mut libc::c_void); free(redirect_uri as *mut libc::c_void); free(token_url as *mut libc::c_void); free(json as *mut libc::c_void); free(error as *mut libc::c_void); free(error_description as *mut libc::c_void); free(oauth2 as *mut libc::c_void); return if !access_token.is_null() { access_token } else { dc_strdup(0 as *const libc::c_char) }; }
projects/deltachat-core/c/dc_chat.c
int dc_chat_get_type(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return DC_CHAT_TYPE_UNDEFINED; } return chat->type; }
projects/deltachat-core/rust/chat.rs
pub fn get_type(&self) -> Chattype { self.typ }
pub struct Chat { /// Database ID. pub id: ChatId, /// Chat type, e.g. 1:1 chat, group chat, mailing list. pub typ: Chattype, /// Chat name. pub name: String, /// Whether the chat is archived or pinned. pub visibility: ChatVisibility, /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and /// ad-hoc groups. pub grpid: String, /// Whether the chat is blocked, unblocked or a contact request. pub blocked: Blocked, /// Additional chat parameters stored in the database. pub param: Params, /// If location streaming is enabled in the chat. is_sending_locations: bool, /// Duration of the chat being muted. pub mute_duration: MuteDuration, /// If the chat is protected (verified). pub(crate) protected: ProtectionStatus, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__70.txt
pub unsafe extern "C" fn dc_chat_get_type(mut chat: *const dc_chat_t) -> libc::c_int { if chat.is_null() || (*chat).magic != 0xc4a7c4a7 as libc::c_uint { return 0 as libc::c_int; } return (*chat).type_0; }
projects/deltachat-core/c/dc_imex.c
char* dc_decrypt_setup_file(dc_context_t* context, const char* passphrase, const char* filecontent) { char* binary = NULL; size_t binary_bytes = 0; size_t indx = 0; void* plain = NULL; size_t plain_bytes = 0; char* payload = NULL; /* decrypt symmetrically */ if (!dc_pgp_symm_decrypt(context, passphrase, binary, binary_bytes, &plain, &plain_bytes)) { goto cleanup; } payload = strndup((const char*)plain, plain_bytes); cleanup: free(plain); if (binary) { mmap_string_unref(binary); } return payload; }
projects/deltachat-core/rust/imex.rs
async fn decrypt_setup_file<T: std::io::Read + std::io::Seek>( passphrase: &str, file: T, ) -> Result<String> { let plain_bytes = pgp::symm_decrypt(passphrase, file).await?; let plain_text = std::string::String::from_utf8(plain_bytes)?; Ok(plain_text) }
pub async fn symm_decrypt<T: std::io::Read + std::io::Seek>( passphrase: &str, ctext: T, ) -> Result<Vec<u8>> { let (enc_msg, _) = Message::from_armor_single(ctext)?; let passphrase = passphrase.to_string(); tokio::task::spawn_blocking(move || { let decryptor = enc_msg.decrypt_with_password(|| passphrase)?; let msgs = decryptor.collect::<pgp::errors::Result<Vec<_>>>()?; if let Some(msg) = msgs.first() { match msg.get_content()? { Some(content) => Ok(content), None => bail!("Decrypted message is empty"), } } else { bail!("No valid messages found") } }) .await? }
use std::any::Any; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use ::pgp::types::KeyTrait; use anyhow::{bail, ensure, format_err, Context as _, Result}; use deltachat_contact_tools::EmailAddress; use futures::StreamExt; use futures_lite::FutureExt; use rand::{thread_rng, Rng}; use tokio::fs::{self, File}; use tokio_tar::Archive; use crate::blob::{BlobDirContents, BlobObject}; use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId}; use crate::config::Config; use crate::contact::ContactId; use crate::context::Context; use crate::e2ee; use crate::events::EventType; use crate::key::{ self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey, }; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::pgp; use crate::sql; use crate::stock_str; use crate::tools::{ create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file, }; use transfer::{get_backup, BackupProvider}; use std::time::Duration; use ::pgp::armor::BlockType; use tokio::task; use super::*; use crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE}; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::{alice_keypair, TestContext, TestContextManager};
projects__deltachat-core__rust__imex__.rs__function__9.txt
pub unsafe extern "C" fn dc_decrypt_setup_file( mut context: *mut dc_context_t, mut passphrase: *const libc::c_char, mut filecontent: *const libc::c_char, ) -> *mut libc::c_char { let mut fc_buf: *mut libc::c_char = 0 as *mut libc::c_char; let mut fc_headerline: *const libc::c_char = 0 as *const libc::c_char; let mut fc_base64: *const libc::c_char = 0 as *const libc::c_char; let mut binary: *mut libc::c_char = 0 as *mut libc::c_char; let mut binary_bytes: size_t = 0 as libc::c_int as size_t; let mut indx: size_t = 0 as libc::c_int as size_t; let mut plain: *mut libc::c_void = 0 as *mut libc::c_void; let mut plain_bytes: size_t = 0 as libc::c_int as size_t; let mut payload: *mut libc::c_char = 0 as *mut libc::c_char; fc_buf = dc_strdup(filecontent); if !(dc_split_armored_data( fc_buf, &mut fc_headerline, 0 as *mut *const libc::c_char, 0 as *mut *const libc::c_char, &mut fc_base64, ) == 0 || fc_headerline.is_null() || strcmp( fc_headerline, b"-----BEGIN PGP MESSAGE-----\0" as *const u8 as *const libc::c_char, ) != 0 as libc::c_int || fc_base64.is_null()) { if !(mailmime_base64_body_parse( fc_base64, strlen(fc_base64), &mut indx, &mut binary, &mut binary_bytes, ) != MAILIMF_NO_ERROR as libc::c_int || binary.is_null() || binary_bytes == 0 as libc::c_int as libc::c_ulong) { if !(dc_pgp_symm_decrypt( context, passphrase, binary as *const libc::c_void, binary_bytes, &mut plain, &mut plain_bytes, ) == 0) { payload = strndup(plain as *const libc::c_char, plain_bytes); } } } free(plain); free(fc_buf as *mut libc::c_void); if !binary.is_null() { mmap_string_unref(binary); } return payload; }
projects/deltachat-core/c/dc_imex.c
char* dc_normalize_setup_code(dc_context_t* context, const char* in) { if (in==NULL) { return NULL; } dc_strbuilder_t out; dc_strbuilder_init(&out, 0); int outlen = 0; const char* p1 = in; while (*p1) { if (*p1 >= '0' && *p1 <= '9') { dc_strbuilder_catf(&out, "%c", *p1); outlen = strlen(out.buf); if (outlen==4 || outlen==9 || outlen==14 || outlen==19 || outlen==24 || outlen==29 || outlen==34 || outlen==39) { dc_strbuilder_cat(&out, "-"); } } p1++; } return out.buf; }
projects/deltachat-core/rust/imex.rs
fn normalize_setup_code(s: &str) -> String { let mut out = String::new(); for c in s.chars() { if c.is_ascii_digit() { out.push(c); if let 4 | 9 | 14 | 19 | 24 | 29 | 34 | 39 = out.len() { out += "-" } } } out }
use std::any::Any; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use ::pgp::types::KeyTrait; use anyhow::{bail, ensure, format_err, Context as _, Result}; use deltachat_contact_tools::EmailAddress; use futures::StreamExt; use futures_lite::FutureExt; use rand::{thread_rng, Rng}; use tokio::fs::{self, File}; use tokio_tar::Archive; use crate::blob::{BlobDirContents, BlobObject}; use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId}; use crate::config::Config; use crate::contact::ContactId; use crate::context::Context; use crate::e2ee; use crate::events::EventType; use crate::key::{ self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey, }; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::pgp; use crate::sql; use crate::stock_str; use crate::tools::{ create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file, }; use transfer::{get_backup, BackupProvider}; use std::time::Duration; use ::pgp::armor::BlockType; use tokio::task; use super::*; use crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE}; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::{alice_keypair, TestContext, TestContextManager};
projects__deltachat-core__rust__imex__.rs__function__10.txt
pub unsafe extern "C" fn dc_normalize_setup_code( mut context: *mut dc_context_t, mut in_0: *const libc::c_char, ) -> *mut libc::c_char { if in_0.is_null() { return 0 as *mut libc::c_char; } let mut out: dc_strbuilder_t = dc_strbuilder_t { buf: 0 as *mut libc::c_char, allocated: 0, free: 0, eos: 0 as *mut libc::c_char, }; dc_strbuilder_init(&mut out, 0 as libc::c_int); let mut outlen: libc::c_int = 0 as libc::c_int; let mut p1: *const libc::c_char = in_0; while *p1 != 0 { if *p1 as libc::c_int >= '0' as i32 && *p1 as libc::c_int <= '9' as i32 { dc_strbuilder_catf( &mut out as *mut dc_strbuilder_t, b"%c\0" as *const u8 as *const libc::c_char, *p1 as libc::c_int, ); outlen = strlen(out.buf) as libc::c_int; if outlen == 4 as libc::c_int || outlen == 9 as libc::c_int || outlen == 14 as libc::c_int || outlen == 19 as libc::c_int || outlen == 24 as libc::c_int || outlen == 29 as libc::c_int || outlen == 34 as libc::c_int || outlen == 39 as libc::c_int { dc_strbuilder_cat(&mut out, b"-\0" as *const u8 as *const libc::c_char); } } p1 = p1.offset(1); p1; } return out.buf; }
projects/deltachat-core/c/dc_aheader.c
int dc_aheader_set_from_string(dc_aheader_t* aheader, const char* header_str__) { /* according to RFC 5322 (Internet Message Format), the given string may contain `\r\n` before any whitespace. we can ignore this issue as (a) no key or value is expected to contain spaces, (b) for the key, non-base64-characters are ignored and (c) for parsing, we ignore `\r\n` as well as tabs for spaces */ #define AHEADER_WS "\t\r\n " char* header_str = NULL; char* p = NULL; char* beg_attr_name = NULL; char* after_attr_name = NULL; char* beg_attr_value = NULL; int success = 0; dc_aheader_empty(aheader); if (aheader==NULL || header_str__==NULL) { goto cleanup; } aheader->prefer_encrypt = DC_PE_NOPREFERENCE; /* value to use if the prefer-encrypted header is missing */ header_str = dc_strdup(header_str__); p = header_str; while (*p) { p += strspn(p, AHEADER_WS "=;"); /* forward to first attribute name beginning */ beg_attr_name = p; beg_attr_value = NULL; p += strcspn(p, AHEADER_WS "=;"); /* get end of attribute name (an attribute may have no value) */ if (p!=beg_attr_name) { /* attribute found */ after_attr_name = p; p += strspn(p, AHEADER_WS); /* skip whitespace between attribute name and possible `=` */ if (*p=='=') { p += strspn(p, AHEADER_WS "="); /* skip spaces and equal signs */ /* read unquoted attribute value until the first semicolon */ beg_attr_value = p; p += strcspn(p, ";"); if (*p!='\0') { *p = '\0'; p++; } dc_trim(beg_attr_value); } else { p += strspn(p, AHEADER_WS ";"); } *after_attr_name = '\0'; if (!add_attribute(aheader, beg_attr_name, beg_attr_value)) { goto cleanup; /* a bad attribute makes the whole header invalid */ } } } /* all needed data found? */ if (aheader->addr && aheader->public_key->binary) { success = 1; } cleanup: free(header_str); if (!success) { dc_aheader_empty(aheader); } return success; }
projects/deltachat-core/rust/aheader.rs
fn from_str(s: &str) -> Result<Self> { let mut attributes: BTreeMap<String, String> = s .split(';') .filter_map(|a| { let attribute: Vec<&str> = a.trim().splitn(2, '=').collect(); match &attribute[..] { [key, value] => Some((key.trim().to_string(), value.trim().to_string())), _ => None, } }) .collect(); let addr = match attributes.remove("addr") { Some(addr) => addr, None => bail!("Autocrypt header has no addr"), }; let public_key: SignedPublicKey = attributes .remove("keydata") .context("keydata attribute is not found") .and_then(|raw| { SignedPublicKey::from_base64(&raw).context("autocrypt key cannot be decoded") }) .and_then(|key| { key.verify() .and(Ok(key)) .context("autocrypt key cannot be verified") })?; let prefer_encrypt = attributes .remove("prefer-encrypt") .and_then(|raw| raw.parse().ok()) .unwrap_or_default(); // Autocrypt-Level0: unknown attributes starting with an underscore can be safely ignored // Autocrypt-Level0: unknown attribute, treat the header as invalid if attributes.keys().any(|k| !k.starts_with('_')) { bail!("Unknown Autocrypt attribute found"); } Ok(Aheader { addr, public_key, prefer_encrypt, }) }
pub struct Aheader { pub addr: String, pub public_key: SignedPublicKey, pub prefer_encrypt: EncryptPreference, } fn from_base64(data: &str) -> Result<Self> { // strip newlines and other whitespace let cleaned: String = data.split_whitespace().collect(); let bytes = base64::engine::general_purpose::STANDARD.decode(cleaned.as_bytes())?; Self::from_slice(&bytes) }
use std::collections::BTreeMap; use std::fmt; use std::str::FromStr; use anyhow::{bail, Context as _, Error, Result}; use crate::key::{DcKey, SignedPublicKey}; use super::*;
projects__deltachat-core__rust__aheader__.rs__function__5.txt
pub unsafe extern "C" fn dc_aheader_set_from_string( mut aheader: *mut dc_aheader_t, mut header_str__: *const libc::c_char, ) -> libc::c_int { let mut current_block: u64; let mut header_str: *mut libc::c_char = 0 as *mut libc::c_char; let mut p: *mut libc::c_char = 0 as *mut libc::c_char; let mut beg_attr_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut after_attr_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut beg_attr_value: *mut libc::c_char = 0 as *mut libc::c_char; let mut success: libc::c_int = 0 as libc::c_int; dc_aheader_empty(aheader); if !(aheader.is_null() || header_str__.is_null()) { (*aheader).prefer_encrypt = 0 as libc::c_int; header_str = dc_strdup(header_str__); p = header_str; loop { if !(*p != 0) { current_block = 11307063007268554308; break; } p = p .offset( strspn(p, b"\t\r\n =;\0" as *const u8 as *const libc::c_char) as isize, ); beg_attr_name = p; beg_attr_value = 0 as *mut libc::c_char; p = p .offset( strcspn(p, b"\t\r\n =;\0" as *const u8 as *const libc::c_char) as isize, ); if !(p != beg_attr_name) { continue; } after_attr_name = p; p = p .offset( strspn(p, b"\t\r\n \0" as *const u8 as *const libc::c_char) as isize, ); if *p as libc::c_int == '=' as i32 { p = p .offset( strspn(p, b"\t\r\n =\0" as *const u8 as *const libc::c_char) as isize, ); beg_attr_value = p; p = p .offset( strcspn(p, b";\0" as *const u8 as *const libc::c_char) as isize, ); if *p as libc::c_int != '\0' as i32 { *p = '\0' as i32 as libc::c_char; p = p.offset(1); p; } dc_trim(beg_attr_value); } else { p = p .offset( strspn(p, b"\t\r\n ;\0" as *const u8 as *const libc::c_char) as isize, ); } *after_attr_name = '\0' as i32 as libc::c_char; if add_attribute(aheader, beg_attr_name, beg_attr_value) == 0 { current_block = 13664586417473622975; break; } } match current_block { 13664586417473622975 => {} _ => { if !((*aheader).addr).is_null() && !((*(*aheader).public_key).binary).is_null() { success = 1 as libc::c_int; } } } } free(header_str as *mut libc::c_void); if success == 0 { dc_aheader_empty(aheader); } return success; }
projects/deltachat-core/c/dc_param.c
dc_param_t* dc_param_new() { dc_param_t* param = NULL; if ((param=calloc(1, sizeof(dc_param_t)))==NULL) { exit(28); /* cannot allocate little memory, unrecoverable error */ } param->packed = calloc(1, 1); return param; }
projects/deltachat-core/rust/param.rs
pub fn new() -> Self { Default::default() }
pub struct Params { inner: BTreeMap<Param, String>, }
use std::collections::BTreeMap; use std::fmt; use std::path::PathBuf; use std::str; use anyhow::{bail, Error, Result}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use crate::blob::BlobObject; use crate::context::Context; use crate::mimeparser::SystemMessage; use std::path::Path; use std::str::FromStr; use tokio::fs; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__param__.rs__function__3.txt
pub unsafe extern "C" fn dc_param_new() -> *mut dc_param_t { let mut param: *mut dc_param_t = 0 as *mut dc_param_t; param = calloc( 1 as libc::c_int as libc::c_ulong, ::core::mem::size_of::<dc_param_t>() as libc::c_ulong, ) as *mut dc_param_t; if param.is_null() { exit(28 as libc::c_int); } (*param) .packed = calloc( 1 as libc::c_int as libc::c_ulong, 1 as libc::c_int as libc::c_ulong, ) as *mut libc::c_char; return param; }
projects/deltachat-core/c/dc_contact.c
int dc_contact_is_blocked(const dc_contact_t* contact) { if (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) { return 0; } return contact->blocked; }
projects/deltachat-core/rust/contact.rs
pub fn is_blocked(&self) -> bool { self.blocked }
pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__14.txt
pub unsafe extern "C" fn dc_contact_is_blocked( mut contact: *const dc_contact_t, ) -> libc::c_int { if contact.is_null() || (*contact).magic != 0xc047ac7 as libc::c_int as libc::c_uint { return 0 as libc::c_int; } return (*contact).blocked; }
projects/deltachat-core/c/dc_context.c
dc_array_t* dc_get_fresh_msgs(dc_context_t* context) { int show_deaddrop = 0; dc_array_t* ret = dc_array_new(context, 128); sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || ret==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id" " FROM msgs m" " LEFT JOIN contacts ct ON m.from_id=ct.id" " LEFT JOIN chats c ON m.chat_id=c.id" " WHERE m.state=?" " AND m.hidden=0" " AND m.chat_id>?" " AND ct.blocked=0" " AND c.blocked=0" " AND NOT(c.muted_until=-1 OR c.muted_until>?)" " ORDER BY m.timestamp DESC,m.id DESC;"); sqlite3_bind_int(stmt, 1, DC_STATE_IN_FRESH); sqlite3_bind_int(stmt, 2, DC_CHAT_ID_LAST_SPECIAL); sqlite3_bind_int(stmt, 3, show_deaddrop? DC_CHAT_DEADDROP_BLOCKED : 0); while (sqlite3_step(stmt)==SQLITE_ROW) { dc_array_add_id(ret, sqlite3_column_int(stmt, 0)); } cleanup: sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/rust/context.rs
pub async fn get_fresh_msgs(&self) -> Result<Vec<MsgId>> { let list = self .sql .query_map( concat!( "SELECT m.id", " FROM msgs m", " LEFT JOIN contacts ct", " ON m.from_id=ct.id", " LEFT JOIN chats c", " ON m.chat_id=c.id", " WHERE m.state=?", " AND m.hidden=0", " AND m.chat_id>9", " AND ct.blocked=0", " AND c.blocked=0", " AND NOT(c.muted_until=-1 OR c.muted_until>?)", " ORDER BY m.timestamp DESC,m.id DESC;" ), (MessageState::InFresh, time()), |row| row.get::<_, MsgId>(0), |rows| { let mut list = Vec::new(); for row in rows { list.push(row?); } Ok(list) }, ) .await?; Ok(list) }
pub(crate) fn time() -> i64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap_or_default() .as_secs() as i64 } pub async fn query_map<T, F, G, H>( &self, sql: &str, params: impl rusqlite::Params + Send, f: F, mut g: G, ) -> Result<H> where F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>, G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>, H: Send + 'static, { self.call(move |conn| { let mut stmt = conn.prepare(sql)?; let res = stmt.query_map(params, f)?; g(res) }) .await } pub struct MsgId(u32); pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub enum MessageState { /// Undefined message state. #[default] Undefined = 0, /// Incoming *fresh* message. Fresh messages are neither noticed /// nor seen and are typically shown in notifications. InFresh = 10, /// Incoming *noticed* message. E.g. chat opened but message not /// yet read - noticed messages are not counted as unread but did /// not marked as read nor resulted in MDNs. InNoticed = 13, /// Incoming message, really *seen* by the user. Marked as read on /// IMAP and MDN may be sent. InSeen = 16, /// For files which need time to be prepared before they can be /// sent, the message enters this state before /// OutPending. OutPreparing = 18, /// Message saved as draft. OutDraft = 19, /// The user has pressed the "send" button but the message is not /// yet sent and is pending in some way. Maybe we're offline (no /// checkmark). OutPending = 20, /// *Unrecoverable* error (*recoverable* errors result in pending /// messages). OutFailed = 24, /// Outgoing message successfully delivered to server (one /// checkmark). Note, that already delivered messages may get into /// the OutFailed state if we get such a hint from the server. OutDelivered = 26, /// Outgoing message read by the recipient (two checkmarks; this /// requires goodwill on the receiver's side) OutMdnRcvd = 28, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, }
use std::collections::{BTreeMap, HashMap}; use std::ffi::OsString; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use pgp::SignedPublicKey; use ratelimit::Ratelimit; use tokio::sync::{Mutex, Notify, OnceCell, RwLock}; use crate::aheader::EncryptPreference; use crate::chat::{get_chat_cnt, ChatId, ProtectionStatus}; use crate::chatlist_events; 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}; 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_public_key, load_self_secret_key, DcKey as _}; use crate::login_param::LoginParam; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::param::{Param, Params}; use crate::peer_channels::Iroh; use crate::peerstate::Peerstate; use crate::push::PushSubscriber; use crate::quota::QuotaInfo; use crate::scheduler::{convert_folder_meaning, SchedulerState}; 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 anyhow::Context as _; use strum::IntoEnumIterator; use tempfile::tempdir; use super::*; use crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration}; use crate::chatlist::Chatlist; use crate::constants::Chattype; use crate::mimeparser::SystemMessage; use crate::receive_imf::receive_imf; use crate::test_utils::{get_chat_msg, TestContext}; use crate::tools::{create_outgoing_rfc724_mid, SystemTime};
projects__deltachat-core__rust__context__.rs__function__44.txt
pub unsafe extern "C" fn dc_get_fresh_msgs( mut context: *mut dc_context_t, ) -> *mut dc_array_t { let mut show_deaddrop: libc::c_int = 0 as libc::c_int; let mut ret: *mut dc_array_t = dc_array_new(context, 128 as libc::c_int as size_t); let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || ret.is_null()) { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT m.id FROM msgs m LEFT JOIN contacts ct ON m.from_id=ct.id LEFT JOIN chats c ON m.chat_id=c.id WHERE m.state=? AND m.hidden=0 AND m.chat_id>? AND ct.blocked=0 AND (c.blocked=0 OR c.blocked=?) ORDER BY m.timestamp DESC,m.id DESC;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, 10 as libc::c_int); sqlite3_bind_int(stmt, 2 as libc::c_int, 9 as libc::c_int); sqlite3_bind_int( stmt, 3 as libc::c_int, if show_deaddrop != 0 { 2 as libc::c_int } else { 0 as libc::c_int }, ); while sqlite3_step(stmt) == 100 as libc::c_int { dc_array_add_id(ret, sqlite3_column_int(stmt, 0 as libc::c_int) as uint32_t); } } sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/c/dc_msg.c
int dc_msg_is_setupmessage(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->type!=DC_MSG_FILE) { return 0; } return dc_param_get_int(msg->param, DC_PARAM_CMD, 0)==DC_CMD_AUTOCRYPT_SETUP_MESSAGE? 1 : 0; }
projects/deltachat-core/rust/message.rs
pub fn is_setupmessage(&self) -> bool { if self.viewtype != Viewtype::File { return false; } self.param.get_cmd() == SystemMessage::AutocryptSetupMessage }
pub fn get_cmd(&self) -> SystemMessage { self.get_int(Param::Cmd) .and_then(SystemMessage::from_i32) .unwrap_or_default() } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub enum Viewtype { /// Unknown message type. #[default] Unknown = 0, /// Text message. /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text(). Text = 10, /// Image message. /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to /// `Gif` when sending the message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension(). Image = 20, /// Animated GIF message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension() /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height(). Gif = 21, /// Message containing a sticker, similar to image. /// If possible, the ui should display the image without borders in a transparent way. /// A click on a sticker will offer to install the sticker set in some future. Sticker = 23, /// Message containing an Audio file. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration(). Audio = 40, /// A voice message that was directly recorded by the user. /// For all other audio messages, the type #DC_MSG_AUDIO should be used. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration() Voice = 41, /// Video messages. /// File, width, height and durarion /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration() /// and retrieved via /// dc_msg_get_file(), dc_msg_get_width(), /// dc_msg_get_height(), dc_msg_get_duration(). Video = 50, /// Message containing any file, eg. a PDF. /// The file is set via dc_msg_set_file() /// and retrieved via dc_msg_get_file(). File = 60, /// Message is an invitation to a videochat. VideochatInvitation = 70, /// Message is an webxdc instance. Webxdc = 80, /// Message containing shared contacts represented as a vCard (virtual contact file) /// with email addresses and possibly other fields. /// Use `parse_vcard()` to retrieve them. Vcard = 90, } pub enum SystemMessage { /// Unknown type of system message. #[default] Unknown = 0, /// Group name changed. GroupNameChanged = 2, /// Group avatar changed. GroupImageChanged = 3, /// Member was added to the group. MemberAddedToGroup = 4, /// Member was removed from the group. MemberRemovedFromGroup = 5, /// Autocrypt Setup Message. AutocryptSetupMessage = 6, /// Secure-join message. SecurejoinMessage = 7, /// Location streaming is enabled. LocationStreamingEnabled = 8, /// Location-only message. LocationOnly = 9, /// Chat ephemeral message timer is changed. EphemeralTimerChanged = 10, /// "Messages are guaranteed to be end-to-end encrypted from now on." ChatProtectionEnabled = 11, /// "%1$s sent a message from another device." ChatProtectionDisabled = 12, /// Message can't be sent because of `Invalid unencrypted mail to <>` /// which is sent by chatmail servers. InvalidUnencryptedMail = 13, /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it /// to complete. SecurejoinWait = 14, /// 1:1 chats info message telling that SecureJoin is still running, but the user may already /// send messages. SecurejoinWaitTimeout = 15, /// Self-sent-message that contains only json used for multi-device-sync; /// if possible, we attach that to other messages as for locations. MultiDeviceSync = 20, /// Sync message that contains a json payload /// sent to the other webxdc instances /// These messages are not shown in the chat. WebxdcStatusUpdate = 30, /// Webxdc info added with `info` set in `send_webxdc_status_update()`. WebxdcInfoMessage = 32, /// This message contains a users iroh node address. IrohNodeAddr = 40, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__60.txt
pub unsafe extern "C" fn dc_msg_is_setupmessage( mut msg: *const dc_msg_t, ) -> libc::c_int { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint || (*msg).type_0 != 60 as libc::c_int { return 0 as libc::c_int; } return if dc_param_get_int((*msg).param, 'S' as i32, 0 as libc::c_int) == 6 as libc::c_int { 1 as libc::c_int } else { 0 as libc::c_int }; }
projects/deltachat-core/c/dc_contact.c
dc_array_t* dc_get_contacts(dc_context_t* context, uint32_t listflags, const char* query) { char* self_addr = NULL; char* self_name = NULL; char* self_name2 = NULL; int add_self = 0; dc_array_t* ret = dc_array_new(context, 100); char* s3strLikeCmd = NULL; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", ""); /* we add DC_CONTACT_ID_SELF explicitly; so avoid doubles if the address is present as a normal entry for some case */ if ((listflags&DC_GCL_VERIFIED_ONLY) || query) { if ((s3strLikeCmd=sqlite3_mprintf("%%%s%%", query? query : ""))==NULL) { goto cleanup; } // see comments in dc_search_msgs() about the LIKE operator stmt = dc_sqlite3_prepare(context->sql, "SELECT c.id FROM contacts c" " LEFT JOIN acpeerstates ps ON c.addr=ps.addr " " WHERE c.addr!=?1 AND c.id>?2 AND c.origin>=?3" " AND c.blocked=0 AND (c.name LIKE ?4 OR c.addr LIKE ?5)" " AND (1=?6 OR LENGTH(ps.verified_key_fingerprint)!=0) " " ORDER BY LOWER(c.name||c.addr),c.id;"); sqlite3_bind_text(stmt, 1, self_addr, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 2, DC_CONTACT_ID_LAST_SPECIAL); sqlite3_bind_int (stmt, 3, DC_ORIGIN_MIN_CONTACT_LIST); sqlite3_bind_text(stmt, 4, s3strLikeCmd, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 5, s3strLikeCmd, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 6, (listflags&DC_GCL_VERIFIED_ONLY)? 0/*force checking for verified_key*/ : 1/*force statement being always true*/); self_name = dc_sqlite3_get_config(context->sql, "displayname", ""); self_name2 = dc_stock_str(context, DC_STR_SELF); if (query==NULL || dc_str_contains(self_addr, query) || dc_str_contains(self_name, query) || dc_str_contains(self_name2, query)) { add_self = 1; } } else { stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM contacts" " WHERE addr!=?1 AND id>?2 AND origin>=?3 AND blocked=0" " ORDER BY LOWER(name||addr),id;"); sqlite3_bind_text(stmt, 1, self_addr, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 2, DC_CONTACT_ID_LAST_SPECIAL); sqlite3_bind_int (stmt, 3, DC_ORIGIN_MIN_CONTACT_LIST); add_self = 1; } while (sqlite3_step(stmt)==SQLITE_ROW) { dc_array_add_id(ret, sqlite3_column_int(stmt, 0)); } /* to the end of the list, add self - this is to be in sync with member lists and to allow the user to start a self talk */ if ((listflags&DC_GCL_ADD_SELF) && add_self) { dc_array_add_id(ret, DC_CONTACT_ID_SELF); } cleanup: sqlite3_finalize(stmt); sqlite3_free(s3strLikeCmd); free(self_addr); free(self_name); free(self_name2); return ret; }
projects/deltachat-core/rust/contact.rs
pub async fn get_all( context: &Context, listflags: u32, query: Option<&str>, ) -> Result<Vec<ContactId>> { let self_addrs = context.get_all_self_addrs().await?; let mut add_self = false; let mut ret = Vec::new(); let flag_verified_only = (listflags & DC_GCL_VERIFIED_ONLY) != 0; let flag_add_self = (listflags & DC_GCL_ADD_SELF) != 0; let minimal_origin = if context.get_config_bool(Config::Bot).await? { Origin::Unknown } else { Origin::IncomingReplyTo }; if flag_verified_only || query.is_some() { let s3str_like_cmd = format!("%{}%", query.unwrap_or("")); context .sql .query_map( &format!( "SELECT c.id FROM contacts c \ LEFT JOIN acpeerstates ps ON c.addr=ps.addr \ WHERE c.addr NOT IN ({}) AND c.id>? \ AND c.origin>=? \ AND c.blocked=0 \ AND (iif(c.name='',c.authname,c.name) LIKE ? OR c.addr LIKE ?) \ AND (1=? OR LENGTH(ps.verified_key_fingerprint)!=0) \ ORDER BY c.last_seen DESC, c.id DESC;", sql::repeat_vars(self_addrs.len()) ), rusqlite::params_from_iter(params_iter(&self_addrs).chain(params_slice![ ContactId::LAST_SPECIAL, minimal_origin, s3str_like_cmd, s3str_like_cmd, if flag_verified_only { 0i32 } else { 1i32 } ])), |row| row.get::<_, ContactId>(0), |ids| { for id in ids { ret.push(id?); } Ok(()) }, ) .await?; if let Some(query) = query { let self_addr = context .get_config(Config::ConfiguredAddr) .await? .unwrap_or_default(); let self_name = context .get_config(Config::Displayname) .await? .unwrap_or_default(); let self_name2 = stock_str::self_msg(context); if self_addr.contains(query) || self_name.contains(query) || self_name2.await.contains(query) { add_self = true; } } else { add_self = true; } } else { add_self = true; context .sql .query_map( &format!( "SELECT id FROM contacts WHERE addr NOT IN ({}) AND id>? AND origin>=? AND blocked=0 ORDER BY last_seen DESC, id DESC;", sql::repeat_vars(self_addrs.len()) ), rusqlite::params_from_iter( params_iter(&self_addrs) .chain(params_slice![ContactId::LAST_SPECIAL, minimal_origin]), ), |row| row.get::<_, ContactId>(0), |ids| { for id in ids { ret.push(id?); } Ok(()) }, ) .await?; } if flag_add_self && add_self { ret.push(ContactId::SELF); } Ok(ret) }
pub async fn get_config_bool(&self, key: Config) -> Result<bool> { Ok(self.get_config_bool_opt(key).await?.unwrap_or_default()) } macro_rules! params_slice { ($($param:expr),+) => { [$(&$param as &dyn $crate::sql::ToSql),+] }; } pub(crate) fn params_iter( iter: &[impl crate::sql::ToSql], ) -> impl Iterator<Item = &dyn crate::sql::ToSql> { iter.iter().map(|item| item as &dyn crate::sql::ToSql) } pub async fn query_map<T, F, G, H>( &self, sql: &str, params: impl rusqlite::Params + Send, f: F, mut g: G, ) -> Result<H> where F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>, G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>, H: Send + 'static, { self.call(move |conn| { let mut stmt = conn.prepare(sql)?; let res = stmt.query_map(params, f)?; g(res) }) .await } pub async fn get_config(&self, key: Config) -> Result<Option<String>> { let env_key = format!("DELTACHAT_{}", key.as_ref().to_uppercase()); if let Ok(value) = env::var(env_key) { return Ok(Some(value)); } let value = match key { Config::Selfavatar => { let rel_path = self.sql.get_raw_config(key.as_ref()).await?; rel_path.map(|p| { get_abs_path(self, Path::new(&p)) .to_string_lossy() .into_owned() }) } Config::SysVersion => Some((*DC_VERSION_STR).clone()), Config::SysMsgsizeMaxRecommended => Some(format!("{RECOMMENDED_FILE_SIZE}")), Config::SysConfigKeys => Some(get_config_keys_string()), _ => self.sql.get_raw_config(key.as_ref()).await?, }; if value.is_some() { return Ok(value); } // Default values match key { Config::ConfiguredInboxFolder => Ok(Some("INBOX".to_owned())), _ => Ok(key.get_str("default").map(|s| s.to_string())), } } pub(crate) async fn get_all_self_addrs(&self) -> Result<Vec<String>> { let primary_addrs = self.get_config(Config::ConfiguredAddr).await?.into_iter(); let secondary_addrs = self.get_secondary_self_addrs().await?.into_iter(); Ok(primary_addrs.chain(secondary_addrs).collect()) } pub fn repeat_vars(count: usize) -> String { let mut s = "?,".repeat(count); s.pop(); // Remove trailing comma s } pub(crate) async fn self_msg(context: &Context) -> String { translated(context, StockMessage::SelfMsg).await } pub fn params_from_iter<I>(iter: I) -> ParamsFromIter<I> where I: IntoIterator, I::Item: ToSql, { ParamsFromIter(iter) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub struct ContactId(u32); impl ContactId { /// The owner of the account. /// /// The email-address is set by `set_config` using "addr". pub const SELF: ContactId = ContactId::new(1); /// ID of the contact for device messages. pub const DEVICE: ContactId = ContactId::new(5); pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9); } pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, } pub enum Config { /// Email address, used in the `From:` field. Addr, /// IMAP server hostname. MailServer, /// IMAP server username. MailUser, /// IMAP server password. MailPw, /// IMAP server port. MailPort, /// IMAP server security (e.g. TLS, STARTTLS). MailSecurity, /// How to check IMAP server TLS certificates. ImapCertificateChecks, /// SMTP server hostname. SendServer, /// SMTP server username. SendUser, /// SMTP server password. SendPw, /// SMTP server port. SendPort, /// SMTP server security (e.g. TLS, STARTTLS). SendSecurity, /// How to check SMTP server TLS certificates. SmtpCertificateChecks, /// Whether to use OAuth 2. /// /// Historically contained other bitflags, which are now deprecated. /// Should not be extended in the future, create new config keys instead. ServerFlags, /// True if SOCKS5 is enabled. /// /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration. Socks5Enabled, /// SOCKS5 proxy server hostname or address. Socks5Host, /// SOCKS5 proxy server port. Socks5Port, /// SOCKS5 proxy server username. Socks5User, /// SOCKS5 proxy server password. Socks5Password, /// Own name to use in the `From:` field when sending messages. Displayname, /// Own status to display, sent in message footer. Selfstatus, /// Own avatar filename. Selfavatar, /// Send BCC copy to self. /// /// Should be enabled for multidevice setups. #[strum(props(default = "1"))] BccSelf, /// True if encryption is preferred according to Autocrypt standard. #[strum(props(default = "1"))] E2eeEnabled, /// True if Message Delivery Notifications (read receipts) should /// be sent and requested. #[strum(props(default = "1"))] MdnsEnabled, /// True if "Sent" folder should be watched for changes. #[strum(props(default = "0"))] SentboxWatch, /// True if chat messages should be moved to a separate folder. #[strum(props(default = "1"))] MvboxMove, /// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only. /// /// This will not entirely disable other folders, e.g. the spam folder will also still /// be watched for new messages. #[strum(props(default = "0"))] OnlyFetchMvbox, /// Whether to show classic emails or only chat messages. #[strum(props(default = "2"))] // also change ShowEmails.default() on changes ShowEmails, /// Quality of the media files to send. #[strum(props(default = "0"))] // also change MediaQuality.default() on changes MediaQuality, /// If set to "1", on the first time `start_io()` is called after configuring, /// the newest existing messages are fetched. /// Existing recipients are added to the contact database regardless of this setting. #[strum(props(default = "0"))] FetchExistingMsgs, /// If set to "1", then existing messages are considered to be already fetched. /// This flag is reset after successful configuration. #[strum(props(default = "1"))] FetchedExistingMsgs, /// Type of the OpenPGP key to generate. #[strum(props(default = "0"))] KeyGenType, /// Timer in seconds after which the message is deleted from the /// server. /// /// Equals to 0 by default, which means the message is never /// deleted. /// /// Value 1 is treated as "delete at once": messages are deleted /// immediately, without moving to DeltaChat folder. #[strum(props(default = "0"))] DeleteServerAfter, /// Timer in seconds after which the message is deleted from the /// device. /// /// Equals to 0 by default, which means the message is never /// deleted. #[strum(props(default = "0"))] DeleteDeviceAfter, /// Move messages to the Trash folder instead of marking them "\Deleted". Overrides /// `ProviderOptions::delete_to_trash`. DeleteToTrash, /// Save raw MIME messages with headers in the database if true. SaveMimeHeaders, /// The primary email address. Also see `SecondaryAddrs`. ConfiguredAddr, /// Configured IMAP server hostname. ConfiguredMailServer, /// Configured IMAP server username. ConfiguredMailUser, /// Configured IMAP server password. ConfiguredMailPw, /// Configured IMAP server port. ConfiguredMailPort, /// Configured IMAP server security (e.g. TLS, STARTTLS). ConfiguredMailSecurity, /// How to check IMAP server TLS certificates. ConfiguredImapCertificateChecks, /// Configured SMTP server hostname. ConfiguredSendServer, /// Configured SMTP server username. ConfiguredSendUser, /// Configured SMTP server password. ConfiguredSendPw, /// Configured SMTP server port. ConfiguredSendPort, /// How to check SMTP server TLS certificates. ConfiguredSmtpCertificateChecks, /// Whether OAuth 2 is used with configured provider. ConfiguredServerFlags, /// Configured SMTP server security (e.g. TLS, STARTTLS). ConfiguredSendSecurity, /// Configured folder for incoming messages. ConfiguredInboxFolder, /// Configured folder for chat messages. ConfiguredMvboxFolder, /// Configured "Sent" folder. ConfiguredSentboxFolder, /// Configured "Trash" folder. ConfiguredTrashFolder, /// Unix timestamp of the last successful configuration. ConfiguredTimestamp, /// ID of the configured provider from the provider database. ConfiguredProvider, /// True if account is configured. Configured, /// True if account is a chatmail account. IsChatmail, /// All secondary self addresses separated by spaces /// (`[email protected] [email protected] [email protected]`) SecondaryAddrs, /// Read-only core version string. #[strum(serialize = "sys.version")] SysVersion, /// Maximal recommended attachment size in bytes. #[strum(serialize = "sys.msgsize_max_recommended")] SysMsgsizeMaxRecommended, /// Space separated list of all config keys available. #[strum(serialize = "sys.config_keys")] SysConfigKeys, /// True if it is a bot account. Bot, /// True when to skip initial start messages in groups. #[strum(props(default = "0"))] SkipStartMessages, /// Whether we send a warning if the password is wrong (set to false when we send a warning /// because we do not want to send a second warning) #[strum(props(default = "0"))] NotifyAboutWrongPw, /// If a warning about exceeding quota was shown recently, /// this is the percentage of quota at the time the warning was given. /// Unset, when quota falls below minimal warning threshold again. QuotaExceeding, /// address to webrtc instance to use for videochats WebrtcInstance, /// Timestamp of the last time housekeeping was run LastHousekeeping, /// Timestamp of the last `CantDecryptOutgoingMsgs` notification. LastCantDecryptOutgoingMsgs, /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely. #[strum(props(default = "60"))] ScanAllFoldersDebounceSecs, /// Whether to avoid using IMAP IDLE even if the server supports it. /// /// This is a developer option for testing "fake idle". #[strum(props(default = "0"))] DisableIdle, /// Defines the max. size (in bytes) of messages downloaded automatically. /// 0 = no limit. #[strum(props(default = "0"))] DownloadLimit, /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set. #[strum(props(default = "1"))] SyncMsgs, /// Space-separated list of all the authserv-ids which we believe /// may be the one of our email server. /// /// See `crate::authres::update_authservid_candidates`. AuthservIdCandidates, /// Make all outgoing messages with Autocrypt header "multipart/signed". SignUnencrypted, /// Let the core save all events to the database. /// This value is used internally to remember the MsgId of the logging xdc #[strum(props(default = "0"))] DebugLogging, /// Last message processed by the bot. LastMsgId, /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by /// default. /// /// This is not supposed to be changed by UIs and only used for testing. #[strum(props(default = "172800"))] GossipPeriod, /// Feature flag for verified 1:1 chats; the UI should set it /// to 1 if it supports verified 1:1 chats. /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified, /// and when the key changes, an info message is posted into the chat. /// 0=Nothing else happens when the key changes. /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true /// until `chat_id.accept()` is called. #[strum(props(default = "0"))] VerifiedOneOnOneChats, /// Row ID of the key in the `keypairs` table /// 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 /// without storing the email address SelfReportingId, /// MsgId of webxdc map integration. WebxdcIntegration, /// Iroh secret key. IrohSecretKey, } pub enum Origin { /// Unknown origin. Can be used as a minimum origin to specify that the caller does not care /// about origin of the contact. #[default] Unknown = 0, /// The contact is a mailing list address, needed to unblock mailing lists MailinglistAddress = 0x2, /// Hidden on purpose, e.g. addresses with the word "noreply" in it Hidden = 0x8, /// From: of incoming messages of unknown sender IncomingUnknownFrom = 0x10, /// Cc: of incoming messages of unknown sender IncomingUnknownCc = 0x20, /// To: of incoming messages of unknown sender IncomingUnknownTo = 0x40, /// address scanned but not verified UnhandledQrScan = 0x80, /// Reply-To: of incoming message of known sender /// Contacts with at least this origin value are shown in the contact list. IncomingReplyTo = 0x100, /// Cc: of incoming message of known sender IncomingCc = 0x200, /// additional To:'s of incoming message of known sender IncomingTo = 0x400, /// a chat was manually created for this user, but no message yet sent CreateChat = 0x800, /// message sent by us OutgoingBcc = 0x1000, /// message sent by us OutgoingCc = 0x2000, /// message sent by us OutgoingTo = 0x4000, /// internal use Internal = 0x40000, /// address is in our address book AddressBook = 0x80000, /// set on Alice's side for contacts like Bob that have scanned the QR code offered by her. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling contact_is_verified() ! SecurejoinInvited = 0x0100_0000, /// set on Bob's side for contacts scanned and verified from a QR code. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling contact_is_verified() ! SecurejoinJoined = 0x0200_0000, /// contact added manually by create_contact(), this should be the largest origin as otherwise the user cannot modify the names ManuallyCreated = 0x0400_0000, }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__28.txt
pub unsafe extern "C" fn dc_get_contacts( mut context: *mut dc_context_t, mut listflags: uint32_t, mut query: *const libc::c_char, ) -> *mut dc_array_t { let mut current_block: u64; let mut self_addr: *mut libc::c_char = 0 as *mut libc::c_char; let mut self_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut self_name2: *mut libc::c_char = 0 as *mut libc::c_char; let mut add_self: libc::c_int = 0 as libc::c_int; let mut ret: *mut dc_array_t = dc_array_new(context, 100 as libc::c_int as size_t); let mut s3strLikeCmd: *mut libc::c_char = 0 as *mut libc::c_char; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint) { self_addr = dc_sqlite3_get_config( (*context).sql, b"configured_addr\0" as *const u8 as *const libc::c_char, b"\0" as *const u8 as *const libc::c_char, ); if listflags & 0x1 as libc::c_int as libc::c_uint != 0 || !query.is_null() { s3strLikeCmd = sqlite3_mprintf( b"%%%s%%\0" as *const u8 as *const libc::c_char, if !query.is_null() { query } else { b"\0" as *const u8 as *const libc::c_char }, ); if s3strLikeCmd.is_null() { current_block = 6126847215165972376; } else { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT c.id FROM contacts c LEFT JOIN acpeerstates ps ON c.addr=ps.addr WHERE c.addr!=?1 AND c.id>?2 AND c.origin>=?3 AND c.blocked=0 AND (c.name LIKE ?4 OR c.addr LIKE ?5) AND (1=?6 OR LENGTH(ps.verified_key_fingerprint)!=0) ORDER BY LOWER(c.name||c.addr),c.id;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_text( stmt, 1 as libc::c_int, self_addr, -(1 as libc::c_int), None, ); sqlite3_bind_int(stmt, 2 as libc::c_int, 9 as libc::c_int); sqlite3_bind_int(stmt, 3 as libc::c_int, 0x100 as libc::c_int); sqlite3_bind_text( stmt, 4 as libc::c_int, s3strLikeCmd, -(1 as libc::c_int), None, ); sqlite3_bind_text( stmt, 5 as libc::c_int, s3strLikeCmd, -(1 as libc::c_int), None, ); sqlite3_bind_int( stmt, 6 as libc::c_int, if listflags & 0x1 as libc::c_int as libc::c_uint != 0 { 0 as libc::c_int } else { 1 as libc::c_int }, ); self_name = dc_sqlite3_get_config( (*context).sql, b"displayname\0" as *const u8 as *const libc::c_char, b"\0" as *const u8 as *const libc::c_char, ); self_name2 = dc_stock_str(context, 2 as libc::c_int); if query.is_null() || dc_str_contains(self_addr, query) != 0 || dc_str_contains(self_name, query) != 0 || dc_str_contains(self_name2, query) != 0 { add_self = 1 as libc::c_int; } current_block = 13242334135786603907; } } else { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT id FROM contacts WHERE addr!=?1 AND id>?2 AND origin>=?3 AND blocked=0 ORDER BY LOWER(name||addr),id;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_text( stmt, 1 as libc::c_int, self_addr, -(1 as libc::c_int), None, ); sqlite3_bind_int(stmt, 2 as libc::c_int, 9 as libc::c_int); sqlite3_bind_int(stmt, 3 as libc::c_int, 0x100 as libc::c_int); add_self = 1 as libc::c_int; current_block = 13242334135786603907; } match current_block { 6126847215165972376 => {} _ => { while sqlite3_step(stmt) == 100 as libc::c_int { dc_array_add_id( ret, sqlite3_column_int(stmt, 0 as libc::c_int) as uint32_t, ); } if listflags & 0x2 as libc::c_int as libc::c_uint != 0 && add_self != 0 { dc_array_add_id(ret, 1 as libc::c_int as uint32_t); } } } } sqlite3_finalize(stmt); sqlite3_free(s3strLikeCmd as *mut libc::c_void); free(self_addr as *mut libc::c_void); free(self_name as *mut libc::c_void); free(self_name2 as *mut libc::c_void); return ret; }
projects/deltachat-core/c/dc_chat.c
dc_array_t* dc_get_chat_contacts(dc_context_t* context, uint32_t chat_id) { /* Normal chats do not include SELF. Group chats do (as it may happen that one is deleted from a groupchat but the chats stays visible, moreover, this makes displaying lists easier) */ dc_array_t* ret = dc_array_new(context, 100); sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT cc.contact_id FROM chats_contacts cc" " LEFT JOIN contacts c ON c.id=cc.contact_id" " WHERE cc.chat_id=?" " ORDER BY c.id=1, c.last_seen DESC, c.id DESC;"); sqlite3_bind_int(stmt, 1, chat_id); while (sqlite3_step(stmt)==SQLITE_ROW) { dc_array_add_id(ret, sqlite3_column_int(stmt, 0)); } cleanup: sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/rust/chat.rs
pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result<Vec<ContactId>> { // Normal chats do not include SELF. Group chats do (as it may happen that one is deleted from a // groupchat but the chats stays visible, moreover, this makes displaying lists easier) let list = context .sql .query_map( "SELECT cc.contact_id FROM chats_contacts cc LEFT JOIN contacts c ON c.id=cc.contact_id WHERE cc.chat_id=? ORDER BY c.id=1, c.last_seen DESC, c.id DESC;", (chat_id,), |row| row.get::<_, ContactId>(0), |ids| ids.collect::<Result<Vec<_>, _>>().map_err(Into::into), ) .await?; Ok(list) }
pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub async fn query_map<T, F, G, H>( &self, sql: &str, params: impl rusqlite::Params + Send, f: F, mut g: G, ) -> Result<H> where F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>, G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>, H: Send + 'static, { self.call(move |conn| { let mut stmt = conn.prepare(sql)?; let res = stmt.query_map(params, f)?; g(res) }) .await } pub struct ChatId(u32); pub struct ContactId(u32);
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__118.txt
pub unsafe extern "C" fn dc_get_chat_contacts( mut context: *mut dc_context_t, mut chat_id: uint32_t, ) -> *mut dc_array_t { let mut ret: *mut dc_array_t = dc_array_new(context, 100 as libc::c_int as size_t); let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint) { if !(chat_id == 1 as libc::c_int as libc::c_uint) { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT cc.contact_id FROM chats_contacts cc LEFT JOIN contacts c ON c.id=cc.contact_id WHERE cc.chat_id=? ORDER BY c.id=1, LOWER(c.name||c.addr), c.id;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, chat_id as libc::c_int); while sqlite3_step(stmt) == 100 as libc::c_int { dc_array_add_id( ret, sqlite3_column_int(stmt, 0 as libc::c_int) as uint32_t, ); } } } sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/c/dc_imex.c
char* dc_create_setup_code(dc_context_t* context) { #define CODE_ELEMS 9 uint16_t random_val = 0; int i = 0; dc_strbuilder_t ret; dc_strbuilder_init(&ret, 0); for (i = 0; i < CODE_ELEMS; i++) { do { if (!RAND_bytes((unsigned char*)&random_val, sizeof(uint16_t))) { dc_log_warning(context, 0, "Falling back to pseudo-number generation for the setup code."); RAND_pseudo_bytes((unsigned char*)&random_val, sizeof(uint16_t)); } } while (random_val > 60000); /* make sure the modulo below does not reduce entropy (range is 0..65535, a module 10000 would make appearing values <=535 one time more often than other values) */ random_val = random_val % 10000; /* force all blocks into the range 0..9999 */ dc_strbuilder_catf(&ret, "%s%04i", i?"-":"", (int)random_val); } return ret.buf; }
projects/deltachat-core/rust/imex.rs
pub fn create_setup_code(_context: &Context) -> String { let mut random_val: u16; let mut rng = thread_rng(); let mut ret = String::new(); for i in 0..9 { loop { random_val = rng.gen(); if random_val as usize <= 60000 { break; } } random_val = (random_val as usize % 10000) as u16; ret += &format!( "{}{:04}", if 0 != i { "-" } else { "" }, random_val as usize ); } ret }
pub struct Context { pub(crate) inner: Arc<InnerContext>, }
use std::any::Any; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use ::pgp::types::KeyTrait; use anyhow::{bail, ensure, format_err, Context as _, Result}; use deltachat_contact_tools::EmailAddress; use futures::StreamExt; use futures_lite::FutureExt; use rand::{thread_rng, Rng}; use tokio::fs::{self, File}; use tokio_tar::Archive; use crate::blob::{BlobDirContents, BlobObject}; use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId}; use crate::config::Config; use crate::contact::ContactId; use crate::context::Context; use crate::e2ee; use crate::events::EventType; use crate::key::{ self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey, }; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::pgp; use crate::sql; use crate::stock_str; use crate::tools::{ create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file, }; use transfer::{get_backup, BackupProvider}; use std::time::Duration; use ::pgp::armor::BlockType; use tokio::task; use super::*; use crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE}; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::{alice_keypair, TestContext, TestContextManager};
projects__deltachat-core__rust__imex__.rs__function__5.txt
pub unsafe extern "C" fn dc_create_setup_code( mut context: *mut dc_context_t, ) -> *mut libc::c_char { let mut random_val: uint16_t = 0 as libc::c_int as uint16_t; let mut i: libc::c_int = 0 as libc::c_int; let mut ret: dc_strbuilder_t = dc_strbuilder_t { buf: 0 as *mut libc::c_char, allocated: 0, free: 0, eos: 0 as *mut libc::c_char, }; dc_strbuilder_init(&mut ret, 0 as libc::c_int); i = 0 as libc::c_int; while i < 9 as libc::c_int { loop { if RAND_bytes( &mut random_val as *mut uint16_t as *mut libc::c_uchar, ::core::mem::size_of::<uint16_t>() as libc::c_ulong as libc::c_int, ) == 0 { dc_log_warning( context, 0 as libc::c_int, b"Falling back to pseudo-number generation for the setup code.\0" as *const u8 as *const libc::c_char, ); RAND_pseudo_bytes( &mut random_val as *mut uint16_t as *mut libc::c_uchar, ::core::mem::size_of::<uint16_t>() as libc::c_ulong as libc::c_int, ); } if !(random_val as libc::c_int > 60000 as libc::c_int) { break; } } random_val = (random_val as libc::c_int % 10000 as libc::c_int) as uint16_t; dc_strbuilder_catf( &mut ret as *mut dc_strbuilder_t, b"%s%04i\0" as *const u8 as *const libc::c_char, if i != 0 { b"-\0" as *const u8 as *const libc::c_char } else { b"\0" as *const u8 as *const libc::c_char }, random_val as libc::c_int, ); i += 1; i; } return ret.buf; }
projects/deltachat-core/c/dc_contact.c
char* dc_contact_get_name(const dc_contact_t* contact) { if (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) { return dc_strdup(NULL); } return dc_strdup(contact->name); }
projects/deltachat-core/rust/contact.rs
pub fn get_name(&self) -> &str { &self.name }
pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__39.txt
pub unsafe extern "C" fn dc_contact_get_name( mut contact: *const dc_contact_t, ) -> *mut libc::c_char { if contact.is_null() || (*contact).magic != 0xc047ac7 as libc::c_int as libc::c_uint { return dc_strdup(0 as *const libc::c_char); } return dc_strdup((*contact).name); }
projects/deltachat-core/c/dc_chat.c
* See also dc_send_msg(). * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id Chat ID to send the text message to. * @param text_to_send Text to send to the chat defined by the chat ID. * Passing an empty text here causes an empty text to be sent, * it's up to the caller to handle this if undesired. * Passing NULL as the text causes the function to return 0. * @return The ID of the message that is about being sent. */ uint32_t dc_send_text_msg(dc_context_t* context, uint32_t chat_id, const char* text_to_send) { dc_msg_t* msg = dc_msg_new(context, DC_MSG_TEXT); uint32_t ret = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL || text_to_send==NULL) { goto cleanup; } msg->text = dc_strdup(text_to_send); ret = dc_send_msg(context, chat_id, msg); cleanup: dc_msg_unref(msg); return ret; }
projects/deltachat-core/rust/chat.rs
pub async fn send_text_msg( context: &Context, chat_id: ChatId, text_to_send: String, ) -> Result<MsgId> { ensure!( !chat_id.is_special(), "bad chat_id, can not be a special chat: {}", chat_id ); let mut msg = Message::new(Viewtype::Text); msg.text = text_to_send; send_msg(context, chat_id, &mut msg).await }
pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result<MsgId> { if chat_id.is_unset() { let forwards = msg.param.get(Param::PrepForwards); if let Some(forwards) = forwards { for forward in forwards.split(' ') { if let Ok(msg_id) = forward.parse::<u32>().map(MsgId::new) { if let Ok(mut msg) = Message::load_from_db(context, msg_id).await { send_msg_inner(context, chat_id, &mut msg).await?; }; } } msg.param.remove(Param::PrepForwards); msg.update_param(context).await?; } return send_msg_inner(context, chat_id, msg).await; } if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing { msg.param.remove(Param::GuaranteeE2ee); msg.param.remove(Param::ForcePlaintext); msg.update_param(context).await?; } send_msg_inner(context, chat_id, msg).await } pub fn is_special(self) -> bool { (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct MsgId(u32); pub struct ChatId(u32); impl Message { /// Creates a new message with given view type. pub fn new(viewtype: Viewtype) -> Self { Message { viewtype, ..Default::default() } } } pub enum Viewtype { /// Unknown message type. #[default] Unknown = 0, /// Text message. /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text(). Text = 10, /// Image message. /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to /// `Gif` when sending the message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension(). Image = 20, /// Animated GIF message. /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension() /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height(). Gif = 21, /// Message containing a sticker, similar to image. /// If possible, the ui should display the image without borders in a transparent way. /// A click on a sticker will offer to install the sticker set in some future. Sticker = 23, /// Message containing an Audio file. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration(). Audio = 40, /// A voice message that was directly recorded by the user. /// For all other audio messages, the type #DC_MSG_AUDIO should be used. /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration() /// and retrieved via dc_msg_get_file(), dc_msg_get_duration() Voice = 41, /// Video messages. /// File, width, height and durarion /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration() /// and retrieved via /// dc_msg_get_file(), dc_msg_get_width(), /// dc_msg_get_height(), dc_msg_get_duration(). Video = 50, /// Message containing any file, eg. a PDF. /// The file is set via dc_msg_set_file() /// and retrieved via dc_msg_get_file(). File = 60, /// Message is an invitation to a videochat. VideochatInvitation = 70, /// Message is an webxdc instance. Webxdc = 80, /// Message containing shared contacts represented as a vCard (virtual contact file) /// with email addresses and possibly other fields. /// Use `parse_vcard()` to retrieve them. Vcard = 90, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__109.txt
pub unsafe extern "C" fn dc_send_msg( mut context: *mut dc_context_t, mut chat_id: uint32_t, mut msg: *mut dc_msg_t, ) -> uint32_t { if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || msg.is_null() { return 0 as libc::c_int as uint32_t; } if (*msg).state != 18 as libc::c_int { if prepare_msg_common(context, chat_id, msg) == 0 { return 0 as libc::c_int as uint32_t; } } else { if chat_id != 0 as libc::c_int as libc::c_uint && chat_id != (*msg).chat_id { return 0 as libc::c_int as uint32_t; } dc_update_msg_state(context, (*msg).id, 20 as libc::c_int); } if dc_job_send_msg(context, (*msg).id) == 0 { return 0 as libc::c_int as uint32_t; } ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, (*msg).chat_id as uintptr_t, (*msg).id as uintptr_t, ); if dc_param_exists((*msg).param, 'l' as i32) != 0 { ((*context).cb) .expect( "non-null function pointer", )( context, 2035 as libc::c_int, 1 as libc::c_int as uintptr_t, 0 as libc::c_int as uintptr_t, ); } if chat_id == 0 { let mut forwards: *mut libc::c_char = dc_param_get( (*msg).param, 'P' as i32, 0 as *const libc::c_char, ); if !forwards.is_null() { let mut p: *mut libc::c_char = forwards; while *p != 0 { let mut id: int32_t = strtol(p, &mut p, 10 as libc::c_int) as int32_t; if id == 0 { break; } let mut copy: *mut dc_msg_t = dc_get_msg(context, id as uint32_t); if !copy.is_null() { dc_send_msg(context, 0 as libc::c_int as uint32_t, copy); } dc_msg_unref(copy); } dc_param_set((*msg).param, 'P' as i32, 0 as *const libc::c_char); dc_msg_save_param_to_disk(msg); } free(forwards as *mut libc::c_void); } return (*msg).id; }
projects/deltachat-core/c/dc_contact.c
char* dc_contact_get_addr(const dc_contact_t* contact) { if (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) { return dc_strdup(NULL); } return dc_strdup(contact->addr); }
projects/deltachat-core/rust/contact.rs
pub fn get_addr(&self) -> &str { &self.addr }
pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__37.txt
pub unsafe extern "C" fn dc_contact_get_addr( mut contact: *const dc_contact_t, ) -> *mut libc::c_char { if contact.is_null() || (*contact).magic != 0xc047ac7 as libc::c_int as libc::c_uint { return dc_strdup(0 as *const libc::c_char); } return dc_strdup((*contact).addr); }
projects/deltachat-core/c/dc_contact.c
* unless it was edited manually by dc_create_contact() before. * @return The number of modified or added contacts. */ int dc_add_address_book(dc_context_t* context, const char* adr_book) { carray* lines = NULL; size_t i = 0; size_t iCnt = 0; int sth_modified = 0; int modify_cnt = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || adr_book==NULL) { goto cleanup; } if ((lines=dc_split_into_lines(adr_book))==NULL) { goto cleanup; } dc_sqlite3_begin_transaction(context->sql); iCnt = carray_count(lines); for (i = 0; i+1 < iCnt; i += 2) { char* name = (char*)carray_get(lines, i); char* addr = (char*)carray_get(lines, i+1); dc_normalize_name(name); dc_normalize_addr(addr); dc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_ADRESS_BOOK, &sth_modified); if (sth_modified) { modify_cnt++; } } dc_sqlite3_commit(context->sql); if (modify_cnt) { context->cb(context, DC_EVENT_CONTACTS_CHANGED, 0, 0); } cleanup: dc_free_splitted_lines(lines); return modify_cnt; }
projects/deltachat-core/rust/contact.rs
pub async fn add_address_book(context: &Context, addr_book: &str) -> Result<usize> { let mut modify_cnt = 0; for (name, addr) in split_address_book(addr_book) { let (name, addr) = sanitize_name_and_addr(name, addr); match ContactAddress::new(&addr) { Ok(addr) => { match Contact::add_or_lookup(context, &name, &addr, Origin::AddressBook).await { Ok((_, modified)) => { if modified != Modifier::None { modify_cnt += 1 } } Err(err) => { warn!( context, "Failed to add address {} from address book: {}", addr, err ); } } } Err(err) => { warn!(context, "{:#}.", err); } } } if modify_cnt > 0 { context.emit_event(EventType::ContactsChanged(None)); } Ok(modify_cnt) }
fn split_address_book(book: &str) -> Vec<(&str, &str)> { book.lines() .collect::<Vec<&str>>() .chunks(2) .filter_map(|chunk| { let name = chunk.first()?; let addr = chunk.get(1)?; Some((*name, *addr)) }) .collect() } pub(crate) async fn add_or_lookup( context: &Context, name: &str, addr: &ContactAddress, mut origin: Origin, ) -> Result<(ContactId, Modifier)> { let mut sth_modified = Modifier::None; ensure!(!addr.is_empty(), "Can not add_or_lookup empty address"); ensure!(origin != Origin::Unknown, "Missing valid origin"); if context.is_self_addr(addr).await? { return Ok((ContactId::SELF, sth_modified)); } let mut name = strip_rtlo_characters(name); #[allow(clippy::collapsible_if)] if origin <= Origin::OutgoingTo { // The user may accidentally have written to a "noreply" address with another MUA: if addr.contains("noreply") || addr.contains("no-reply") || addr.starts_with("notifications@") // Filter out use-once addresses (like [email protected]): || (addr.len() > 50 && addr.contains('+')) { info!(context, "hiding contact {}", addr); origin = Origin::Hidden; // For these kind of email addresses, sender and address often don't belong together // (like hocuri <[email protected]>). In this example, hocuri shouldn't // be saved as the displayname for [email protected]. name = "".to_string(); } } // If the origin indicates that user entered the contact manually, from the address book or // from the QR-code scan (potentially from the address book of their other phone), then name // should go into the "name" column and never into "authname" column, to avoid leaking it // into the network. let manual = matches!( origin, Origin::ManuallyCreated | Origin::AddressBook | Origin::UnhandledQrScan ); let mut update_addr = false; let row_id = context.sql.transaction(|transaction| { let row = transaction.query_row( "SELECT id, name, addr, origin, authname FROM contacts WHERE addr=? COLLATE NOCASE", [addr.to_string()], |row| { let row_id: isize = row.get(0)?; let row_name: String = row.get(1)?; let row_addr: String = row.get(2)?; let row_origin: Origin = row.get(3)?; let row_authname: String = row.get(4)?; Ok((row_id, row_name, row_addr, row_origin, row_authname)) }).optional()?; let row_id; if let Some((id, row_name, row_addr, row_origin, row_authname)) = row { let update_name = manual && name != row_name; let update_authname = !manual && name != row_authname && !name.is_empty() && (origin >= row_origin || origin == Origin::IncomingUnknownFrom || row_authname.is_empty()); row_id = u32::try_from(id)?; if origin >= row_origin && addr.as_ref() != row_addr { update_addr = true; } if update_name || update_authname || update_addr || origin > row_origin { let new_name = if update_name { name.to_string() } else { row_name }; transaction .execute( "UPDATE contacts SET name=?, addr=?, origin=?, authname=? WHERE id=?;", ( new_name, if update_addr { addr.to_string() } else { row_addr }, if origin > row_origin { origin } else { row_origin }, if update_authname { name.to_string() } else { row_authname }, row_id ), )?; if update_name || update_authname { // Update the contact name also if it is used as a group name. // This is one of the few duplicated data, however, getting the chat list is easier this way. let chat_id: Option<ChatId> = transaction.query_row( "SELECT id FROM chats WHERE type=? AND id IN(SELECT chat_id FROM chats_contacts WHERE contact_id=?)", (Chattype::Single, isize::try_from(row_id)?), |row| { let chat_id: ChatId = row.get(0)?; Ok(chat_id) } ).optional()?; if let Some(chat_id) = chat_id { let contact_id = ContactId::new(row_id); let (addr, name, authname) = transaction.query_row( "SELECT addr, name, authname FROM contacts WHERE id=?", (contact_id,), |row| { let addr: String = row.get(0)?; let name: String = row.get(1)?; let authname: String = row.get(2)?; Ok((addr, name, authname)) })?; let chat_name = if !name.is_empty() { name } else if !authname.is_empty() { authname } else { addr }; let count = transaction.execute( "UPDATE chats SET name=?1 WHERE id=?2 AND name!=?1", (chat_name, chat_id))?; if count > 0 { // Chat name updated context.emit_event(EventType::ChatModified(chat_id)); chatlist_events::emit_chatlist_items_changed_for_contact(context, contact_id); } } } sth_modified = Modifier::Modified; } } else { let update_name = manual; let update_authname = !manual; transaction .execute( "INSERT INTO contacts (name, addr, origin, authname) VALUES (?, ?, ?, ?);", ( if update_name { name.to_string() } else { "".to_string() }, &addr, origin, if update_authname { name.to_string() } else { "".to_string() } ), )?; sth_modified = Modifier::Created; row_id = u32::try_from(transaction.last_insert_rowid())?; info!(context, "Added contact id={row_id} addr={addr}."); } Ok(row_id) }).await?; let contact_id = ContactId::new(row_id); Ok((contact_id, sth_modified)) } impl ContactAddress { /// Constructs a new contact address from string, /// normalizing and validating it. pub fn new(s: &str) -> Result<Self> { let addr = addr_normalize(s); if !may_be_valid_addr(&addr) { bail!("invalid address {:?}", s); } Ok(Self(addr.to_string())) } } macro_rules! warn { ($ctx:expr, $msg:expr) => { warn!($ctx, $msg,) }; ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{ let formatted = format!($msg, $($args),*); let full = format!("{file}:{line}: {msg}", file = file!(), line = line!(), msg = &formatted); $ctx.emit_event($crate::EventType::Warning(full)); }}; } pub fn emit_event(&self, event: EventType) { { let lock = self.debug_logging.read().expect("RwLock is poisoned"); if let Some(debug_logging) = &*lock { debug_logging.log_event(event.clone()); } } self.events.emit(Event { id: self.id, typ: event, }); } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub enum Origin { /// Unknown origin. Can be used as a minimum origin to specify that the caller does not care /// about origin of the contact. #[default] Unknown = 0, /// The contact is a mailing list address, needed to unblock mailing lists MailinglistAddress = 0x2, /// Hidden on purpose, e.g. addresses with the word "noreply" in it Hidden = 0x8, /// From: of incoming messages of unknown sender IncomingUnknownFrom = 0x10, /// Cc: of incoming messages of unknown sender IncomingUnknownCc = 0x20, /// To: of incoming messages of unknown sender IncomingUnknownTo = 0x40, /// address scanned but not verified UnhandledQrScan = 0x80, /// Reply-To: of incoming message of known sender /// Contacts with at least this origin value are shown in the contact list. IncomingReplyTo = 0x100, /// Cc: of incoming message of known sender IncomingCc = 0x200, /// additional To:'s of incoming message of known sender IncomingTo = 0x400, /// a chat was manually created for this user, but no message yet sent CreateChat = 0x800, /// message sent by us OutgoingBcc = 0x1000, /// message sent by us OutgoingCc = 0x2000, /// message sent by us OutgoingTo = 0x4000, /// internal use Internal = 0x40000, /// address is in our address book AddressBook = 0x80000, /// set on Alice's side for contacts like Bob that have scanned the QR code offered by her. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling contact_is_verified() ! SecurejoinInvited = 0x0100_0000, /// set on Bob's side for contacts scanned and verified from a QR code. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling contact_is_verified() ! SecurejoinJoined = 0x0200_0000, /// contact added manually by create_contact(), this should be the largest origin as otherwise the user cannot modify the names ManuallyCreated = 0x0400_0000, } pub enum EventType { /// The library-user may write an informational string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Info(String), /// Emitted when SMTP connection is established and login was successful. SmtpConnected(String), /// Emitted when IMAP connection is established and login was successful. ImapConnected(String), /// Emitted when a message was successfully sent to the SMTP server. SmtpMessageSent(String), /// Emitted when an IMAP message has been marked as deleted ImapMessageDeleted(String), /// Emitted when an IMAP message has been moved ImapMessageMoved(String), /// Emitted before going into IDLE on the Inbox folder. ImapInboxIdle, /// Emitted when an new file in the $BLOBDIR was created NewBlobFile(String), /// Emitted when an file in the $BLOBDIR was deleted DeletedBlobFile(String), /// The library-user should write a warning string to the log. /// /// This event should *not* be reported to the end-user using a popup or something like /// that. Warning(String), /// The library-user should report an error to the end-user. /// /// As most things are asynchronous, things may go wrong at any time and the user /// should not be disturbed by a dialog or so. Instead, use a bubble or so. /// /// However, for ongoing processes (eg. configure()) /// or for functions that are expected to fail (eg. dc_continue_key_transfer()) /// it might be better to delay showing these events until the function has really /// failed (returned false). It should be sufficient to report only the *last* error /// in a messasge box then. Error(String), /// An action cannot be performed because the user is not in the group. /// Reported eg. after a call to /// dc_set_chat_name(), dc_set_chat_profile_image(), /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(), /// dc_send_text_msg() or another sending function. ErrorSelfNotInGroup(String), /// Messages or chats changed. One or more messages or chats changed for various /// reasons in the database: /// - Messages sent, received or removed /// - Chats created, deleted or archived /// - A draft has been set /// MsgsChanged { /// Set if only a single chat is affected by the changes, otherwise 0. chat_id: ChatId, /// Set if only a single message is affected by the changes, otherwise 0. msg_id: MsgId, }, /// Reactions for the message changed. ReactionsChanged { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message for which reactions were changed. msg_id: MsgId, /// ID of the contact whose reaction set is changed. contact_id: ContactId, }, /// There is a fresh message. Typically, the user will show an notification /// when receiving this message. /// /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event. IncomingMsg { /// ID of the chat where the message is assigned. chat_id: ChatId, /// ID of the message. msg_id: MsgId, }, /// Downloading a bunch of messages just finished. IncomingMsgBunch, /// Messages were seen or noticed. /// chat id is always set. MsgsNoticed(ChatId), /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state(). MsgDelivered { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was successfully sent. msg_id: MsgId, }, /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_FAILED, see dc_msg_get_state(). MsgFailed { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that could not be sent. msg_id: MsgId, }, /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state(). MsgRead { /// ID of the chat which the message belongs to. chat_id: ChatId, /// ID of the message that was read. msg_id: MsgId, }, /// A single message was deleted. /// /// This event means that the message will no longer appear in the messagelist. /// UI should remove the message from the messagelist /// in response to this event if the message is currently displayed. /// /// The message may have been explicitly deleted by the user or expired. /// Internally the message may have been removed from the database, /// moved to the trash chat or hidden. /// /// This event does not indicate the message /// deletion from the server. MsgDeleted { /// ID of the chat where the message was prior to deletion. /// Never 0 or trash chat. chat_id: ChatId, /// ID of the deleted message. Never 0. msg_id: MsgId, }, /// Chat changed. The name or the image of a chat group was changed or members were added or removed. /// Or the verify state of a chat has changed. /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat() /// and dc_remove_contact_from_chat(). /// /// This event does not include ephemeral timer modification, which /// is a separate event. ChatModified(ChatId), /// Chat ephemeral timer changed. ChatEphemeralTimerModified { /// Chat ID. chat_id: ChatId, /// New ephemeral timer value. timer: EphemeralTimer, }, /// Contact(s) created, renamed, blocked, deleted or changed their "recently seen" status. /// /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected. ContactsChanged(Option<ContactId>), /// Location of one or more contact has changed. /// /// @param data1 (u32) contact_id of the contact for which the location has changed. /// If the locations of several contacts have been changed, /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`. LocationChanged(Option<ContactId>), /// Inform about the configuration progress started by configure(). ConfigureProgress { /// Progress. /// /// 0=error, 1-999=progress in permille, 1000=success and done progress: usize, /// Progress comment or error, something to display to the user. comment: Option<String>, }, /// Inform about the import/export progress started by imex(). /// /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done /// @param data2 0 ImexProgress(usize), /// A file has been exported. A file has been written by imex(). /// This event may be sent multiple times by a single call to imex(). /// /// A typical purpose for a handler of this event may be to make the file public to some system /// services. /// /// @param data2 0 ImexFileWritten(PathBuf), /// Progress information of a secure-join handshake from the view of the inviter /// (Alice, the person who shows the QR code). /// /// These events are typically sent after a joiner has scanned the QR code /// generated by dc_get_securejoin_qr(). SecurejoinInviterProgress { /// ID of the contact that wants to join. contact_id: ContactId, /// Progress as: /// 300=vg-/vc-request received, typically shown as "bob@addr joins". /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as "bob@addr verified". /// 800=contact added to chat, shown as "bob@addr securely joined GROUP". Only for the verified-group-protocol. /// 1000=Protocol finished for this contact. progress: usize, }, /// Progress information of a secure-join handshake from the view of the joiner /// (Bob, the person who scans the QR code). /// The events are typically sent while dc_join_securejoin(), which /// may take some time, is executed. SecurejoinJoinerProgress { /// ID of the inviting contact. contact_id: ContactId, /// Progress as: /// 400=vg-/vc-request-with-auth sent, typically shown as "alice@addr verified, introducing myself." /// (Bob has verified alice and waits until Alice does the same for him) /// 1000=vg-member-added/vc-contact-confirm received progress: usize, }, /// The connectivity to the server changed. /// This means that you should refresh the connectivity view /// and possibly the connectivtiy HTML; see dc_get_connectivity() and /// dc_get_connectivity_html() for details. ConnectivityChanged, /// The user's avatar changed. /// Deprecated by `ConfigSynced`. SelfavatarChanged, /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For /// uniformity this is emitted on the source device too. The value isn't here, otherwise it /// would be logged which might not be good for privacy. ConfigSynced { /// Configuration key. key: Config, }, /// Webxdc status update received. WebxdcStatusUpdate { /// Message ID. msg_id: MsgId, /// Status update ID. status_update_serial: StatusUpdateSerial, }, /// Data received over an ephemeral peer channel. WebxdcRealtimeData { /// Message ID. msg_id: MsgId, /// Realtime data. data: Vec<u8>, }, /// Inform that a message containing a webxdc instance has been deleted. WebxdcInstanceDeleted { /// ID of the deleted message. msg_id: MsgId, }, /// Tells that the Background fetch was completed (or timed out). /// This event acts as a marker, when you reach this event you can be sure /// that all events emitted during the background fetch were processed. /// /// This event is only emitted by the account manager AccountsBackgroundFetchDone, /// Inform that set of chats or the order of the chats in the chatlist has changed. /// /// Sometimes this is emitted together with `UIChatlistItemChanged`. ChatlistChanged, /// Inform that a single chat list item changed and needs to be rerendered. /// If `chat_id` is set to None, then all currently visible chats need to be rerendered, and all not-visible items need to be cleared from cache if the UI has a cache. ChatlistItemChanged { /// ID of the changed chat chat_id: Option<ChatId>, }, /// Event for using in tests, e.g. as a fence between normally generated events. #[cfg(test)] Test, /// Inform than some events have been skipped due to event channel overflow. EventChannelOverflow { /// Number of events skipped. n: u64, }, } pub(crate) enum Modifier { None, Modified, Created, } pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__27.txt
pub unsafe extern "C" fn dc_create_contact( mut context: *mut dc_context_t, mut name: *const libc::c_char, mut addr: *const libc::c_char, ) -> uint32_t { let mut contact_id: uint32_t = 0 as libc::c_int as uint32_t; let mut sth_modified: libc::c_int = 0 as libc::c_int; let mut blocked: libc::c_int = 0 as libc::c_int; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || addr.is_null() || *addr.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int) { contact_id = dc_add_or_lookup_contact( context, name, addr, 0x4000000 as libc::c_int, &mut sth_modified, ); blocked = dc_is_contact_blocked(context, contact_id); ((*context).cb) .expect( "non-null function pointer", )( context, 2030 as libc::c_int, (if sth_modified == 2 as libc::c_int { contact_id } else { 0 as libc::c_int as libc::c_uint }) as uintptr_t, 0 as libc::c_int as uintptr_t, ); if blocked != 0 { dc_block_contact(context, contact_id, 0 as libc::c_int); } } return contact_id; }
projects/deltachat-core/c/dc_sqlite3.c
int dc_sqlite3_execute(dc_sqlite3_t* sql, const char* querystr) { int success = 0; sqlite3_stmt* stmt = NULL; int sqlState = 0; stmt = dc_sqlite3_prepare(sql, querystr); if (stmt==NULL) { goto cleanup; } sqlState = sqlite3_step(stmt); if (sqlState != SQLITE_DONE && sqlState != SQLITE_ROW) { dc_sqlite3_log_error(sql, "Cannot execute \"%s\".", querystr); goto cleanup; } success = 1; cleanup: sqlite3_finalize(stmt); return success; }
projects/deltachat-core/rust/sql.rs
pub async fn execute( &self, query: &str, params: impl rusqlite::Params + Send, ) -> Result<usize> { self.call_write(move |conn| { let res = conn.execute(query, params)?; Ok(res) }) .await }
pub async fn call_write<'a, F, R>(&'a self, function: F) -> Result<R> where F: 'a + FnOnce(&mut Connection) -> Result<R> + Send, R: Send + 'static, { let _lock = self.write_lock().await; self.call(function).await } pub struct Params { inner: BTreeMap<Param, String>, } pub struct Sql { /// Database file path pub(crate) dbfile: PathBuf, /// Write transactions mutex. /// /// See [`Self::write_lock`]. write_mtx: Mutex<()>, /// SQL connection pool. pool: RwLock<Option<Pool>>, /// None if the database is not open, true if it is open with passphrase and false if it is /// open without a passphrase. is_encrypted: RwLock<Option<bool>>, /// Cache of `config` table. pub(crate) config_cache: RwLock<HashMap<String, Option<String>>>, }
use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use anyhow::{bail, Context as _, Result}; use rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row}; use tokio::sync::{Mutex, MutexGuard, RwLock}; use crate::blob::BlobObject; use crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon}; use crate::config::Config; use crate::constants::DC_CHAT_ID_TRASH; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::ephemeral::start_ephemeral_timers; use crate::imex::BLOBS_BACKUP_NAME; use crate::location::delete_orphaned_poi_locations; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::stock_str; use crate::tools::{delete_file, time, SystemTime}; use pool::Pool; use super::*; use crate::{test_utils::TestContext, EventType}; use tempfile::tempdir; use tempfile::tempdir; use tempfile::tempdir;
projects__deltachat-core__rust__sql__.rs__function__16.txt
pub unsafe extern "C" fn dc_sqlite3_execute( mut sql: *mut dc_sqlite3_t, mut querystr: *const libc::c_char, ) -> libc::c_int { let mut success: libc::c_int = 0 as libc::c_int; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; let mut sqlState: libc::c_int = 0 as libc::c_int; stmt = dc_sqlite3_prepare(sql, querystr); if !stmt.is_null() { sqlState = sqlite3_step(stmt); if sqlState != 101 as libc::c_int && sqlState != 100 as libc::c_int { dc_sqlite3_log_error( sql, b"Cannot execute \"%s\".\0" as *const u8 as *const libc::c_char, querystr, ); } else { success = 1 as libc::c_int; } } sqlite3_finalize(stmt); return success; }
projects/deltachat-core/c/dc_contact.c
* normalize() is _not_ called for the name. If the contact is blocked, it is unblocked. * * To add a number of contacts, see dc_add_address_book() which is much faster for adding * a bunch of addresses. * * May result in a #DC_EVENT_CONTACTS_CHANGED event. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @param name Name of the contact to add. If you do not know the name belonging * to the address, you can give NULL here. * @param addr E-mail-address of the contact to add. If the email address * already exists, the name is updated and the origin is increased to * "manually created". * @return Contact ID of the created or reused contact. */ uint32_t dc_create_contact(dc_context_t* context, const char* name, const char* addr) { uint32_t contact_id = 0; int sth_modified = 0; int blocked = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || addr==NULL || addr[0]==0) { goto cleanup; } contact_id = dc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_MANUALLY_CREATED, &sth_modified); blocked = dc_is_contact_blocked(context, contact_id); context->cb(context, DC_EVENT_CONTACTS_CHANGED, sth_modified==CONTACT_CREATED? contact_id : 0, 0); if (blocked) { dc_block_contact(context, contact_id, 0); } cleanup: return contact_id; }
projects/deltachat-core/rust/contact.rs
pub async fn create(context: &Context, name: &str, addr: &str) -> Result<ContactId> { Self::create_ex(context, Sync, name, addr).await }
pub(crate) async fn create_ex( context: &Context, sync: sync::Sync, name: &str, addr: &str, ) -> Result<ContactId> { let name = improve_single_line_input(name); let (name, addr) = sanitize_name_and_addr(&name, addr); let addr = ContactAddress::new(&addr)?; let (contact_id, sth_modified) = Contact::add_or_lookup(context, &name, &addr, Origin::ManuallyCreated) .await .context("add_or_lookup")?; let blocked = Contact::is_blocked_load(context, contact_id).await?; match sth_modified { Modifier::None => {} Modifier::Modified | Modifier::Created => { context.emit_event(EventType::ContactsChanged(Some(contact_id))) } } if blocked { set_blocked(context, Nosync, contact_id, false).await?; } if sync.into() { chat::sync( context, chat::SyncId::ContactAddr(addr.to_string()), chat::SyncAction::Rename(name.to_string()), ) .await .log_err(context) .ok(); } Ok(contact_id) } pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct ContactId(u32);
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__20.txt
pub unsafe extern "C" fn dc_create_contact( mut context: *mut dc_context_t, mut name: *const libc::c_char, mut addr: *const libc::c_char, ) -> uint32_t { let mut contact_id: uint32_t = 0 as libc::c_int as uint32_t; let mut sth_modified: libc::c_int = 0 as libc::c_int; let mut blocked: libc::c_int = 0 as libc::c_int; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || addr.is_null() || *addr.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int) { contact_id = dc_add_or_lookup_contact( context, name, addr, 0x4000000 as libc::c_int, &mut sth_modified, ); blocked = dc_is_contact_blocked(context, contact_id); ((*context).cb) .expect( "non-null function pointer", )( context, 2030 as libc::c_int, (if sth_modified == 2 as libc::c_int { contact_id } else { 0 as libc::c_int as libc::c_uint }) as uintptr_t, 0 as libc::c_int as uintptr_t, ); if blocked != 0 { dc_block_contact(context, contact_id, 0 as libc::c_int); } } return contact_id; }
projects/deltachat-core/c/dc_msg.c
int dc_msg_get_state(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return DC_STATE_UNDEFINED; } return msg->state; }
projects/deltachat-core/rust/message.rs
pub fn get_state(&self) -> MessageState { self.state }
pub struct MsgId(u32); pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__36.txt
pub unsafe extern "C" fn dc_msg_get_state(mut msg: *const dc_msg_t) -> libc::c_int { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return 0 as libc::c_int; } return (*msg).state; }
projects/deltachat-core/c/dc_chatlist.c
* 0 and dc_chatlist_get_cnt()-1. */ uint32_t dc_chatlist_get_chat_id(const dc_chatlist_t* chatlist, size_t index) { if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC || chatlist->chatNlastmsg_ids==NULL || index>=chatlist->cnt) { return 0; } return dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT); }
projects/deltachat-core/rust/chatlist.rs
pub fn get_chat_id(&self, index: usize) -> Result<ChatId> { let (chat_id, _msg_id) = self .ids .get(index) .context("chatlist index is out of range")?; Ok(*chat_id) }
pub struct Chatlist { /// Stores pairs of `chat_id, message_id` ids: Vec<(ChatId, Option<MsgId>)>, }
use anyhow::{ensure, Context as _, Result}; use once_cell::sync::Lazy; use crate::chat::{update_special_chat_names, Chat, ChatId, ChatVisibility}; use crate::constants::{ Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_GCL_ADD_ALLDONE_HINT, DC_GCL_ARCHIVED_ONLY, DC_GCL_FOR_FORWARDING, DC_GCL_NO_SPECIALS, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::message::{Message, MessageState, MsgId}; use crate::param::{Param, Params}; use crate::stock_str; use crate::summary::Summary; use crate::tools::IsNoneOrEmpty; use super::*; use crate::chat::{ add_contact_to_chat, create_group_chat, get_chat_contacts, remove_contact_from_chat, send_text_msg, ProtectionStatus, }; use crate::message::Viewtype; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::TestContext;
projects__deltachat-core__rust__chatlist__.rs__function__5.txt
pub unsafe extern "C" fn dc_chatlist_get_cnt( mut chatlist: *const dc_chatlist_t, ) -> size_t { if chatlist.is_null() || (*chatlist).magic != 0xc4a71157 as libc::c_uint { return 0 as libc::c_int as size_t; } return (*chatlist).cnt; }
projects/deltachat-core/c/dc_msg.c
int dc_msg_has_location(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return (msg->location_id!=0); }
projects/deltachat-core/rust/message.rs
pub fn has_location(&self) -> bool { self.location_id != 0 }
pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__27.txt
pub unsafe extern "C" fn dc_msg_has_location(mut msg: *const dc_msg_t) -> libc::c_int { if msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint { return 0 as libc::c_int; } return ((*msg).location_id != 0 as libc::c_int as libc::c_uint) as libc::c_int; }
projects/deltachat-core/c/dc_sqlite3.c
static int is_file_in_use(dc_hash_t* files_in_use, const char* namespc, const char* name) { char* name_to_check = dc_strdup(name); if (namespc) { int name_len = strlen(name); int namespc_len = strlen(namespc); if (name_len<=namespc_len || strcmp(&name[name_len-namespc_len], namespc)!=0) { return 0; } name_to_check[name_len-namespc_len] = 0; } int ret = (dc_hash_find_str(files_in_use, name_to_check)!=NULL); free(name_to_check); return ret; }
projects/deltachat-core/rust/sql.rs
fn is_file_in_use(files_in_use: &HashSet<String>, namespc_opt: Option<&str>, name: &str) -> bool { let name_to_check = if let Some(namespc) = namespc_opt { let name_len = name.len(); let namespc_len = namespc.len(); if name_len <= namespc_len || !name.ends_with(namespc) { return false; } &name[..name_len - namespc_len] } else { name }; files_in_use.contains(name_to_check) }
use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use anyhow::{bail, Context as _, Result}; use rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row}; use tokio::sync::{Mutex, MutexGuard, RwLock}; use crate::blob::BlobObject; use crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon}; use crate::config::Config; use crate::constants::DC_CHAT_ID_TRASH; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::ephemeral::start_ephemeral_timers; use crate::imex::BLOBS_BACKUP_NAME; use crate::location::delete_orphaned_poi_locations; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::stock_str; use crate::tools::{delete_file, time, SystemTime}; use pool::Pool; use super::*; use crate::{test_utils::TestContext, EventType}; use tempfile::tempdir; use tempfile::tempdir; use tempfile::tempdir;
projects__deltachat-core__rust__sql__.rs__function__41.txt
unsafe extern "C" fn is_file_in_use( mut files_in_use: *mut dc_hash_t, mut namespc: *const libc::c_char, mut name: *const libc::c_char, ) -> libc::c_int { let mut name_to_check: *mut libc::c_char = dc_strdup(name); if !namespc.is_null() { let mut name_len: libc::c_int = strlen(name) as libc::c_int; let mut namespc_len: libc::c_int = strlen(namespc) as libc::c_int; if name_len <= namespc_len || strcmp(&*name.offset((name_len - namespc_len) as isize), namespc) != 0 as libc::c_int { return 0 as libc::c_int; } *name_to_check .offset( (name_len - namespc_len) as isize, ) = 0 as libc::c_int as libc::c_char; } let mut ret: libc::c_int = (dc_hash_find( files_in_use, name_to_check as *const libc::c_void, strlen(name_to_check) as libc::c_int, ) != 0 as *mut libc::c_void) as libc::c_int; free(name_to_check as *mut libc::c_void); return ret; }
projects/deltachat-core/c/dc_chat.c
* After the creation with dc_create_group_chat() the chat is usually unpromoted * until the first call to dc_send_text_msg() or another sending function. * * With unpromoted chats, members can be added * and settings can be modified without the need of special status messages being sent. * * While the core takes care of the unpromoted state on its own, * checking the state from the UI side may be useful to decide whether a hint as * "Send the first message to allow others to reply within the group" * should be shown to the user or not. * * @memberof dc_chat_t * @param chat The chat object. * @return 1=chat is still unpromoted, no message was ever send to the chat, * 0=chat is not unpromoted, messages were send and/or received * or the chat is not group chat. */ int dc_chat_is_unpromoted(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0); }
projects/deltachat-core/rust/chat.rs
pub fn is_unpromoted(&self) -> bool { self.param.get_bool(Param::Unpromoted).unwrap_or_default() }
pub fn get_bool(&self, key: Param) -> Option<bool> { self.get_int(key).map(|v| v != 0) } pub struct Chat { /// Database ID. pub id: ChatId, /// Chat type, e.g. 1:1 chat, group chat, mailing list. pub typ: Chattype, /// Chat name. pub name: String, /// Whether the chat is archived or pinned. pub visibility: ChatVisibility, /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and /// ad-hoc groups. pub grpid: String, /// Whether the chat is blocked, unblocked or a contact request. pub blocked: Blocked, /// Additional chat parameters stored in the database. pub param: Params, /// If location streaming is enabled in the chat. is_sending_locations: bool, /// Duration of the chat being muted. pub mute_duration: MuteDuration, /// If the chat is protected (verified). pub(crate) protected: ProtectionStatus, } pub struct ChatId(u32); pub enum Param { /// For messages File = b'f', /// For messages: original filename (as shown in chat) Filename = b'v', /// For messages: This name should be shown instead of contact.get_display_name() /// (used if this is a mailinglist /// or explicitly set using set_override_sender_name(), eg. by bots) OverrideSenderDisplayname = b'O', /// For Messages Width = b'w', /// For Messages Height = b'h', /// For Messages Duration = b'd', /// For Messages MimeType = b'm', /// For Messages: HTML to be written to the database and to be send. /// `SendHtml` param is not used for received messages. /// Use `MsgId::get_html()` to get HTML of received messages. SendHtml = b'T', /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send GuaranteeE2ee = b'c', /// For Messages: quoted message is encrypted. /// /// If this message is sent unencrypted, quote text should be replaced. ProtectQuote = b'0', /// For Messages: decrypted with validation errors or without mutual set, if neither /// 'c' nor 'e' are preset, the messages is only transport encrypted. ErroneousE2ee = b'e', /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum. ForcePlaintext = b'u', /// For Messages: do not include Autocrypt header. SkipAutocrypt = b'o', /// For Messages WantsMdn = b'r', /// For Messages: the message is a reaction. Reaction = b'x', /// For Chats: the timestamp of the last reaction. LastReactionTimestamp = b'y', /// For Chats: Message ID of the last reaction. LastReactionMsgId = b'Y', /// For Chats: Contact ID of the last reaction. LastReactionContactId = b'1', /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot"). Bot = b'b', /// For Messages: unset or 0=not forwarded, /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id Forwarded = b'a', /// For Messages: quoted text. Quote = b'q', /// For Messages Cmd = b'S', /// For Messages Arg = b'E', /// For Messages Arg2 = b'F', /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages. Arg3 = b'G', /// Deprecated `Secure-Join-Group` header for messages. Arg4 = b'H', /// For Messages AttachGroupImage = b'A', /// For Messages WebrtcRoom = b'V', /// For Messages: space-separated list of messaged IDs of forwarded copies. /// /// This is used when a [crate::message::Message] is in the /// [crate::message::MessageState::OutPending] state but is already forwarded. /// In this case the forwarded messages are written to the /// database and their message IDs are added to this parameter of /// the original message, which is also saved in the database. /// When the original message is then finally sent this parameter /// is used to also send all the forwarded messages. PrepForwards = b'P', /// For Messages SetLatitude = b'l', /// For Messages SetLongitude = b'n', /// For Groups /// /// An unpromoted group has not had any messages sent to it and thus only exists on the /// creator's device. Any changes made to an unpromoted group do not need to send /// system messages to the group members to update them of the changes. Once a message /// has been sent to a group it is promoted and group changes require sending system /// messages to all members. Unpromoted = b'U', /// For Groups and Contacts ProfileImage = b'i', /// For Chats /// Signals whether the chat is the `saved messages` chat Selftalk = b'K', /// For Chats: On sending a new message we set the subject to `Re: <last subject>`. /// Usually we just use the subject of the parent message, but if the parent message /// is deleted, we use the LastSubject of the chat. LastSubject = b't', /// For Chats Devicetalk = b'D', /// For Chats: If this is a mailing list chat, contains the List-Post address. /// None if there simply is no `List-Post` header in the mailing list. /// Some("") if the mailing list is using multiple different List-Post headers. /// /// The List-Post address is the email address where the user can write to in order to /// post something to the mailing list. ListPost = b'p', /// For Contacts: If this is the List-Post address of a mailing list, contains /// the List-Id of the mailing list (which is also used as the group id of the chat). ListId = b's', /// For Contacts: timestamp of status (aka signature or footer) update. StatusTimestamp = b'j', /// For Contacts and Chats: timestamp of avatar update. AvatarTimestamp = b'J', /// For Chats: timestamp of status/signature/footer update. EphemeralSettingsTimestamp = b'B', /// For Chats: timestamp of subject update. SubjectTimestamp = b'C', /// For Chats: timestamp of group name update. GroupNameTimestamp = b'g', /// For Chats: timestamp of member list update. MemberListTimestamp = b'k', /// For Webxdc Message Instances: Current document name WebxdcDocument = b'R', /// For Webxdc Message Instances: timestamp of document name update. WebxdcDocumentTimestamp = b'W', /// For Webxdc Message Instances: Current summary WebxdcSummary = b'N', /// For Webxdc Message Instances: timestamp of summary update. WebxdcSummaryTimestamp = b'Q', /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration() WebxdcIntegration = b'3', /// For Webxdc Message Instances: Chat to integrate the Webxdc for. WebxdcIntegrateFor = b'2', /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced. ForceSticker = b'X', // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production. }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__78.txt
pub unsafe extern "C" fn dc_create_group_chat( mut context: *mut dc_context_t, mut verified: libc::c_int, mut chat_name: *const libc::c_char, ) -> uint32_t { let mut chat_id: uint32_t = 0 as libc::c_int as uint32_t; let mut draft_txt: *mut libc::c_char = 0 as *mut libc::c_char; let mut draft_msg: *mut dc_msg_t = 0 as *mut dc_msg_t; let mut grpid: *mut libc::c_char = 0 as *mut libc::c_char; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || chat_name.is_null() || *chat_name.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int { return 0 as libc::c_int as uint32_t; } draft_txt = dc_stock_str_repl_string(context, 14 as libc::c_int, chat_name); grpid = dc_create_id(); stmt = dc_sqlite3_prepare( (*context).sql, b"INSERT INTO chats (type, name, grpid, param) VALUES(?, ?, ?, 'U=1');\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int( stmt, 1 as libc::c_int, if verified != 0 { 130 as libc::c_int } else { 120 as libc::c_int }, ); sqlite3_bind_text(stmt, 2 as libc::c_int, chat_name, -(1 as libc::c_int), None); sqlite3_bind_text(stmt, 3 as libc::c_int, grpid, -(1 as libc::c_int), None); if !(sqlite3_step(stmt) != 101 as libc::c_int) { chat_id = dc_sqlite3_get_rowid( (*context).sql, b"chats\0" as *const u8 as *const libc::c_char, b"grpid\0" as *const u8 as *const libc::c_char, grpid, ); if !(chat_id == 0 as libc::c_int as libc::c_uint) { if !(dc_add_to_chat_contacts_table( context, chat_id, 1 as libc::c_int as uint32_t, ) == 0) { draft_msg = dc_msg_new(context, 10 as libc::c_int); dc_msg_set_text(draft_msg, draft_txt); set_draft_raw(context, chat_id, draft_msg); } } } sqlite3_finalize(stmt); free(draft_txt as *mut libc::c_void); dc_msg_unref(draft_msg); free(grpid as *mut libc::c_void); if chat_id != 0 { ((*context).cb) .expect( "non-null function pointer", )( context, 2000 as libc::c_int, 0 as libc::c_int as uintptr_t, 0 as libc::c_int as uintptr_t, ); } return chat_id; }
projects/deltachat-core/c/dc_imex.c
char* dc_imex_has_backup(dc_context_t* context, const char* dir_name) { char* ret = NULL; DIR* dir_handle = NULL; struct dirent* dir_entry = NULL; int prefix_len = strlen(DC_BAK_PREFIX); int suffix_len = strlen(DC_BAK_SUFFIX); char* curr_pathNfilename = NULL; dc_sqlite3_t* test_sql = NULL; char *newest_backup_name = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return NULL; } if ((dir_handle=opendir(dir_name))==NULL) { dc_log_info(context, 0, "Backup check: Cannot open directory \"%s\".", dir_name); /* this is not an error - eg. the directory may not exist or the user has not given us access to read data from the storage */ goto cleanup; } while ((dir_entry=readdir(dir_handle))!=NULL) { const char* name = dir_entry->d_name; /* name without path; may also be `.` or `..` */ int name_len = strlen(name); free(curr_pathNfilename); curr_pathNfilename = dc_mprintf("%s/%s", dir_name, name); if (name_len > prefix_len && strncmp(name, DC_BAK_PREFIX, prefix_len)==0 && name_len > suffix_len && strncmp(&name[name_len-suffix_len-1], "." DC_BAK_SUFFIX, suffix_len)==0) && (newest_backup_name == NULL || strcmp(name, newest_backup_name) > 0) { free(newest_backup_name); newest_backup_name = strdup(name); free(ret); ret = curr_pathNfilename; curr_pathNfilename = NULL; } } cleanup: if (dir_handle) { closedir(dir_handle); } free(curr_pathNfilename); return ret; }
projects/deltachat-core/rust/imex.rs
pub async fn has_backup(_context: &Context, dir_name: &Path) -> Result<String> { let mut dir_iter = tokio::fs::read_dir(dir_name).await?; let mut newest_backup_name = "".to_string(); let mut newest_backup_path: Option<PathBuf> = None; while let Ok(Some(dirent)) = dir_iter.next_entry().await { let path = dirent.path(); let name = dirent.file_name(); let name: String = name.to_string_lossy().into(); if name.starts_with("delta-chat") && name.ends_with(".tar") && (newest_backup_name.is_empty() || name > newest_backup_name) { // We just use string comparison to determine which backup is newer. // This works fine because the filenames have the form `[email protected]` newest_backup_path = Some(path); newest_backup_name = name; } } match newest_backup_path { Some(path) => Ok(path.to_string_lossy().into_owned()), None => bail!("no backup found in {}", dir_name.display()), } }
pub fn is_empty(&self) -> bool { self.inner.is_empty() } pub struct Context { pub(crate) inner: Arc<InnerContext>, }
use std::any::Any; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use ::pgp::types::KeyTrait; use anyhow::{bail, ensure, format_err, Context as _, Result}; use deltachat_contact_tools::EmailAddress; use futures::StreamExt; use futures_lite::FutureExt; use rand::{thread_rng, Rng}; use tokio::fs::{self, File}; use tokio_tar::Archive; use crate::blob::{BlobDirContents, BlobObject}; use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId}; use crate::config::Config; use crate::contact::ContactId; use crate::context::Context; use crate::e2ee; use crate::events::EventType; use crate::key::{ self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey, }; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::pgp; use crate::sql; use crate::stock_str; use crate::tools::{ create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file, }; use transfer::{get_backup, BackupProvider}; use std::time::Duration; use ::pgp::armor::BlockType; use tokio::task; use super::*; use crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE}; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::{alice_keypair, TestContext, TestContextManager};
projects__deltachat-core__rust__imex__.rs__function__2.txt
pub unsafe extern "C" fn dc_imex_has_backup( mut context: *mut dc_context_t, mut dir_name: *const libc::c_char, ) -> *mut libc::c_char { let mut ret: *mut libc::c_char = 0 as *mut libc::c_char; let mut ret_backup_time: time_t = 0 as libc::c_int as time_t; let mut dir_handle: *mut DIR = 0 as *mut DIR; let mut dir_entry: *mut dirent = 0 as *mut dirent; let mut prefix_len: libc::c_int = strlen( b"delta-chat\0" as *const u8 as *const libc::c_char, ) as libc::c_int; let mut suffix_len: libc::c_int = strlen( b"bak\0" as *const u8 as *const libc::c_char, ) as libc::c_int; let mut curr_pathNfilename: *mut libc::c_char = 0 as *mut libc::c_char; let mut test_sql: *mut dc_sqlite3_t = 0 as *mut dc_sqlite3_t; if context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint { return 0 as *mut libc::c_char; } dir_handle = opendir(dir_name); if dir_handle.is_null() { dc_log_info( context, 0 as libc::c_int, b"Backup check: Cannot open directory \"%s\".\0" as *const u8 as *const libc::c_char, dir_name, ); } else { loop { dir_entry = readdir(dir_handle); if dir_entry.is_null() { break; } let mut name: *const libc::c_char = ((*dir_entry).d_name).as_mut_ptr(); let mut name_len: libc::c_int = strlen(name) as libc::c_int; if name_len > prefix_len && strncmp( name, b"delta-chat\0" as *const u8 as *const libc::c_char, prefix_len as libc::c_ulong, ) == 0 as libc::c_int && name_len > suffix_len && strncmp( &*name.offset((name_len - suffix_len - 1 as libc::c_int) as isize), b".bak\0" as *const u8 as *const libc::c_char, suffix_len as libc::c_ulong, ) == 0 as libc::c_int { free(curr_pathNfilename as *mut libc::c_void); curr_pathNfilename = dc_mprintf( b"%s/%s\0" as *const u8 as *const libc::c_char, dir_name, name, ); dc_sqlite3_unref(test_sql); test_sql = dc_sqlite3_new(context); if !test_sql.is_null() && dc_sqlite3_open(test_sql, curr_pathNfilename, 0x1 as libc::c_int) != 0 { let mut curr_backup_time: time_t = dc_sqlite3_get_config_int( test_sql, b"backup_time\0" as *const u8 as *const libc::c_char, 0 as libc::c_int, ) as time_t; if curr_backup_time > 0 as libc::c_int as libc::c_long && curr_backup_time > ret_backup_time { free(ret as *mut libc::c_void); ret = curr_pathNfilename; ret_backup_time = curr_backup_time; curr_pathNfilename = 0 as *mut libc::c_char; } } } } } if !dir_handle.is_null() { closedir(dir_handle); } free(curr_pathNfilename as *mut libc::c_void); dc_sqlite3_unref(test_sql); return ret; }
projects/deltachat-core/c/dc_param.c
int dc_param_exists(dc_param_t* param, int key) { char *p2 = NULL; if (param==NULL || key==0) { return 0; } return find_param(param->packed, key, &p2)? 1 : 0; }
projects/deltachat-core/rust/param.rs
pub fn exists(&self, key: Param) -> bool { self.inner.contains_key(&key) }
pub struct Params { inner: BTreeMap<Param, String>, }
use std::collections::BTreeMap; use std::fmt; use std::path::PathBuf; use std::str; use anyhow::{bail, Error, Result}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use crate::blob::BlobObject; use crate::context::Context; use crate::mimeparser::SystemMessage; use std::path::Path; use std::str::FromStr; use tokio::fs; use super::*; use crate::test_utils::TestContext;
projects__deltachat-core__rust__param__.rs__function__5.txt
pub unsafe extern "C" fn dc_param_exists( mut param: *mut dc_param_t, mut key: libc::c_int, ) -> libc::c_int { let mut p2: *mut libc::c_char = 0 as *mut libc::c_char; if param.is_null() || key == 0 as libc::c_int { return 0 as libc::c_int; } return if !(find_param((*param).packed, key, &mut p2)).is_null() { 1 as libc::c_int } else { 0 as libc::c_int }; }
projects/deltachat-core/c/dc_imex.c
int dc_continue_key_transfer(dc_context_t* context, uint32_t msg_id, const char* setup_code) { int success = 0; dc_msg_t* msg = NULL; char* filename = NULL; char* filecontent = NULL; size_t filebytes = 0; char* armored_key = NULL; char* norm_sc = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_id <= DC_MSG_ID_LAST_SPECIAL || setup_code==NULL) { goto cleanup; } if ((msg=dc_get_msg(context, msg_id))==NULL || !dc_msg_is_setupmessage(msg) || (filename=dc_msg_get_file(msg))==NULL || filename[0]==0) { dc_log_error(context, 0, "Message is no Autocrypt Setup Message."); goto cleanup; } if (!dc_read_file(context, filename, (void**)&filecontent, &filebytes) || filecontent==NULL || filebytes <= 0) { dc_log_error(context, 0, "Cannot read Autocrypt Setup Message file."); goto cleanup; } if ((norm_sc = dc_normalize_setup_code(context, setup_code))==NULL) { dc_log_warning(context, 0, "Cannot normalize Setup Code."); goto cleanup; } if ((armored_key=dc_decrypt_setup_file(context, norm_sc, filecontent))==NULL) { dc_log_warning(context, 0, "Cannot decrypt Autocrypt Setup Message."); /* do not log as error - this is quite normal after entering the bad setup code */ goto cleanup; } if (!set_self_key(context, armored_key, 1/*set default*/)) { goto cleanup; /* error already logged */ } success = 1; cleanup: free(armored_key); free(filecontent); free(filename); dc_msg_unref(msg); free(norm_sc); return success; }
projects/deltachat-core/rust/imex.rs
pub async fn continue_key_transfer( context: &Context, msg_id: MsgId, setup_code: &str, ) -> Result<()> { ensure!(!msg_id.is_special(), "wrong id"); let msg = Message::load_from_db(context, msg_id).await?; ensure!( msg.is_setupmessage(), "Message is no Autocrypt Setup Message." ); if let Some(filename) = msg.get_file(context) { let file = open_file_std(context, filename)?; let sc = normalize_setup_code(setup_code); let armored_key = decrypt_setup_file(&sc, file).await?; set_self_key(context, &armored_key, true).await?; maybe_add_bcc_self_device_msg(context).await?; Ok(()) } else { bail!("Message is no Autocrypt Setup Message."); } }
pub fn is_special(self) -> bool { self.0 <= DC_MSG_ID_LAST_SPECIAL } pub async fn load_from_db(context: &Context, id: MsgId) -> Result<Message> { let message = Self::load_from_db_optional(context, id) .await? .with_context(|| format!("Message {id} does not exist"))?; Ok(message) } fn normalize_setup_code(s: &str) -> String { let mut out = String::new(); for c in s.chars() { if c.is_ascii_digit() { out.push(c); if let 4 | 9 | 14 | 19 | 24 | 29 | 34 | 39 = out.len() { out += "-" } } } out } pub fn open_file_std(context: &Context, path: impl AsRef<Path>) -> Result<std::fs::File> { let path_abs = get_abs_path(context, path.as_ref()); match std::fs::File::open(path_abs) { Ok(bytes) => Ok(bytes), Err(err) => { warn!( context, "Cannot read \"{}\" or file is empty: {}", path.as_ref().display(), err ); Err(err.into()) } } } pub fn get_file(&self, context: &Context) -> Option<PathBuf> { self.param.get_path(Param::File, context).unwrap_or(None) } async fn set_self_key(context: &Context, armored: &str, set_default: bool) -> Result<()> { // try hard to only modify key-state let (private_key, header) = SignedSecretKey::from_asc(armored)?; let public_key = private_key.split_public_key()?; if let Some(preferencrypt) = header.get("Autocrypt-Prefer-Encrypt") { let e2ee_enabled = match preferencrypt.as_str() { "nopreference" => 0, "mutual" => 1, _ => { bail!("invalid Autocrypt-Prefer-Encrypt header: {:?}", header); } }; context .sql .set_raw_config_int("e2ee_enabled", e2ee_enabled) .await?; } else { // `Autocrypt-Prefer-Encrypt` is not included // in keys exported to file. // // `Autocrypt-Prefer-Encrypt` also SHOULD be sent // in Autocrypt Setup Message according to Autocrypt specification, // but K-9 6.802 does not include this header. // // We keep current setting in this case. info!(context, "No Autocrypt-Prefer-Encrypt header."); }; let self_addr = context.get_primary_self_addr().await?; let addr = EmailAddress::new(&self_addr)?; let keypair = pgp::KeyPair { addr, public: public_key, secret: private_key, }; key::store_self_keypair( context, &keypair, if set_default { key::KeyPairUse::Default } else { key::KeyPairUse::ReadOnly }, ) .await?; info!(context, "stored self key: {:?}", keypair.secret.key_id()); Ok(()) } async fn maybe_add_bcc_self_device_msg(context: &Context) -> Result<()> { if !context.sql.get_raw_config_bool("bcc_self").await? { let mut msg = Message::new(Viewtype::Text); // TODO: define this as a stockstring once the wording is settled. msg.text = "It seems you are using multiple devices with Delta Chat. Great!\n\n\ If you also want to synchronize outgoing messages across all devices, \ go to \"Settings → Advanced\" and enable \"Send Copy to Self\"." .to_string(); chat::add_device_msg(context, Some("bcc-self-hint"), Some(&mut msg)).await?; } Ok(()) } async fn decrypt_setup_file<T: std::io::Read + std::io::Seek>( passphrase: &str, file: T, ) -> Result<String> { let plain_bytes = pgp::symm_decrypt(passphrase, file).await?; let plain_text = std::string::String::from_utf8(plain_bytes)?; Ok(plain_text) } pub struct MsgId(u32); pub struct Context { pub(crate) inner: Arc<InnerContext>, }
use std::any::Any; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use ::pgp::types::KeyTrait; use anyhow::{bail, ensure, format_err, Context as _, Result}; use deltachat_contact_tools::EmailAddress; use futures::StreamExt; use futures_lite::FutureExt; use rand::{thread_rng, Rng}; use tokio::fs::{self, File}; use tokio_tar::Archive; use crate::blob::{BlobDirContents, BlobObject}; use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId}; use crate::config::Config; use crate::contact::ContactId; use crate::context::Context; use crate::e2ee; use crate::events::EventType; use crate::key::{ self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey, }; use crate::log::LogExt; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::pgp; use crate::sql; use crate::stock_str; use crate::tools::{ create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file, }; use transfer::{get_backup, BackupProvider}; use std::time::Duration; use ::pgp::armor::BlockType; use tokio::task; use super::*; use crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE}; use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::{alice_keypair, TestContext, TestContextManager};
projects__deltachat-core__rust__imex__.rs__function__7.txt
pub unsafe extern "C" fn dc_continue_key_transfer( mut context: *mut dc_context_t, mut msg_id: uint32_t, mut setup_code: *const libc::c_char, ) -> libc::c_int { let mut success: libc::c_int = 0 as libc::c_int; let mut msg: *mut dc_msg_t = 0 as *mut dc_msg_t; let mut filename: *mut libc::c_char = 0 as *mut libc::c_char; let mut filecontent: *mut libc::c_char = 0 as *mut libc::c_char; let mut filebytes: size_t = 0 as libc::c_int as size_t; let mut armored_key: *mut libc::c_char = 0 as *mut libc::c_char; let mut norm_sc: *mut libc::c_char = 0 as *mut libc::c_char; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || msg_id <= 9 as libc::c_int as libc::c_uint || setup_code.is_null()) { msg = dc_get_msg(context, msg_id); if msg.is_null() || dc_msg_is_setupmessage(msg) == 0 || { filename = dc_msg_get_file(msg); filename.is_null() } || *filename.offset(0 as libc::c_int as isize) as libc::c_int == 0 as libc::c_int { dc_log_error( context, 0 as libc::c_int, b"Message is no Autocrypt Setup Message.\0" as *const u8 as *const libc::c_char, ); } else if dc_read_file( context, filename, &mut filecontent as *mut *mut libc::c_char as *mut *mut libc::c_void, &mut filebytes, ) == 0 || filecontent.is_null() || filebytes <= 0 as libc::c_int as libc::c_ulong { dc_log_error( context, 0 as libc::c_int, b"Cannot read Autocrypt Setup Message file.\0" as *const u8 as *const libc::c_char, ); } else { norm_sc = dc_normalize_setup_code(context, setup_code); if norm_sc.is_null() { dc_log_warning( context, 0 as libc::c_int, b"Cannot normalize Setup Code.\0" as *const u8 as *const libc::c_char, ); } else { armored_key = dc_decrypt_setup_file(context, norm_sc, filecontent); if armored_key.is_null() { dc_log_warning( context, 0 as libc::c_int, b"Cannot decrypt Autocrypt Setup Message.\0" as *const u8 as *const libc::c_char, ); } else if !(set_self_key(context, armored_key, 1 as libc::c_int) == 0) { success = 1 as libc::c_int; } } } } free(armored_key as *mut libc::c_void); free(filecontent as *mut libc::c_void); free(filename as *mut libc::c_void); dc_msg_unref(msg); free(norm_sc as *mut libc::c_void); return success; }
projects/deltachat-core/c/dc_contact.c
* Known and unblocked contacts will be returned by dc_get_contacts(). * * To validate an e-mail address independently of the contact database * use dc_may_be_valid_addr(). * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @param addr The e-mail-address to check. * @return 1=address is a contact in use, 0=address is not a contact in use. */ uint32_t dc_lookup_contact_id_by_addr(dc_context_t* context, const char* addr) { int contact_id = 0; char* addr_normalized = NULL; char* addr_self = NULL; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || addr==NULL || addr[0]==0) { goto cleanup; } addr_normalized = dc_addr_normalize(addr); addr_self = dc_sqlite3_get_config(context->sql, "configured_addr", ""); if (strcasecmp(addr_normalized, addr_self)==0) { contact_id = DC_CONTACT_ID_SELF; goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM contacts" " WHERE addr=?1 COLLATE NOCASE" " AND id>?2 AND origin>=?3 AND blocked=0;"); sqlite3_bind_text(stmt, 1, (const char*)addr_normalized, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 2, DC_CONTACT_ID_LAST_SPECIAL); sqlite3_bind_int (stmt, 3, DC_ORIGIN_MIN_CONTACT_LIST); if (sqlite3_step(stmt)==SQLITE_ROW) { contact_id = sqlite3_column_int(stmt, 0); } cleanup: sqlite3_finalize(stmt); free(addr_normalized); free(addr_self); return contact_id; }
projects/deltachat-core/rust/contact.rs
pub async fn lookup_id_by_addr( context: &Context, addr: &str, min_origin: Origin, ) -> Result<Option<ContactId>> { Self::lookup_id_by_addr_ex(context, addr, min_origin, Some(Blocked::Not)).await }
pub(crate) async fn lookup_id_by_addr_ex( context: &Context, addr: &str, min_origin: Origin, blocked: Option<Blocked>, ) -> Result<Option<ContactId>> { if addr.is_empty() { bail!("lookup_id_by_addr: empty address"); } let addr_normalized = addr_normalize(addr); if context.is_self_addr(&addr_normalized).await? { return Ok(Some(ContactId::SELF)); } let id = context .sql .query_get_value( "SELECT id FROM contacts \ WHERE addr=?1 COLLATE NOCASE \ AND id>?2 AND origin>=?3 AND (? OR blocked=?)", ( &addr_normalized, ContactId::LAST_SPECIAL, min_origin as u32, blocked.is_none(), blocked.unwrap_or_default(), ), ) .await?; Ok(id) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct ContactId(u32); pub struct Contact { /// The contact ID. pub id: ContactId, /// Contact name. It is recommended to use `Contact::get_name`, /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field. /// May be empty, initially set to `authname`. name: String, /// Name authorized by the contact himself. Only this name may be spread to others, /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`, /// to access this field. authname: String, /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. last_seen: i64, /// The origin/source of the contact. pub origin: Origin, /// Parameters as Param::ProfileImage pub param: Params, /// Last seen message signature for this contact, to be displayed in the profile. status: String, /// If the contact is a bot. is_bot: bool, }
use std::cmp::{min, Reverse}; use std::collections::BinaryHeap; use std::fmt; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; use anyhow::{bail, ensure, Context as _, Result}; use async_channel::{self as channel, Receiver, Sender}; use base64::Engine as _; use deltachat_contact_tools::may_be_valid_addr; use deltachat_contact_tools::{ self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters, ContactAddress, VcardContact, }; use deltachat_derive::{FromSql, ToSql}; use rusqlite::OptionalExtension; use serde::{Deserialize, Serialize}; use tokio::task; use tokio::time::{timeout, Duration}; use crate::aheader::{Aheader, EncryptPreference}; use crate::blob::BlobObject; use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus}; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; use crate::events::EventType; use crate::key::{load_self_public_key, DcKey, SignedPublicKey}; use crate::log::LogExt; use crate::login_param::LoginParam; use crate::message::MessageState; use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::sql::{self, params_iter}; use crate::sync::{self, Sync::*}; use crate::tools::{ duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime, }; use crate::{chat, chatlist_events, stock_str}; use deltachat_contact_tools::{may_be_valid_addr, normalize_name}; use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext, TestContextManager};
projects__deltachat-core__rust__contact__.rs__function__24.txt
pub unsafe extern "C" fn dc_get_contacts( mut context: *mut dc_context_t, mut listflags: uint32_t, mut query: *const libc::c_char, ) -> *mut dc_array_t { let mut current_block: u64; let mut self_addr: *mut libc::c_char = 0 as *mut libc::c_char; let mut self_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut self_name2: *mut libc::c_char = 0 as *mut libc::c_char; let mut add_self: libc::c_int = 0 as libc::c_int; let mut ret: *mut dc_array_t = dc_array_new(context, 100 as libc::c_int as size_t); let mut s3strLikeCmd: *mut libc::c_char = 0 as *mut libc::c_char; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint) { self_addr = dc_sqlite3_get_config( (*context).sql, b"configured_addr\0" as *const u8 as *const libc::c_char, b"\0" as *const u8 as *const libc::c_char, ); if listflags & 0x1 as libc::c_int as libc::c_uint != 0 || !query.is_null() { s3strLikeCmd = sqlite3_mprintf( b"%%%s%%\0" as *const u8 as *const libc::c_char, if !query.is_null() { query } else { b"\0" as *const u8 as *const libc::c_char }, ); if s3strLikeCmd.is_null() { current_block = 6126847215165972376; } else { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT c.id FROM contacts c LEFT JOIN acpeerstates ps ON c.addr=ps.addr WHERE c.addr!=?1 AND c.id>?2 AND c.origin>=?3 AND c.blocked=0 AND (c.name LIKE ?4 OR c.addr LIKE ?5) AND (1=?6 OR LENGTH(ps.verified_key_fingerprint)!=0) ORDER BY LOWER(c.name||c.addr),c.id;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_text( stmt, 1 as libc::c_int, self_addr, -(1 as libc::c_int), None, ); sqlite3_bind_int(stmt, 2 as libc::c_int, 9 as libc::c_int); sqlite3_bind_int(stmt, 3 as libc::c_int, 0x100 as libc::c_int); sqlite3_bind_text( stmt, 4 as libc::c_int, s3strLikeCmd, -(1 as libc::c_int), None, ); sqlite3_bind_text( stmt, 5 as libc::c_int, s3strLikeCmd, -(1 as libc::c_int), None, ); sqlite3_bind_int( stmt, 6 as libc::c_int, if listflags & 0x1 as libc::c_int as libc::c_uint != 0 { 0 as libc::c_int } else { 1 as libc::c_int }, ); self_name = dc_sqlite3_get_config( (*context).sql, b"displayname\0" as *const u8 as *const libc::c_char, b"\0" as *const u8 as *const libc::c_char, ); self_name2 = dc_stock_str(context, 2 as libc::c_int); if query.is_null() || dc_str_contains(self_addr, query) != 0 || dc_str_contains(self_name, query) != 0 || dc_str_contains(self_name2, query) != 0 { add_self = 1 as libc::c_int; } current_block = 13242334135786603907; } } else { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT id FROM contacts WHERE addr!=?1 AND id>?2 AND origin>=?3 AND blocked=0 ORDER BY LOWER(name||addr),id;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_text( stmt, 1 as libc::c_int, self_addr, -(1 as libc::c_int), None, ); sqlite3_bind_int(stmt, 2 as libc::c_int, 9 as libc::c_int); sqlite3_bind_int(stmt, 3 as libc::c_int, 0x100 as libc::c_int); add_self = 1 as libc::c_int; current_block = 13242334135786603907; } match current_block { 6126847215165972376 => {} _ => { while sqlite3_step(stmt) == 100 as libc::c_int { dc_array_add_id( ret, sqlite3_column_int(stmt, 0 as libc::c_int) as uint32_t, ); } if listflags & 0x2 as libc::c_int as libc::c_uint != 0 && add_self != 0 { dc_array_add_id(ret, 1 as libc::c_int as uint32_t); } } } } sqlite3_finalize(stmt); sqlite3_free(s3strLikeCmd as *mut libc::c_void); free(self_addr as *mut libc::c_void); free(self_name as *mut libc::c_void); free(self_name2 as *mut libc::c_void); return ret; }
projects/deltachat-core/c/dc_msg.c
int dc_msg_get_info_type(const dc_msg_t* msg) { return dc_param_get_int(msg->param, DC_PARAM_CMD, 0); }
projects/deltachat-core/rust/message.rs
pub fn get_info_type(&self) -> SystemMessage { self.param.get_cmd() }
pub fn get_cmd(&self) -> SystemMessage { self.get_int(Param::Cmd) .and_then(SystemMessage::from_i32) .unwrap_or_default() } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__57.txt
projects/deltachat-core/c/dc_msg.c
void dc_update_msg_state(dc_context_t* context, uint32_t msg_id, int state) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET state=? WHERE id=? AND (?=? OR state<?)"); sqlite3_bind_int(stmt, 1, state); sqlite3_bind_int(stmt, 2, msg_id); sqlite3_bind_int(stmt, 3, state); sqlite3_bind_int(stmt, 4, DC_STATE_OUT_DELIVERED); sqlite3_bind_int(stmt, 5, DC_STATE_OUT_DELIVERED); sqlite3_step(stmt); sqlite3_finalize(stmt); }
projects/deltachat-core/rust/message.rs
pub(crate) async fn update_msg_state( context: &Context, msg_id: MsgId, state: MessageState, ) -> Result<()> { ensure!(state != MessageState::OutFailed, "use set_msg_failed()!"); let error_subst = match state >= MessageState::OutPending { true => ", error=''", false => "", }; context .sql .execute( &format!("UPDATE msgs SET state=?1 {error_subst} WHERE id=?2 AND (?1!=?3 OR state<?3)"), (state, msg_id, MessageState::OutDelivered), ) .await?; Ok(()) }
pub async fn execute( &self, query: &str, params: impl rusqlite::Params + Send, ) -> Result<usize> { self.call_write(move |conn| { let res = conn.execute(query, params)?; Ok(res) }) .await } pub struct MsgId(u32); pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, } pub enum MessageState { /// Undefined message state. #[default] Undefined = 0, /// Incoming *fresh* message. Fresh messages are neither noticed /// nor seen and are typically shown in notifications. InFresh = 10, /// Incoming *noticed* message. E.g. chat opened but message not /// yet read - noticed messages are not counted as unread but did /// not marked as read nor resulted in MDNs. InNoticed = 13, /// Incoming message, really *seen* by the user. Marked as read on /// IMAP and MDN may be sent. InSeen = 16, /// For files which need time to be prepared before they can be /// sent, the message enters this state before /// OutPending. OutPreparing = 18, /// Message saved as draft. OutDraft = 19, /// The user has pressed the "send" button but the message is not /// yet sent and is pending in some way. Maybe we're offline (no /// checkmark). OutPending = 20, /// *Unrecoverable* error (*recoverable* errors result in pending /// messages). OutFailed = 24, /// Outgoing message successfully delivered to server (one /// checkmark). Note, that already delivered messages may get into /// the OutFailed state if we get such a hint from the server. OutDelivered = 26, /// Outgoing message read by the recipient (two checkmarks; this /// requires goodwill on the receiver's side) OutMdnRcvd = 28, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__91.txt
pub unsafe extern "C" fn dc_update_msg_state( mut context: *mut dc_context_t, mut msg_id: uint32_t, mut state: libc::c_int, ) { let mut stmt: *mut sqlite3_stmt = dc_sqlite3_prepare( (*context).sql, b"UPDATE msgs SET state=? WHERE id=?;\0" as *const u8 as *const libc::c_char, ); sqlite3_bind_int(stmt, 1 as libc::c_int, state); sqlite3_bind_int(stmt, 2 as libc::c_int, msg_id as libc::c_int); sqlite3_step(stmt); sqlite3_finalize(stmt); }
projects/deltachat-core/c/dc_chat.c
size_t dc_get_chat_cnt(dc_context_t* context) { size_t ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql->cobj==NULL) { goto cleanup; /* no database, no chats - this is no error (needed eg. for information) */ } stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM chats WHERE id>" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) " AND blocked=0;"); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/rust/chat.rs
pub(crate) async fn get_chat_cnt(context: &Context) -> Result<usize> { if context.sql.is_open().await { // no database, no chats - this is no error (needed eg. for information) let count = context .sql .count("SELECT COUNT(*) FROM chats WHERE id>9 AND blocked=0;", ()) .await?; Ok(count) } else { Ok(0) } }
pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result<usize> { let count: isize = self.query_row(query, params, |row| row.get(0)).await?; Ok(usize::try_from(count)?) } pub async fn is_open(&self) -> bool { self.sql.is_open().await } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct InnerContext { /// Blob directory path pub(crate) blobdir: PathBuf, pub(crate) sql: Sql, pub(crate) smeared_timestamp: SmearedTimestamp, /// The global "ongoing" process state. /// /// This is a global mutex-like state for operations which should be modal in the /// clients. running_state: RwLock<RunningState>, /// Mutex to avoid generating the key for the user more than once. pub(crate) generating_key_mutex: Mutex<()>, /// Mutex to enforce only a single running oauth2 is running. pub(crate) oauth2_mutex: Mutex<()>, /// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent. pub(crate) wrong_pw_warning_mutex: Mutex<()>, pub(crate) translated_stockstrings: StockStrings, pub(crate) events: Events, pub(crate) scheduler: SchedulerState, pub(crate) ratelimit: RwLock<Ratelimit>, /// Recently loaded quota information, if any. /// Set to `None` if quota was never tried to load. pub(crate) quota: RwLock<Option<QuotaInfo>>, /// IMAP UID resync request. pub(crate) resync_request: AtomicBool, /// Notify about new messages. /// /// This causes [`Context::wait_next_msgs`] to wake up. pub(crate) new_msgs_notify: Notify, /// Server ID response if ID capability is supported /// and the server returned non-NIL on the inbox connection. /// <https://datatracker.ietf.org/doc/html/rfc2971> pub(crate) server_id: RwLock<Option<HashMap<String, String>>>, /// IMAP METADATA. pub(crate) metadata: RwLock<Option<ServerMetadata>>, pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>, /// ID for this `Context` in the current process. /// /// This allows for multiple `Context`s open in a single process where each context can /// be identified by this ID. pub(crate) id: u32, creation_time: tools::Time, /// The text of the last error logged and emitted as an event. /// If the ui wants to display an error after a failure, /// `last_error` should be used to avoid races with the event thread. pub(crate) last_error: std::sync::RwLock<String>, /// If debug logging is enabled, this contains all necessary information /// /// Standard RwLock instead of [`tokio::sync::RwLock`] is used /// because the lock is used from synchronous [`Context::emit_event`]. pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>, /// Push subscriber to store device token /// and register for heartbeat notifications. pub(crate) push_subscriber: PushSubscriber, /// True if account has subscribed to push notifications via IMAP. pub(crate) push_subscribed: AtomicBool, /// Iroh for realtime peer channels. pub(crate) iroh: OnceCell<Iroh>, }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use anyhow::{anyhow, bail, ensure, Context as _, Result}; use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use tokio::task; use crate::aheader::EncryptPreference; use crate::blob::BlobObject; use crate::chatlist::Chatlist; use crate::chatlist_events; use crate::color::str_to_color; use crate::config::Config; use crate::constants::{ self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS, }; use crate::contact::{self, Contact, ContactId, Origin}; use crate::context::Context; use crate::debug_logging::maybe_set_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; use crate::location; use crate::log::LogExt; use crate::message::{self, Message, MessageState, MsgId, Viewtype}; use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::Peerstate; use crate::receive_imf::ReceivedMsg; use crate::securejoin::BobState; use crate::smtp::send_msg_to_smtp; use crate::sql; use crate::stock_str; use crate::sync::{self, Sync::*, SyncData}; use crate::tools::{ buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input, smeared_time, time, IsNoneOrEmpty, SystemTime, }; use crate::webxdc::WEBXDC_SUFFIX; use CantSendReason::*; use super::*; use crate::chatlist::get_archived_cnt; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::message::delete_msgs; use crate::receive_imf::receive_imf; use crate::test_utils::{sync, TestContext, TestContextManager}; use strum::IntoEnumIterator; use tokio::fs;
projects__deltachat-core__rust__chat__.rs__function__141.txt
pub unsafe extern "C" fn dc_get_chat_cnt(mut context: *mut dc_context_t) -> size_t { let mut ret: size_t = 0 as libc::c_int as size_t; let mut stmt: *mut sqlite3_stmt = 0 as *mut sqlite3_stmt; if !(context.is_null() || (*context).magic != 0x11a11807 as libc::c_int as libc::c_uint || ((*(*context).sql).cobj).is_null()) { stmt = dc_sqlite3_prepare( (*context).sql, b"SELECT COUNT(*) FROM chats WHERE id>9 AND blocked=0;\0" as *const u8 as *const libc::c_char, ); if !(sqlite3_step(stmt) != 100 as libc::c_int) { ret = sqlite3_column_int(stmt, 0 as libc::c_int) as size_t; } } sqlite3_finalize(stmt); return ret; }
projects/deltachat-core/c/dc_msg.c
dc_lot_t* dc_msg_get_summary(const dc_msg_t* msg, const dc_chat_t* chat) { dc_lot_t* ret = dc_lot_new(); dc_contact_t* contact = NULL; dc_chat_t* chat_to_delete = NULL; if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { goto cleanup; } if (chat==NULL) { if ((chat_to_delete=dc_get_chat(msg->context, msg->chat_id))==NULL) { goto cleanup; } chat = chat_to_delete; } if (msg->from_id!=DC_CONTACT_ID_SELF && DC_CHAT_TYPE_IS_MULTI(chat->type)) { contact = dc_get_contact(chat->context, msg->from_id); } dc_lot_fill(ret, msg, chat, contact, msg->context); cleanup: dc_contact_unref(contact); dc_chat_unref(chat_to_delete); return ret; }
projects/deltachat-core/rust/message.rs
pub async fn get_summary(&self, context: &Context, chat: Option<&Chat>) -> Result<Summary> { let chat_loaded: Chat; let chat = if let Some(chat) = chat { chat } else { let chat = Chat::load_from_db(context, self.chat_id).await?; chat_loaded = chat; &chat_loaded }; let contact = if self.from_id != ContactId::SELF { match chat.typ { Chattype::Group | Chattype::Broadcast | Chattype::Mailinglist => { Some(Contact::get_by_id(context, self.from_id).await?) } Chattype::Single => None, } } else { None }; Summary::new(context, self, chat, contact.as_ref()).await }
pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> { let mut chat = context .sql .query_row( "SELECT c.type, c.name, c.grpid, c.param, c.archived, c.blocked, c.locations_send_until, c.muted_until, c.protected FROM chats c WHERE c.id=?;", (chat_id,), |row| { let c = Chat { id: chat_id, typ: row.get(0)?, name: row.get::<_, String>(1)?, grpid: row.get::<_, String>(2)?, param: row.get::<_, String>(3)?.parse().unwrap_or_default(), visibility: row.get(4)?, blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(), is_sending_locations: row.get(6)?, mute_duration: row.get(7)?, protected: row.get(8)?, }; Ok(c) }, ) .await .context(format!("Failed loading chat {chat_id} from database"))?; if chat.id.is_archived_link() { chat.name = stock_str::archived_chats(context).await; } else { if chat.typ == Chattype::Single && chat.name.is_empty() { // chat.name is set to contact.display_name on changes, // however, if things went wrong somehow, we do this here explicitly. let mut chat_name = "Err [Name not found]".to_owned(); match get_chat_contacts(context, chat.id).await { Ok(contacts) => { if let Some(contact_id) = contacts.first() { if let Ok(contact) = Contact::get_by_id(context, *contact_id).await { contact.get_display_name().clone_into(&mut chat_name); } } } Err(err) => { error!( context, "Failed to load contacts for {}: {:#}.", chat.id, err ); } } chat.name = chat_name; } if chat.param.exists(Param::Selftalk) { chat.name = stock_str::saved_messages(context).await; } else if chat.param.exists(Param::Devicetalk) { chat.name = stock_str::device_messages(context).await; } } Ok(chat) } pub async fn new( context: &Context, msg: &Message, chat: &Chat, contact: Option<&Contact>, ) -> Result<Summary> { let prefix = if msg.state == MessageState::OutDraft { Some(SummaryPrefix::Draft(stock_str::draft(context).await)) } else if msg.from_id == ContactId::SELF { if msg.is_info() || chat.is_self_talk() { None } else { Some(SummaryPrefix::Me(stock_str::self_msg(context).await)) } } else { match chat.typ { Chattype::Group | Chattype::Broadcast | Chattype::Mailinglist => { if msg.is_info() || contact.is_none() { None } else { msg.get_override_sender_name() .or_else(|| contact.map(|contact| msg.get_sender_name(contact))) .map(SummaryPrefix::Username) } } Chattype::Single => None, } }; let mut text = msg.get_summary_text(context).await; if text.is_empty() && msg.quoted_text().is_some() { text = stock_str::reply_noun(context).await } let thumbnail_path = if msg.viewtype == Viewtype::Image || msg.viewtype == Viewtype::Gif || msg.viewtype == Viewtype::Sticker { msg.get_file(context) .and_then(|path| path.to_str().map(|p| p.to_owned())) } else { None }; Ok(Summary { prefix, text, timestamp: msg.get_timestamp(), state: msg.state, thumbnail_path, }) pub async fn get_by_id(context: &Context, contact_id: ContactId) -> Result<Self> { let contact = Self::get_by_id_optional(context, contact_id) .await? .with_context(|| format!("contact {contact_id} not found"))?; Ok(contact) } pub struct Context { pub(crate) inner: Arc<InnerContext>, } pub struct Message { /// Message ID. pub(crate) id: MsgId, /// `From:` contact ID. pub(crate) from_id: ContactId, /// ID of the first contact in the `To:` header. pub(crate) to_id: ContactId, /// ID of the chat message belongs to. pub(crate) chat_id: ChatId, /// Type of the message. pub(crate) viewtype: Viewtype, /// State of the message. pub(crate) state: MessageState, pub(crate) download_state: DownloadState, /// Whether the message is hidden. pub(crate) hidden: bool, pub(crate) timestamp_sort: i64, pub(crate) timestamp_sent: i64, pub(crate) timestamp_rcvd: i64, pub(crate) ephemeral_timer: EphemeralTimer, pub(crate) ephemeral_timestamp: i64, pub(crate) text: String, /// Message subject. /// /// If empty, a default subject will be generated when sending. pub(crate) subject: String, /// `Message-ID` header value. pub(crate) rfc724_mid: String, /// `In-Reply-To` header value. pub(crate) in_reply_to: Option<String>, pub(crate) is_dc_message: MessengerMessage, pub(crate) mime_modified: bool, pub(crate) chat_blocked: Blocked, pub(crate) location_id: u32, pub(crate) error: Option<String>, pub(crate) param: Params, } pub struct Summary { /// Part displayed before ":", such as an username or a string "Draft". pub prefix: Option<SummaryPrefix>, /// Summary text, always present. pub text: String, /// Message timestamp. pub timestamp: i64, /// Message state. pub state: MessageState, /// Message preview image path pub thumbnail_path: Option<String>, } pub struct ContactId(u32); impl ContactId { /// Undefined contact. Used as a placeholder for trashed messages. pub const UNDEFINED: ContactId = ContactId::new(0); /// The owner of the account. /// /// The email-address is set by `set_config` using "addr". pub const SELF: ContactId = ContactId::new(1); /// ID of the contact for info messages. pub const INFO: ContactId = ContactId::new(2); /// ID of the contact for device messages. pub const DEVICE: ContactId = ContactId::new(5); pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9); /// Address to go with [`ContactId::DEVICE`]. /// /// This is used by APIs which need to return an email address for this contact. pub const DEVICE_ADDR: &'static str = "device@localhost"; } pub enum Chattype { /// 1:1 chat. Single = 100, /// Group chat. Group = 120, /// Mailing list. Mailinglist = 140, /// Broadcast list. Broadcast = 160, }
use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use anyhow::{ensure, format_err, Context as _, Result}; use deltachat_contact_tools::{parse_vcard, VcardContact}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use tokio::{fs, io}; use crate::blob::BlobObject; use crate::chat::{Chat, ChatId, ChatIdBlocked}; use crate::chatlist_events; use crate::config::Config; use crate::constants::{ Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL, }; use crate::contact::{Contact, ContactId}; use crate::context::Context; use crate::debug_logging::set_debug_logging_xdc; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; use crate::imap::markseen_on_imap_table; use crate::location::delete_poi_location; use crate::mimeparser::{parse_message_id, SystemMessage}; use crate::param::{Param, Params}; use crate::pgp::split_armored_data; use crate::reaction::get_msg_reactions; use crate::sql; use crate::summary::Summary; use crate::tools::{ buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time, timestamp_to_str, truncate, }; use MessageState::*; use MessageState::*; use num_traits::FromPrimitive; use super::*; use crate::chat::{ self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus, }; use crate::chatlist::Chatlist; use crate::config::Config; use crate::reaction::send_reaction; use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::{TestContext, TestContextManager};
projects__deltachat-core__rust__message__.rs__function__50.txt
pub unsafe extern "C" fn dc_msg_get_summary( mut msg: *const dc_msg_t, mut chat: *const dc_chat_t, ) -> *mut dc_lot_t { let mut current_block: u64; let mut ret: *mut dc_lot_t = dc_lot_new(); let mut contact: *mut dc_contact_t = 0 as *mut dc_contact_t; let mut chat_to_delete: *mut dc_chat_t = 0 as *mut dc_chat_t; if !(msg.is_null() || (*msg).magic != 0x11561156 as libc::c_int as libc::c_uint) { if chat.is_null() { chat_to_delete = dc_get_chat((*msg).context, (*msg).chat_id); if chat_to_delete.is_null() { current_block = 1657710228249902046; } else { chat = chat_to_delete; current_block = 6873731126896040597; } } else { current_block = 6873731126896040597; } match current_block { 1657710228249902046 => {} _ => { if (*msg).from_id != 1 as libc::c_int as libc::c_uint && ((*chat).type_0 == 120 as libc::c_int || (*chat).type_0 == 130 as libc::c_int) { contact = dc_get_contact((*chat).context, (*msg).from_id); } dc_lot_fill(ret, msg, chat, contact, (*msg).context); } } } dc_contact_unref(contact); dc_chat_unref(chat_to_delete); return ret; }