{"c_path": "projects/deltachat-core/c/dc_oauth2.c", "c_func": "char* dc_get_oauth2_addr(dc_context_t* context, const char* addr,\n const char* code)\n{\n\tchar* access_token = NULL;\n\tchar* addr_out = NULL;\n\toauth2_t* oauth2 = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC\n\t || (oauth2=get_info(addr))==NULL || oauth2->get_userinfo==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\taccess_token = dc_get_oauth2_access_token(context, addr, code, 0);\n\taddr_out = get_oauth2_addr(context, oauth2, access_token);\n\tif (addr_out==NULL) {\n\t\tfree(access_token);\n\t\taccess_token = dc_get_oauth2_access_token(context, addr, code, DC_REGENERATE);\n\t\taddr_out = get_oauth2_addr(context, oauth2, access_token);\n\t}\n\ncleanup:\n\tfree(access_token);\n\tfree(oauth2);\n\treturn addr_out;\n}", "rust_path": "projects/deltachat-core/rust/oauth2.rs", "rust_func": "pub(crate) async fn get_oauth2_addr(\n context: &Context,\n addr: &str,\n code: &str,\n) -> Result> {\n let socks5_enabled = context.get_config_bool(Config::Socks5Enabled).await?;\n let oauth2 = match Oauth2::from_address(context, addr, socks5_enabled).await {\n Some(o) => o,\n None => return Ok(None),\n };\n if oauth2.get_userinfo.is_none() {\n return Ok(None);\n }\n\n if let Some(access_token) = get_oauth2_access_token(context, addr, code, false).await? {\n let addr_out = oauth2.get_addr(context, &access_token).await;\n if addr_out.is_none() {\n // regenerate\n if let Some(access_token) = get_oauth2_access_token(context, addr, code, true).await? {\n Ok(oauth2.get_addr(context, &access_token).await)\n } else {\n Ok(None)\n }\n } else {\n Ok(addr_out)\n }\n } else {\n Ok(None)\n }\n}", "rust_context": "pub async fn get_config_bool(&self, key: Config) -> Result {\n Ok(self.get_config_bool_opt(key).await?.unwrap_or_default())\n }\n\nasync fn get_addr(&self, context: &Context, access_token: &str) -> Option {\n let userinfo_url = self.get_userinfo.unwrap_or(\"\");\n let userinfo_url = replace_in_uri(userinfo_url, \"$ACCESS_TOKEN\", access_token);\n\n // should returns sth. as\n // {\n // \"id\": \"100000000831024152393\",\n // \"email\": \"NAME@gmail.com\",\n // \"verified_email\": true,\n // \"picture\": \"https://lh4.googleusercontent.com/-Gj5jh_9R0BY/AAAAAAAAAAI/AAAAAAAAAAA/IAjtjfjtjNA/photo.jpg\"\n // }\n let socks5_config = Socks5Config::from_database(&context.sql).await.ok()?;\n let client = match crate::net::http::get_client(socks5_config) {\n Ok(cl) => cl,\n Err(err) => {\n warn!(context, \"failed to get HTTP client: {}\", err);\n return None;\n }\n };\n let response = match client.get(userinfo_url).send().await {\n Ok(response) => response,\n Err(err) => {\n warn!(context, \"failed to get userinfo: {}\", err);\n return None;\n }\n };\n let response: Result, _> = response.json().await;\n let parsed = match response {\n Ok(parsed) => parsed,\n Err(err) => {\n warn!(context, \"Error getting userinfo: {}\", err);\n return None;\n }\n };\n // CAVE: serde_json::Value.as_str() removes the quotes of json-strings\n // but serde_json::Value.to_string() does not!\n if let Some(addr) = parsed.get(\"email\") {\n if let Some(s) = addr.as_str() {\n Some(s.to_string())\n } else {\n warn!(context, \"E-mail in userinfo is not a string: {}\", addr);\n None\n }\n } else {\n warn!(context, \"E-mail missing in userinfo.\");\n None\n }\n }\n\npub(crate) async fn get_oauth2_access_token(\n context: &Context,\n addr: &str,\n code: &str,\n regenerate: bool,\n) -> Result> {\n let socks5_enabled = context.get_config_bool(Config::Socks5Enabled).await?;\n if let Some(oauth2) = Oauth2::from_address(context, addr, socks5_enabled).await {\n let lock = context.oauth2_mutex.lock().await;\n\n // read generated token\n if !regenerate && !is_expired(context).await? {\n let access_token = context.sql.get_raw_config(\"oauth2_access_token\").await?;\n if access_token.is_some() {\n // success\n return Ok(access_token);\n }\n }\n\n // generate new token: build & call auth url\n let refresh_token = context.sql.get_raw_config(\"oauth2_refresh_token\").await?;\n let refresh_token_for = context\n .sql\n .get_raw_config(\"oauth2_refresh_token_for\")\n .await?\n .unwrap_or_else(|| \"unset\".into());\n\n let (redirect_uri, token_url, update_redirect_uri_on_success) =\n if refresh_token.is_none() || refresh_token_for != code {\n info!(context, \"Generate OAuth2 refresh_token and access_token...\",);\n (\n context\n .sql\n .get_raw_config(\"oauth2_pending_redirect_uri\")\n .await?\n .unwrap_or_else(|| \"unset\".into()),\n oauth2.init_token,\n true,\n )\n } else {\n info!(\n context,\n \"Regenerate OAuth2 access_token by refresh_token...\",\n );\n (\n context\n .sql\n .get_raw_config(\"oauth2_redirect_uri\")\n .await?\n .unwrap_or_else(|| \"unset\".into()),\n oauth2.refresh_token,\n false,\n )\n };\n\n // to allow easier specification of different configurations,\n // token_url is in GET-method-format, sth. as -\n // convert this to POST-format ...\n let mut parts = token_url.splitn(2, '?');\n let post_url = parts.next().unwrap_or_default();\n let post_args = parts.next().unwrap_or_default();\n let mut post_param = HashMap::new();\n for key_value_pair in post_args.split('&') {\n let mut parts = key_value_pair.splitn(2, '=');\n let key = parts.next().unwrap_or_default();\n let mut value = parts.next().unwrap_or_default();\n\n if value == \"$CLIENT_ID\" {\n value = oauth2.client_id;\n } else if value == \"$REDIRECT_URI\" {\n value = &redirect_uri;\n } else if value == \"$CODE\" {\n value = code;\n } else if value == \"$REFRESH_TOKEN\" {\n if let Some(refresh_token) = refresh_token.as_ref() {\n value = refresh_token;\n }\n }\n\n post_param.insert(key, value);\n }\n\n // ... and POST\n let socks5_config = Socks5Config::from_database(&context.sql).await?;\n let client = crate::net::http::get_client(socks5_config)?;\n\n let response: Response = match client.post(post_url).form(&post_param).send().await {\n Ok(resp) => match resp.json().await {\n Ok(response) => response,\n Err(err) => {\n warn!(\n context,\n \"Failed to parse OAuth2 JSON response from {}: error: {}\", token_url, err\n );\n return Ok(None);\n }\n },\n Err(err) => {\n warn!(context, \"Error calling OAuth2 at {}: {:?}\", token_url, err);\n return Ok(None);\n }\n };\n\n // update refresh_token if given, typically on the first round, but we update it later as well.\n if let Some(ref token) = response.refresh_token {\n context\n .sql\n .set_raw_config(\"oauth2_refresh_token\", Some(token))\n .await?;\n context\n .sql\n .set_raw_config(\"oauth2_refresh_token_for\", Some(code))\n .await?;\n }\n\n // after that, save the access token.\n // if it's unset, we may get it in the next round as we have the refresh_token now.\n if let Some(ref token) = response.access_token {\n context\n .sql\n .set_raw_config(\"oauth2_access_token\", Some(token))\n .await?;\n let expires_in = response\n .expires_in\n // refresh a bit before\n .map(|t| time() + t as i64 - 5)\n .unwrap_or_else(|| 0);\n context\n .sql\n .set_raw_config_int64(\"oauth2_timestamp_expires\", expires_in)\n .await?;\n\n if update_redirect_uri_on_success {\n context\n .sql\n .set_raw_config(\"oauth2_redirect_uri\", Some(redirect_uri.as_ref()))\n .await?;\n }\n } else {\n warn!(context, \"Failed to find OAuth2 access token\");\n }\n\n drop(lock);\n\n Ok(response.access_token)\n } else {\n warn!(context, \"Internal OAuth2 error: 2\");\n\n Ok(None)\n }\n}\n\nasync fn from_address(context: &Context, addr: &str, skip_mx: bool) -> Option {\n let addr_normalized = normalize_addr(addr);\n if let Some(domain) = addr_normalized\n .find('@')\n .map(|index| addr_normalized.split_at(index + 1).1)\n {\n if let Some(oauth2_authorizer) = provider::get_provider_info(context, domain, skip_mx)\n .await\n .and_then(|provider| provider.oauth2_authorizer.as_ref())\n {\n return Some(match oauth2_authorizer {\n Oauth2Authorizer::Gmail => OAUTH2_GMAIL,\n Oauth2Authorizer::Yandex => OAUTH2_YANDEX,\n });\n }\n }\n None\n }\n\npub enum Config {\n /// Email address, used in the `From:` field.\n Addr,\n\n /// IMAP server hostname.\n MailServer,\n\n /// IMAP server username.\n MailUser,\n\n /// IMAP server password.\n MailPw,\n\n /// IMAP server port.\n MailPort,\n\n /// IMAP server security (e.g. TLS, STARTTLS).\n MailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ImapCertificateChecks,\n\n /// SMTP server hostname.\n SendServer,\n\n /// SMTP server username.\n SendUser,\n\n /// SMTP server password.\n SendPw,\n\n /// SMTP server port.\n SendPort,\n\n /// SMTP server security (e.g. TLS, STARTTLS).\n SendSecurity,\n\n /// How to check SMTP server TLS certificates.\n SmtpCertificateChecks,\n\n /// Whether to use OAuth 2.\n ///\n /// Historically contained other bitflags, which are now deprecated.\n /// Should not be extended in the future, create new config keys instead.\n ServerFlags,\n\n /// True if SOCKS5 is enabled.\n ///\n /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.\n Socks5Enabled,\n\n /// SOCKS5 proxy server hostname or address.\n Socks5Host,\n\n /// SOCKS5 proxy server port.\n Socks5Port,\n\n /// SOCKS5 proxy server username.\n Socks5User,\n\n /// SOCKS5 proxy server password.\n Socks5Password,\n\n /// Own name to use in the `From:` field when sending messages.\n Displayname,\n\n /// Own status to display, sent in message footer.\n Selfstatus,\n\n /// Own avatar filename.\n Selfavatar,\n\n /// Send BCC copy to self.\n ///\n /// Should be enabled for multidevice setups.\n #[strum(props(default = \"1\"))]\n BccSelf,\n\n /// True if encryption is preferred according to Autocrypt standard.\n #[strum(props(default = \"1\"))]\n E2eeEnabled,\n\n /// True if Message Delivery Notifications (read receipts) should\n /// be sent and requested.\n #[strum(props(default = \"1\"))]\n MdnsEnabled,\n\n /// True if \"Sent\" folder should be watched for changes.\n #[strum(props(default = \"0\"))]\n SentboxWatch,\n\n /// True if chat messages should be moved to a separate folder.\n #[strum(props(default = \"1\"))]\n MvboxMove,\n\n /// Watch for new messages in the \"Mvbox\" (aka DeltaChat folder) only.\n ///\n /// This will not entirely disable other folders, e.g. the spam folder will also still\n /// be watched for new messages.\n #[strum(props(default = \"0\"))]\n OnlyFetchMvbox,\n\n /// Whether to show classic emails or only chat messages.\n #[strum(props(default = \"2\"))] // also change ShowEmails.default() on changes\n ShowEmails,\n\n /// Quality of the media files to send.\n #[strum(props(default = \"0\"))] // also change MediaQuality.default() on changes\n MediaQuality,\n\n /// If set to \"1\", on the first time `start_io()` is called after configuring,\n /// the newest existing messages are fetched.\n /// Existing recipients are added to the contact database regardless of this setting.\n #[strum(props(default = \"0\"))]\n FetchExistingMsgs,\n\n /// If set to \"1\", then existing messages are considered to be already fetched.\n /// This flag is reset after successful configuration.\n #[strum(props(default = \"1\"))]\n FetchedExistingMsgs,\n\n /// Type of the OpenPGP key to generate.\n #[strum(props(default = \"0\"))]\n KeyGenType,\n\n /// Timer in seconds after which the message is deleted from the\n /// server.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n ///\n /// Value 1 is treated as \"delete at once\": messages are deleted\n /// immediately, without moving to DeltaChat folder.\n #[strum(props(default = \"0\"))]\n DeleteServerAfter,\n\n /// Timer in seconds after which the message is deleted from the\n /// device.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n #[strum(props(default = \"0\"))]\n DeleteDeviceAfter,\n\n /// Move messages to the Trash folder instead of marking them \"\\Deleted\". Overrides\n /// `ProviderOptions::delete_to_trash`.\n DeleteToTrash,\n\n /// Save raw MIME messages with headers in the database if true.\n SaveMimeHeaders,\n\n /// The primary email address. Also see `SecondaryAddrs`.\n ConfiguredAddr,\n\n /// Configured IMAP server hostname.\n ConfiguredMailServer,\n\n /// Configured IMAP server username.\n ConfiguredMailUser,\n\n /// Configured IMAP server password.\n ConfiguredMailPw,\n\n /// Configured IMAP server port.\n ConfiguredMailPort,\n\n /// Configured IMAP server security (e.g. TLS, STARTTLS).\n ConfiguredMailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ConfiguredImapCertificateChecks,\n\n /// Configured SMTP server hostname.\n ConfiguredSendServer,\n\n /// Configured SMTP server username.\n ConfiguredSendUser,\n\n /// Configured SMTP server password.\n ConfiguredSendPw,\n\n /// Configured SMTP server port.\n ConfiguredSendPort,\n\n /// How to check SMTP server TLS certificates.\n ConfiguredSmtpCertificateChecks,\n\n /// Whether OAuth 2 is used with configured provider.\n ConfiguredServerFlags,\n\n /// Configured SMTP server security (e.g. TLS, STARTTLS).\n ConfiguredSendSecurity,\n\n /// Configured folder for incoming messages.\n ConfiguredInboxFolder,\n\n /// Configured folder for chat messages.\n ConfiguredMvboxFolder,\n\n /// Configured \"Sent\" folder.\n ConfiguredSentboxFolder,\n\n /// Configured \"Trash\" folder.\n ConfiguredTrashFolder,\n\n /// Unix timestamp of the last successful configuration.\n ConfiguredTimestamp,\n\n /// ID of the configured provider from the provider database.\n ConfiguredProvider,\n\n /// True if account is configured.\n Configured,\n\n /// True if account is a chatmail account.\n IsChatmail,\n\n /// All secondary self addresses separated by spaces\n /// (`addr1@example.org addr2@example.org addr3@example.org`)\n SecondaryAddrs,\n\n /// Read-only core version string.\n #[strum(serialize = \"sys.version\")]\n SysVersion,\n\n /// Maximal recommended attachment size in bytes.\n #[strum(serialize = \"sys.msgsize_max_recommended\")]\n SysMsgsizeMaxRecommended,\n\n /// Space separated list of all config keys available.\n #[strum(serialize = \"sys.config_keys\")]\n SysConfigKeys,\n\n /// True if it is a bot account.\n Bot,\n\n /// True when to skip initial start messages in groups.\n #[strum(props(default = \"0\"))]\n SkipStartMessages,\n\n /// Whether we send a warning if the password is wrong (set to false when we send a warning\n /// because we do not want to send a second warning)\n #[strum(props(default = \"0\"))]\n NotifyAboutWrongPw,\n\n /// If a warning about exceeding quota was shown recently,\n /// this is the percentage of quota at the time the warning was given.\n /// Unset, when quota falls below minimal warning threshold again.\n QuotaExceeding,\n\n /// address to webrtc instance to use for videochats\n WebrtcInstance,\n\n /// Timestamp of the last time housekeeping was run\n LastHousekeeping,\n\n /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.\n LastCantDecryptOutgoingMsgs,\n\n /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.\n #[strum(props(default = \"60\"))]\n ScanAllFoldersDebounceSecs,\n\n /// Whether to avoid using IMAP IDLE even if the server supports it.\n ///\n /// This is a developer option for testing \"fake idle\".\n #[strum(props(default = \"0\"))]\n DisableIdle,\n\n /// Defines the max. size (in bytes) of messages downloaded automatically.\n /// 0 = no limit.\n #[strum(props(default = \"0\"))]\n DownloadLimit,\n\n /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.\n #[strum(props(default = \"1\"))]\n SyncMsgs,\n\n /// Space-separated list of all the authserv-ids which we believe\n /// may be the one of our email server.\n ///\n /// See `crate::authres::update_authservid_candidates`.\n AuthservIdCandidates,\n\n /// Make all outgoing messages with Autocrypt header \"multipart/signed\".\n SignUnencrypted,\n\n /// Let the core save all events to the database.\n /// This value is used internally to remember the MsgId of the logging xdc\n #[strum(props(default = \"0\"))]\n DebugLogging,\n\n /// Last message processed by the bot.\n LastMsgId,\n\n /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by\n /// default.\n ///\n /// This is not supposed to be changed by UIs and only used for testing.\n #[strum(props(default = \"172800\"))]\n GossipPeriod,\n\n /// Feature flag for verified 1:1 chats; the UI should set it\n /// to 1 if it supports verified 1:1 chats.\n /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,\n /// and when the key changes, an info message is posted into the chat.\n /// 0=Nothing else happens when the key changes.\n /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true\n /// until `chat_id.accept()` is called.\n #[strum(props(default = \"0\"))]\n VerifiedOneOnOneChats,\n\n /// Row ID of the key in the `keypairs` table\n /// used for signatures, encryption to self and included in `Autocrypt` header.\n KeyId,\n\n /// This key is sent to the self_reporting bot so that the bot can recognize the user\n /// without storing the email address\n SelfReportingId,\n\n /// MsgId of webxdc map integration.\n WebxdcIntegration,\n\n /// Iroh secret key.\n IrohSecretKey,\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}", "rust_imports": "use std::collections::HashMap;\nuse anyhow::Result;\nuse percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};\nuse serde::Deserialize;\nuse crate::config::Config;\nuse crate::context::Context;\nuse crate::provider;\nuse crate::provider::Oauth2Authorizer;\nuse crate::socks::Socks5Config;\nuse crate::tools::time;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__oauth2__.rs__function__3.txt"} {"c_path": "projects/deltachat-core/c/dc_tools.c", "c_func": "int dc_get_filemeta(const void* buf_start, size_t buf_bytes, uint32_t* ret_width, uint32_t *ret_height)\n{\n\t/* Strategy:\n\treading GIF dimensions requires the first 10 bytes of the file\n\treading PNG dimensions requires the first 24 bytes of the file\n\treading JPEG dimensions requires scanning through jpeg chunks\n\tIn all formats, the file is at least 24 bytes big, so we'll read that always\n\tinspired by http://www.cplusplus.com/forum/beginner/45217/ */\n\tconst unsigned char* buf = buf_start;\n\tif (buf_bytes<24) {\n\t\treturn 0;\n\t}\n\n\t/* For JPEGs, we need to check the first bytes of each DCT chunk. */\n\tif (buf[0]==0xFF && buf[1]==0xD8 && buf[2]==0xFF)\n\t{\n\t\tlong pos = 2;\n\t\twhile (buf[pos]==0xFF)\n\t\t{\n\t\t\tif (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) {\n\t\t\t\t*ret_height = (buf[pos+5]<<8) + buf[pos+6]; /* sic! height is first */\n\t\t\t\t*ret_width = (buf[pos+7]<<8) + buf[pos+8];\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tpos += 2+(buf[pos+2]<<8)+buf[pos+3];\n\t\t\tif (pos+12>buf_bytes) { break; }\n\t\t}\n\t}\n\n\t/* GIF: first three bytes say \"GIF\", next three give version number. Then dimensions */\n\tif (buf[0]=='G' && buf[1]=='I' && buf[2]=='F')\n\t{\n\t\t*ret_width = buf[6] + (buf[7]<<8);\n\t\t*ret_height = buf[8] + (buf[9]<<8);\n\t\treturn 1;\n\t}\n\n\t/* PNG: the first frame is by definition an IHDR frame, which gives dimensions */\n\tif (buf[0]==0x89 && buf[1]=='P' && buf[2]=='N' && buf[3]=='G' && buf[4]==0x0D && buf[5]==0x0A && buf[6]==0x1A && buf[7]==0x0A\n\t && buf[12]=='I' && buf[13]=='H' && buf[14]=='D' && buf[15]=='R')\n\t{\n\t\t*ret_width = (buf[16]<<24) + (buf[17]<<16) + (buf[18]<<8) + (buf[19]<<0);\n\t\t*ret_height = (buf[20]<<24) + (buf[21]<<16) + (buf[22]<<8) + (buf[23]<<0);\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}", "rust_path": "projects/deltachat-core/rust/tools.rs", "rust_func": "pub fn get_filemeta(buf: &[u8]) -> Result<(u32, u32)> {\n let image = image::io::Reader::new(Cursor::new(buf)).with_guessed_format()?;\n let dimensions = image.into_dimensions()?;\n Ok(dimensions)\n}", "rust_context": "", "rust_imports": "use std::borrow::Cow;\nuse std::io::{Cursor, Write};\nuse std::mem;\nuse std::path::{Path, PathBuf};\nuse std::str::from_utf8;\nuse std::time::Duration;\nuse std::time::SystemTime as Time;\nuse std::time::SystemTime;\nuse anyhow::{bail, Context as _, Result};\nuse base64::Engine as _;\nuse chrono::{Local, NaiveDateTime, NaiveTime, TimeZone};\nuse deltachat_contact_tools::{strip_rtlo_characters, EmailAddress};\nuse deltachat_time::SystemTimeTools as SystemTime;\nuse futures::{StreamExt, TryStreamExt};\nuse mailparse::dateparse;\nuse mailparse::headers::Headers;\nuse mailparse::MailHeaderMap;\nuse rand::{thread_rng, Rng};\nuse tokio::{fs, io};\nuse url::Url;\nuse crate::chat::{add_device_msg, add_device_msg_with_importance};\nuse crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, Viewtype};\nuse crate::stock_str;\nuse chrono::NaiveDate;\nuse proptest::prelude::*;\nuse super::*;\nuse crate::chatlist::Chatlist;\nuse crate::{chat, test_utils};\nuse crate::{receive_imf::receive_imf, test_utils::TestContext};\nuse super::*;", "rustrepotrans_file": "projects__deltachat-core__rust__tools__.rs__function__17.txt"} {"c_path": "projects/deltachat-core/c/dc_chatlist.c", "c_func": "dc_lot_t* dc_chatlist_get_summary(const dc_chatlist_t* chatlist, size_t index, dc_chat_t* chat /*may be NULL*/)\n{\n\t/* The summary is created by the chat, not by the last message.\n\tThis is because we may want to display drafts here or stuff as\n\t\"is typing\".\n\tAlso, sth. as \"No messages\" would not work if the summary comes from a\n\tmessage. */\n\n\tdc_lot_t* ret = dc_lot_new(); /* the function never returns NULL */\n\tuint32_t lastmsg_id = 0;\n\tdc_msg_t* lastmsg = NULL;\n\tdc_contact_t* lastcontact = NULL;\n\tdc_chat_t* chat_to_delete = NULL;\n\n\tif (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC || index>=chatlist->cnt) {\n\t\tret->text2 = dc_strdup(\"ErrBadChatlistIndex\");\n\t\tgoto cleanup;\n\t}\n\n\tlastmsg_id = dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT+1);\n\n\tif (chat==NULL) {\n\t\tchat = dc_chat_new(chatlist->context);\n\t\tchat_to_delete = chat;\n\t\tif (!dc_chat_load_from_db(chat, dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT))) {\n\t\t\tret->text2 = dc_strdup(\"ErrCannotReadChat\");\n\t\t\tgoto cleanup;\n\t\t}\n\t}\n\n\tif (lastmsg_id)\n\t{\n\t\tlastmsg = dc_msg_new_untyped(chatlist->context);\n\t\tdc_msg_load_from_db(lastmsg, chatlist->context, lastmsg_id);\n\n\t\tif (lastmsg->from_id!=DC_CONTACT_ID_SELF && DC_CHAT_TYPE_IS_MULTI(chat->type))\n\t\t{\n\t\t\tlastcontact = dc_contact_new(chatlist->context);\n\t\t\tdc_contact_load_from_db(lastcontact, chatlist->context->sql, lastmsg->from_id);\n\t\t}\n\t}\n\n\tif (chat->id==DC_CHAT_ID_ARCHIVED_LINK)\n\t{\n\t\tret->text2 = dc_strdup(NULL);\n\t}\n\telse if (lastmsg==NULL || lastmsg->from_id==0)\n\t{\n\t\t/* no messages */\n\t\tret->text2 = dc_stock_str(chatlist->context, DC_STR_NOMESSAGES);\n\t}\n\telse\n\t{\n\t\t/* show the last message */\n\t\tdc_lot_fill(ret, lastmsg, chat, lastcontact, chatlist->context);\n\t}\n\ncleanup:\n\tdc_msg_unref(lastmsg);\n\tdc_contact_unref(lastcontact);\n\tdc_chat_unref(chat_to_delete);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/chatlist.rs", "rust_func": "pub async fn get_summary(\n &self,\n context: &Context,\n index: usize,\n chat: Option<&Chat>,\n ) -> Result {\n // The summary is created by the chat, not by the last message.\n // This is because we may want to display drafts here or stuff as\n // \"is typing\".\n // Also, sth. as \"No messages\" would not work if the summary comes from a message.\n let (chat_id, lastmsg_id) = self\n .ids\n .get(index)\n .context(\"chatlist index is out of range\")?;\n Chatlist::get_summary2(context, *chat_id, *lastmsg_id, chat).await\n }", "rust_context": "pub fn get(&self, key: Param) -> Option<&str> {\n self.inner.get(&key).map(|s| s.as_str())\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct Chatlist {\n /// Stores pairs of `chat_id, message_id`\n ids: Vec<(ChatId, Option)>,\n}\n\npub async fn get_summary2(\n context: &Context,\n chat_id: ChatId,\n lastmsg_id: Option,\n chat: Option<&Chat>,\n ) -> Result {\n let chat_loaded: Chat;\n let chat = if let Some(chat) = chat {\n chat\n } else {\n let chat = Chat::load_from_db(context, chat_id).await?;\n chat_loaded = chat;\n &chat_loaded\n };\n\n let (lastmsg, lastcontact) = if let Some(lastmsg_id) = lastmsg_id {\n let lastmsg = Message::load_from_db(context, lastmsg_id)\n .await\n .context(\"loading message failed\")?;\n if lastmsg.from_id == ContactId::SELF {\n (Some(lastmsg), None)\n } else {\n match chat.typ {\n Chattype::Group | Chattype::Broadcast | Chattype::Mailinglist => {\n let lastcontact = Contact::get_by_id(context, lastmsg.from_id)\n .await\n .context(\"loading contact failed\")?;\n (Some(lastmsg), Some(lastcontact))\n }\n Chattype::Single => (Some(lastmsg), None),\n }\n }\n } else {\n (None, None)\n };\n\n if chat.id.is_archived_link() {\n Ok(Default::default())\n } else if let Some(lastmsg) = lastmsg.filter(|msg| msg.from_id != ContactId::UNDEFINED) {\n Summary::new_with_reaction_details(context, &lastmsg, chat, lastcontact.as_ref()).await\n } else {\n Ok(Summary {\n text: stock_str::no_messages(context).await,\n ..Default::default()\n })\n }\n }\n \npub struct Summary {\n /// Part displayed before \":\", such as an username or a string \"Draft\".\n pub prefix: Option,\n\n /// Summary text, always present.\n pub text: String,\n\n /// Message timestamp.\n pub timestamp: i64,\n\n /// Message state.\n pub state: MessageState,\n\n /// Message preview image path\n pub thumbnail_path: Option,\n}", "rust_imports": "use anyhow::{ensure, Context as _, Result};\nuse once_cell::sync::Lazy;\nuse crate::chat::{update_special_chat_names, Chat, ChatId, ChatVisibility};\nuse crate::constants::{\n Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_GCL_ADD_ALLDONE_HINT,\n DC_GCL_ARCHIVED_ONLY, DC_GCL_FOR_FORWARDING, DC_GCL_NO_SPECIALS,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::message::{Message, MessageState, MsgId};\nuse crate::param::{Param, Params};\nuse crate::stock_str;\nuse crate::summary::Summary;\nuse crate::tools::IsNoneOrEmpty;\nuse super::*;\nuse crate::chat::{\n add_contact_to_chat, create_group_chat, get_chat_contacts, remove_contact_from_chat,\n send_text_msg, ProtectionStatus,\n };\nuse crate::message::Viewtype;\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__chatlist__.rs__function__7.txt"} {"c_path": "projects/deltachat-core/c/dc_configure.c", "c_func": "* Frees the process allocated with dc_alloc_ongoing() - independingly of dc_shall_stop_ongoing.\n * If dc_alloc_ongoing() fails, this function MUST NOT be called.\n */\nvoid dc_free_ongoing(dc_context_t* context)\n{\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\treturn;\n\t}\n\n\tcontext->ongoing_running = 0;\n\tcontext->shall_stop_ongoing = 1; /* avoids dc_stop_ongoing_process() to stop the thread */\n}", "rust_path": "projects/deltachat-core/rust/context.rs", "rust_func": "pub(crate) async fn free_ongoing(&self) {\n let mut s = self.running_state.write().await;\n if let RunningState::ShallStop { request } = *s {\n info!(self, \"Ongoing stopped in {:?}\", time_elapsed(&request));\n }\n *s = RunningState::Stopped;\n }", "rust_context": "macro_rules! info {\n ($ctx:expr, $msg:expr) => {\n info!($ctx, $msg,)\n };\n ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{\n let formatted = format!($msg, $($args),*);\n let full = format!(\"{file}:{line}: {msg}\",\n file = file!(),\n line = line!(),\n msg = &formatted);\n $ctx.emit_event($crate::EventType::Info(full));\n }};\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\nenum RunningState {\n /// Ongoing process is allocated.\n Running { cancel_sender: Sender<()> },\n\n /// Cancel signal has been sent, waiting for ongoing process to be freed.\n ShallStop { request: tools::Time },\n\n /// There is no ongoing process, a new one can be allocated.\n Stopped,\n}", "rust_imports": "use std::collections::{BTreeMap, HashMap};\nuse std::ffi::OsString;\nuse std::ops::Deref;\nuse std::path::{Path, PathBuf};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\nuse std::time::Duration;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse pgp::SignedPublicKey;\nuse ratelimit::Ratelimit;\nuse tokio::sync::{Mutex, Notify, OnceCell, RwLock};\nuse crate::aheader::EncryptPreference;\nuse crate::chat::{get_chat_cnt, ChatId, ProtectionStatus};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::debug_logging::DebugLogging;\nuse crate::download::DownloadState;\nuse crate::events::{Event, EventEmitter, EventType, Events};\nuse crate::imap::{FolderMeaning, Imap, ServerMetadata};\nuse crate::key::{load_self_public_key, load_self_secret_key, DcKey as _};\nuse crate::login_param::LoginParam;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peer_channels::Iroh;\nuse crate::peerstate::Peerstate;\nuse crate::push::PushSubscriber;\nuse crate::quota::QuotaInfo;\nuse crate::scheduler::{convert_folder_meaning, SchedulerState};\nuse crate::sql::Sql;\nuse crate::stock_str::StockStrings;\nuse crate::timesmearing::SmearedTimestamp;\nuse crate::tools::{self, create_id, duration_to_str, time, time_elapsed};\nuse anyhow::Context as _;\nuse strum::IntoEnumIterator;\nuse tempfile::tempdir;\nuse super::*;\nuse crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration};\nuse crate::chatlist::Chatlist;\nuse crate::constants::Chattype;\nuse crate::mimeparser::SystemMessage;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{get_chat_msg, TestContext};\nuse crate::tools::{create_outgoing_rfc724_mid, SystemTime};", "rustrepotrans_file": "projects__deltachat-core__rust__context__.rs__function__38.txt"} {"c_path": "projects/deltachat-core/c/dc_param.c", "c_func": "int32_t dc_param_get_int(const dc_param_t* param, int key, int32_t def)\n{\n\tif (param==NULL || key==0) {\n\t\treturn def;\n\t}\n\n char* str = dc_param_get(param, key, NULL);\n if (str==NULL) {\n\t\treturn def;\n }\n int32_t ret = atol(str);\n free(str);\n return ret;\n}", "rust_path": "projects/deltachat-core/rust/param.rs", "rust_func": "pub fn get_int(&self, key: Param) -> Option {\n self.get(key).and_then(|s| s.parse().ok())\n }", "rust_context": "pub fn get(&self, key: Param) -> Option<&str> {\n self.inner.get(&key).map(|s| s.as_str())\n }\n\npub struct Params {\n inner: BTreeMap,\n}", "rust_imports": "use std::collections::BTreeMap;\nuse std::fmt;\nuse std::path::PathBuf;\nuse std::str;\nuse anyhow::{bail, Error, Result};\nuse num_traits::FromPrimitive;\nuse serde::{Deserialize, Serialize};\nuse crate::blob::BlobObject;\nuse crate::context::Context;\nuse crate::mimeparser::SystemMessage;\nuse std::path::Path;\nuse std::str::FromStr;\nuse tokio::fs;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__param__.rs__function__11.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "static uint32_t get_draft_msg_id(dc_context_t* context, uint32_t chat_id)\n{\n\tuint32_t draft_msg_id = 0;\n\n\tsqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT id FROM msgs WHERE chat_id=? AND state=?;\");\n\tsqlite3_bind_int(stmt, 1, chat_id);\n\tsqlite3_bind_int(stmt, 2, DC_STATE_OUT_DRAFT);\n\tif (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\tdraft_msg_id = sqlite3_column_int(stmt, 0);\n\t}\n\tsqlite3_finalize(stmt);\n\n\treturn draft_msg_id;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "async fn get_draft_msg_id(self, context: &Context) -> Result> {\n let msg_id: Option = context\n .sql\n .query_get_value(\n \"SELECT id FROM msgs WHERE chat_id=? AND state=?;\",\n (self, MessageState::OutDraft),\n )\n .await?;\n Ok(msg_id)\n }", "rust_context": "pub struct Context {\n pub(crate) inner: Arc,\n}\n\nub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\n pub async fn query_get_value(\n &self,\n query: &str,\n params: impl rusqlite::Params + Send,\n ) -> Result>\n where\n T: rusqlite::types::FromSql + Send + 'static,\n {\n self.query_row_optional(query, params, |row| row.get::<_, T>(0))\n .await\n }\n\npub enum MessageState {\n /// Undefined message state.\n #[default]\n Undefined = 0,\n\n /// Incoming *fresh* message. Fresh messages are neither noticed\n /// nor seen and are typically shown in notifications.\n InFresh = 10,\n\n /// Incoming *noticed* message. E.g. chat opened but message not\n /// yet read - noticed messages are not counted as unread but did\n /// not marked as read nor resulted in MDNs.\n InNoticed = 13,\n\n /// Incoming message, really *seen* by the user. Marked as read on\n /// IMAP and MDN may be sent.\n InSeen = 16,\n\n /// For files which need time to be prepared before they can be\n /// sent, the message enters this state before\n /// OutPending.\n OutPreparing = 18,\n\n /// Message saved as draft.\n OutDraft = 19,\n\n /// The user has pressed the \"send\" button but the message is not\n /// yet sent and is pending in some way. Maybe we're offline (no\n /// checkmark).\n OutPending = 20,\n\n /// *Unrecoverable* error (*recoverable* errors result in pending\n /// messages).\n OutFailed = 24,\n\n /// Outgoing message successfully delivered to server (one\n /// checkmark). Note, that already delivered messages may get into\n /// the OutFailed state if we get such a hint from the server.\n OutDelivered = 26,\n\n /// Outgoing message read by the recipient (two checkmarks; this\n /// requires goodwill on the receiver's side)\n OutMdnRcvd = 28,\n}\n\npub struct MsgId(u32);\n\npub struct ChatId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__32.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_is_info(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn 0;\n\t}\n\n\tint cmd = dc_param_get_int(msg->param, DC_PARAM_CMD, 0);\n\n\tif (msg->from_id==DC_CONTACT_ID_INFO\n\t || msg->to_id==DC_CONTACT_ID_INFO\n\t || (cmd && cmd!=DC_CMD_AUTOCRYPT_SETUP_MESSAGE)) {\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn is_info(&self) -> bool {\n let cmd = self.param.get_cmd();\n self.from_id == ContactId::INFO\n || self.to_id == ContactId::INFO\n || cmd != SystemMessage::Unknown && cmd != SystemMessage::AutocryptSetupMessage\n }", "rust_context": "pub fn get_cmd(&self) -> SystemMessage {\n self.get_int(Param::Cmd)\n .and_then(SystemMessage::from_i32)\n .unwrap_or_default()\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub struct ContactId(u32);\n\nimpl ContactId {\n /// Undefined contact. Used as a placeholder for trashed messages.\n pub const UNDEFINED: ContactId = ContactId::new(0);\n\n /// The owner of the account.\n ///\n /// The email-address is set by `set_config` using \"addr\".\n pub const SELF: ContactId = ContactId::new(1);\n\n /// ID of the contact for info messages.\n pub const INFO: ContactId = ContactId::new(2);\n\n /// ID of the contact for device messages.\n pub const DEVICE: ContactId = ContactId::new(5);\n pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9);\n\n /// Address to go with [`ContactId::DEVICE`].\n ///\n /// This is used by APIs which need to return an email address for this contact.\n pub const DEVICE_ADDR: &'static str = \"device@localhost\";\n}\n\npub enum SystemMessage {\n /// Unknown type of system message.\n #[default]\n Unknown = 0,\n\n /// Group name changed.\n GroupNameChanged = 2,\n\n /// Group avatar changed.\n GroupImageChanged = 3,\n\n /// Member was added to the group.\n MemberAddedToGroup = 4,\n\n /// Member was removed from the group.\n MemberRemovedFromGroup = 5,\n\n /// Autocrypt Setup Message.\n AutocryptSetupMessage = 6,\n\n /// Secure-join message.\n SecurejoinMessage = 7,\n\n /// Location streaming is enabled.\n LocationStreamingEnabled = 8,\n\n /// Location-only message.\n LocationOnly = 9,\n\n /// Chat ephemeral message timer is changed.\n EphemeralTimerChanged = 10,\n\n /// \"Messages are guaranteed to be end-to-end encrypted from now on.\"\n ChatProtectionEnabled = 11,\n\n /// \"%1$s sent a message from another device.\"\n ChatProtectionDisabled = 12,\n\n /// Message can't be sent because of `Invalid unencrypted mail to <>`\n /// which is sent by chatmail servers.\n InvalidUnencryptedMail = 13,\n\n /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it\n /// to complete.\n SecurejoinWait = 14,\n\n /// 1:1 chats info message telling that SecureJoin is still running, but the user may already\n /// send messages.\n SecurejoinWaitTimeout = 15,\n\n /// Self-sent-message that contains only json used for multi-device-sync;\n /// if possible, we attach that to other messages as for locations.\n MultiDeviceSync = 20,\n\n /// Sync message that contains a json payload\n /// sent to the other webxdc instances\n /// These messages are not shown in the chat.\n WebxdcStatusUpdate = 30,\n\n /// Webxdc info added with `info` set in `send_webxdc_status_update()`.\n WebxdcInfoMessage = 32,\n\n /// This message contains a users iroh node address.\n IrohNodeAddr = 40,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__56.txt"} {"c_path": "projects/deltachat-core/c/dc_simplify.c", "c_func": "static int is_plain_quote(const char* buf)\n{\n\tif (buf[0]=='>') {\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "rust_path": "projects/deltachat-core/rust/simplify.rs", "rust_func": "fn is_plain_quote(buf: &str) -> bool {\n buf.starts_with('>')\n}", "rust_context": "", "rust_imports": "", "rustrepotrans_file": "projects__deltachat-core__rust__simplify__.rs__function__14.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* If the group is already _promoted_ (any message was sent to the group),\n * all group members are informed by a special status message that is sent automatically by this function.\n *\n * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent.\n *\n * @memberof dc_context_t\n * @param context The context as created by dc_context_new().\n * @param chat_id The chat ID to remove the contact from. Must be a group chat.\n * @param contact_id The contact ID to remove from the chat.\n * @return 1=member removed from group, 0=error\n */\nint dc_remove_contact_from_chat(dc_context_t* context, uint32_t chat_id, uint32_t contact_id /*may be DC_CONTACT_ID_SELF*/)\n{\n\tint success = 0;\n\tdc_contact_t* contact = dc_get_contact(context, contact_id);\n\tdc_chat_t* chat = dc_chat_new(context);\n\tdc_msg_t* msg = dc_msg_new_untyped(context);\n\tchar* q3 = NULL;\n\n\tif (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)) {\n\t\tgoto cleanup; /* we do not check if \"contact_id\" exists but just delete all records with the id from chats_contacts */\n\t} /* this allows to delete pending references to deleted contacts. Of course, this should _not_ happen. */\n\n\tif (0==real_group_exists(context, chat_id)\n\t || 0==dc_chat_load_from_db(chat, chat_id)) {\n\t\tgoto cleanup;\n\t}\n\n\tif (!IS_SELF_IN_GROUP) {\n\t\tdc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0,\n\t\t \"Cannot remove contact from chat; self not in group.\");\n\t\tgoto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */\n\t}\n\n\t/* send a status mail to all group members - we need to do this before we update the database -\n\totherwise the !IS_SELF_IN_GROUP__-check in dc_chat_send_msg() will fail. */\n\tif (contact)\n\t{\n\t\tif (DO_SEND_STATUS_MAILS)\n\t\t{\n\t\t\tmsg->type = DC_MSG_TEXT;\n\t\t\tif (contact->id==DC_CONTACT_ID_SELF) {\n\t\t\t\tdc_set_group_explicitly_left(context, chat->grpid);\n\t\t\t\tmsg->text = dc_stock_system_msg(context, DC_STR_MSGGROUPLEFT, NULL, NULL, DC_CONTACT_ID_SELF);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmsg->text = dc_stock_system_msg(context, DC_STR_MSGDELMEMBER, contact->addr, NULL, DC_CONTACT_ID_SELF);\n\t\t\t}\n\t\t\tdc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_MEMBER_REMOVED_FROM_GROUP);\n\t\t\tdc_param_set (msg->param, DC_PARAM_CMD_ARG, contact->addr);\n\t\t\tmsg->id = dc_send_msg(context, chat_id, msg);\n\t\t\tcontext->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, msg->id);\n\t\t}\n\t}\n\n\tq3 = sqlite3_mprintf(\"DELETE FROM chats_contacts WHERE chat_id=%i AND contact_id=%i;\", chat_id, contact_id);\n\tif (!dc_sqlite3_execute(context->sql, q3)) {\n\t\tgoto cleanup;\n\t}\n\n\tcontext->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0);\n\n\tsuccess = 1;\n\ncleanup:\n\tsqlite3_free(q3);\n\tdc_chat_unref(chat);\n\tdc_contact_unref(contact);\n\tdc_msg_unref(msg);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn remove_contact_from_chat(\n context: &Context,\n chat_id: ChatId,\n contact_id: ContactId,\n) -> Result<()> {\n ensure!(\n !chat_id.is_special(),\n \"bad chat_id, can not be special chat: {}\",\n chat_id\n );\n ensure!(\n !contact_id.is_special() || contact_id == ContactId::SELF,\n \"Cannot remove special contact\"\n );\n\n let mut msg = Message::default();\n\n let chat = Chat::load_from_db(context, chat_id).await?;\n if chat.typ == Chattype::Group || chat.typ == Chattype::Broadcast {\n if !chat.is_self_in_chat(context).await? {\n let err_msg = format!(\n \"Cannot remove contact {contact_id} from chat {chat_id}: self not in group.\"\n );\n context.emit_event(EventType::ErrorSelfNotInGroup(err_msg.clone()));\n bail!(\"{}\", err_msg);\n } else {\n let mut sync = Nosync;\n // We do not return an error if the contact does not exist in the database.\n // This allows to delete dangling references to deleted contacts\n // in case of the database becoming inconsistent due to a bug.\n if let Some(contact) = Contact::get_by_id_optional(context, contact_id).await? {\n if chat.typ == Chattype::Group && chat.is_promoted() {\n msg.viewtype = Viewtype::Text;\n if contact.id == ContactId::SELF {\n set_group_explicitly_left(context, &chat.grpid).await?;\n msg.text = stock_str::msg_group_left_local(context, ContactId::SELF).await;\n } else {\n msg.text = stock_str::msg_del_member_local(\n context,\n contact.get_addr(),\n ContactId::SELF,\n )\n .await;\n }\n msg.param.set_cmd(SystemMessage::MemberRemovedFromGroup);\n msg.param.set(Param::Arg, contact.get_addr().to_lowercase());\n msg.id = send_msg(context, chat_id, &mut msg).await?;\n } else {\n sync = Sync;\n }\n }\n // we remove the member from the chat after constructing the\n // to-be-send message. If between send_msg() and here the\n // process dies the user will have to re-do the action. It's\n // better than the other way round: you removed\n // someone from DB but no peer or device gets to know about it and\n // group membership is thus different on different devices.\n // Note also that sending a message needs all recipients\n // in order to correctly determine encryption so if we\n // removed it first, it would complicate the\n // check/encryption logic.\n remove_from_chat_contacts_table(context, chat_id, contact_id).await?;\n context.emit_event(EventType::ChatModified(chat_id));\n if sync.into() {\n chat.sync_contacts(context).await.log_err(context).ok();\n }\n }\n } else {\n bail!(\"Cannot remove members from non-group chats.\");\n }\n\n Ok(())\n}", "rust_context": "async fn set_group_explicitly_left(context: &Context, grpid: &str) -> Result<()> {\n if !is_group_explicitly_left(context, grpid).await? {\n context\n .sql\n .execute(\"INSERT INTO leftgrps (grpid) VALUES(?);\", (grpid,))\n .await?;\n }\n\n Ok(())\n}\n\npub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result {\n if chat_id.is_unset() {\n let forwards = msg.param.get(Param::PrepForwards);\n if let Some(forwards) = forwards {\n for forward in forwards.split(' ') {\n if let Ok(msg_id) = forward.parse::().map(MsgId::new) {\n if let Ok(mut msg) = Message::load_from_db(context, msg_id).await {\n send_msg_inner(context, chat_id, &mut msg).await?;\n };\n }\n }\n msg.param.remove(Param::PrepForwards);\n msg.update_param(context).await?;\n }\n return send_msg_inner(context, chat_id, msg).await;\n }\n\n if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing {\n msg.param.remove(Param::GuaranteeE2ee);\n msg.param.remove(Param::ForcePlaintext);\n msg.update_param(context).await?;\n }\n send_msg_inner(context, chat_id, msg).await\n}\n\npub(crate) async fn sync_contacts(&self, context: &Context) -> Result<()> {\n let addrs = context\n .sql\n .query_map(\n \"SELECT c.addr \\\n FROM contacts c INNER JOIN chats_contacts cc \\\n ON c.id=cc.contact_id \\\n WHERE cc.chat_id=?\",\n (self.id,),\n |row| row.get::<_, String>(0),\n |addrs| addrs.collect::, _>>().map_err(Into::into),\n )\n .await?;\n self.sync(context, SyncAction::SetContacts(addrs)).await\n }\n\npub fn set_cmd(&mut self, value: SystemMessage) {\n self.set_int(Param::Cmd, value as i32);\n }\n\npub fn is_promoted(&self) -> bool {\n !self.is_unpromoted()\n }\n\npub(crate) async fn is_self_in_chat(&self, context: &Context) -> Result {\n match self.typ {\n Chattype::Single | Chattype::Broadcast | Chattype::Mailinglist => Ok(true),\n Chattype::Group => is_contact_in_chat(context, self.id, ContactId::SELF).await,\n }\n }\n\nfn log_err(self, context: &Context) -> Result {\n if let Err(e) = &self {\n let location = std::panic::Location::caller();\n\n // We are using Anyhow's .context() and to show the inner error, too, we need the {:#}:\n let full = format!(\n \"{file}:{line}: {e:#}\",\n file = location.file(),\n line = location.line(),\n e = e\n );\n // We can't use the warn!() macro here as the file!() and line!() macros\n // don't work with #[track_caller]\n context.emit_event(crate::EventType::Warning(full));\n };\n self\n }\n\npub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self {\n self.inner.insert(key, value.to_string());\n self\n }\n\npub fn emit_event(&self, event: EventType) {\n {\n let lock = self.debug_logging.read().expect(\"RwLock is poisoned\");\n if let Some(debug_logging) = &*lock {\n debug_logging.log_event(event.clone());\n }\n }\n self.events.emit(Event {\n id: self.id,\n typ: event,\n });\n }\n\npub(crate) async fn remove_from_chat_contacts_table(\n context: &Context,\n chat_id: ChatId,\n contact_id: ContactId,\n) -> Result<()> {\n context\n .sql\n .execute(\n \"DELETE FROM chats_contacts WHERE chat_id=? AND contact_id=?\",\n (chat_id, contact_id),\n )\n .await?;\n Ok(())\n}\n\npub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result {\n let mut chat = context\n .sql\n .query_row(\n \"SELECT c.type, c.name, c.grpid, c.param, c.archived,\n c.blocked, c.locations_send_until, c.muted_until, c.protected\n FROM chats c\n WHERE c.id=?;\",\n (chat_id,),\n |row| {\n let c = Chat {\n id: chat_id,\n typ: row.get(0)?,\n name: row.get::<_, String>(1)?,\n grpid: row.get::<_, String>(2)?,\n param: row.get::<_, String>(3)?.parse().unwrap_or_default(),\n visibility: row.get(4)?,\n blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),\n is_sending_locations: row.get(6)?,\n mute_duration: row.get(7)?,\n protected: row.get(8)?,\n };\n Ok(c)\n },\n )\n .await\n .context(format!(\"Failed loading chat {chat_id} from database\"))?;\n\n if chat.id.is_archived_link() {\n chat.name = stock_str::archived_chats(context).await;\n } else {\n if chat.typ == Chattype::Single && chat.name.is_empty() {\n // chat.name is set to contact.display_name on changes,\n // however, if things went wrong somehow, we do this here explicitly.\n let mut chat_name = \"Err [Name not found]\".to_owned();\n match get_chat_contacts(context, chat.id).await {\n Ok(contacts) => {\n if let Some(contact_id) = contacts.first() {\n if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {\n contact.get_display_name().clone_into(&mut chat_name);\n }\n }\n }\n Err(err) => {\n error!(\n context,\n \"Failed to load contacts for {}: {:#}.\", chat.id, err\n );\n }\n }\n chat.name = chat_name;\n }\n if chat.param.exists(Param::Selftalk) {\n chat.name = stock_str::saved_messages(context).await;\n } else if chat.param.exists(Param::Devicetalk) {\n chat.name = stock_str::device_messages(context).await;\n }\n }\n\n Ok(chat)\n }\n\npub fn get_addr(&self) -> &str {\n &self.addr\n }\n\npub async fn get_by_id_optional(\n context: &Context,\n contact_id: ContactId,\n ) -> Result> {\n if let Some(mut contact) = context\n .sql\n .query_row_optional(\n \"SELECT c.name, c.addr, c.origin, c.blocked, c.last_seen,\n c.authname, c.param, c.status, c.is_bot\n FROM contacts c\n WHERE c.id=?;\",\n (contact_id,),\n |row| {\n let name: String = row.get(0)?;\n let addr: String = row.get(1)?;\n let origin: Origin = row.get(2)?;\n let blocked: Option = row.get(3)?;\n let last_seen: i64 = row.get(4)?;\n let authname: String = row.get(5)?;\n let param: String = row.get(6)?;\n let status: Option = row.get(7)?;\n let is_bot: bool = row.get(8)?;\n let contact = Self {\n id: contact_id,\n name,\n authname,\n addr,\n blocked: blocked.unwrap_or_default(),\n last_seen,\n origin,\n param: param.parse().unwrap_or_default(),\n status: status.unwrap_or_default(),\n is_bot,\n };\n Ok(contact)\n },\n )\n .await?\n {\n if contact_id == ContactId::SELF {\n contact.name = stock_str::self_msg(context).await;\n contact.authname = context\n .get_config(Config::Displayname)\n .await?\n .unwrap_or_default();\n contact.addr = context\n .get_config(Config::ConfiguredAddr)\n .await?\n .unwrap_or_default();\n contact.status = context\n .get_config(Config::Selfstatus)\n .await?\n .unwrap_or_default();\n } else if contact_id == ContactId::DEVICE {\n contact.name = stock_str::device_messages(context).await;\n contact.addr = ContactId::DEVICE_ADDR.to_string();\n contact.status = stock_str::device_messages_hint(context).await;\n }\n Ok(Some(contact))\n } else {\n Ok(None)\n }\n }\n\npub(crate) async fn msg_group_left_local(context: &Context, by_contact: ContactId) -> String {\n if by_contact == ContactId::SELF {\n translated(context, StockMessage::MsgYouLeftGroup).await\n } else {\n translated(context, StockMessage::MsgGroupLeftBy)\n .await\n .replace1(&by_contact.get_stock_name_n_addr(context).await)\n }\n}\n\npub(crate) async fn msg_del_member_local(\n context: &Context,\n removed_member_addr: &str,\n by_contact: ContactId,\n) -> String {\n let addr = removed_member_addr;\n let whom = &match Contact::lookup_id_by_addr(context, addr, Origin::Unknown).await {\n Ok(Some(contact_id)) => Contact::get_by_id(context, contact_id)\n .await\n .map(|contact| contact.get_name_n_addr())\n .unwrap_or_else(|_| addr.to_string()),\n _ => addr.to_string(),\n };\n if by_contact == ContactId::SELF {\n translated(context, StockMessage::MsgYouDelMember)\n .await\n .replace1(whom)\n } else {\n translated(context, StockMessage::MsgDelMemberBy)\n .await\n .replace1(whom)\n .replace2(&by_contact.get_stock_name_n_addr(context).await)\n }\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}\n\n\npub struct ContactId(u32);\n\npub struct ChatId(u32);\n\nimpl ContactId {\n /// The owner of the account.\n ///\n /// The email-address is set by `set_config` using \"addr\".\n pub const SELF: ContactId = ContactId::new(1);\n}\n\npub enum Chattype {\n /// 1:1 chat.\n Single = 100,\n\n /// Group chat.\n Group = 120,\n\n /// Mailing list.\n Mailinglist = 140,\n\n /// Broadcast list.\n Broadcast = 160,\n}\n\npub enum SystemMessage {\n /// Unknown type of system message.\n #[default]\n Unknown = 0,\n\n /// Group name changed.\n GroupNameChanged = 2,\n\n /// Group avatar changed.\n GroupImageChanged = 3,\n\n /// Member was added to the group.\n MemberAddedToGroup = 4,\n\n /// Member was removed from the group.\n MemberRemovedFromGroup = 5,\n\n /// Autocrypt Setup Message.\n AutocryptSetupMessage = 6,\n\n /// Secure-join message.\n SecurejoinMessage = 7,\n\n /// Location streaming is enabled.\n LocationStreamingEnabled = 8,\n\n /// Location-only message.\n LocationOnly = 9,\n\n /// Chat ephemeral message timer is changed.\n EphemeralTimerChanged = 10,\n\n /// \"Messages are guaranteed to be end-to-end encrypted from now on.\"\n ChatProtectionEnabled = 11,\n\n /// \"%1$s sent a message from another device.\"\n ChatProtectionDisabled = 12,\n\n /// Message can't be sent because of `Invalid unencrypted mail to <>`\n /// which is sent by chatmail servers.\n InvalidUnencryptedMail = 13,\n\n /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it\n /// to complete.\n SecurejoinWait = 14,\n\n /// 1:1 chats info message telling that SecureJoin is still running, but the user may already\n /// send messages.\n SecurejoinWaitTimeout = 15,\n\n /// Self-sent-message that contains only json used for multi-device-sync;\n /// if possible, we attach that to other messages as for locations.\n MultiDeviceSync = 20,\n\n /// Sync message that contains a json payload\n /// sent to the other webxdc instances\n /// These messages are not shown in the chat.\n WebxdcStatusUpdate = 30,\n\n /// Webxdc info added with `info` set in `send_webxdc_status_update()`.\n WebxdcInfoMessage = 32,\n\n /// This message contains a users iroh node address.\n IrohNodeAddr = 40,\n}\n\n\npub enum EventType {\n /// The library-user may write an informational string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Info(String),\n\n /// Emitted when SMTP connection is established and login was successful.\n SmtpConnected(String),\n\n /// Emitted when IMAP connection is established and login was successful.\n ImapConnected(String),\n\n /// Emitted when a message was successfully sent to the SMTP server.\n SmtpMessageSent(String),\n\n /// Emitted when an IMAP message has been marked as deleted\n ImapMessageDeleted(String),\n\n /// Emitted when an IMAP message has been moved\n ImapMessageMoved(String),\n\n /// Emitted before going into IDLE on the Inbox folder.\n ImapInboxIdle,\n\n /// Emitted when an new file in the $BLOBDIR was created\n NewBlobFile(String),\n\n /// Emitted when an file in the $BLOBDIR was deleted\n DeletedBlobFile(String),\n\n /// The library-user should write a warning string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Warning(String),\n\n /// The library-user should report an error to the end-user.\n ///\n /// As most things are asynchronous, things may go wrong at any time and the user\n /// should not be disturbed by a dialog or so. Instead, use a bubble or so.\n ///\n /// However, for ongoing processes (eg. configure())\n /// or for functions that are expected to fail (eg. dc_continue_key_transfer())\n /// it might be better to delay showing these events until the function has really\n /// failed (returned false). It should be sufficient to report only the *last* error\n /// in a messasge box then.\n Error(String),\n\n /// An action cannot be performed because the user is not in the group.\n /// Reported eg. after a call to\n /// dc_set_chat_name(), dc_set_chat_profile_image(),\n /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(),\n /// dc_send_text_msg() or another sending function.\n ErrorSelfNotInGroup(String),\n\n /// Messages or chats changed. One or more messages or chats changed for various\n /// reasons in the database:\n /// - Messages sent, received or removed\n /// - Chats created, deleted or archived\n /// - A draft has been set\n ///\n MsgsChanged {\n /// Set if only a single chat is affected by the changes, otherwise 0.\n chat_id: ChatId,\n\n /// Set if only a single message is affected by the changes, otherwise 0.\n msg_id: MsgId,\n },\n\n /// Reactions for the message changed.\n ReactionsChanged {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message for which reactions were changed.\n msg_id: MsgId,\n\n /// ID of the contact whose reaction set is changed.\n contact_id: ContactId,\n },\n\n /// There is a fresh message. Typically, the user will show an notification\n /// when receiving this message.\n ///\n /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event.\n IncomingMsg {\n /// ID of the chat where the message is assigned.\n chat_id: ChatId,\n\n /// ID of the message.\n msg_id: MsgId,\n },\n\n /// Downloading a bunch of messages just finished.\n IncomingMsgBunch,\n\n /// Messages were seen or noticed.\n /// chat id is always set.\n MsgsNoticed(ChatId),\n\n /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to\n /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state().\n MsgDelivered {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was successfully sent.\n msg_id: MsgId,\n },\n\n /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_FAILED, see dc_msg_get_state().\n MsgFailed {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that could not be sent.\n msg_id: MsgId,\n },\n\n /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state().\n MsgRead {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was read.\n msg_id: MsgId,\n },\n\n /// A single message was deleted.\n ///\n /// This event means that the message will no longer appear in the messagelist.\n /// UI should remove the message from the messagelist\n /// in response to this event if the message is currently displayed.\n ///\n /// The message may have been explicitly deleted by the user or expired.\n /// Internally the message may have been removed from the database,\n /// moved to the trash chat or hidden.\n ///\n /// This event does not indicate the message\n /// deletion from the server.\n MsgDeleted {\n /// ID of the chat where the message was prior to deletion.\n /// Never 0 or trash chat.\n chat_id: ChatId,\n\n /// ID of the deleted message. Never 0.\n msg_id: MsgId,\n },\n\n /// Chat changed. The name or the image of a chat group was changed or members were added or removed.\n /// Or the verify state of a chat has changed.\n /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat()\n /// and dc_remove_contact_from_chat().\n ///\n /// This event does not include ephemeral timer modification, which\n /// is a separate event.\n ChatModified(ChatId),\n\n /// Chat ephemeral timer changed.\n ChatEphemeralTimerModified {\n /// Chat ID.\n chat_id: ChatId,\n\n /// New ephemeral timer value.\n timer: EphemeralTimer,\n },\n\n /// Contact(s) created, renamed, blocked, deleted or changed their \"recently seen\" status.\n ///\n /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected.\n ContactsChanged(Option),\n\n /// Location of one or more contact has changed.\n ///\n /// @param data1 (u32) contact_id of the contact for which the location has changed.\n /// If the locations of several contacts have been changed,\n /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`.\n LocationChanged(Option),\n\n /// Inform about the configuration progress started by configure().\n ConfigureProgress {\n /// Progress.\n ///\n /// 0=error, 1-999=progress in permille, 1000=success and done\n progress: usize,\n\n /// Progress comment or error, something to display to the user.\n comment: Option,\n },\n\n /// Inform about the import/export progress started by imex().\n ///\n /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done\n /// @param data2 0\n ImexProgress(usize),\n\n /// A file has been exported. A file has been written by imex().\n /// This event may be sent multiple times by a single call to imex().\n ///\n /// A typical purpose for a handler of this event may be to make the file public to some system\n /// services.\n ///\n /// @param data2 0\n ImexFileWritten(PathBuf),\n\n /// Progress information of a secure-join handshake from the view of the inviter\n /// (Alice, the person who shows the QR code).\n ///\n /// These events are typically sent after a joiner has scanned the QR code\n /// generated by dc_get_securejoin_qr().\n SecurejoinInviterProgress {\n /// ID of the contact that wants to join.\n contact_id: ContactId,\n\n /// Progress as:\n /// 300=vg-/vc-request received, typically shown as \"bob@addr joins\".\n /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as \"bob@addr verified\".\n /// 800=contact added to chat, shown as \"bob@addr securely joined GROUP\". Only for the verified-group-protocol.\n /// 1000=Protocol finished for this contact.\n progress: usize,\n },\n\n /// Progress information of a secure-join handshake from the view of the joiner\n /// (Bob, the person who scans the QR code).\n /// The events are typically sent while dc_join_securejoin(), which\n /// may take some time, is executed.\n SecurejoinJoinerProgress {\n /// ID of the inviting contact.\n contact_id: ContactId,\n\n /// Progress as:\n /// 400=vg-/vc-request-with-auth sent, typically shown as \"alice@addr verified, introducing myself.\"\n /// (Bob has verified alice and waits until Alice does the same for him)\n /// 1000=vg-member-added/vc-contact-confirm received\n progress: usize,\n },\n\n /// The connectivity to the server changed.\n /// This means that you should refresh the connectivity view\n /// and possibly the connectivtiy HTML; see dc_get_connectivity() and\n /// dc_get_connectivity_html() for details.\n ConnectivityChanged,\n\n /// The user's avatar changed.\n /// Deprecated by `ConfigSynced`.\n SelfavatarChanged,\n\n /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For\n /// uniformity this is emitted on the source device too. The value isn't here, otherwise it\n /// would be logged which might not be good for privacy.\n ConfigSynced {\n /// Configuration key.\n key: Config,\n },\n\n /// Webxdc status update received.\n WebxdcStatusUpdate {\n /// Message ID.\n msg_id: MsgId,\n\n /// Status update ID.\n status_update_serial: StatusUpdateSerial,\n },\n\n /// Data received over an ephemeral peer channel.\n WebxdcRealtimeData {\n /// Message ID.\n msg_id: MsgId,\n\n /// Realtime data.\n data: Vec,\n },\n\n /// Inform that a message containing a webxdc instance has been deleted.\n WebxdcInstanceDeleted {\n /// ID of the deleted message.\n msg_id: MsgId,\n },\n\n /// Tells that the Background fetch was completed (or timed out).\n /// This event acts as a marker, when you reach this event you can be sure\n /// that all events emitted during the background fetch were processed.\n ///\n /// This event is only emitted by the account manager\n AccountsBackgroundFetchDone,\n /// Inform that set of chats or the order of the chats in the chatlist has changed.\n ///\n /// Sometimes this is emitted together with `UIChatlistItemChanged`.\n ChatlistChanged,\n\n /// Inform that a single chat list item changed and needs to be rerendered.\n /// 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.\n ChatlistItemChanged {\n /// ID of the changed chat\n chat_id: Option,\n },\n\n /// Event for using in tests, e.g. as a fence between normally generated events.\n #[cfg(test)]\n Test,\n\n /// Inform than some events have been skipped due to event channel overflow.\n EventChannelOverflow {\n /// Number of events skipped.\n n: u64,\n },\n}\n\npub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__133.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "int dc_chat_is_self_talk(const dc_chat_t* chat)\n{\n\tif (chat==NULL || chat->magic!=DC_CHAT_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn dc_param_exists(chat->param, DC_PARAM_SELFTALK);\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub fn is_self_talk(&self) -> bool {\n self.param.exists(Param::Selftalk)\n }", "rust_context": "pub fn exists(&self, key: Param) -> bool {\n self.inner.contains_key(&key)\n }\n\npub struct Chat {\n /// Database ID.\n pub id: ChatId,\n\n /// Chat type, e.g. 1:1 chat, group chat, mailing list.\n pub typ: Chattype,\n\n /// Chat name.\n pub name: String,\n\n /// Whether the chat is archived or pinned.\n pub visibility: ChatVisibility,\n\n /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and\n /// ad-hoc groups.\n pub grpid: String,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n\n /// Additional chat parameters stored in the database.\n pub param: Params,\n\n /// If location streaming is enabled in the chat.\n is_sending_locations: bool,\n\n /// Duration of the chat being muted.\n pub mute_duration: MuteDuration,\n\n /// If the chat is protected (verified).\n pub(crate) protected: ProtectionStatus,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}\n\npub struct ChatId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__61.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "void dc_msg_set_file(dc_msg_t* msg, const char* file, const char* filemime)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn;\n\t}\n\tdc_param_set(msg->param, DC_PARAM_FILE, file);\n\tdc_param_set_optional(msg->param, DC_PARAM_MIMETYPE, filemime);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn set_file(&mut self, file: impl ToString, filemime: Option<&str>) {\n if let Some(name) = Path::new(&file.to_string()).file_name() {\n if let Some(name) = name.to_str() {\n self.param.set(Param::Filename, name);\n }\n }\n self.param.set(Param::File, file);\n self.param.set_optional(Param::MimeType, filemime);\n }", "rust_context": "pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self {\n self.inner.insert(key, value.to_string());\n self\n }\n\npub fn set_optional(&mut self, key: Param, value: Option) -> &mut Self {\n if let Some(value) = value {\n self.set(key, value)\n } else {\n self.remove(key)\n }\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__68.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "int dc_is_contact_in_chat(dc_context_t* context, uint32_t chat_id, uint32_t contact_id)\n{\n\t/* this function works for group and for normal chats, however, it is more useful for group chats.\n\tDC_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) */\n\tint ret = 0;\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT COUNT(*) FROM chats_contacts WHERE chat_id=? AND contact_id=?;\");\n\tsqlite3_bind_int(stmt, 1, chat_id);\n\tsqlite3_bind_int(stmt, 2, contact_id);\n\tret = sqlite3_step(stmt);\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn is_contact_in_chat(\n context: &Context,\n chat_id: ChatId,\n contact_id: ContactId,\n) -> Result {\n // this function works for group and for normal chats, however, it is more useful\n // for group chats.\n // ContactId::SELF may be used to check, if the user itself is in a group\n // chat (ContactId::SELF is not added to normal chats)\n\n let exists = context\n .sql\n .exists(\n \"SELECT COUNT(*) FROM chats_contacts WHERE chat_id=? AND contact_id=?;\",\n (chat_id, contact_id),\n )\n .await?;\n Ok(exists)\n}", "rust_context": "pub async fn exists(&self, sql: &str, params: impl rusqlite::Params + Send) -> Result {\n let count = self.count(sql, params).await?;\n Ok(count > 0)\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub struct ContactId(u32);\n\npub struct ChatId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__103.txt"} {"c_path": "projects/deltachat-core/c/dc_context.c", "c_func": "* The returned string must be free()'d.\n */\nchar* dc_get_blobdir(const dc_context_t* context)\n{\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\treturn dc_strdup(NULL);\n\t}\n\treturn dc_strdup(context->blobdir);\n}", "rust_path": "projects/deltachat-core/rust/context.rs", "rust_func": "pub fn get_blobdir(&self) -> &Path {\n self.blobdir.as_path()\n }", "rust_context": "pub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}", "rust_imports": "use std::collections::{BTreeMap, HashMap};\nuse std::ffi::OsString;\nuse std::ops::Deref;\nuse std::path::{Path, PathBuf};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\nuse std::time::Duration;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse pgp::SignedPublicKey;\nuse ratelimit::Ratelimit;\nuse tokio::sync::{Mutex, Notify, OnceCell, RwLock};\nuse crate::aheader::EncryptPreference;\nuse crate::chat::{get_chat_cnt, ChatId, ProtectionStatus};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::debug_logging::DebugLogging;\nuse crate::download::DownloadState;\nuse crate::events::{Event, EventEmitter, EventType, Events};\nuse crate::imap::{FolderMeaning, Imap, ServerMetadata};\nuse crate::key::{load_self_public_key, load_self_secret_key, DcKey as _};\nuse crate::login_param::LoginParam;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peer_channels::Iroh;\nuse crate::peerstate::Peerstate;\nuse crate::push::PushSubscriber;\nuse crate::quota::QuotaInfo;\nuse crate::scheduler::{convert_folder_meaning, SchedulerState};\nuse crate::sql::Sql;\nuse crate::stock_str::StockStrings;\nuse crate::timesmearing::SmearedTimestamp;\nuse crate::tools::{self, create_id, duration_to_str, time, time_elapsed};\nuse anyhow::Context as _;\nuse strum::IntoEnumIterator;\nuse tempfile::tempdir;\nuse super::*;\nuse crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration};\nuse crate::chatlist::Chatlist;\nuse crate::constants::Chattype;\nuse crate::mimeparser::SystemMessage;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{get_chat_msg, TestContext};\nuse crate::tools::{create_outgoing_rfc724_mid, SystemTime};", "rustrepotrans_file": "projects__deltachat-core__rust__context__.rs__function__29.txt"} {"c_path": "projects/deltachat-core/c/dc_e2ee.c", "c_func": "static int has_decrypted_pgp_armor(const char* str__, int str_bytes)\n{\n\tconst unsigned char* str_end = (const unsigned char*)str__+str_bytes;\n\tconst unsigned char* p=(const unsigned char*)str__;\n\twhile (p < str_end) {\n\t\tif (*p > ' ') {\n\t\t\tbreak;\n\t\t}\n\t\tp++;\n\t\tstr_bytes--;\n\t}\n\tif (str_bytes>26 && strncmp((const char*)p, \"-----BEGIN PGP MESSAGE-----\", 27)==0) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "rust_path": "projects/deltachat-core/rust/decrypt.rs", "rust_func": "fn has_decrypted_pgp_armor(input: &[u8]) -> bool {\n if let Some(index) = input.iter().position(|b| *b > b' ') {\n if input.len() - index > 26 {\n let start = index;\n let end = start + 27;\n\n return &input[start..end] == b\"-----BEGIN PGP MESSAGE-----\";\n }\n }\n\n false\n}", "rust_context": "", "rust_imports": "use std::collections::HashSet;\nuse std::str::FromStr;\nuse anyhow::Result;\nuse deltachat_contact_tools::addr_cmp;\nuse mailparse::ParsedMail;\nuse crate::aheader::Aheader;\nuse crate::authres::handle_authres;\nuse crate::authres::{self, DkimResults};\nuse crate::context::Context;\nuse crate::headerdef::{HeaderDef, HeaderDefMap};\nuse crate::key::{DcKey, Fingerprint, SignedPublicKey, SignedSecretKey};\nuse crate::peerstate::Peerstate;\nuse crate::pgp;\nuse super::*;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__decrypt__.rs__function__8.txt"} {"c_path": "projects/deltachat-core/c/dc_tools.c", "c_func": "int dc_write_file(dc_context_t* context, const char* pathNfilename, const void* buf, size_t buf_bytes)\n{\n\tint success = 0;\n\tchar* pathNfilename_abs = NULL;\n\n\tif ((pathNfilename_abs=dc_get_abs_path(context, pathNfilename))==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tFILE* f = fopen(pathNfilename_abs, \"wb\");\n\tif (f) {\n\t\tif (fwrite(buf, 1, buf_bytes, f)==buf_bytes) {\n\t\t\tsuccess = 1;\n\t\t}\n\t\telse {\n\t\t\tdc_log_warning(context, 0, \"Cannot write %lu bytes to \\\"%s\\\".\", (unsigned long)buf_bytes, pathNfilename);\n\t\t}\n\t\tfclose(f);\n\t}\n\telse {\n\t\tdc_log_warning(context, 0, \"Cannot open \\\"%s\\\" for writing.\", pathNfilename);\n\t}\n\ncleanup:\n\tfree(pathNfilename_abs);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/tools.rs", "rust_func": "pub(crate) async fn write_file(\n context: &Context,\n path: impl AsRef,\n buf: &[u8],\n) -> Result<(), io::Error> {\n let path_abs = get_abs_path(context, path.as_ref());\n fs::write(&path_abs, buf).await.map_err(|err| {\n warn!(\n context,\n \"Cannot write {} bytes to \\\"{}\\\": {}\",\n buf.len(),\n path.as_ref().display(),\n err\n );\n err\n })\n}", "rust_context": "pub(crate) fn get_abs_path(context: &Context, path: &Path) -> PathBuf {\n if let Ok(p) = path.strip_prefix(\"$BLOBDIR\") {\n context.get_blobdir().join(p)\n } else {\n path.into()\n }\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}", "rust_imports": "use std::borrow::Cow;\nuse std::io::{Cursor, Write};\nuse std::mem;\nuse std::path::{Path, PathBuf};\nuse std::str::from_utf8;\nuse std::time::Duration;\nuse std::time::SystemTime as Time;\nuse std::time::SystemTime;\nuse anyhow::{bail, Context as _, Result};\nuse base64::Engine as _;\nuse chrono::{Local, NaiveDateTime, NaiveTime, TimeZone};\nuse deltachat_contact_tools::{strip_rtlo_characters, EmailAddress};\nuse deltachat_time::SystemTimeTools as SystemTime;\nuse futures::{StreamExt, TryStreamExt};\nuse mailparse::dateparse;\nuse mailparse::headers::Headers;\nuse mailparse::MailHeaderMap;\nuse rand::{thread_rng, Rng};\nuse tokio::{fs, io};\nuse url::Url;\nuse crate::chat::{add_device_msg, add_device_msg_with_importance};\nuse crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, Viewtype};\nuse crate::stock_str;\nuse chrono::NaiveDate;\nuse proptest::prelude::*;\nuse super::*;\nuse crate::chatlist::Chatlist;\nuse crate::{chat, test_utils};\nuse crate::{receive_imf::receive_imf, test_utils::TestContext};\nuse super::*;", "rustrepotrans_file": "projects__deltachat-core__rust__tools__.rs__function__23.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_get_height(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn dc_param_get_int(msg->param, DC_PARAM_HEIGHT, 0);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn get_height(&self) -> i32 {\n self.param.get_int(Param::Height).unwrap_or_default()\n }", "rust_context": "pub fn get_int(&self, key: Param) -> Option {\n self.get(key).and_then(|s| s.parse().ok())\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__44.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "uint32_t dc_chat_get_id(const dc_chat_t* chat)\n{\n\tif (chat==NULL || chat->magic!=DC_CHAT_MAGIC) {\n\t\treturn 0;\n\t}\n\n\treturn chat->id;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub fn get_id(&self) -> ChatId {\n self.id\n }", "rust_context": "pub struct Chat {\n /// Database ID.\n pub id: ChatId,\n\n /// Chat type, e.g. 1:1 chat, group chat, mailing list.\n pub typ: Chattype,\n\n /// Chat name.\n pub name: String,\n\n /// Whether the chat is archived or pinned.\n pub visibility: ChatVisibility,\n\n /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and\n /// ad-hoc groups.\n pub grpid: String,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n\n /// Additional chat parameters stored in the database.\n pub param: Params,\n\n /// If location streaming is enabled in the chat.\n is_sending_locations: bool,\n\n /// Duration of the chat being muted.\n pub mute_duration: MuteDuration,\n\n /// If the chat is protected (verified).\n pub(crate) protected: ProtectionStatus,\n}\n\npub struct ChatId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__69.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "void dc_msg_set_text(dc_msg_t* msg, const char* text)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn;\n\t}\n\tfree(msg->text);\n\tmsg->text = dc_strdup(text);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn set_text(&mut self, text: String) {\n self.text = text;\n }", "rust_context": "pub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__66.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "uint32_t dc_get_chat_id_by_grpid(dc_context_t* context, const char* grpid, int* ret_blocked, int* ret_verified)\n{\n\tuint32_t chat_id = 0;\n\tsqlite3_stmt* stmt = NULL;\n\n\tif(ret_blocked) { *ret_blocked = 0; }\n\tif(ret_verified) { *ret_verified = 0; }\n\n\tif (context==NULL || grpid==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT id, blocked, protected FROM chats WHERE grpid=?;\");\n\tsqlite3_bind_text (stmt, 1, grpid, -1, SQLITE_STATIC);\n\tif (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\t chat_id = sqlite3_column_int(stmt, 0);\n\t\tif(ret_blocked) { *ret_blocked = sqlite3_column_int(stmt, 1); }\n\t\tif(ret_verified) { *ret_verified = (sqlite3_column_int(stmt, 2)==DC_CHAT_PROTECTIONSTATUS_PROTECTED); }\n\t}\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn chat_id;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub(crate) async fn get_chat_id_by_grpid(\n context: &Context,\n grpid: &str,\n) -> Result> {\n context\n .sql\n .query_row_optional(\n \"SELECT id, blocked, protected FROM chats WHERE grpid=?;\",\n (grpid,),\n |row| {\n let chat_id = row.get::<_, ChatId>(0)?;\n\n let b = row.get::<_, Option>(1)?.unwrap_or_default();\n let p = row\n .get::<_, Option>(2)?\n .unwrap_or_default();\n Ok((chat_id, p == ProtectionStatus::Protected, b))\n },\n )\n .await\n}", "rust_context": "pub async fn query_row_optional(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n ) -> Result>\n where\n F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result,\n T: Send + 'static,\n {\n self.call(move |conn| match conn.query_row(sql.as_ref(), params, f) {\n Ok(res) => Ok(Some(res)),\n Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),\n Err(rusqlite::Error::InvalidColumnType(_, _, rusqlite::types::Type::Null)) => Ok(None),\n Err(err) => Err(err.into()),\n })\n .await\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ChatId(u32);\n\npub enum Blocked {\n #[default]\n Not = 0,\n Yes = 1,\n Request = 2,\n}\n\npub enum ProtectionStatus {\n /// Chat is not protected.\n #[default]\n Unprotected = 0,\n\n /// Chat is protected.\n ///\n /// All members of the chat must be verified.\n Protected = 1,\n\n /// The chat was protected, but now a new message came in\n /// which was not encrypted / signed correctly.\n /// The user has to confirm that this is OK.\n ///\n /// We only do this in 1:1 chats; in group chats, the chat just\n /// stays protected.\n ProtectionBroken = 3, // `2` was never used as a value.\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__142.txt"} {"c_path": "projects/deltachat-core/c/dc_strencode.c", "c_func": "int dc_needs_ext_header(const char* to_check)\n{\n\tif (to_check) {\n\t\twhile (*to_check)\n\t\t{\n\t\t\tif (!isalnum(*to_check) && *to_check!='-' && *to_check!='_' && *to_check!='.' && *to_check!='~' && *to_check!='%') {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tto_check++;\n\t\t}\n\t}\n\n\treturn 0;\n}", "rust_path": "projects/deltachat-core/rust/mimefactory.rs", "rust_func": "fn needs_encoding(to_check: &str) -> bool {\n !to_check.chars().all(|c| {\n c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' || c == '%'\n })\n}", "rust_context": "", "rust_imports": "use deltachat_contact_tools::ContactAddress;\nuse mailparse::{addrparse_header, MailHeaderMap};\nuse std::str;\nuse super::*;\nuse crate::chat::{\n add_contact_to_chat, create_group_chat, remove_contact_from_chat, send_text_msg, ChatId,\n ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::constants;\nuse crate::contact::Origin;\nuse crate::mimeparser::MimeMessage;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{get_chat_msg, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__mimefactory__.rs__function__26.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "void dc_set_msg_failed(dc_context_t* context, uint32_t msg_id, const char* error)\n{\n\tdc_msg_t* msg = dc_msg_new_untyped(context);\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (!dc_msg_load_from_db(msg, context, msg_id)) {\n\t\tgoto cleanup;\n\t}\n\n\tif (DC_STATE_OUT_PREPARING==msg->state ||\n\t DC_STATE_OUT_PENDING ==msg->state ||\n\t DC_STATE_OUT_DELIVERED==msg->state)\n\t{\n\t\tmsg->state = DC_STATE_OUT_FAILED;\n\t}\n\n\tif (error) {\n\t\tdc_param_set(msg->param, DC_PARAM_ERROR, error);\n\t\tdc_log_error(context, 0, \"%s\", error);\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"UPDATE msgs SET state=?, param=? WHERE id=?;\");\n\tsqlite3_bind_int (stmt, 1, msg->state);\n\tsqlite3_bind_text(stmt, 2, msg->param->packed, -1, SQLITE_STATIC);\n\tsqlite3_bind_int (stmt, 3, msg_id);\n\tsqlite3_step(stmt);\n\n\tcontext->cb(context, DC_EVENT_MSG_FAILED, msg->chat_id, msg_id);\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\tdc_msg_unref(msg);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub(crate) async fn set_msg_failed(\n context: &Context,\n msg: &mut Message,\n error: &str,\n) -> Result<()> {\n if msg.state.can_fail() {\n msg.state = MessageState::OutFailed;\n warn!(context, \"{} failed: {}\", msg.id, error);\n } else {\n warn!(\n context,\n \"{} seems to have failed ({}), but state is {}\", msg.id, error, msg.state\n )\n }\n msg.error = Some(error.to_string());\n\n context\n .sql\n .execute(\n \"UPDATE msgs SET state=?, error=? WHERE id=?;\",\n (msg.state, error, msg.id),\n )\n .await?;\n\n context.emit_event(EventType::MsgFailed {\n chat_id: msg.chat_id,\n msg_id: msg.id,\n });\n chatlist_events::emit_chatlist_item_changed(context, msg.chat_id);\n\n Ok(())\n}", "rust_context": "pub fn can_fail(self) -> bool {\n use MessageState::*;\n matches!(\n self,\n OutPreparing | OutPending | OutDelivered | OutMdnRcvd // OutMdnRcvd can still fail because it could be a group message and only some recipients failed.\n )\n }\n\nmacro_rules! warn {\n ($ctx:expr, $msg:expr) => {\n warn!($ctx, $msg,)\n };\n ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{\n let formatted = format!($msg, $($args),*);\n let full = format!(\"{file}:{line}: {msg}\",\n file = file!(),\n line = line!(),\n msg = &formatted);\n $ctx.emit_event($crate::EventType::Warning(full));\n }};\n}\n\npub fn emit_event(&self, event: EventType) {\n {\n let lock = self.debug_logging.read().expect(\"RwLock is poisoned\");\n if let Some(debug_logging) = &*lock {\n debug_logging.log_event(event.clone());\n }\n }\n self.events.emit(Event {\n id: self.id,\n typ: event,\n });\n }\n\npub(crate) fn emit_chatlist_item_changed(context: &Context, chat_id: ChatId) {\n context.emit_event(EventType::ChatlistItemChanged {\n chat_id: Some(chat_id),\n });\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum MessageState {\n /// Undefined message state.\n #[default]\n Undefined = 0,\n\n /// Incoming *fresh* message. Fresh messages are neither noticed\n /// nor seen and are typically shown in notifications.\n InFresh = 10,\n\n /// Incoming *noticed* message. E.g. chat opened but message not\n /// yet read - noticed messages are not counted as unread but did\n /// not marked as read nor resulted in MDNs.\n InNoticed = 13,\n\n /// Incoming message, really *seen* by the user. Marked as read on\n /// IMAP and MDN may be sent.\n InSeen = 16,\n\n /// For files which need time to be prepared before they can be\n /// sent, the message enters this state before\n /// OutPending.\n OutPreparing = 18,\n\n /// Message saved as draft.\n OutDraft = 19,\n\n /// The user has pressed the \"send\" button but the message is not\n /// yet sent and is pending in some way. Maybe we're offline (no\n /// checkmark).\n OutPending = 20,\n\n /// *Unrecoverable* error (*recoverable* errors result in pending\n /// messages).\n OutFailed = 24,\n\n /// Outgoing message successfully delivered to server (one\n /// checkmark). Note, that already delivered messages may get into\n /// the OutFailed state if we get such a hint from the server.\n OutDelivered = 26,\n\n /// Outgoing message read by the recipient (two checkmarks; this\n /// requires goodwill on the receiver's side)\n OutMdnRcvd = 28,\n}\n\npub enum EventType {\n /// The library-user may write an informational string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Info(String),\n\n /// Emitted when SMTP connection is established and login was successful.\n SmtpConnected(String),\n\n /// Emitted when IMAP connection is established and login was successful.\n ImapConnected(String),\n\n /// Emitted when a message was successfully sent to the SMTP server.\n SmtpMessageSent(String),\n\n /// Emitted when an IMAP message has been marked as deleted\n ImapMessageDeleted(String),\n\n /// Emitted when an IMAP message has been moved\n ImapMessageMoved(String),\n\n /// Emitted before going into IDLE on the Inbox folder.\n ImapInboxIdle,\n\n /// Emitted when an new file in the $BLOBDIR was created\n NewBlobFile(String),\n\n /// Emitted when an file in the $BLOBDIR was deleted\n DeletedBlobFile(String),\n\n /// The library-user should write a warning string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Warning(String),\n\n /// The library-user should report an error to the end-user.\n ///\n /// As most things are asynchronous, things may go wrong at any time and the user\n /// should not be disturbed by a dialog or so. Instead, use a bubble or so.\n ///\n /// However, for ongoing processes (eg. configure())\n /// or for functions that are expected to fail (eg. dc_continue_key_transfer())\n /// it might be better to delay showing these events until the function has really\n /// failed (returned false). It should be sufficient to report only the *last* error\n /// in a messasge box then.\n Error(String),\n\n /// An action cannot be performed because the user is not in the group.\n /// Reported eg. after a call to\n /// dc_set_chat_name(), dc_set_chat_profile_image(),\n /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(),\n /// dc_send_text_msg() or another sending function.\n ErrorSelfNotInGroup(String),\n\n /// Messages or chats changed. One or more messages or chats changed for various\n /// reasons in the database:\n /// - Messages sent, received or removed\n /// - Chats created, deleted or archived\n /// - A draft has been set\n ///\n MsgsChanged {\n /// Set if only a single chat is affected by the changes, otherwise 0.\n chat_id: ChatId,\n\n /// Set if only a single message is affected by the changes, otherwise 0.\n msg_id: MsgId,\n },\n\n /// Reactions for the message changed.\n ReactionsChanged {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message for which reactions were changed.\n msg_id: MsgId,\n\n /// ID of the contact whose reaction set is changed.\n contact_id: ContactId,\n },\n\n /// There is a fresh message. Typically, the user will show an notification\n /// when receiving this message.\n ///\n /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event.\n IncomingMsg {\n /// ID of the chat where the message is assigned.\n chat_id: ChatId,\n\n /// ID of the message.\n msg_id: MsgId,\n },\n\n /// Downloading a bunch of messages just finished.\n IncomingMsgBunch,\n\n /// Messages were seen or noticed.\n /// chat id is always set.\n MsgsNoticed(ChatId),\n\n /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to\n /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state().\n MsgDelivered {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was successfully sent.\n msg_id: MsgId,\n },\n\n /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_FAILED, see dc_msg_get_state().\n MsgFailed {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that could not be sent.\n msg_id: MsgId,\n },\n\n /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state().\n MsgRead {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was read.\n msg_id: MsgId,\n },\n\n /// A single message was deleted.\n ///\n /// This event means that the message will no longer appear in the messagelist.\n /// UI should remove the message from the messagelist\n /// in response to this event if the message is currently displayed.\n ///\n /// The message may have been explicitly deleted by the user or expired.\n /// Internally the message may have been removed from the database,\n /// moved to the trash chat or hidden.\n ///\n /// This event does not indicate the message\n /// deletion from the server.\n MsgDeleted {\n /// ID of the chat where the message was prior to deletion.\n /// Never 0 or trash chat.\n chat_id: ChatId,\n\n /// ID of the deleted message. Never 0.\n msg_id: MsgId,\n },\n\n /// Chat changed. The name or the image of a chat group was changed or members were added or removed.\n /// Or the verify state of a chat has changed.\n /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat()\n /// and dc_remove_contact_from_chat().\n ///\n /// This event does not include ephemeral timer modification, which\n /// is a separate event.\n ChatModified(ChatId),\n\n /// Chat ephemeral timer changed.\n ChatEphemeralTimerModified {\n /// Chat ID.\n chat_id: ChatId,\n\n /// New ephemeral timer value.\n timer: EphemeralTimer,\n },\n\n /// Contact(s) created, renamed, blocked, deleted or changed their \"recently seen\" status.\n ///\n /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected.\n ContactsChanged(Option),\n\n /// Location of one or more contact has changed.\n ///\n /// @param data1 (u32) contact_id of the contact for which the location has changed.\n /// If the locations of several contacts have been changed,\n /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`.\n LocationChanged(Option),\n\n /// Inform about the configuration progress started by configure().\n ConfigureProgress {\n /// Progress.\n ///\n /// 0=error, 1-999=progress in permille, 1000=success and done\n progress: usize,\n\n /// Progress comment or error, something to display to the user.\n comment: Option,\n },\n\n /// Inform about the import/export progress started by imex().\n ///\n /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done\n /// @param data2 0\n ImexProgress(usize),\n\n /// A file has been exported. A file has been written by imex().\n /// This event may be sent multiple times by a single call to imex().\n ///\n /// A typical purpose for a handler of this event may be to make the file public to some system\n /// services.\n ///\n /// @param data2 0\n ImexFileWritten(PathBuf),\n\n /// Progress information of a secure-join handshake from the view of the inviter\n /// (Alice, the person who shows the QR code).\n ///\n /// These events are typically sent after a joiner has scanned the QR code\n /// generated by dc_get_securejoin_qr().\n SecurejoinInviterProgress {\n /// ID of the contact that wants to join.\n contact_id: ContactId,\n\n /// Progress as:\n /// 300=vg-/vc-request received, typically shown as \"bob@addr joins\".\n /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as \"bob@addr verified\".\n /// 800=contact added to chat, shown as \"bob@addr securely joined GROUP\". Only for the verified-group-protocol.\n /// 1000=Protocol finished for this contact.\n progress: usize,\n },\n\n /// Progress information of a secure-join handshake from the view of the joiner\n /// (Bob, the person who scans the QR code).\n /// The events are typically sent while dc_join_securejoin(), which\n /// may take some time, is executed.\n SecurejoinJoinerProgress {\n /// ID of the inviting contact.\n contact_id: ContactId,\n\n /// Progress as:\n /// 400=vg-/vc-request-with-auth sent, typically shown as \"alice@addr verified, introducing myself.\"\n /// (Bob has verified alice and waits until Alice does the same for him)\n /// 1000=vg-member-added/vc-contact-confirm received\n progress: usize,\n },\n\n /// The connectivity to the server changed.\n /// This means that you should refresh the connectivity view\n /// and possibly the connectivtiy HTML; see dc_get_connectivity() and\n /// dc_get_connectivity_html() for details.\n ConnectivityChanged,\n\n /// The user's avatar changed.\n /// Deprecated by `ConfigSynced`.\n SelfavatarChanged,\n\n /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For\n /// uniformity this is emitted on the source device too. The value isn't here, otherwise it\n /// would be logged which might not be good for privacy.\n ConfigSynced {\n /// Configuration key.\n key: Config,\n },\n\n /// Webxdc status update received.\n WebxdcStatusUpdate {\n /// Message ID.\n msg_id: MsgId,\n\n /// Status update ID.\n status_update_serial: StatusUpdateSerial,\n },\n\n /// Data received over an ephemeral peer channel.\n WebxdcRealtimeData {\n /// Message ID.\n msg_id: MsgId,\n\n /// Realtime data.\n data: Vec,\n },\n\n /// Inform that a message containing a webxdc instance has been deleted.\n WebxdcInstanceDeleted {\n /// ID of the deleted message.\n msg_id: MsgId,\n },\n\n /// Tells that the Background fetch was completed (or timed out).\n /// This event acts as a marker, when you reach this event you can be sure\n /// that all events emitted during the background fetch were processed.\n ///\n /// This event is only emitted by the account manager\n AccountsBackgroundFetchDone,\n /// Inform that set of chats or the order of the chats in the chatlist has changed.\n ///\n /// Sometimes this is emitted together with `UIChatlistItemChanged`.\n ChatlistChanged,\n\n /// Inform that a single chat list item changed and needs to be rerendered.\n /// 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.\n ChatlistItemChanged {\n /// ID of the changed chat\n chat_id: Option,\n },\n\n /// Event for using in tests, e.g. as a fence between normally generated events.\n #[cfg(test)]\n Test,\n\n /// Inform than some events have been skipped due to event channel overflow.\n EventChannelOverflow {\n /// Number of events skipped.\n n: u64,\n },\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__92.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* using dc_set_chat_profile_image().\n * For normal chats, this is the image set by each remote user on their own\n * using dc_set_config(context, \"selfavatar\", image).\n *\n * @memberof dc_chat_t\n * @param chat The chat object.\n * @return Path and file if the profile image, if any.\n * NULL otherwise.\n * Must be free()'d after usage.\n */\nchar* dc_chat_get_profile_image(const dc_chat_t* chat)\n{\n\tchar* image_rel = NULL;\n\tchar* image_abs = NULL;\n\tdc_array_t* contacts = NULL;\n\tdc_contact_t* contact = NULL;\n\n\tif (chat==NULL || chat->magic!=DC_CHAT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\timage_rel = dc_param_get(chat->param, DC_PARAM_PROFILE_IMAGE, NULL);\n\tif (image_rel && image_rel[0]) {\n\t\timage_abs = dc_get_abs_path(chat->context, image_rel);\n\t}\n else if (chat-id == DC_CHAT_ID_ARCHIVED_LINK) {\n image_rel = dc_get_archive_icon(chat->context);\n if (image_rel){\n image_abs = dc_get_abs_path(chat->context, image_rel); \n }\n }\n\telse if(chat->type==DC_CHAT_TYPE_SINGLE) {\n\t\tcontacts = dc_get_chat_contacts(chat->context, chat->id);\n\t\tif (contacts->count >= 1) {\n\t\t\tcontact = dc_get_contact(chat->context, contacts->array[0]);\n\t\t\timage_abs = dc_contact_get_profile_image(contact);\n\t\t}\n\t}\n else if(chat->type==DC_CHAT_TYPE_BROADCAST) {\n\t\timage_rel = dc_get_broadcast_icon(chat->context);\n if (image_rel){\n image_abs = dc_get_abs_path(chat->context, image_rel); \n }\n\t}\n\ncleanup:\n\tfree(image_rel);\n\tdc_array_unref(contacts);\n\tdc_contact_unref(contact);\n\treturn image_abs;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn get_profile_image(&self, context: &Context) -> Result> {\n if let Some(image_rel) = self.param.get(Param::ProfileImage) {\n if !image_rel.is_empty() {\n return Ok(Some(get_abs_path(context, Path::new(&image_rel))));\n }\n } else if self.id.is_archived_link() {\n if let Ok(image_rel) = get_archive_icon(context).await {\n return Ok(Some(get_abs_path(context, Path::new(&image_rel))));\n }\n } else if self.typ == Chattype::Single {\n let contacts = get_chat_contacts(context, self.id).await?;\n if let Some(contact_id) = contacts.first() {\n if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {\n return contact.get_profile_image(context).await;\n }\n }\n } else if self.typ == Chattype::Broadcast {\n if let Ok(image_rel) = get_broadcast_icon(context).await {\n return Ok(Some(get_abs_path(context, Path::new(&image_rel))));\n }\n }\n Ok(None)\n }", "rust_context": "pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result> {\n // Normal chats do not include SELF. Group chats do (as it may happen that one is deleted from a\n // groupchat but the chats stays visible, moreover, this makes displaying lists easier)\n\n let list = context\n .sql\n .query_map(\n \"SELECT cc.contact_id\n FROM chats_contacts cc\n LEFT JOIN contacts c\n ON c.id=cc.contact_id\n WHERE cc.chat_id=?\n ORDER BY c.id=1, c.last_seen DESC, c.id DESC;\",\n (chat_id,),\n |row| row.get::<_, ContactId>(0),\n |ids| ids.collect::, _>>().map_err(Into::into),\n )\n .await?;\n\n Ok(list)\n}\n\npub(crate) async fn get_broadcast_icon(context: &Context) -> Result {\n if let Some(icon) = context.sql.get_raw_config(\"icon-broadcast\").await? {\n return Ok(icon);\n }\n\n let icon = include_bytes!(\"../assets/icon-broadcast.png\");\n let blob = BlobObject::create(context, \"icon-broadcast.png\", icon).await?;\n let icon = blob.as_name().to_string();\n context\n .sql\n .set_raw_config(\"icon-broadcast\", Some(&icon))\n .await?;\n Ok(icon)\n}\n\npub fn get(&self, key: Param) -> Option<&str> {\n self.inner.get(&key).map(|s| s.as_str())\n }\n\npub fn is_archived_link(self) -> bool {\n self == DC_CHAT_ID_ARCHIVED_LINK\n }\n\npub(crate) async fn get_archive_icon(context: &Context) -> Result {\n if let Some(icon) = context.sql.get_raw_config(\"icon-archive\").await? {\n return Ok(icon);\n }\n\n let icon = include_bytes!(\"../assets/icon-archive.png\");\n let blob = BlobObject::create(context, \"icon-archive.png\", icon).await?;\n let icon = blob.as_name().to_string();\n context\n .sql\n .set_raw_config(\"icon-archive\", Some(&icon))\n .await?;\n Ok(icon)\n}\n\npub fn is_empty(&self) -> bool {\n self.inner.is_empty()\n }\n\npub(crate) fn get_abs_path(context: &Context, path: &Path) -> PathBuf {\n if let Ok(p) = path.strip_prefix(\"$BLOBDIR\") {\n context.get_blobdir().join(p)\n } else {\n path.into()\n }\n}\n\npub async fn get_by_id(context: &Context, contact_id: ContactId) -> Result {\n let contact = Self::get_by_id_optional(context, contact_id)\n .await?\n .with_context(|| format!(\"contact {contact_id} not found\"))?;\n Ok(contact)\n }\n\npub fn new + ?Sized>(s: &S) -> &Path {\n unsafe { &*(s.as_ref() as *const OsStr as *const Path) }\n }\n\npub struct Chat {\n /// Database ID.\n pub id: ChatId,\n\n /// Chat type, e.g. 1:1 chat, group chat, mailing list.\n pub typ: Chattype,\n\n /// Chat name.\n pub name: String,\n\n /// Whether the chat is archived or pinned.\n pub visibility: ChatVisibility,\n\n /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and\n /// ad-hoc groups.\n pub grpid: String,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n\n /// Additional chat parameters stored in the database.\n pub param: Params,\n\n /// If location streaming is enabled in the chat.\n is_sending_locations: bool,\n\n /// Duration of the chat being muted.\n pub mute_duration: MuteDuration,\n\n /// If the chat is protected (verified).\n pub(crate) protected: ProtectionStatus,\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub enum Chattype {\n /// 1:1 chat.\n Single = 100,\n\n /// Group chat.\n Group = 120,\n\n /// Mailing list.\n Mailinglist = 140,\n\n /// Broadcast list.\n Broadcast = 160,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__73.txt"} {"c_path": "projects/deltachat-core/c/dc_location.c", "c_func": "dc_kml_t* dc_kml_parse(dc_context_t* context,\n const char* content, size_t content_bytes)\n{\n\tdc_kml_t* kml = calloc(1, sizeof(dc_kml_t));\n\tchar* content_nullterminated = NULL;\n\tdc_saxparser_t saxparser;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tif (content_bytes > 1*1024*1024) {\n\t\tdc_log_warning(context, 0,\n\t\t\t\"A kml-files with %i bytes is larger than reasonably expected.\",\n\t\t\tcontent_bytes);\n\t\tgoto cleanup;\n\t}\n\n\tcontent_nullterminated = dc_null_terminate(content, content_bytes);\n\tif (content_nullterminated==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tkml->locations = dc_array_new_typed(context, DC_ARRAY_LOCATIONS, 100);\n\n\tdc_saxparser_init (&saxparser, kml);\n\tdc_saxparser_set_tag_handler (&saxparser, kml_starttag_cb, kml_endtag_cb);\n\tdc_saxparser_set_text_handler(&saxparser, kml_text_cb);\n\tdc_saxparser_parse (&saxparser, content_nullterminated);\n\ncleanup:\n\tfree(content_nullterminated);\n\treturn kml;\n}", "rust_path": "projects/deltachat-core/rust/location.rs", "rust_func": "pub fn parse(to_parse: &[u8]) -> Result {\n ensure!(to_parse.len() <= 1024 * 1024, \"kml-file is too large\");\n\n let mut reader = quick_xml::Reader::from_reader(to_parse);\n reader.trim_text(true);\n\n let mut kml = Kml::new();\n kml.locations = Vec::with_capacity(100);\n\n let mut buf = Vec::new();\n\n loop {\n match reader.read_event_into(&mut buf).with_context(|| {\n format!(\n \"location parsing error at position {}\",\n reader.buffer_position()\n )\n })? {\n quick_xml::events::Event::Start(ref e) => kml.starttag_cb(e, &reader),\n quick_xml::events::Event::End(ref e) => kml.endtag_cb(e),\n quick_xml::events::Event::Text(ref e) => kml.text_cb(e),\n quick_xml::events::Event::Eof => break,\n _ => (),\n }\n buf.clear();\n }\n\n Ok(kml)\n }", "rust_context": "fn endtag_cb(&mut self, event: &BytesEnd) {\n let tag = String::from_utf8_lossy(event.name().as_ref())\n .trim()\n .to_lowercase();\n\n match self.tag {\n KmlTag::PlacemarkTimestampWhen => {\n if tag == \"when\" {\n self.tag = KmlTag::PlacemarkTimestamp\n }\n }\n KmlTag::PlacemarkTimestamp => {\n if tag == \"timestamp\" {\n self.tag = KmlTag::Placemark\n }\n }\n KmlTag::PlacemarkPointCoordinates => {\n if tag == \"coordinates\" {\n self.tag = KmlTag::PlacemarkPoint\n }\n }\n KmlTag::PlacemarkPoint => {\n if tag == \"point\" {\n self.tag = KmlTag::Placemark\n }\n }\n KmlTag::Placemark => {\n if tag == \"placemark\" {\n if 0 != self.curr.timestamp\n && 0. != self.curr.latitude\n && 0. != self.curr.longitude\n {\n self.locations\n .push(std::mem::replace(&mut self.curr, Location::new()));\n }\n self.tag = KmlTag::Undefined;\n }\n }\n KmlTag::Undefined => {}\n }\n }\n\nfn starttag_cb(\n &mut self,\n event: &BytesStart,\n reader: &quick_xml::Reader,\n ) {\n let tag = String::from_utf8_lossy(event.name().as_ref())\n .trim()\n .to_lowercase();\n if tag == \"document\" {\n if let Some(addr) = event.attributes().filter_map(|a| a.ok()).find(|attr| {\n String::from_utf8_lossy(attr.key.as_ref())\n .trim()\n .to_lowercase()\n == \"addr\"\n }) {\n self.addr = addr\n .decode_and_unescape_value(reader)\n .ok()\n .map(|a| a.into_owned());\n }\n } else if tag == \"placemark\" {\n self.tag = KmlTag::Placemark;\n self.curr.timestamp = 0;\n self.curr.latitude = 0.0;\n self.curr.longitude = 0.0;\n self.curr.accuracy = 0.0\n } else if tag == \"timestamp\" && self.tag == KmlTag::Placemark {\n self.tag = KmlTag::PlacemarkTimestamp;\n } else if tag == \"when\" && self.tag == KmlTag::PlacemarkTimestamp {\n self.tag = KmlTag::PlacemarkTimestampWhen;\n } else if tag == \"point\" && self.tag == KmlTag::Placemark {\n self.tag = KmlTag::PlacemarkPoint;\n } else if tag == \"coordinates\" && self.tag == KmlTag::PlacemarkPoint {\n self.tag = KmlTag::PlacemarkPointCoordinates;\n if let Some(acc) = event.attributes().find(|attr| {\n attr.as_ref()\n .map(|a| {\n String::from_utf8_lossy(a.key.as_ref())\n .trim()\n .to_lowercase()\n == \"accuracy\"\n })\n .unwrap_or_default()\n }) {\n let v = acc\n .unwrap()\n .decode_and_unescape_value(reader)\n .unwrap_or_default();\n\n self.curr.accuracy = v.trim().parse().unwrap_or_default();\n }\n }\n }\n\nfn text_cb(&mut self, event: &BytesText) {\n if self.tag == KmlTag::PlacemarkTimestampWhen\n || self.tag == KmlTag::PlacemarkPointCoordinates\n {\n let val = event.unescape().unwrap_or_default();\n\n let val = val.replace(['\\n', '\\r', '\\t', ' '], \"\");\n\n if self.tag == KmlTag::PlacemarkTimestampWhen && val.len() >= 19 {\n // YYYY-MM-DDTHH:MM:SSZ\n // 0 4 7 10 13 16 19\n match chrono::NaiveDateTime::parse_from_str(&val, \"%Y-%m-%dT%H:%M:%SZ\") {\n Ok(res) => {\n self.curr.timestamp = res.and_utc().timestamp();\n let now = time();\n if self.curr.timestamp > now {\n self.curr.timestamp = now;\n }\n }\n Err(_err) => {\n self.curr.timestamp = time();\n }\n }\n } else if self.tag == KmlTag::PlacemarkPointCoordinates {\n let parts = val.splitn(2, ',').collect::>();\n if let [longitude, latitude] = &parts[..] {\n self.curr.longitude = longitude.parse().unwrap_or_default();\n self.curr.latitude = latitude.parse().unwrap_or_default();\n }\n }\n }\n }\n\npub struct Kml {\n /// Nonstandard `addr` attribute of the `Document` tag storing the user email address.\n pub addr: Option,\n\n /// Placemarks.\n pub locations: Vec,\n\n /// Currently parsed XML tag.\n tag: KmlTag,\n\n /// Currently parsed placemark.\n pub curr: Location,\n}", "rust_imports": "use std::time::Duration;\nuse anyhow::{ensure, Context as _, Result};\nuse async_channel::Receiver;\nuse quick_xml::events::{BytesEnd, BytesStart, BytesText};\nuse tokio::time::timeout;\nuse crate::chat::{self, ChatId};\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::tools::{duration_to_str, time};\nuse crate::{chatlist_events, stock_str};\nuse super::*;\nuse crate::config::Config;\nuse crate::message::MessageState;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{TestContext, TestContextManager};\nuse crate::tools::SystemTime;", "rustrepotrans_file": "projects__deltachat-core__rust__location__.rs__function__3.txt"} {"c_path": "projects/deltachat-core/c/dc_oauth2.c", "c_func": "char* dc_get_oauth2_url(dc_context_t* context, const char* addr,\n const char* redirect_uri)\n{\n\t#define CLIENT_ID \"959970109878-4mvtgf6feshskf7695nfln6002mom908.apps.googleusercontent.com\"\n\toauth2_t* oauth2 = NULL;\n\tchar* oauth2_url = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC\n\t || redirect_uri==NULL || redirect_uri[0]==0) {\n\t\tgoto cleanup;\n\t}\n\n\toauth2 = get_info(addr);\n\tif (oauth2==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tdc_sqlite3_set_config(context->sql, \"oauth2_pending_redirect_uri\", redirect_uri);\n\n\toauth2_url = dc_strdup(oauth2->get_code);\n\treplace_in_uri(&oauth2_url, \"$CLIENT_ID\", oauth2->client_id);\n\treplace_in_uri(&oauth2_url, \"$REDIRECT_URI\", redirect_uri);\n\ncleanup:\n\tfree(oauth2);\n\treturn oauth2_url;\n}", "rust_path": "projects/deltachat-core/rust/oauth2.rs", "rust_func": "pub async fn get_oauth2_url(\n context: &Context,\n addr: &str,\n redirect_uri: &str,\n) -> Result> {\n let socks5_enabled = context.get_config_bool(Config::Socks5Enabled).await?;\n if let Some(oauth2) = Oauth2::from_address(context, addr, socks5_enabled).await {\n context\n .sql\n .set_raw_config(\"oauth2_pending_redirect_uri\", Some(redirect_uri))\n .await?;\n let oauth2_url = replace_in_uri(oauth2.get_code, \"$CLIENT_ID\", oauth2.client_id);\n let oauth2_url = replace_in_uri(&oauth2_url, \"$REDIRECT_URI\", redirect_uri);\n\n Ok(Some(oauth2_url))\n } else {\n Ok(None)\n }\n}", "rust_context": "pub async fn get_config_bool(&self, key: Config) -> Result {\n Ok(self.get_config_bool_opt(key).await?.unwrap_or_default())\n }\n\nfn replace_in_uri(uri: &str, key: &str, value: &str) -> String {\n let value_urlencoded = utf8_percent_encode(value, NON_ALPHANUMERIC).to_string();\n uri.replace(key, &value_urlencoded)\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub async fn set_raw_config(&self, key: &str, value: Option<&str>) -> Result<()> {\n let mut lock = self.config_cache.write().await;\n if let Some(value) = value {\n self.execute(\n \"INSERT OR REPLACE INTO config (keyname, value) VALUES (?, ?)\",\n (key, value),\n )\n .await?;\n } else {\n self.execute(\"DELETE FROM config WHERE keyname=?\", (key,))\n .await?;\n }\n lock.insert(key.to_string(), value.map(|s| s.to_string()));\n drop(lock);\n\n Ok(())\n }\n \nasync fn from_address(context: &Context, addr: &str, skip_mx: bool) -> Option {\n let addr_normalized = normalize_addr(addr);\n if let Some(domain) = addr_normalized\n .find('@')\n .map(|index| addr_normalized.split_at(index + 1).1)\n {\n if let Some(oauth2_authorizer) = provider::get_provider_info(context, domain, skip_mx)\n .await\n .and_then(|provider| provider.oauth2_authorizer.as_ref())\n {\n return Some(match oauth2_authorizer {\n Oauth2Authorizer::Gmail => OAUTH2_GMAIL,\n Oauth2Authorizer::Yandex => OAUTH2_YANDEX,\n });\n }\n }\n None\n }\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub enum Config {\n /// Email address, used in the `From:` field.\n Addr,\n\n /// IMAP server hostname.\n MailServer,\n\n /// IMAP server username.\n MailUser,\n\n /// IMAP server password.\n MailPw,\n\n /// IMAP server port.\n MailPort,\n\n /// IMAP server security (e.g. TLS, STARTTLS).\n MailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ImapCertificateChecks,\n\n /// SMTP server hostname.\n SendServer,\n\n /// SMTP server username.\n SendUser,\n\n /// SMTP server password.\n SendPw,\n\n /// SMTP server port.\n SendPort,\n\n /// SMTP server security (e.g. TLS, STARTTLS).\n SendSecurity,\n\n /// How to check SMTP server TLS certificates.\n SmtpCertificateChecks,\n\n /// Whether to use OAuth 2.\n ///\n /// Historically contained other bitflags, which are now deprecated.\n /// Should not be extended in the future, create new config keys instead.\n ServerFlags,\n\n /// True if SOCKS5 is enabled.\n ///\n /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.\n Socks5Enabled,\n\n /// SOCKS5 proxy server hostname or address.\n Socks5Host,\n\n /// SOCKS5 proxy server port.\n Socks5Port,\n\n /// SOCKS5 proxy server username.\n Socks5User,\n\n /// SOCKS5 proxy server password.\n Socks5Password,\n\n /// Own name to use in the `From:` field when sending messages.\n Displayname,\n\n /// Own status to display, sent in message footer.\n Selfstatus,\n\n /// Own avatar filename.\n Selfavatar,\n\n /// Send BCC copy to self.\n ///\n /// Should be enabled for multidevice setups.\n #[strum(props(default = \"1\"))]\n BccSelf,\n\n /// True if encryption is preferred according to Autocrypt standard.\n #[strum(props(default = \"1\"))]\n E2eeEnabled,\n\n /// True if Message Delivery Notifications (read receipts) should\n /// be sent and requested.\n #[strum(props(default = \"1\"))]\n MdnsEnabled,\n\n /// True if \"Sent\" folder should be watched for changes.\n #[strum(props(default = \"0\"))]\n SentboxWatch,\n\n /// True if chat messages should be moved to a separate folder.\n #[strum(props(default = \"1\"))]\n MvboxMove,\n\n /// Watch for new messages in the \"Mvbox\" (aka DeltaChat folder) only.\n ///\n /// This will not entirely disable other folders, e.g. the spam folder will also still\n /// be watched for new messages.\n #[strum(props(default = \"0\"))]\n OnlyFetchMvbox,\n\n /// Whether to show classic emails or only chat messages.\n #[strum(props(default = \"2\"))] // also change ShowEmails.default() on changes\n ShowEmails,\n\n /// Quality of the media files to send.\n #[strum(props(default = \"0\"))] // also change MediaQuality.default() on changes\n MediaQuality,\n\n /// If set to \"1\", on the first time `start_io()` is called after configuring,\n /// the newest existing messages are fetched.\n /// Existing recipients are added to the contact database regardless of this setting.\n #[strum(props(default = \"0\"))]\n FetchExistingMsgs,\n\n /// If set to \"1\", then existing messages are considered to be already fetched.\n /// This flag is reset after successful configuration.\n #[strum(props(default = \"1\"))]\n FetchedExistingMsgs,\n\n /// Type of the OpenPGP key to generate.\n #[strum(props(default = \"0\"))]\n KeyGenType,\n\n /// Timer in seconds after which the message is deleted from the\n /// server.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n ///\n /// Value 1 is treated as \"delete at once\": messages are deleted\n /// immediately, without moving to DeltaChat folder.\n #[strum(props(default = \"0\"))]\n DeleteServerAfter,\n\n /// Timer in seconds after which the message is deleted from the\n /// device.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n #[strum(props(default = \"0\"))]\n DeleteDeviceAfter,\n\n /// Move messages to the Trash folder instead of marking them \"\\Deleted\". Overrides\n /// `ProviderOptions::delete_to_trash`.\n DeleteToTrash,\n\n /// Save raw MIME messages with headers in the database if true.\n SaveMimeHeaders,\n\n /// The primary email address. Also see `SecondaryAddrs`.\n ConfiguredAddr,\n\n /// Configured IMAP server hostname.\n ConfiguredMailServer,\n\n /// Configured IMAP server username.\n ConfiguredMailUser,\n\n /// Configured IMAP server password.\n ConfiguredMailPw,\n\n /// Configured IMAP server port.\n ConfiguredMailPort,\n\n /// Configured IMAP server security (e.g. TLS, STARTTLS).\n ConfiguredMailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ConfiguredImapCertificateChecks,\n\n /// Configured SMTP server hostname.\n ConfiguredSendServer,\n\n /// Configured SMTP server username.\n ConfiguredSendUser,\n\n /// Configured SMTP server password.\n ConfiguredSendPw,\n\n /// Configured SMTP server port.\n ConfiguredSendPort,\n\n /// How to check SMTP server TLS certificates.\n ConfiguredSmtpCertificateChecks,\n\n /// Whether OAuth 2 is used with configured provider.\n ConfiguredServerFlags,\n\n /// Configured SMTP server security (e.g. TLS, STARTTLS).\n ConfiguredSendSecurity,\n\n /// Configured folder for incoming messages.\n ConfiguredInboxFolder,\n\n /// Configured folder for chat messages.\n ConfiguredMvboxFolder,\n\n /// Configured \"Sent\" folder.\n ConfiguredSentboxFolder,\n\n /// Configured \"Trash\" folder.\n ConfiguredTrashFolder,\n\n /// Unix timestamp of the last successful configuration.\n ConfiguredTimestamp,\n\n /// ID of the configured provider from the provider database.\n ConfiguredProvider,\n\n /// True if account is configured.\n Configured,\n\n /// True if account is a chatmail account.\n IsChatmail,\n\n /// All secondary self addresses separated by spaces\n /// (`addr1@example.org addr2@example.org addr3@example.org`)\n SecondaryAddrs,\n\n /// Read-only core version string.\n #[strum(serialize = \"sys.version\")]\n SysVersion,\n\n /// Maximal recommended attachment size in bytes.\n #[strum(serialize = \"sys.msgsize_max_recommended\")]\n SysMsgsizeMaxRecommended,\n\n /// Space separated list of all config keys available.\n #[strum(serialize = \"sys.config_keys\")]\n SysConfigKeys,\n\n /// True if it is a bot account.\n Bot,\n\n /// True when to skip initial start messages in groups.\n #[strum(props(default = \"0\"))]\n SkipStartMessages,\n\n /// Whether we send a warning if the password is wrong (set to false when we send a warning\n /// because we do not want to send a second warning)\n #[strum(props(default = \"0\"))]\n NotifyAboutWrongPw,\n\n /// If a warning about exceeding quota was shown recently,\n /// this is the percentage of quota at the time the warning was given.\n /// Unset, when quota falls below minimal warning threshold again.\n QuotaExceeding,\n\n /// address to webrtc instance to use for videochats\n WebrtcInstance,\n\n /// Timestamp of the last time housekeeping was run\n LastHousekeeping,\n\n /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.\n LastCantDecryptOutgoingMsgs,\n\n /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.\n #[strum(props(default = \"60\"))]\n ScanAllFoldersDebounceSecs,\n\n /// Whether to avoid using IMAP IDLE even if the server supports it.\n ///\n /// This is a developer option for testing \"fake idle\".\n #[strum(props(default = \"0\"))]\n DisableIdle,\n\n /// Defines the max. size (in bytes) of messages downloaded automatically.\n /// 0 = no limit.\n #[strum(props(default = \"0\"))]\n DownloadLimit,\n\n /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.\n #[strum(props(default = \"1\"))]\n SyncMsgs,\n\n /// Space-separated list of all the authserv-ids which we believe\n /// may be the one of our email server.\n ///\n /// See `crate::authres::update_authservid_candidates`.\n AuthservIdCandidates,\n\n /// Make all outgoing messages with Autocrypt header \"multipart/signed\".\n SignUnencrypted,\n\n /// Let the core save all events to the database.\n /// This value is used internally to remember the MsgId of the logging xdc\n #[strum(props(default = \"0\"))]\n DebugLogging,\n\n /// Last message processed by the bot.\n LastMsgId,\n\n /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by\n /// default.\n ///\n /// This is not supposed to be changed by UIs and only used for testing.\n #[strum(props(default = \"172800\"))]\n GossipPeriod,\n\n /// Feature flag for verified 1:1 chats; the UI should set it\n /// to 1 if it supports verified 1:1 chats.\n /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,\n /// and when the key changes, an info message is posted into the chat.\n /// 0=Nothing else happens when the key changes.\n /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true\n /// until `chat_id.accept()` is called.\n #[strum(props(default = \"0\"))]\n VerifiedOneOnOneChats,\n\n /// Row ID of the key in the `keypairs` table\n /// used for signatures, encryption to self and included in `Autocrypt` header.\n KeyId,\n\n /// This key is sent to the self_reporting bot so that the bot can recognize the user\n /// without storing the email address\n SelfReportingId,\n\n /// MsgId of webxdc map integration.\n WebxdcIntegration,\n\n /// Iroh secret key.\n IrohSecretKey,\n}", "rust_imports": "use std::collections::HashMap;\nuse anyhow::Result;\nuse percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};\nuse serde::Deserialize;\nuse crate::config::Config;\nuse crate::context::Context;\nuse crate::provider;\nuse crate::provider::Oauth2Authorizer;\nuse crate::socks::Socks5Config;\nuse crate::tools::time;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__oauth2__.rs__function__1.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "time_t dc_msg_get_timestamp(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn 0;\n\t}\n\n\treturn msg->timestamp_sent? msg->timestamp_sent : msg->timestamp_sort;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn get_timestamp(&self) -> i64 {\n if 0 != self.timestamp_sent {\n self.timestamp_sent\n } else {\n self.timestamp_sort\n }\n }", "rust_context": "pub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__29.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* so you have to free it using dc_msg_unref() as usual.\n * @return The ID of the message that is being prepared.\n */\nuint32_t dc_prepare_msg(dc_context_t* context, uint32_t chat_id, dc_msg_t* msg)\n{\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg==NULL || chat_id<=DC_CHAT_ID_LAST_SPECIAL) {\n\t\treturn 0;\n\t}\n\n\tuint32_t msg_id = prepare_msg_common(context, chat_id, msg);\n\n\tcontext->cb(context, DC_EVENT_MSGS_CHANGED, msg->chat_id, msg->id);\n\tif (dc_param_exists(msg->param, DC_PARAM_SET_LATITUDE)) {\n\t\tcontext->cb(context, DC_EVENT_LOCATION_CHANGED, DC_CONTACT_ID_SELF, 0);\n\t}\n\n\treturn msg_id;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn prepare_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result {\n ensure!(\n !chat_id.is_special(),\n \"Cannot prepare message for special chat\"\n );\n\n let msg_id = prepare_msg_common(context, chat_id, msg, MessageState::OutPreparing).await?;\n context.emit_msgs_changed(msg.chat_id, msg.id);\n\n Ok(msg_id)\n}", "rust_context": "pub fn is_special(self) -> bool {\n (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)\n }\n\npub fn emit_msgs_changed(&self, chat_id: ChatId, msg_id: MsgId) {\n self.emit_event(EventType::MsgsChanged { chat_id, msg_id });\n chatlist_events::emit_chatlist_changed(self);\n chatlist_events::emit_chatlist_item_changed(self, chat_id);\n }\n\nasync fn prepare_msg_common(\n context: &Context,\n chat_id: ChatId,\n msg: &mut Message,\n change_state_to: MessageState,\n) -> Result {\n let mut chat = Chat::load_from_db(context, chat_id).await?;\n\n // Check if the chat can be sent to.\n if let Some(reason) = chat.why_cant_send(context).await? {\n if matches!(\n reason,\n CantSendReason::ProtectionBroken\n | CantSendReason::ContactRequest\n | CantSendReason::SecurejoinWait\n ) && msg.param.get_cmd() == SystemMessage::SecurejoinMessage\n {\n // Send out the message, the securejoin message is supposed to repair the verification.\n // If the chat is a contact request, let the user accept it later.\n } else {\n bail!(\"cannot send to {chat_id}: {reason}\");\n }\n }\n\n // Check a quote reply is not leaking data from other chats.\n // This is meant as a last line of defence, the UI should check that before as well.\n // (We allow Chattype::Single in general for \"Reply Privately\";\n // checking for exact contact_id will produce false positives when ppl just left the group)\n if chat.typ != Chattype::Single && !context.get_config_bool(Config::Bot).await? {\n if let Some(quoted_message) = msg.quoted_message(context).await? {\n if quoted_message.chat_id != chat_id {\n bail!(\"Bad quote reply\");\n }\n }\n }\n\n // check current MessageState for drafts (to keep msg_id) ...\n let update_msg_id = if msg.state == MessageState::OutDraft {\n msg.hidden = false;\n if !msg.id.is_special() && msg.chat_id == chat_id {\n Some(msg.id)\n } else {\n None\n }\n } else {\n None\n };\n\n // ... then change the MessageState in the message object\n msg.state = change_state_to;\n\n prepare_msg_blob(context, msg).await?;\n if !msg.hidden {\n chat_id.unarchive_if_not_muted(context, msg.state).await?;\n }\n msg.id = chat\n .prepare_msg_raw(\n context,\n msg,\n update_msg_id,\n create_smeared_timestamp(context),\n )\n .await?;\n msg.chat_id = chat_id;\n\n Ok(msg.id)\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct MsgId(u32);\n\npub struct ChatId(u32);\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum MessageState {\n /// Undefined message state.\n #[default]\n Undefined = 0,\n\n /// Incoming *fresh* message. Fresh messages are neither noticed\n /// nor seen and are typically shown in notifications.\n InFresh = 10,\n\n /// Incoming *noticed* message. E.g. chat opened but message not\n /// yet read - noticed messages are not counted as unread but did\n /// not marked as read nor resulted in MDNs.\n InNoticed = 13,\n\n /// Incoming message, really *seen* by the user. Marked as read on\n /// IMAP and MDN may be sent.\n InSeen = 16,\n\n /// For files which need time to be prepared before they can be\n /// sent, the message enters this state before\n /// OutPending.\n OutPreparing = 18,\n\n /// Message saved as draft.\n OutDraft = 19,\n\n /// The user has pressed the \"send\" button but the message is not\n /// yet sent and is pending in some way. Maybe we're offline (no\n /// checkmark).\n OutPending = 20,\n\n /// *Unrecoverable* error (*recoverable* errors result in pending\n /// messages).\n OutFailed = 24,\n\n /// Outgoing message successfully delivered to server (one\n /// checkmark). Note, that already delivered messages may get into\n /// the OutFailed state if we get such a hint from the server.\n OutDelivered = 26,\n\n /// Outgoing message read by the recipient (two checkmarks; this\n /// requires goodwill on the receiver's side)\n OutMdnRcvd = 28,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__100.txt"} {"c_path": "projects/deltachat-core/c/dc_tools.c", "c_func": "time_t dc_create_smeared_timestamp(dc_context_t* context)\n{\n\ttime_t now = time(NULL);\n\ttime_t ret = now;\n\tSMEAR_LOCK\n\t\tcontext->last_smeared_timestamp = ret;\n\tSMEAR_UNLOCK\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/tools.rs", "rust_func": "pub(crate) fn create_smeared_timestamp(context: &Context) -> i64 {\n let now = time();\n context.smeared_timestamp.create(now)\n}", "rust_context": "pub fn create(&self, now: i64) -> i64 {\n self.create_n(now, 1)\n }\n\npub(crate) fn time() -> i64 {\n SystemTime::now()\n .duration_since(SystemTime::UNIX_EPOCH)\n .unwrap_or_default()\n .as_secs() as i64\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}", "rust_imports": "use std::borrow::Cow;\nuse std::io::{Cursor, Write};\nuse std::mem;\nuse std::path::{Path, PathBuf};\nuse std::str::from_utf8;\nuse std::time::Duration;\nuse std::time::SystemTime as Time;\nuse std::time::SystemTime;\nuse anyhow::{bail, Context as _, Result};\nuse base64::Engine as _;\nuse chrono::{Local, NaiveDateTime, NaiveTime, TimeZone};\nuse deltachat_contact_tools::{strip_rtlo_characters, EmailAddress};\nuse deltachat_time::SystemTimeTools as SystemTime;\nuse futures::{StreamExt, TryStreamExt};\nuse mailparse::dateparse;\nuse mailparse::headers::Headers;\nuse mailparse::MailHeaderMap;\nuse rand::{thread_rng, Rng};\nuse tokio::{fs, io};\nuse url::Url;\nuse crate::chat::{add_device_msg, add_device_msg_with_importance};\nuse crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, Viewtype};\nuse crate::stock_str;\nuse chrono::NaiveDate;\nuse proptest::prelude::*;\nuse super::*;\nuse crate::chatlist::Chatlist;\nuse crate::{chat, test_utils};\nuse crate::{receive_imf::receive_imf, test_utils::TestContext};\nuse super::*;", "rustrepotrans_file": "projects__deltachat-core__rust__tools__.rs__function__7.txt"} {"c_path": "projects/deltachat-core/c/dc_imex.c", "c_func": "char* dc_initiate_key_transfer(dc_context_t* context)\n{\n\tint success = 0;\n\tchar* setup_code = NULL;\n\tchar* setup_file_content = NULL;\n\tchar* setup_file_name = NULL;\n\tuint32_t chat_id = 0;\n\tdc_msg_t* msg = NULL;\n\tuint32_t msg_id = 0;\n\n\tif (!dc_alloc_ongoing(context)) {\n\t\treturn 0; /* no cleanup as this would call dc_free_ongoing() */\n\t}\n\t#define CHECK_EXIT if (context->shall_stop_ongoing) { goto cleanup; }\n\n\tif ((setup_code=dc_create_setup_code(context))==NULL) { /* this may require a keypair to be created. this may take a second ... */\n\t\tgoto cleanup;\n\t}\n\n\tCHECK_EXIT\n\n\tif ((setup_file_content=dc_render_setup_file(context, setup_code))==NULL) { /* encrypting may also take a while ... */\n\t\tgoto cleanup;\n\t}\n\n\tCHECK_EXIT\n\n\tif ((setup_file_name=dc_get_fine_pathNfilename(context, \"$BLOBDIR\", \"autocrypt-setup-message.html\"))==NULL\n\t || !dc_write_file(context, setup_file_name, setup_file_content, strlen(setup_file_content))) {\n\t\tgoto cleanup;\n\t}\n\n\tif ((chat_id=dc_create_chat_by_contact_id(context, DC_CONTACT_ID_SELF))==0) {\n\t\tgoto cleanup;\n\t}\n\n\tmsg = dc_msg_new_untyped(context);\n\tmsg->type = DC_MSG_FILE;\n\tdc_param_set (msg->param, DC_PARAM_FILE, setup_file_name);\n\tdc_param_set (msg->param, DC_PARAM_MIMETYPE, \"application/autocrypt-setup\");\n\tdc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_AUTOCRYPT_SETUP_MESSAGE);\n\tdc_param_set_int(msg->param, DC_PARAM_FORCE_PLAINTEXT, DC_FP_NO_AUTOCRYPT_HEADER);\n\n\tCHECK_EXIT\n\n\tif ((msg_id = dc_send_msg(context, chat_id, msg))==0) {\n\t\tgoto cleanup;\n\t}\n\n\tdc_msg_unref(msg);\n\tmsg = NULL;\n\n\t/* wait until the message is really sent */\n\tdc_log_info(context, 0, \"Wait for setup message being sent ...\");\n\n\twhile (1)\n\t{\n\t\tCHECK_EXIT\n\n\t\tsleep(1);\n\n\t\tmsg = dc_get_msg(context, msg_id);\n\t\tif (dc_msg_is_sent(msg)) {\n\t\t\tbreak;\n\t\t}\n\t\tdc_msg_unref(msg);\n\t\tmsg = NULL;\n\t}\n\n\tdc_log_info(context, 0, \"... setup message sent.\");\n\n\tsuccess = 1;\n\ncleanup:\n\tif (!success) { free(setup_code); setup_code = NULL; }\n\tfree(setup_file_name);\n\tfree(setup_file_content);\n\tdc_msg_unref(msg);\n\tdc_free_ongoing(context);\n\treturn setup_code;\n}", "rust_path": "projects/deltachat-core/rust/imex.rs", "rust_func": "pub async fn initiate_key_transfer(context: &Context) -> Result {\n let setup_code = create_setup_code(context);\n /* this may require a keypair to be created. this may take a second ... */\n let setup_file_content = render_setup_file(context, &setup_code).await?;\n /* encrypting may also take a while ... */\n let setup_file_blob = BlobObject::create(\n context,\n \"autocrypt-setup-message.html\",\n setup_file_content.as_bytes(),\n )\n .await?;\n\n let chat_id = ChatId::create_for_contact(context, ContactId::SELF).await?;\n let mut msg = Message {\n viewtype: Viewtype::File,\n ..Default::default()\n };\n msg.param.set(Param::File, setup_file_blob.as_name());\n msg.subject = stock_str::ac_setup_msg_subject(context).await;\n msg.param\n .set(Param::MimeType, \"application/autocrypt-setup\");\n msg.param.set_cmd(SystemMessage::AutocryptSetupMessage);\n msg.force_plaintext();\n msg.param.set_int(Param::SkipAutocrypt, 1);\n\n chat::send_msg(context, chat_id, &mut msg).await?;\n // no maybe_add_bcc_self_device_msg() here.\n // the ui shows the dialog with the setup code on this device,\n // it would be too much noise to have two things popping up at the same time.\n // maybe_add_bcc_self_device_msg() is called on the other device\n // once the transfer is completed.\n Ok(setup_code)\n}", "rust_context": "pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result {\n if chat_id.is_unset() {\n let forwards = msg.param.get(Param::PrepForwards);\n if let Some(forwards) = forwards {\n for forward in forwards.split(' ') {\n if let Ok(msg_id) = forward.parse::().map(MsgId::new) {\n if let Ok(mut msg) = Message::load_from_db(context, msg_id).await {\n send_msg_inner(context, chat_id, &mut msg).await?;\n };\n }\n }\n msg.param.remove(Param::PrepForwards);\n msg.update_param(context).await?;\n }\n return send_msg_inner(context, chat_id, msg).await;\n }\n\n if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing {\n msg.param.remove(Param::GuaranteeE2ee);\n msg.param.remove(Param::ForcePlaintext);\n msg.update_param(context).await?;\n }\n send_msg_inner(context, chat_id, msg).await\n}\n\npub fn as_name(&self) -> &str {\n &self.name\n }\n\npub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self {\n self.inner.insert(key, value.to_string());\n self\n }\n\npub fn set_int(&mut self, key: Param, value: i32) -> &mut Self {\n self.set(key, format!(\"{value}\"));\n self\n }\n\npub async fn render_setup_file(context: &Context, passphrase: &str) -> Result {\n let passphrase_begin = if let Some(passphrase_begin) = passphrase.get(..2) {\n passphrase_begin\n } else {\n bail!(\"Passphrase must be at least 2 chars long.\");\n };\n let private_key = load_self_secret_key(context).await?;\n let ac_headers = match context.get_config_bool(Config::E2eeEnabled).await? {\n false => None,\n true => Some((\"Autocrypt-Prefer-Encrypt\", \"mutual\")),\n };\n let private_key_asc = private_key.to_asc(ac_headers);\n let encr = pgp::symm_encrypt(passphrase, private_key_asc.as_bytes())\n .await?\n .replace('\\n', \"\\r\\n\");\n\n let replacement = format!(\n concat!(\n \"-----BEGIN PGP MESSAGE-----\\r\\n\",\n \"Passphrase-Format: numeric9x4\\r\\n\",\n \"Passphrase-Begin: {}\"\n ),\n passphrase_begin\n );\n let pgp_msg = encr.replace(\"-----BEGIN PGP MESSAGE-----\", &replacement);\n\n let msg_subj = stock_str::ac_setup_msg_subject(context).await;\n let msg_body = stock_str::ac_setup_msg_body(context).await;\n let msg_body_html = msg_body.replace('\\r', \"\").replace('\\n', \"
\");\n Ok(format!(\n concat!(\n \"\\r\\n\",\n \"\\r\\n\",\n \" \\r\\n\",\n \" {}\\r\\n\",\n \" \\r\\n\",\n \" \\r\\n\",\n \"

{}

\\r\\n\",\n \"

{}

\\r\\n\",\n \"
\\r\\n{}\\r\\n
\\r\\n\",\n \" \\r\\n\",\n \"\\r\\n\"\n ),\n msg_subj, msg_subj, msg_body_html, pgp_msg\n ))\n}\n\npub fn set_cmd(&mut self, value: SystemMessage) {\n self.set_int(Param::Cmd, value as i32);\n }\n\npub fn force_plaintext(&mut self) {\n self.param.set_int(Param::ForcePlaintext, 1);\n }\n\npub async fn create(\n context: &'a Context,\n suggested_name: &str,\n data: &[u8],\n ) -> Result> {\n let blobdir = context.get_blobdir();\n let (stem, ext) = BlobObject::sanitise_name(suggested_name);\n let (name, mut file) = BlobObject::create_new_file(context, blobdir, &stem, &ext).await?;\n file.write_all(data).await.context(\"file write failure\")?;\n\n // workaround a bug in async-std\n // (the executor does not handle blocking operation in Drop correctly,\n // see )\n let _ = file.flush().await;\n\n let blob = BlobObject {\n blobdir,\n name: format!(\"$BLOBDIR/{name}\"),\n };\n context.emit_event(EventType::NewBlobFile(blob.as_name().to_string()));\n Ok(blob)\n }\n\npub async fn create_for_contact(context: &Context, contact_id: ContactId) -> Result {\n ChatId::create_for_contact_with_blocked(context, contact_id, Blocked::Not).await\n }\n\npub fn create_setup_code(_context: &Context) -> String {\n let mut random_val: u16;\n let mut rng = thread_rng();\n let mut ret = String::new();\n\n for i in 0..9 {\n loop {\n random_val = rng.gen();\n if random_val as usize <= 60000 {\n break;\n }\n }\n random_val = (random_val as usize % 10000) as u16;\n ret += &format!(\n \"{}{:04}\",\n if 0 != i { \"-\" } else { \"\" },\n random_val as usize\n );\n }\n\n ret\n}\n\npub fn new(viewtype: Viewtype) -> Self {\n Message {\n viewtype,\n ..Default::default()\n }\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}\n\npub(crate) async fn ac_setup_msg_subject(context: &Context) -> String {\n translated(context, StockMessage::AcSetupMsgSubject).await\n}\n\nimpl ContactId {\n /// Undefined contact. Used as a placeholder for trashed messages.\n pub const UNDEFINED: ContactId = ContactId::new(0);\n\n /// The owner of the account.\n ///\n /// The email-address is set by `set_config` using \"addr\".\n pub const SELF: ContactId = ContactId::new(1);\n\n /// ID of the contact for info messages.\n pub const INFO: ContactId = ContactId::new(2);\n\n /// ID of the contact for device messages.\n pub const DEVICE: ContactId = ContactId::new(5);\n pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9);\n\n /// Address to go with [`ContactId::DEVICE`].\n ///\n /// This is used by APIs which need to return an email address for this contact.\n pub const DEVICE_ADDR: &'static str = \"device@localhost\";\n}\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum SystemMessage {\n /// Unknown type of system message.\n #[default]\n Unknown = 0,\n\n /// Group name changed.\n GroupNameChanged = 2,\n\n /// Group avatar changed.\n GroupImageChanged = 3,\n\n /// Member was added to the group.\n MemberAddedToGroup = 4,\n\n /// Member was removed from the group.\n MemberRemovedFromGroup = 5,\n\n /// Autocrypt Setup Message.\n AutocryptSetupMessage = 6,\n\n /// Secure-join message.\n SecurejoinMessage = 7,\n\n /// Location streaming is enabled.\n LocationStreamingEnabled = 8,\n\n /// Location-only message.\n LocationOnly = 9,\n\n /// Chat ephemeral message timer is changed.\n EphemeralTimerChanged = 10,\n\n /// \"Messages are guaranteed to be end-to-end encrypted from now on.\"\n ChatProtectionEnabled = 11,\n\n /// \"%1$s sent a message from another device.\"\n ChatProtectionDisabled = 12,\n\n /// Message can't be sent because of `Invalid unencrypted mail to <>`\n /// which is sent by chatmail servers.\n InvalidUnencryptedMail = 13,\n\n /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it\n /// to complete.\n SecurejoinWait = 14,\n\n /// 1:1 chats info message telling that SecureJoin is still running, but the user may already\n /// send messages.\n SecurejoinWaitTimeout = 15,\n\n /// Self-sent-message that contains only json used for multi-device-sync;\n /// if possible, we attach that to other messages as for locations.\n MultiDeviceSync = 20,\n\n /// Sync message that contains a json payload\n /// sent to the other webxdc instances\n /// These messages are not shown in the chat.\n WebxdcStatusUpdate = 30,\n\n /// Webxdc info added with `info` set in `send_webxdc_status_update()`.\n WebxdcInfoMessage = 32,\n\n /// This message contains a users iroh node address.\n IrohNodeAddr = 40,\n}", "rust_imports": "use std::any::Any;\nuse std::ffi::OsStr;\nuse std::path::{Path, PathBuf};\nuse ::pgp::types::KeyTrait;\nuse anyhow::{bail, ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse futures::StreamExt;\nuse futures_lite::FutureExt;\nuse rand::{thread_rng, Rng};\nuse tokio::fs::{self, File};\nuse tokio_tar::Archive;\nuse crate::blob::{BlobDirContents, BlobObject};\nuse crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};\nuse crate::config::Config;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::e2ee;\nuse crate::events::EventType;\nuse crate::key::{\n self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,\n};\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::param::Param;\nuse crate::pgp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{\n create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,\n};\nuse transfer::{get_backup, BackupProvider};\nuse std::time::Duration;\nuse ::pgp::armor::BlockType;\nuse tokio::task;\nuse super::*;\nuse crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::{alice_keypair, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__imex__.rs__function__3.txt"} {"c_path": "projects/deltachat-core/c/dc_chatlist.c", "c_func": "int dc_get_archived_cnt(dc_context_t* context)\n{\n\tint ret = 0;\n\tsqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT COUNT(*) FROM chats WHERE blocked!=1 AND archived=1;\");\n\tif (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\tret = sqlite3_column_int(stmt, 0);\n\t}\n\tsqlite3_finalize(stmt);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/chatlist.rs", "rust_func": "pub async fn get_archived_cnt(context: &Context) -> Result {\n let count = context\n .sql\n .count(\n \"SELECT COUNT(*) FROM chats WHERE blocked!=? AND archived=?;\",\n (Blocked::Yes, ChatVisibility::Archived),\n )\n .await?;\n Ok(count)\n}", "rust_context": "pub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result {\n let count: isize = self.query_row(query, params, |row| row.get(0)).await?;\n Ok(usize::try_from(count)?)\n }\n\npub enum Blocked {\n #[default]\n Not = 0,\n Yes = 1,\n Request = 2,\n}\n\npub enum ChatVisibility {\n /// Chat is neither archived nor pinned.\n Normal = 0,\n\n /// Chat is archived.\n Archived = 1,\n\n /// Chat is pinned to the top of the chatlist.\n Pinned = 2,\n}", "rust_imports": "use anyhow::{ensure, Context as _, Result};\nuse once_cell::sync::Lazy;\nuse crate::chat::{update_special_chat_names, Chat, ChatId, ChatVisibility};\nuse crate::constants::{\n Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_GCL_ADD_ALLDONE_HINT,\n DC_GCL_ARCHIVED_ONLY, DC_GCL_FOR_FORWARDING, DC_GCL_NO_SPECIALS,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::message::{Message, MessageState, MsgId};\nuse crate::param::{Param, Params};\nuse crate::stock_str;\nuse crate::summary::Summary;\nuse crate::tools::IsNoneOrEmpty;\nuse super::*;\nuse crate::chat::{\n add_contact_to_chat, create_group_chat, get_chat_contacts, remove_contact_from_chat,\n send_text_msg, ProtectionStatus,\n };\nuse crate::message::Viewtype;\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__chatlist__.rs__function__11.txt"} {"c_path": "projects/deltachat-core/c/dc_imex.c", "c_func": "static int export_key_to_asc_file(dc_context_t* context, const char* dir, int id, const dc_key_t* key, int is_default)\n{\n\tint success = 0;\n\tchar* file_name = NULL;\n\n\tif (is_default) {\n\t\tfile_name = dc_mprintf(\"%s/%s-key-default.asc\", dir, key->type==DC_KEY_PUBLIC? \"public\" : \"private\");\n\t}\n\telse {\n\t\tfile_name = dc_mprintf(\"%s/%s-key-%i.asc\", dir, key->type==DC_KEY_PUBLIC? \"public\" : \"private\", id);\n\t}\n\tdc_log_info(context, 0, \"Exporting key %s\", file_name);\n\tdc_delete_file(context, file_name);\n\tif (!dc_key_render_asc_to_file(key, file_name, context)) {\n\t\tdc_log_error(context, 0, \"Cannot write key to %s\", file_name);\n\t\tgoto cleanup;\n\t}\n\n\tcontext->cb(context, DC_EVENT_IMEX_FILE_WRITTEN, (uintptr_t)file_name, 0);\n\tsuccess = 1;\n\ncleanup:\n\tfree(file_name);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/imex.rs", "rust_func": "async fn export_key_to_asc_file(\n context: &Context,\n dir: &Path,\n id: Option,\n key: &T,\n) -> Result<()>\nwhere\n T: DcKey + Any,\n{\n let file_name = {\n let any_key = key as &dyn Any;\n let kind = if any_key.downcast_ref::().is_some() {\n \"public\"\n } else if any_key.downcast_ref::().is_some() {\n \"private\"\n } else {\n \"unknown\"\n };\n let id = id.map_or(\"default\".into(), |i| i.to_string());\n dir.join(format!(\"{}-key-{}.asc\", kind, &id))\n };\n info!(\n context,\n \"Exporting key {:?} to {}\",\n key.key_id(),\n file_name.display()\n );\n\n // Delete the file if it already exists.\n delete_file(context, &file_name).await.ok();\n\n let content = key.to_asc(None).into_bytes();\n write_file(context, &file_name, &content)\n .await\n .with_context(|| format!(\"cannot write key to {}\", file_name.display()))?;\n context.emit_event(EventType::ImexFileWritten(file_name));\n Ok(())\n}", "rust_context": "pub(crate) async fn write_file(\n context: &Context,\n path: impl AsRef,\n buf: &[u8],\n) -> Result<(), io::Error> {\n let path_abs = get_abs_path(context, path.as_ref());\n fs::write(&path_abs, buf).await.map_err(|err| {\n warn!(\n context,\n \"Cannot write {} bytes to \\\"{}\\\": {}\",\n buf.len(),\n path.as_ref().display(),\n err\n );\n err\n })\n}\n\npub fn emit_event(&self, event: EventType) {\n {\n let lock = self.debug_logging.read().expect(\"RwLock is poisoned\");\n if let Some(debug_logging) = &*lock {\n debug_logging.log_event(event.clone());\n }\n }\n self.events.emit(Event {\n id: self.id,\n typ: event,\n });\n }\n\nfn to_asc(&self, header: Option<(&str, &str)>) -> String {\n // Not using .to_armored_string() to make clear *why* it is\n // safe to do these unwraps.\n // Because we write to a Vec the io::Write impls never\n // fail and we can hide this error. The string is always ASCII.\n let headers = header.map(|(key, value)| {\n let mut m = BTreeMap::new();\n m.insert(key.to_string(), value.to_string());\n m\n });\n let mut buf = Vec::new();\n self.to_armored_writer(&mut buf, headers.as_ref())\n .unwrap_or_default();\n std::string::String::from_utf8(buf).unwrap_or_default()\n }\n\nmacro_rules! info {\n ($ctx:expr, $msg:expr) => {\n info!($ctx, $msg,)\n };\n ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{\n let formatted = format!($msg, $($args),*);\n let full = format!(\"{file}:{line}: {msg}\",\n file = file!(),\n line = line!(),\n msg = &formatted);\n $ctx.emit_event($crate::EventType::Info(full));\n }};\n}\n\npub(crate) async fn delete_file(context: &Context, path: impl AsRef) -> Result<()> {\n let path = path.as_ref();\n let path_abs = get_abs_path(context, path);\n if !path_abs.exists() {\n bail!(\"path {} does not exist\", path_abs.display());\n }\n if !path_abs.is_file() {\n warn!(context, \"refusing to delete non-file {}.\", path.display());\n bail!(\"not a file: \\\"{}\\\"\", path.display());\n }\n\n let dpath = format!(\"{}\", path.to_string_lossy());\n fs::remove_file(path_abs)\n .await\n .with_context(|| format!(\"cannot delete {dpath:?}\"))?;\n context.emit_event(EventType::DeletedBlobFile(dpath));\n Ok(())\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub enum EventType {\n /// The library-user may write an informational string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Info(String),\n\n /// Emitted when SMTP connection is established and login was successful.\n SmtpConnected(String),\n\n /// Emitted when IMAP connection is established and login was successful.\n ImapConnected(String),\n\n /// Emitted when a message was successfully sent to the SMTP server.\n SmtpMessageSent(String),\n\n /// Emitted when an IMAP message has been marked as deleted\n ImapMessageDeleted(String),\n\n /// Emitted when an IMAP message has been moved\n ImapMessageMoved(String),\n\n /// Emitted before going into IDLE on the Inbox folder.\n ImapInboxIdle,\n\n /// Emitted when an new file in the $BLOBDIR was created\n NewBlobFile(String),\n\n /// Emitted when an file in the $BLOBDIR was deleted\n DeletedBlobFile(String),\n\n /// The library-user should write a warning string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Warning(String),\n\n /// The library-user should report an error to the end-user.\n ///\n /// As most things are asynchronous, things may go wrong at any time and the user\n /// should not be disturbed by a dialog or so. Instead, use a bubble or so.\n ///\n /// However, for ongoing processes (eg. configure())\n /// or for functions that are expected to fail (eg. dc_continue_key_transfer())\n /// it might be better to delay showing these events until the function has really\n /// failed (returned false). It should be sufficient to report only the *last* error\n /// in a messasge box then.\n Error(String),\n\n /// An action cannot be performed because the user is not in the group.\n /// Reported eg. after a call to\n /// dc_set_chat_name(), dc_set_chat_profile_image(),\n /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(),\n /// dc_send_text_msg() or another sending function.\n ErrorSelfNotInGroup(String),\n\n /// Messages or chats changed. One or more messages or chats changed for various\n /// reasons in the database:\n /// - Messages sent, received or removed\n /// - Chats created, deleted or archived\n /// - A draft has been set\n ///\n MsgsChanged {\n /// Set if only a single chat is affected by the changes, otherwise 0.\n chat_id: ChatId,\n\n /// Set if only a single message is affected by the changes, otherwise 0.\n msg_id: MsgId,\n },\n\n /// Reactions for the message changed.\n ReactionsChanged {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message for which reactions were changed.\n msg_id: MsgId,\n\n /// ID of the contact whose reaction set is changed.\n contact_id: ContactId,\n },\n\n /// There is a fresh message. Typically, the user will show an notification\n /// when receiving this message.\n ///\n /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event.\n IncomingMsg {\n /// ID of the chat where the message is assigned.\n chat_id: ChatId,\n\n /// ID of the message.\n msg_id: MsgId,\n },\n\n /// Downloading a bunch of messages just finished.\n IncomingMsgBunch,\n\n /// Messages were seen or noticed.\n /// chat id is always set.\n MsgsNoticed(ChatId),\n\n /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to\n /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state().\n MsgDelivered {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was successfully sent.\n msg_id: MsgId,\n },\n\n /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_FAILED, see dc_msg_get_state().\n MsgFailed {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that could not be sent.\n msg_id: MsgId,\n },\n\n /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state().\n MsgRead {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was read.\n msg_id: MsgId,\n },\n\n /// A single message was deleted.\n ///\n /// This event means that the message will no longer appear in the messagelist.\n /// UI should remove the message from the messagelist\n /// in response to this event if the message is currently displayed.\n ///\n /// The message may have been explicitly deleted by the user or expired.\n /// Internally the message may have been removed from the database,\n /// moved to the trash chat or hidden.\n ///\n /// This event does not indicate the message\n /// deletion from the server.\n MsgDeleted {\n /// ID of the chat where the message was prior to deletion.\n /// Never 0 or trash chat.\n chat_id: ChatId,\n\n /// ID of the deleted message. Never 0.\n msg_id: MsgId,\n },\n\n /// Chat changed. The name or the image of a chat group was changed or members were added or removed.\n /// Or the verify state of a chat has changed.\n /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat()\n /// and dc_remove_contact_from_chat().\n ///\n /// This event does not include ephemeral timer modification, which\n /// is a separate event.\n ChatModified(ChatId),\n\n /// Chat ephemeral timer changed.\n ChatEphemeralTimerModified {\n /// Chat ID.\n chat_id: ChatId,\n\n /// New ephemeral timer value.\n timer: EphemeralTimer,\n },\n\n /// Contact(s) created, renamed, blocked, deleted or changed their \"recently seen\" status.\n ///\n /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected.\n ContactsChanged(Option),\n\n /// Location of one or more contact has changed.\n ///\n /// @param data1 (u32) contact_id of the contact for which the location has changed.\n /// If the locations of several contacts have been changed,\n /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`.\n LocationChanged(Option),\n\n /// Inform about the configuration progress started by configure().\n ConfigureProgress {\n /// Progress.\n ///\n /// 0=error, 1-999=progress in permille, 1000=success and done\n progress: usize,\n\n /// Progress comment or error, something to display to the user.\n comment: Option,\n },\n\n /// Inform about the import/export progress started by imex().\n ///\n /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done\n /// @param data2 0\n ImexProgress(usize),\n\n /// A file has been exported. A file has been written by imex().\n /// This event may be sent multiple times by a single call to imex().\n ///\n /// A typical purpose for a handler of this event may be to make the file public to some system\n /// services.\n ///\n /// @param data2 0\n ImexFileWritten(PathBuf),\n\n /// Progress information of a secure-join handshake from the view of the inviter\n /// (Alice, the person who shows the QR code).\n ///\n /// These events are typically sent after a joiner has scanned the QR code\n /// generated by dc_get_securejoin_qr().\n SecurejoinInviterProgress {\n /// ID of the contact that wants to join.\n contact_id: ContactId,\n\n /// Progress as:\n /// 300=vg-/vc-request received, typically shown as \"bob@addr joins\".\n /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as \"bob@addr verified\".\n /// 800=contact added to chat, shown as \"bob@addr securely joined GROUP\". Only for the verified-group-protocol.\n /// 1000=Protocol finished for this contact.\n progress: usize,\n },\n\n /// Progress information of a secure-join handshake from the view of the joiner\n /// (Bob, the person who scans the QR code).\n /// The events are typically sent while dc_join_securejoin(), which\n /// may take some time, is executed.\n SecurejoinJoinerProgress {\n /// ID of the inviting contact.\n contact_id: ContactId,\n\n /// Progress as:\n /// 400=vg-/vc-request-with-auth sent, typically shown as \"alice@addr verified, introducing myself.\"\n /// (Bob has verified alice and waits until Alice does the same for him)\n /// 1000=vg-member-added/vc-contact-confirm received\n progress: usize,\n },\n\n /// The connectivity to the server changed.\n /// This means that you should refresh the connectivity view\n /// and possibly the connectivtiy HTML; see dc_get_connectivity() and\n /// dc_get_connectivity_html() for details.\n ConnectivityChanged,\n\n /// The user's avatar changed.\n /// Deprecated by `ConfigSynced`.\n SelfavatarChanged,\n\n /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For\n /// uniformity this is emitted on the source device too. The value isn't here, otherwise it\n /// would be logged which might not be good for privacy.\n ConfigSynced {\n /// Configuration key.\n key: Config,\n },\n\n /// Webxdc status update received.\n WebxdcStatusUpdate {\n /// Message ID.\n msg_id: MsgId,\n\n /// Status update ID.\n status_update_serial: StatusUpdateSerial,\n },\n\n /// Data received over an ephemeral peer channel.\n WebxdcRealtimeData {\n /// Message ID.\n msg_id: MsgId,\n\n /// Realtime data.\n data: Vec,\n },\n\n /// Inform that a message containing a webxdc instance has been deleted.\n WebxdcInstanceDeleted {\n /// ID of the deleted message.\n msg_id: MsgId,\n },\n\n /// Tells that the Background fetch was completed (or timed out).\n /// This event acts as a marker, when you reach this event you can be sure\n /// that all events emitted during the background fetch were processed.\n ///\n /// This event is only emitted by the account manager\n AccountsBackgroundFetchDone,\n /// Inform that set of chats or the order of the chats in the chatlist has changed.\n ///\n /// Sometimes this is emitted together with `UIChatlistItemChanged`.\n ChatlistChanged,\n\n /// Inform that a single chat list item changed and needs to be rerendered.\n /// 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.\n ChatlistItemChanged {\n /// ID of the changed chat\n chat_id: Option,\n },\n\n /// Event for using in tests, e.g. as a fence between normally generated events.\n #[cfg(test)]\n Test,\n\n /// Inform than some events have been skipped due to event channel overflow.\n EventChannelOverflow {\n /// Number of events skipped.\n n: u64,\n },\n}", "rust_imports": "use std::any::Any;\nuse std::ffi::OsStr;\nuse std::path::{Path, PathBuf};\nuse ::pgp::types::KeyTrait;\nuse anyhow::{bail, ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse futures::StreamExt;\nuse futures_lite::FutureExt;\nuse rand::{thread_rng, Rng};\nuse tokio::fs::{self, File};\nuse tokio_tar::Archive;\nuse crate::blob::{BlobDirContents, BlobObject};\nuse crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};\nuse crate::config::Config;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::e2ee;\nuse crate::events::EventType;\nuse crate::key::{\n self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,\n};\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::param::Param;\nuse crate::pgp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{\n create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,\n};\nuse transfer::{get_backup, BackupProvider};\nuse std::time::Duration;\nuse ::pgp::armor::BlockType;\nuse tokio::task;\nuse super::*;\nuse crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::{alice_keypair, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__imex__.rs__function__20.txt"} {"c_path": "projects/deltachat-core/c/dc_imex.c", "c_func": "char* dc_render_setup_file(dc_context_t* context, const char* passphrase)\n{\n\tsqlite3_stmt* stmt = NULL;\n\tchar* self_addr = NULL;\n\tdc_key_t* curr_private_key = dc_key_new();\n\n\tchar passphrase_begin[8];\n\tchar* encr_string = NULL;\n\n\tchar* ret_setupfilecontent = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || passphrase==NULL\n\t || strlen(passphrase)<2 || curr_private_key==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tstrncpy(passphrase_begin, passphrase, 2);\n\tpassphrase_begin[2] = 0;\n\n\t/* create the payload */\n\n\tif (!dc_ensure_secret_key_exists(context)) {\n\t\tgoto cleanup;\n\t}\n\n\t{\n\t\t\tself_addr = dc_sqlite3_get_config(context->sql, \"configured_addr\", NULL);\n\t\t\tdc_key_load_self_private(curr_private_key, self_addr, context->sql);\n\n\t\t\tint e2ee_enabled = dc_sqlite3_get_config_int(context->sql, \"e2ee_enabled\", DC_E2EE_DEFAULT_ENABLED);\n\t\t\tchar* payload_key_asc = dc_key_render_asc(curr_private_key, e2ee_enabled? \"Autocrypt-Prefer-Encrypt: mutual\\r\\n\" : NULL);\n\t\t\tif (payload_key_asc==NULL) {\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\n\t\tif(!dc_pgp_symm_encrypt(context, passphrase, payload_key_asc, strlen(payload_key_asc), &encr_string)) {\n\t\t\tgoto cleanup;\n\t\t}\n\n\t\tfree(payload_key_asc);\n\t}\n\n\t/* add additional header to armored block */\n\n\t#define LINEEND \"\\r\\n\" /* use the same lineends as the PGP armored data */\n\t{\n\t\tchar* replacement = dc_mprintf(\"-----BEGIN PGP MESSAGE-----\" LINEEND\n\t\t \"Passphrase-Format: numeric9x4\" LINEEND\n\t\t \"Passphrase-Begin: %s\", passphrase_begin);\n\t\tdc_str_replace(&encr_string, \"-----BEGIN PGP MESSAGE-----\", replacement);\n\t\tfree(replacement);\n\t}\n\n\t/* wrap HTML-commands with instructions around the encrypted payload */\n\n\t{\n\t\tchar* setup_message_title = dc_stock_str(context, DC_STR_AC_SETUP_MSG_SUBJECT);\n\t\tchar* setup_message_body = dc_stock_str(context, DC_STR_AC_SETUP_MSG_BODY);\n\n\t\tdc_str_replace(&setup_message_body, \"\\r\", NULL);\n\t\tdc_str_replace(&setup_message_body, \"\\n\", \"
\");\n\n\t\tret_setupfilecontent = dc_mprintf(\n\t\t\t\"\" LINEEND\n\t\t\t\"\" LINEEND\n\t\t\t\t\"\" LINEEND\n\t\t\t\t\t\"%s\" LINEEND\n\t\t\t\t\"\" LINEEND\n\t\t\t\t\"\" LINEEND\n\t\t\t\t\t\"

%s

\" LINEEND\n\t\t\t\t\t\"

%s

\" LINEEND\n\t\t\t\t\t\"
\" LINEEND\n\t\t\t\t\t\"%s\" LINEEND\n\t\t\t\t\t\"
\" LINEEND\n\t\t\t\t\"\" LINEEND\n\t\t\t\"\" LINEEND,\n\t\t\tsetup_message_title,\n\t\t\tsetup_message_title,\n\t\t\tsetup_message_body,\n\t\t\tencr_string);\n\n\t\tfree(setup_message_title);\n\t\tfree(setup_message_body);\n\t}\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\n\tdc_key_unref(curr_private_key);\n\tfree(encr_string);\n\tfree(self_addr);\n\n\treturn ret_setupfilecontent;\n}", "rust_path": "projects/deltachat-core/rust/imex.rs", "rust_func": "pub async fn render_setup_file(context: &Context, passphrase: &str) -> Result {\n let passphrase_begin = if let Some(passphrase_begin) = passphrase.get(..2) {\n passphrase_begin\n } else {\n bail!(\"Passphrase must be at least 2 chars long.\");\n };\n let private_key = load_self_secret_key(context).await?;\n let ac_headers = match context.get_config_bool(Config::E2eeEnabled).await? {\n false => None,\n true => Some((\"Autocrypt-Prefer-Encrypt\", \"mutual\")),\n };\n let private_key_asc = private_key.to_asc(ac_headers);\n let encr = pgp::symm_encrypt(passphrase, private_key_asc.as_bytes())\n .await?\n .replace('\\n', \"\\r\\n\");\n\n let replacement = format!(\n concat!(\n \"-----BEGIN PGP MESSAGE-----\\r\\n\",\n \"Passphrase-Format: numeric9x4\\r\\n\",\n \"Passphrase-Begin: {}\"\n ),\n passphrase_begin\n );\n let pgp_msg = encr.replace(\"-----BEGIN PGP MESSAGE-----\", &replacement);\n\n let msg_subj = stock_str::ac_setup_msg_subject(context).await;\n let msg_body = stock_str::ac_setup_msg_body(context).await;\n let msg_body_html = msg_body.replace('\\r', \"\").replace('\\n', \"
\");\n Ok(format!(\n concat!(\n \"\\r\\n\",\n \"\\r\\n\",\n \" \\r\\n\",\n \" {}\\r\\n\",\n \" \\r\\n\",\n \" \\r\\n\",\n \"

{}

\\r\\n\",\n \"

{}

\\r\\n\",\n \"
\\r\\n{}\\r\\n
\\r\\n\",\n \" \\r\\n\",\n \"\\r\\n\"\n ),\n msg_subj, msg_subj, msg_body_html, pgp_msg\n ))\n}", "rust_context": "pub fn get(&self, key: Param) -> Option<&str> {\n self.inner.get(&key).map(|s| s.as_str())\n }\n\npub async fn get_config_bool(&self, key: Config) -> Result {\n Ok(self.get_config_bool_opt(key).await?.unwrap_or_default())\n }\n\npub(crate) async fn load_self_secret_key(context: &Context) -> Result {\n let private_key = context\n .sql\n .query_row_optional(\n \"SELECT private_key\n FROM keypairs\n WHERE id=(SELECT value FROM config WHERE keyname='key_id')\",\n (),\n |row| {\n let bytes: Vec = row.get(0)?;\n Ok(bytes)\n },\n )\n .await?;\n match private_key {\n Some(bytes) => SignedSecretKey::from_slice(&bytes),\n None => {\n let keypair = generate_keypair(context).await?;\n Ok(keypair.secret)\n }\n }\n}\n\npub(crate) async fn ac_setup_msg_subject(context: &Context) -> String {\n translated(context, StockMessage::AcSetupMsgSubject).await\n}\n\npub(crate) async fn ac_setup_msg_body(context: &Context) -> String {\n translated(context, StockMessage::AcSetupMsgBody).await\n}\n\npub async fn symm_encrypt(passphrase: &str, plain: &[u8]) -> Result {\n let lit_msg = Message::new_literal_bytes(\"\", plain);\n let passphrase = passphrase.to_string();\n\n tokio::task::spawn_blocking(move || {\n let mut rng = thread_rng();\n let s2k = StringToKey::new_default(&mut rng);\n let msg =\n lit_msg.encrypt_with_password(&mut rng, s2k, SYMMETRIC_KEY_ALGORITHM, || passphrase)?;\n\n let encoded_msg = msg.to_armored_string(None)?;\n\n Ok(encoded_msg)\n })\n .await?\n}\n\nfn to_asc(&self, header: Option<(&str, &str)>) -> String {\n // Not using .to_armored_string() to make clear *why* it is\n // safe to do these unwraps.\n // Because we write to a Vec the io::Write impls never\n // fail and we can hide this error. The string is always ASCII.\n let headers = header.map(|(key, value)| {\n let mut m = BTreeMap::new();\n m.insert(key.to_string(), value.to_string());\n m\n });\n let mut buf = Vec::new();\n self.to_armored_writer(&mut buf, headers.as_ref())\n .unwrap_or_default();\n std::string::String::from_utf8(buf).unwrap_or_default()\n }\n\npub enum Config {\n /// Email address, used in the `From:` field.\n Addr,\n\n /// IMAP server hostname.\n MailServer,\n\n /// IMAP server username.\n MailUser,\n\n /// IMAP server password.\n MailPw,\n\n /// IMAP server port.\n MailPort,\n\n /// IMAP server security (e.g. TLS, STARTTLS).\n MailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ImapCertificateChecks,\n\n /// SMTP server hostname.\n SendServer,\n\n /// SMTP server username.\n SendUser,\n\n /// SMTP server password.\n SendPw,\n\n /// SMTP server port.\n SendPort,\n\n /// SMTP server security (e.g. TLS, STARTTLS).\n SendSecurity,\n\n /// How to check SMTP server TLS certificates.\n SmtpCertificateChecks,\n\n /// Whether to use OAuth 2.\n ///\n /// Historically contained other bitflags, which are now deprecated.\n /// Should not be extended in the future, create new config keys instead.\n ServerFlags,\n\n /// True if SOCKS5 is enabled.\n ///\n /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.\n Socks5Enabled,\n\n /// SOCKS5 proxy server hostname or address.\n Socks5Host,\n\n /// SOCKS5 proxy server port.\n Socks5Port,\n\n /// SOCKS5 proxy server username.\n Socks5User,\n\n /// SOCKS5 proxy server password.\n Socks5Password,\n\n /// Own name to use in the `From:` field when sending messages.\n Displayname,\n\n /// Own status to display, sent in message footer.\n Selfstatus,\n\n /// Own avatar filename.\n Selfavatar,\n\n /// Send BCC copy to self.\n ///\n /// Should be enabled for multidevice setups.\n #[strum(props(default = \"1\"))]\n BccSelf,\n\n /// True if encryption is preferred according to Autocrypt standard.\n #[strum(props(default = \"1\"))]\n E2eeEnabled,\n\n /// True if Message Delivery Notifications (read receipts) should\n /// be sent and requested.\n #[strum(props(default = \"1\"))]\n MdnsEnabled,\n\n /// True if \"Sent\" folder should be watched for changes.\n #[strum(props(default = \"0\"))]\n SentboxWatch,\n\n /// True if chat messages should be moved to a separate folder.\n #[strum(props(default = \"1\"))]\n MvboxMove,\n\n /// Watch for new messages in the \"Mvbox\" (aka DeltaChat folder) only.\n ///\n /// This will not entirely disable other folders, e.g. the spam folder will also still\n /// be watched for new messages.\n #[strum(props(default = \"0\"))]\n OnlyFetchMvbox,\n\n /// Whether to show classic emails or only chat messages.\n #[strum(props(default = \"2\"))] // also change ShowEmails.default() on changes\n ShowEmails,\n\n /// Quality of the media files to send.\n #[strum(props(default = \"0\"))] // also change MediaQuality.default() on changes\n MediaQuality,\n\n /// If set to \"1\", on the first time `start_io()` is called after configuring,\n /// the newest existing messages are fetched.\n /// Existing recipients are added to the contact database regardless of this setting.\n #[strum(props(default = \"0\"))]\n FetchExistingMsgs,\n\n /// If set to \"1\", then existing messages are considered to be already fetched.\n /// This flag is reset after successful configuration.\n #[strum(props(default = \"1\"))]\n FetchedExistingMsgs,\n\n /// Type of the OpenPGP key to generate.\n #[strum(props(default = \"0\"))]\n KeyGenType,\n\n /// Timer in seconds after which the message is deleted from the\n /// server.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n ///\n /// Value 1 is treated as \"delete at once\": messages are deleted\n /// immediately, without moving to DeltaChat folder.\n #[strum(props(default = \"0\"))]\n DeleteServerAfter,\n\n /// Timer in seconds after which the message is deleted from the\n /// device.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n #[strum(props(default = \"0\"))]\n DeleteDeviceAfter,\n\n /// Move messages to the Trash folder instead of marking them \"\\Deleted\". Overrides\n /// `ProviderOptions::delete_to_trash`.\n DeleteToTrash,\n\n /// Save raw MIME messages with headers in the database if true.\n SaveMimeHeaders,\n\n /// The primary email address. Also see `SecondaryAddrs`.\n ConfiguredAddr,\n\n /// Configured IMAP server hostname.\n ConfiguredMailServer,\n\n /// Configured IMAP server username.\n ConfiguredMailUser,\n\n /// Configured IMAP server password.\n ConfiguredMailPw,\n\n /// Configured IMAP server port.\n ConfiguredMailPort,\n\n /// Configured IMAP server security (e.g. TLS, STARTTLS).\n ConfiguredMailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ConfiguredImapCertificateChecks,\n\n /// Configured SMTP server hostname.\n ConfiguredSendServer,\n\n /// Configured SMTP server username.\n ConfiguredSendUser,\n\n /// Configured SMTP server password.\n ConfiguredSendPw,\n\n /// Configured SMTP server port.\n ConfiguredSendPort,\n\n /// How to check SMTP server TLS certificates.\n ConfiguredSmtpCertificateChecks,\n\n /// Whether OAuth 2 is used with configured provider.\n ConfiguredServerFlags,\n\n /// Configured SMTP server security (e.g. TLS, STARTTLS).\n ConfiguredSendSecurity,\n\n /// Configured folder for incoming messages.\n ConfiguredInboxFolder,\n\n /// Configured folder for chat messages.\n ConfiguredMvboxFolder,\n\n /// Configured \"Sent\" folder.\n ConfiguredSentboxFolder,\n\n /// Configured \"Trash\" folder.\n ConfiguredTrashFolder,\n\n /// Unix timestamp of the last successful configuration.\n ConfiguredTimestamp,\n\n /// ID of the configured provider from the provider database.\n ConfiguredProvider,\n\n /// True if account is configured.\n Configured,\n\n /// True if account is a chatmail account.\n IsChatmail,\n\n /// All secondary self addresses separated by spaces\n /// (`addr1@example.org addr2@example.org addr3@example.org`)\n SecondaryAddrs,\n\n /// Read-only core version string.\n #[strum(serialize = \"sys.version\")]\n SysVersion,\n\n /// Maximal recommended attachment size in bytes.\n #[strum(serialize = \"sys.msgsize_max_recommended\")]\n SysMsgsizeMaxRecommended,\n\n /// Space separated list of all config keys available.\n #[strum(serialize = \"sys.config_keys\")]\n SysConfigKeys,\n\n /// True if it is a bot account.\n Bot,\n\n /// True when to skip initial start messages in groups.\n #[strum(props(default = \"0\"))]\n SkipStartMessages,\n\n /// Whether we send a warning if the password is wrong (set to false when we send a warning\n /// because we do not want to send a second warning)\n #[strum(props(default = \"0\"))]\n NotifyAboutWrongPw,\n\n /// If a warning about exceeding quota was shown recently,\n /// this is the percentage of quota at the time the warning was given.\n /// Unset, when quota falls below minimal warning threshold again.\n QuotaExceeding,\n\n /// address to webrtc instance to use for videochats\n WebrtcInstance,\n\n /// Timestamp of the last time housekeeping was run\n LastHousekeeping,\n\n /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.\n LastCantDecryptOutgoingMsgs,\n\n /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.\n #[strum(props(default = \"60\"))]\n ScanAllFoldersDebounceSecs,\n\n /// Whether to avoid using IMAP IDLE even if the server supports it.\n ///\n /// This is a developer option for testing \"fake idle\".\n #[strum(props(default = \"0\"))]\n DisableIdle,\n\n /// Defines the max. size (in bytes) of messages downloaded automatically.\n /// 0 = no limit.\n #[strum(props(default = \"0\"))]\n DownloadLimit,\n\n /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.\n #[strum(props(default = \"1\"))]\n SyncMsgs,\n\n /// Space-separated list of all the authserv-ids which we believe\n /// may be the one of our email server.\n ///\n /// See `crate::authres::update_authservid_candidates`.\n AuthservIdCandidates,\n\n /// Make all outgoing messages with Autocrypt header \"multipart/signed\".\n SignUnencrypted,\n\n /// Let the core save all events to the database.\n /// This value is used internally to remember the MsgId of the logging xdc\n #[strum(props(default = \"0\"))]\n DebugLogging,\n\n /// Last message processed by the bot.\n LastMsgId,\n\n /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by\n /// default.\n ///\n /// This is not supposed to be changed by UIs and only used for testing.\n #[strum(props(default = \"172800\"))]\n GossipPeriod,\n\n /// Feature flag for verified 1:1 chats; the UI should set it\n /// to 1 if it supports verified 1:1 chats.\n /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,\n /// and when the key changes, an info message is posted into the chat.\n /// 0=Nothing else happens when the key changes.\n /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true\n /// until `chat_id.accept()` is called.\n #[strum(props(default = \"0\"))]\n VerifiedOneOnOneChats,\n\n /// Row ID of the key in the `keypairs` table\n /// used for signatures, encryption to self and included in `Autocrypt` header.\n KeyId,\n\n /// This key is sent to the self_reporting bot so that the bot can recognize the user\n /// without storing the email address\n SelfReportingId,\n\n /// MsgId of webxdc map integration.\n WebxdcIntegration,\n\n /// Iroh secret key.\n IrohSecretKey,\n}\n\n\npub struct Context {\n pub(crate) inner: Arc,\n}", "rust_imports": "use std::any::Any;\nuse std::ffi::OsStr;\nuse std::path::{Path, PathBuf};\nuse ::pgp::types::KeyTrait;\nuse anyhow::{bail, ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse futures::StreamExt;\nuse futures_lite::FutureExt;\nuse rand::{thread_rng, Rng};\nuse tokio::fs::{self, File};\nuse tokio_tar::Archive;\nuse crate::blob::{BlobDirContents, BlobObject};\nuse crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};\nuse crate::config::Config;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::e2ee;\nuse crate::events::EventType;\nuse crate::key::{\n self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,\n};\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::param::Param;\nuse crate::pgp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{\n create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,\n};\nuse transfer::{get_backup, BackupProvider};\nuse std::time::Duration;\nuse ::pgp::armor::BlockType;\nuse tokio::task;\nuse super::*;\nuse crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::{alice_keypair, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__imex__.rs__function__4.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "uint32_t dc_chat_get_color(const dc_chat_t* chat)\n{\n\tuint32_t color = 0;\n\tdc_array_t* contacts = NULL;\n\tdc_contact_t* contact = NULL;\n\n\tif (chat==NULL || chat->magic!=DC_CHAT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tif(chat->type==DC_CHAT_TYPE_SINGLE) {\n\t\tcontacts = dc_get_chat_contacts(chat->context, chat->id);\n\t\tif (contacts->count >= 1) {\n\t\t\tcontact = dc_get_contact(chat->context, contacts->array[0]);\n\t\t\tcolor = dc_str_to_color(contact->addr);\n\t\t}\n\t}\n\telse {\n\t\tcolor = dc_str_to_color(chat->name);\n\t}\n\ncleanup:\n\tdc_array_unref(contacts);\n\tdc_contact_unref(contact);\n\treturn color;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn get_color(&self, context: &Context) -> Result {\n let mut color = 0;\n\n if self.typ == Chattype::Single {\n let contacts = get_chat_contacts(context, self.id).await?;\n if let Some(contact_id) = contacts.first() {\n if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {\n color = contact.get_color();\n }\n }\n } else {\n color = str_to_color(&self.name);\n }\n\n Ok(color)\n }", "rust_context": "pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result> {\n // Normal chats do not include SELF. Group chats do (as it may happen that one is deleted from a\n // groupchat but the chats stays visible, moreover, this makes displaying lists easier)\n\n let list = context\n .sql\n .query_map(\n \"SELECT cc.contact_id\n FROM chats_contacts cc\n LEFT JOIN contacts c\n ON c.id=cc.contact_id\n WHERE cc.chat_id=?\n ORDER BY c.id=1, c.last_seen DESC, c.id DESC;\",\n (chat_id,),\n |row| row.get::<_, ContactId>(0),\n |ids| ids.collect::, _>>().map_err(Into::into),\n )\n .await?;\n\n Ok(list)\n}\n\npub async fn get_by_id(context: &Context, contact_id: ContactId) -> Result {\n let contact = Self::get_by_id_optional(context, contact_id)\n .await?\n .with_context(|| format!(\"contact {contact_id} not found\"))?;\n Ok(contact)\n }\n\npub fn get_color(&self) -> u32 {\n str_to_color(&self.addr.to_lowercase())\n }\n\npub fn str_to_color(s: &str) -> u32 {\n rgb_to_u32(hsluv_to_rgb((str_to_angle(s), 100.0, 50.0)))\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct Chat {\n /// Database ID.\n pub id: ChatId,\n\n /// Chat type, e.g. 1:1 chat, group chat, mailing list.\n pub typ: Chattype,\n\n /// Chat name.\n pub name: String,\n\n /// Whether the chat is archived or pinned.\n pub visibility: ChatVisibility,\n\n /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and\n /// ad-hoc groups.\n pub grpid: String,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n\n /// Additional chat parameters stored in the database.\n pub param: Params,\n\n /// If location streaming is enabled in the chat.\n is_sending_locations: bool,\n\n /// Duration of the chat being muted.\n pub mute_duration: MuteDuration,\n\n /// If the chat is protected (verified).\n pub(crate) protected: ProtectionStatus,\n}\n\npub enum Chattype {\n /// 1:1 chat.\n Single = 100,\n\n /// Group chat.\n Group = 120,\n\n /// Mailing list.\n Mailinglist = 140,\n\n /// Broadcast list.\n Broadcast = 160,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__74.txt"} {"c_path": "projects/deltachat-core/c/dc_qr.c", "c_func": "dc_lot_t* dc_check_qr(dc_context_t* context, const char* qr)\n{\n\tchar* payload = NULL;\n\tchar* addr = NULL; // must be normalized, if set\n\tchar* fingerprint = NULL; // must be normalized, if set\n\tchar* name = NULL;\n\tchar* invitenumber = NULL;\n\tchar* auth = NULL;\n\tdc_apeerstate_t* peerstate = dc_apeerstate_new(context);\n\tdc_lot_t* qr_parsed = dc_lot_new();\n\tuint32_t chat_id = 0;\n\tchar* device_msg = NULL;\n\tchar* grpid = NULL;\n\tchar* grpname = NULL;\n\n\tqr_parsed->state = 0;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || qr==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tdc_log_info(context, 0, \"Scanned QR code: %s\", qr);\n\n\t/* split parameters from the qr code*/\n\n\tif (strncasecmp(qr, DC_OPENPGP4FPR_SCHEME, strlen(DC_OPENPGP4FPR_SCHEME))==0)\n\t{\n\t\t/* scheme: OPENPGP4FPR:FINGERPRINT#a=ADDR&n=NAME&i=INVITENUMBER&s=AUTH\n\t\t or: OPENPGP4FPR:FINGERPRINT#a=ADDR&g=GROUPNAME&x=GROUPID&i=INVITENUMBER&s=AUTH */\n\n\t\tpayload = dc_strdup(&qr[strlen(DC_OPENPGP4FPR_SCHEME)]);\n\t\tchar* fragment = strchr(payload, '#'); /* must not be freed, only a pointer inside payload */\n\t\tif (fragment)\n\t\t{\n\t\t\t*fragment = 0;\n\t\t\tfragment++;\n\n\t\t\tdc_param_t* param = dc_param_new();\n\t\t\tdc_param_set_urlencoded(param, fragment);\n\n\t\t\taddr = dc_param_get(param, 'a', NULL);\n\t\t\tif (addr) {\n\t\t\t\tchar* urlencoded = dc_param_get(param, 'n', NULL);\n\t\t\t\tif(urlencoded) {\n\t\t\t\t\tname = dc_urldecode(urlencoded);\n\t\t\t\t\tdc_normalize_name(name);\n\t\t\t\t\tfree(urlencoded);\n\t\t\t\t}\n\n\t\t\t\tinvitenumber = dc_param_get(param, 'i', NULL);\n\t\t\t\tauth = dc_param_get(param, 's', NULL);\n\n\t\t\t\tgrpid = dc_param_get(param, 'x', NULL);\n\t\t\t\tif (grpid) {\n\t\t\t\t\turlencoded = dc_param_get(param, 'g', NULL);\n\t\t\t\t\tif (urlencoded) {\n\t\t\t\t\t\tgrpname = dc_urldecode(urlencoded);\n\t\t\t\t\t\tfree(urlencoded);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdc_param_unref(param);\n\t\t}\n\n\t\tfingerprint = dc_normalize_fingerprint(payload);\n\t}\n\telse if (strncasecmp(qr, MAILTO_SCHEME, strlen(MAILTO_SCHEME))==0)\n\t{\n\t\t/* scheme: mailto:addr...?subject=...&body=... */\n\t\tpayload = dc_strdup(&qr[strlen(MAILTO_SCHEME)]);\n\t\tchar* query = strchr(payload, '?'); /* must not be freed, only a pointer inside payload */\n\t\tif (query) {\n\t\t\t*query = 0;\n\t\t}\n\t\taddr = dc_strdup(payload);\n\t}\n\telse if (strncasecmp(qr, SMTP_SCHEME, strlen(SMTP_SCHEME))==0)\n\t{\n\t\t/* scheme: `SMTP:addr...:subject...:body...` */\n\t\tpayload = dc_strdup(&qr[strlen(SMTP_SCHEME)]);\n\t\tchar* colon = strchr(payload, ':'); /* must not be freed, only a pointer inside payload */\n\t\tif (colon) {\n\t\t\t*colon = 0;\n\t\t}\n\t\taddr = dc_strdup(payload);\n\t}\n\telse if (strncasecmp(qr, MATMSG_SCHEME, strlen(MATMSG_SCHEME))==0)\n\t{\n\t\t/* scheme: `MATMSG:TO:addr...;SUB:subject...;BODY:body...;` - there may or may not be linebreaks after the fields */\n\t\tchar* 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. */\n\t\tif (to) {\n\t\t\taddr = dc_strdup(&to[3]);\n\t\t\tchar* semicolon = strchr(addr, ';');\n\t\t\tif (semicolon) { *semicolon = 0; }\n\t\t}\n\t\telse {\n\t\t\tqr_parsed->state = DC_QR_ERROR;\n\t\t\tqr_parsed->text1 = dc_strdup(\"Bad e-mail address.\");\n\t\t\tgoto cleanup;\n\t\t}\n\t}\n\telse if (strncasecmp(qr, VCARD_BEGIN, strlen(VCARD_BEGIN))==0)\n\t{\n\t\t/* scheme: `VCARD:BEGIN\\nN:last name;first name;...;\\nEMAIL:addr...;` */\n\t\tcarray* lines = dc_split_into_lines(qr);\n\t\tfor (int i = 0; i < carray_count(lines); i++) {\n\t\t\tchar* key = (char*)carray_get(lines, i); dc_trim(key);\n\t\t\tchar* value = strchr(key, ':');\n\t\t\tif (value) {\n\t\t\t\t*value = 0;\n\t\t\t\tvalue++;\n\t\t\t\tchar* semicolon = strchr(key, ';'); if (semicolon) { *semicolon = 0; } /* handle `EMAIL;type=work:` stuff */\n\t\t\t\tif (strcasecmp(key, \"EMAIL\")==0) {\n\t\t\t\t\tsemicolon = strchr(value, ';'); if (semicolon) { *semicolon = 0; } /* use the first EMAIL */\n\t\t\t\t\taddr = dc_strdup(value);\n\t\t\t\t}\n\t\t\t\telse if (strcasecmp(key, \"N\")==0) {\n\t\t\t\t\tsemicolon = 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 */\n\t\t\t\t\tname = dc_strdup(value);\n\t\t\t\t\tdc_str_replace(&name, \";\", \",\"); /* the format \"lastname,prename\" is handled by dc_normalize_name() */\n\t\t\t\t\tdc_normalize_name(name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdc_free_splitted_lines(lines);\n\t}\n\n\t/* check the paramters */\n\n\tif (addr) {\n\t\tchar* temp = dc_urldecode(addr); free(addr); addr = temp; /* urldecoding is needed at least for OPENPGP4FPR but should not hurt in the other cases */\n\t\t temp = dc_addr_normalize(addr); free(addr); addr = temp;\n\n\t\tif (!dc_may_be_valid_addr(addr)) {\n\t\t\tqr_parsed->state = DC_QR_ERROR;\n\t\t\tqr_parsed->text1 = dc_strdup(\"Bad e-mail address.\");\n\t\t\tgoto cleanup;\n\t\t}\n\t}\n\n\tif (fingerprint) {\n\t\tif (strlen(fingerprint) != 40) {\n\t\t\tqr_parsed->state = DC_QR_ERROR;\n\t\t\tqr_parsed->text1 = dc_strdup(\"Bad fingerprint length in QR code.\");\n\t\t\tgoto cleanup;\n\t\t}\n\t}\n\n\t/* let's see what we can do with the parameters */\n\n\tif (fingerprint)\n\t{\n\t\t/* fingerprint set ... */\n\n\t\tif (addr==NULL || invitenumber==NULL || auth==NULL)\n\t\t{\n\t\t\t// _only_ fingerprint set ...\n\t\t\t// (we could also do this before/instead of a secure-join, however, this may require complicated questions in the ui)\n\t\t\tif (dc_apeerstate_load_by_fingerprint(peerstate, context->sql, fingerprint)) {\n\t\t\t\tqr_parsed->state = DC_QR_FPR_OK;\n\t\t\t\tqr_parsed->id = dc_add_or_lookup_contact(context, NULL, peerstate->addr, DC_ORIGIN_UNHANDLED_QR_SCAN, NULL);\n\n\t\t\t\tdc_create_or_lookup_nchat_by_contact_id(context, qr_parsed->id, DC_CHAT_DEADDROP_BLOCKED, &chat_id, NULL);\n\t\t\t\tdevice_msg = dc_mprintf(\"%s verified.\", peerstate->addr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tqr_parsed->text1 = dc_format_fingerprint(fingerprint);\n\t\t\t\tqr_parsed->state = DC_QR_FPR_WITHOUT_ADDR;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// fingerprint + addr set, secure-join requested\n\t\t\t// do not comapre the fingerprint already - it may have changed - errors are catched later more proberly.\n\t\t\t// (theroretically, there is also the state \"addr=set, fingerprint=set, invitenumber=0\", however, currently, we won't get into this state)\n\t\t\tif (grpid && grpname) {\n\t\t\t\tqr_parsed->state = DC_QR_ASK_VERIFYGROUP;\n\t\t\t\tqr_parsed->text1 = dc_strdup(grpname);\n\t\t\t\tqr_parsed->text2 = dc_strdup(grpid);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tqr_parsed->state = DC_QR_ASK_VERIFYCONTACT;\n\t\t\t}\n\n\t\t\tqr_parsed->id = dc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_UNHANDLED_QR_SCAN, NULL);\n\t\t\tqr_parsed->fingerprint = dc_strdup(fingerprint);\n\t\t\tqr_parsed->invitenumber = dc_strdup(invitenumber);\n\t\t\tqr_parsed->auth = dc_strdup(auth);\n\t\t}\n\t}\n\telse if (addr)\n\t{\n qr_parsed->state = DC_QR_ADDR;\n\t\tqr_parsed->id = dc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_UNHANDLED_QR_SCAN, NULL);\n\t}\n\telse if (strstr(qr, \"http://\")==qr || strstr(qr, \"https://\")==qr)\n\t{\n\t\tqr_parsed->state = DC_QR_URL;\n\t\tqr_parsed->text1 = dc_strdup(qr);\n\t}\n\telse\n\t{\n qr_parsed->state = DC_QR_TEXT;\n\t\tqr_parsed->text1 = dc_strdup(qr);\n\t}\n\n\tif (device_msg) {\n\t\tdc_add_device_msg(context, chat_id, device_msg);\n\t}\n\ncleanup:\n\tfree(addr);\n\tfree(fingerprint);\n\tdc_apeerstate_unref(peerstate);\n\tfree(payload);\n\tfree(name);\n\tfree(invitenumber);\n\tfree(auth);\n\tfree(device_msg);\n\tfree(grpname);\n\tfree(grpid);\n\treturn qr_parsed;\n}", "rust_path": "projects/deltachat-core/rust/qr.rs", "rust_func": "pub async fn check_qr(context: &Context, qr: &str) -> Result {\n let qrcode = if starts_with_ignore_case(qr, OPENPGP4FPR_SCHEME) {\n decode_openpgp(context, qr)\n .await\n .context(\"failed to decode OPENPGP4FPR QR code\")?\n } else if qr.starts_with(IDELTACHAT_SCHEME) {\n decode_ideltachat(context, IDELTACHAT_SCHEME, qr).await?\n } else if qr.starts_with(IDELTACHAT_NOSLASH_SCHEME) {\n decode_ideltachat(context, IDELTACHAT_NOSLASH_SCHEME, qr).await?\n } else if starts_with_ignore_case(qr, DCACCOUNT_SCHEME) {\n decode_account(qr)?\n } else if starts_with_ignore_case(qr, DCLOGIN_SCHEME) {\n dclogin_scheme::decode_login(qr)?\n } else if starts_with_ignore_case(qr, DCWEBRTC_SCHEME) {\n decode_webrtc_instance(context, qr)?\n } else if starts_with_ignore_case(qr, DCBACKUP_SCHEME) {\n decode_backup(qr)?\n } else if qr.starts_with(MAILTO_SCHEME) {\n decode_mailto(context, qr).await?\n } else if qr.starts_with(SMTP_SCHEME) {\n decode_smtp(context, qr).await?\n } else if qr.starts_with(MATMSG_SCHEME) {\n decode_matmsg(context, qr).await?\n } else if qr.starts_with(VCARD_SCHEME) {\n decode_vcard(context, qr).await?\n } else if qr.starts_with(HTTP_SCHEME) || qr.starts_with(HTTPS_SCHEME) {\n Qr::Url {\n url: qr.to_string(),\n }\n } else {\n Qr::Text {\n text: qr.to_string(),\n }\n };\n Ok(qrcode)\n}", "rust_context": "async fn decode_mailto(context: &Context, qr: &str) -> Result {\n let payload = &qr[MAILTO_SCHEME.len()..];\n\n let (addr, query) = if let Some(query_index) = payload.find('?') {\n (&payload[..query_index], &payload[query_index + 1..])\n } else {\n (payload, \"\")\n };\n\n let param: BTreeMap<&str, &str> = query\n .split('&')\n .filter_map(|s| {\n if let [key, value] = s.splitn(2, '=').collect::>()[..] {\n Some((key, value))\n } else {\n None\n }\n })\n .collect();\n\n let subject = if let Some(subject) = param.get(\"subject\") {\n subject.to_string()\n } else {\n \"\".to_string()\n };\n let draft = if let Some(body) = param.get(\"body\") {\n if subject.is_empty() {\n body.to_string()\n } else {\n subject + \"\\n\" + body\n }\n } else {\n subject\n };\n let draft = draft.replace('+', \"%20\"); // sometimes spaces are encoded as `+`\n let draft = match percent_decode_str(&draft).decode_utf8() {\n Ok(decoded_draft) => decoded_draft.to_string(),\n Err(_err) => draft,\n };\n\n let addr = normalize_address(addr)?;\n let name = \"\";\n Qr::from_address(\n context,\n name,\n &addr,\n if draft.is_empty() { None } else { Some(draft) },\n )\n .await\n}\n\nfn decode_backup(qr: &str) -> Result {\n let payload = qr\n .strip_prefix(DCBACKUP_SCHEME)\n .ok_or_else(|| anyhow!(\"invalid DCBACKUP scheme\"))?;\n let ticket: iroh::provider::Ticket = payload.parse().context(\"invalid DCBACKUP payload\")?;\n Ok(Qr::Backup { ticket })\n}\n\nasync fn decode_matmsg(context: &Context, qr: &str) -> Result {\n // Does not work when the text `TO:` is used in subject/body _and_ TO: is not the first field.\n // we ignore this case.\n let addr = if let Some(to_index) = qr.find(\"TO:\") {\n let addr = qr[to_index + 3..].trim();\n if let Some(semi_index) = addr.find(';') {\n addr[..semi_index].trim()\n } else {\n addr\n }\n } else {\n bail!(\"Invalid MATMSG found\");\n };\n\n let addr = normalize_address(addr)?;\n let name = \"\";\n Qr::from_address(context, name, &addr, None).await\n}\n\nasync fn decode_smtp(context: &Context, qr: &str) -> Result {\n let payload = &qr[SMTP_SCHEME.len()..];\n\n let addr = if let Some(query_index) = payload.find(':') {\n &payload[..query_index]\n } else {\n bail!(\"Invalid SMTP found\");\n };\n\n let addr = normalize_address(addr)?;\n let name = \"\";\n Qr::from_address(context, name, &addr, None).await\n}\n\nasync fn decode_vcard(context: &Context, qr: &str) -> Result {\n let name = VCARD_NAME_RE\n .captures(qr)\n .and_then(|caps| {\n let last_name = caps.get(1)?.as_str().trim();\n let first_name = caps.get(2)?.as_str().trim();\n\n Some(format!(\"{first_name} {last_name}\"))\n })\n .unwrap_or_default();\n\n let addr = if let Some(caps) = VCARD_EMAIL_RE.captures(qr) {\n normalize_address(caps[2].trim())?\n } else {\n bail!(\"Bad e-mail address\");\n };\n\n Qr::from_address(context, &name, &addr, None).await\n}\n\nasync fn decode_openpgp(context: &Context, qr: &str) -> Result {\n let payload = &qr[OPENPGP4FPR_SCHEME.len()..];\n\n // macOS and iOS sometimes replace the # with %23 (uri encode it), we should be able to parse this wrong format too.\n // see issue https://github.com/deltachat/deltachat-core-rust/issues/1969 for more info\n let (fingerprint, fragment) = match payload\n .split_once('#')\n .or_else(|| payload.split_once(\"%23\"))\n {\n Some(pair) => pair,\n None => (payload, \"\"),\n };\n let fingerprint: Fingerprint = fingerprint\n .parse()\n .context(\"Failed to parse fingerprint in the QR code\")?;\n\n let param: BTreeMap<&str, &str> = fragment\n .split('&')\n .filter_map(|s| {\n if let [key, value] = s.splitn(2, '=').collect::>()[..] {\n Some((key, value))\n } else {\n None\n }\n })\n .collect();\n\n let addr = if let Some(addr) = param.get(\"a\") {\n Some(normalize_address(addr)?)\n } else {\n None\n };\n\n let name = if let Some(encoded_name) = param.get(\"n\") {\n let encoded_name = encoded_name.replace('+', \"%20\"); // sometimes spaces are encoded as `+`\n match percent_decode_str(&encoded_name).decode_utf8() {\n Ok(name) => name.to_string(),\n Err(err) => bail!(\"Invalid name: {}\", err),\n }\n } else {\n \"\".to_string()\n };\n\n let invitenumber = param\n .get(\"i\")\n .filter(|&s| validate_id(s))\n .map(|s| s.to_string());\n let authcode = param\n .get(\"s\")\n .filter(|&s| validate_id(s))\n .map(|s| s.to_string());\n let grpid = param\n .get(\"x\")\n .filter(|&s| validate_id(s))\n .map(|s| s.to_string());\n\n let grpname = if grpid.is_some() {\n if let Some(encoded_name) = param.get(\"g\") {\n let encoded_name = encoded_name.replace('+', \"%20\"); // sometimes spaces are encoded as `+`\n match percent_decode_str(&encoded_name).decode_utf8() {\n Ok(name) => Some(name.to_string()),\n Err(err) => bail!(\"Invalid group name: {}\", err),\n }\n } else {\n None\n }\n } else {\n None\n };\n\n // retrieve known state for this fingerprint\n let peerstate = Peerstate::from_fingerprint(context, &fingerprint)\n .await\n .context(\"Can't load peerstate\")?;\n\n if let (Some(addr), Some(invitenumber), Some(authcode)) = (&addr, invitenumber, authcode) {\n let addr = ContactAddress::new(addr)?;\n let (contact_id, _) =\n Contact::add_or_lookup(context, &name, &addr, Origin::UnhandledQrScan)\n .await\n .with_context(|| format!(\"failed to add or lookup contact for address {addr:?}\"))?;\n\n if let (Some(grpid), Some(grpname)) = (grpid, grpname) {\n if context\n .is_self_addr(&addr)\n .await\n .with_context(|| format!(\"can't check if address {addr:?} is our address\"))?\n {\n if token::exists(context, token::Namespace::InviteNumber, &invitenumber).await? {\n Ok(Qr::WithdrawVerifyGroup {\n grpname,\n grpid,\n contact_id,\n fingerprint,\n invitenumber,\n authcode,\n })\n } else {\n Ok(Qr::ReviveVerifyGroup {\n grpname,\n grpid,\n contact_id,\n fingerprint,\n invitenumber,\n authcode,\n })\n }\n } else {\n Ok(Qr::AskVerifyGroup {\n grpname,\n grpid,\n contact_id,\n fingerprint,\n invitenumber,\n authcode,\n })\n }\n } else if context.is_self_addr(&addr).await? {\n if token::exists(context, token::Namespace::InviteNumber, &invitenumber).await? {\n Ok(Qr::WithdrawVerifyContact {\n contact_id,\n fingerprint,\n invitenumber,\n authcode,\n })\n } else {\n Ok(Qr::ReviveVerifyContact {\n contact_id,\n fingerprint,\n invitenumber,\n authcode,\n })\n }\n } else {\n Ok(Qr::AskVerifyContact {\n contact_id,\n fingerprint,\n invitenumber,\n authcode,\n })\n }\n } else if let Some(addr) = addr {\n if let Some(peerstate) = peerstate {\n let peerstate_addr = ContactAddress::new(&peerstate.addr)?;\n let (contact_id, _) =\n Contact::add_or_lookup(context, &name, &peerstate_addr, Origin::UnhandledQrScan)\n .await\n .context(\"add_or_lookup\")?;\n ChatIdBlocked::get_for_contact(context, contact_id, Blocked::Request)\n .await\n .context(\"Failed to create (new) chat for contact\")?;\n Ok(Qr::FprOk { contact_id })\n } else {\n let contact_id = Contact::lookup_id_by_addr(context, &addr, Origin::Unknown)\n .await\n .with_context(|| format!(\"Error looking up contact {addr:?}\"))?;\n Ok(Qr::FprMismatch { contact_id })\n }\n } else {\n Ok(Qr::FprWithoutAddr {\n fingerprint: fingerprint.to_string(),\n })\n }\n}\n\nfn starts_with_ignore_case(string: &str, pattern: &str) -> bool {\n string.to_lowercase().starts_with(&pattern.to_lowercase())\n}\n\nfn decode_account(qr: &str) -> Result {\n let payload = qr\n .get(DCACCOUNT_SCHEME.len()..)\n .context(\"invalid DCACCOUNT payload\")?;\n let url = url::Url::parse(payload).context(\"Invalid account URL\")?;\n if url.scheme() == \"http\" || url.scheme() == \"https\" {\n Ok(Qr::Account {\n domain: url\n .host_str()\n .context(\"can't extract WebRTC instance domain\")?\n .to_string(),\n })\n } else {\n bail!(\"Bad scheme for account URL: {:?}.\", url.scheme());\n }\n}\n\nfn decode_webrtc_instance(_context: &Context, qr: &str) -> Result {\n let payload = qr\n .get(DCWEBRTC_SCHEME.len()..)\n .context(\"invalid DCWEBRTC payload\")?;\n\n let (_type, url) = Message::parse_webrtc_instance(payload);\n let url = url::Url::parse(&url).context(\"Invalid WebRTC instance\")?;\n\n if url.scheme() == \"http\" || url.scheme() == \"https\" {\n Ok(Qr::WebrtcInstance {\n domain: url\n .host_str()\n .context(\"can't extract WebRTC instance domain\")?\n .to_string(),\n instance_pattern: payload.to_string(),\n })\n } else {\n bail!(\"Bad URL scheme for WebRTC instance: {:?}\", url.scheme());\n }\n}\n\nasync fn decode_ideltachat(context: &Context, prefix: &str, qr: &str) -> Result {\n let qr = qr.replacen(prefix, OPENPGP4FPR_SCHEME, 1);\n let qr = qr.replacen('&', \"#\", 1);\n decode_openpgp(context, &qr)\n .await\n .context(\"failed to decode {prefix} QR code\")\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\nconst OPENPGP4FPR_SCHEME: &str = \"OPENPGP4FPR:\"; // yes: uppercase\nconst IDELTACHAT_SCHEME: &str = \"https://i.delta.chat/#\";\nconst IDELTACHAT_NOSLASH_SCHEME: &str = \"https://i.delta.chat#\";\nconst DCACCOUNT_SCHEME: &str = \"DCACCOUNT:\";\npub(super) const DCLOGIN_SCHEME: &str = \"DCLOGIN:\";\nconst DCWEBRTC_SCHEME: &str = \"DCWEBRTC:\";\nconst MAILTO_SCHEME: &str = \"mailto:\";\nconst MATMSG_SCHEME: &str = \"MATMSG:\";\nconst VCARD_SCHEME: &str = \"BEGIN:VCARD\";\nconst SMTP_SCHEME: &str = \"SMTP:\";\nconst HTTP_SCHEME: &str = \"http://\";\nconst HTTPS_SCHEME: &str = \"https://\";\npub(crate) const DCBACKUP_SCHEME: &str = \"DCBACKUP:\";", "rust_imports": "use std::collections::BTreeMap;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse dclogin_scheme::LoginOptions;\nuse deltachat_contact_tools::{addr_normalize, may_be_valid_addr, ContactAddress};\nuse once_cell::sync::Lazy;\nuse percent_encoding::percent_decode_str;\nuse serde::Deserialize;\nuse self::dclogin_scheme::configure_from_login_qr;\nuse crate::chat::{get_chat_id_by_grpid, ChatIdBlocked};\nuse crate::config::Config;\nuse crate::constants::Blocked;\nuse crate::contact::{Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::Fingerprint;\nuse crate::message::Message;\nuse crate::peerstate::Peerstate;\nuse crate::socks::Socks5Config;\nuse crate::token;\nuse crate::tools::validate_id;\nuse iroh_old as iroh;\nuse super::*;\nuse crate::aheader::EncryptPreference;\nuse crate::chat::{create_group_chat, ProtectionStatus};\nuse crate::key::DcKey;\nuse crate::securejoin::get_securejoin_qr;\nuse crate::test_utils::{alice_keypair, TestContext};", "rustrepotrans_file": "projects__deltachat-core__rust__qr__.rs__function__2.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* If dc_prepare_msg() was called before, this parameter can be 0.\n * @param msg Message object to send to the chat defined by the chat ID.\n * On succcess, msg_id of the object is set up,\n * The function does not take ownership of the object,\n * so you have to free it using dc_msg_unref() as usual.\n * @return The ID of the message that is about to be sent. 0 in case of errors.\n */\nuint32_t dc_send_msg(dc_context_t* context, uint32_t chat_id, dc_msg_t* msg)\n{\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg==NULL) {\n\t\treturn 0;\n\t}\n\n\t// recursively send any forwarded copies\n\tif (!chat_id) {\n\t\tchar* forwards = dc_param_get(msg->param, DC_PARAM_PREP_FORWARDS, NULL);\n\t\tif (forwards) {\n\t\t\tchar* p = forwards;\n\t\t\twhile (*p) {\n\t\t\t\tint32_t id = strtol(p, &p, 10);\n\t\t\t\tif (!id) break; // avoid hanging if user tampers with db\n\t\t\t\tdc_msg_t* copy = dc_get_msg(context, id);\n\t\t\t\tif (copy) {\n\t\t\t\t\tdc_send_msg(context, chat_id, copy);\n\t\t\t\t}\n\t\t\t\tdc_msg_unref(copy);\n\t\t\t}\n\t\t\tdc_param_set(msg->param, DC_PARAM_PREP_FORWARDS, NULL);\n\t\t\tdc_msg_save_param_to_disk(msg);\n\t\t}\n\t\tfree(forwards);\n\t\tdc_send_msg(context, chat_id, msg);\n\t\treturn msg->id;\n\t}\n\n\t\n\t// automatically prepare normal messages\n\tif (msg->state!=DC_STATE_OUT_PREPARING && msg-state!=DC_STATE_UNDEFINED) {\n\t\tdc_param_set(msg->param, DC_PARAM_GUARANTEE_E2EE, NULL);\n\t\tdc_param_set(msg->param, DC_PARAM_FORCE_PLAINTEXT, NULL);\n\t\tdc_msg_save_param_to_disk(msg);\n\t}\n\tdc_send_msg(context, chat_id, msg);\n\treturn msg->id;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result {\n if chat_id.is_unset() {\n let forwards = msg.param.get(Param::PrepForwards);\n if let Some(forwards) = forwards {\n for forward in forwards.split(' ') {\n if let Ok(msg_id) = forward.parse::().map(MsgId::new) {\n if let Ok(mut msg) = Message::load_from_db(context, msg_id).await {\n send_msg_inner(context, chat_id, &mut msg).await?;\n };\n }\n }\n msg.param.remove(Param::PrepForwards);\n msg.update_param(context).await?;\n }\n return send_msg_inner(context, chat_id, msg).await;\n }\n\n if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing {\n msg.param.remove(Param::GuaranteeE2ee);\n msg.param.remove(Param::ForcePlaintext);\n msg.update_param(context).await?;\n }\n send_msg_inner(context, chat_id, msg).await\n}", "rust_context": "pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> {\n context\n .sql\n .execute(\n \"UPDATE chats SET param=? WHERE id=?\",\n (self.param.to_string(), self.id),\n )\n .await?;\n Ok(())\n }\n\npub fn remove(&mut self, key: Param) -> &mut Self {\n self.inner.remove(&key);\n self\n }\n\npub fn get(&self, key: Param) -> Option<&str> {\n self.inner.get(&key).map(|s| s.as_str())\n }\n\npub fn is_unset(self) -> bool {\n self.0 == 0\n }\n\nasync fn send_msg_inner(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result {\n // protect all system messages against RTLO attacks\n if msg.is_system_message() {\n msg.text = strip_rtlo_characters(&msg.text);\n }\n\n if !prepare_send_msg(context, chat_id, msg).await?.is_empty() {\n if !msg.hidden {\n context.emit_msgs_changed(msg.chat_id, msg.id);\n }\n\n if msg.param.exists(Param::SetLatitude) {\n context.emit_location_changed(Some(ContactId::SELF)).await?;\n }\n\n context.scheduler.interrupt_smtp().await;\n }\n\n Ok(msg.id)\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct MsgId(u32);\n\npub struct ChatId(u32);\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\nimpl Message {\n /// Loads message with given ID from the database.\n ///\n /// Returns an error if the message does not exist.\n pub async fn load_from_db(context: &Context, id: MsgId) -> Result {\n let message = Self::load_from_db_optional(context, id)\n .await?\n .with_context(|| format!(\"Message {id} does not exist\"))?;\n Ok(message)\n }\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}\n\nimpl MsgId {\n /// Create a new [MsgId].\n pub fn new(id: u32) -> MsgId {\n MsgId(id)\n }\n}\n\npub enum MessageState {\n /// Undefined message state.\n #[default]\n Undefined = 0,\n\n /// Incoming *fresh* message. Fresh messages are neither noticed\n /// nor seen and are typically shown in notifications.\n InFresh = 10,\n\n /// Incoming *noticed* message. E.g. chat opened but message not\n /// yet read - noticed messages are not counted as unread but did\n /// not marked as read nor resulted in MDNs.\n InNoticed = 13,\n\n /// Incoming message, really *seen* by the user. Marked as read on\n /// IMAP and MDN may be sent.\n InSeen = 16,\n\n /// For files which need time to be prepared before they can be\n /// sent, the message enters this state before\n /// OutPending.\n OutPreparing = 18,\n\n /// Message saved as draft.\n OutDraft = 19,\n\n /// The user has pressed the \"send\" button but the message is not\n /// yet sent and is pending in some way. Maybe we're offline (no\n /// checkmark).\n OutPending = 20,\n\n /// *Unrecoverable* error (*recoverable* errors result in pending\n /// messages).\n OutFailed = 24,\n\n /// Outgoing message successfully delivered to server (one\n /// checkmark). Note, that already delivered messages may get into\n /// the OutFailed state if we get such a hint from the server.\n OutDelivered = 26,\n\n /// Outgoing message read by the recipient (two checkmarks; this\n /// requires goodwill on the receiver's side)\n OutMdnRcvd = 28,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__104.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "int dc_add_contact_to_chat_ex(dc_context_t* context, uint32_t chat_id, uint32_t contact_id, int flags)\n{\n\tint success = 0;\n\tdc_contact_t* contact = dc_get_contact(context, contact_id);\n\tdc_chat_t* chat = dc_chat_new(context);\n\tdc_msg_t* msg = dc_msg_new_untyped(context);\n\tchar* self_addr = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || contact==NULL || chat_id<=DC_CHAT_ID_LAST_SPECIAL) {\n\t\tgoto cleanup;\n\t}\n\n\tdc_reset_gossiped_timestamp(context, chat_id);\n\n\tif (0==real_group_exists(context, chat_id) /*this also makes sure, not contacts are added to special or normal chats*/\n\t || (0==dc_real_contact_exists(context, contact_id) && contact_id!=DC_CONTACT_ID_SELF)\n\t || 0==dc_chat_load_from_db(chat, chat_id)) {\n\t\tgoto cleanup;\n\t}\n\n\tif (!IS_SELF_IN_GROUP) {\n\t\tdc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0,\n\t\t \"Cannot add contact to group; self not in group.\");\n\t\tgoto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */\n\t}\n\n\tif ((flags&DC_FROM_HANDSHAKE) && dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0)==1) {\n\t\t// after a handshake, force sending the `Chat-Group-Member-Added` message\n\t\tdc_param_set(chat->param, DC_PARAM_UNPROMOTED, NULL);\n\t\tdc_chat_update_param(chat);\n\t}\n\n\tself_addr = dc_sqlite3_get_config(context->sql, \"configured_addr\", \"\");\n\tif (strcasecmp(contact->addr, self_addr)==0) {\n\t\tgoto 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. */\n\t}\n\n\tif (dc_is_contact_in_chat(context, chat_id, contact_id))\n\t{\n\t\tif (!(flags&DC_FROM_HANDSHAKE)) {\n\t\t\tsuccess = 1;\n\t\t\tgoto cleanup;\n\t\t}\n\t\t// else continue and send status mail\n\t}\n\telse\n\t{\n if (dc_chat_is_protected() && dc_contact_is_verified(contact)!=DC_BIDIRECT_VERIFIED) {\n dc_log_error(context, 0, \"Only bidirectional verified contacts can be added to verified groups.\");\n goto cleanup;\n }\n if (dc_is_contact_in_chat(context, chat_id, contact_id)){\n goto cleanup; \n }\n\t\tif (0==dc_add_to_chat_contacts_table(context, chat_id, contact_id)) {\n\t\t\tgoto cleanup;\n\t\t}\n\t}\n\n\t/* send a status mail to all group members */\n\tif (chat->type==DC_CHAT_TYPE_GROUP && dc_chat_is_unpromoted() == 0)\n\t{\n\t\tmsg->type = DC_MSG_TEXT;\n\t\tmsg->text = dc_stock_system_msg(context, DC_STR_MSGADDMEMBER, contact->addr, NULL, DC_CONTACT_ID_SELF);\n\t\tdc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_MEMBER_ADDED_TO_GROUP);\n\t\tdc_param_set (msg->param, DC_PARAM_CMD_ARG, contact->addr);\n\t\tdc_param_set_int(msg->param, DC_PARAM_CMD_ARG2, flags); // combine the Secure-Join protocol headers with the Chat-Group-Member-Added header\n\t\tmsg->id = dc_send_msg(context, chat_id, msg);\n\t}\n\tcontext->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0);\n\n\tsuccess = 1;\n\ncleanup:\n\tdc_chat_unref(chat);\n\tdc_contact_unref(contact);\n\tdc_msg_unref(msg);\n\tfree(self_addr);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub(crate) async fn add_contact_to_chat_ex(\n context: &Context,\n mut sync: sync::Sync,\n chat_id: ChatId,\n contact_id: ContactId,\n from_handshake: bool,\n) -> Result {\n ensure!(!chat_id.is_special(), \"can not add member to special chats\");\n let contact = Contact::get_by_id(context, contact_id).await?;\n let mut msg = Message::default();\n\n chat_id.reset_gossiped_timestamp(context).await?;\n\n // this also makes sure, no contacts are added to special or normal chats\n let mut chat = Chat::load_from_db(context, chat_id).await?;\n ensure!(\n chat.typ == Chattype::Group || chat.typ == Chattype::Broadcast,\n \"{} is not a group/broadcast where one can add members\",\n chat_id\n );\n ensure!(\n Contact::real_exists_by_id(context, contact_id).await? || contact_id == ContactId::SELF,\n \"invalid contact_id {} for adding to group\",\n contact_id\n );\n ensure!(!chat.is_mailing_list(), \"Mailing lists can't be changed\");\n ensure!(\n chat.typ != Chattype::Broadcast || contact_id != ContactId::SELF,\n \"Cannot add SELF to broadcast.\"\n );\n\n if !chat.is_self_in_chat(context).await? {\n context.emit_event(EventType::ErrorSelfNotInGroup(\n \"Cannot add contact to group; self not in group.\".into(),\n ));\n bail!(\"can not add contact because the account is not part of the group/broadcast\");\n }\n\n if from_handshake && chat.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 {\n chat.param.remove(Param::Unpromoted);\n chat.update_param(context).await?;\n let _ = context\n .sync_qr_code_tokens(Some(chat_id))\n .await\n .log_err(context)\n .is_ok()\n && context.send_sync_msg().await.log_err(context).is_ok();\n }\n\n if context.is_self_addr(contact.get_addr()).await? {\n // ourself is added using ContactId::SELF, do not add this address explicitly.\n // if SELF is not in the group, members cannot be added at all.\n warn!(\n context,\n \"Invalid attempt to add self e-mail address to group.\"\n );\n return Ok(false);\n }\n\n if is_contact_in_chat(context, chat_id, contact_id).await? {\n if !from_handshake {\n return Ok(true);\n }\n } else {\n // else continue and send status mail\n if chat.is_protected() && !contact.is_verified(context).await? {\n error!(\n context,\n \"Cannot add non-bidirectionally verified contact {contact_id} to protected chat {chat_id}.\"\n );\n return Ok(false);\n }\n if is_contact_in_chat(context, chat_id, contact_id).await? {\n return Ok(false);\n }\n add_to_chat_contacts_table(context, chat_id, &[contact_id]).await?;\n }\n if chat.typ == Chattype::Group && chat.is_promoted() {\n msg.viewtype = Viewtype::Text;\n\n let contact_addr = contact.get_addr().to_lowercase();\n msg.text = stock_str::msg_add_member_local(context, &contact_addr, ContactId::SELF).await;\n msg.param.set_cmd(SystemMessage::MemberAddedToGroup);\n msg.param.set(Param::Arg, contact_addr);\n msg.param.set_int(Param::Arg2, from_handshake.into());\n msg.id = send_msg(context, chat_id, &mut msg).await?;\n sync = Nosync;\n }\n context.emit_event(EventType::ChatModified(chat_id));\n if sync.into() {\n chat.sync_contacts(context).await.log_err(context).ok();\n }\n Ok(true)\n}", "rust_context": "pub fn is_special(self) -> bool {\n (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)\n }\n\npub async fn get_by_id(context: &Context, contact_id: ContactId) -> Result {\n let contact = Self::get_by_id_optional(context, contact_id)\n .await?\n .with_context(|| format!(\"contact {contact_id} not found\"))?;\n Ok(contact)\n }\n\npub(crate) async fn msg_add_member_local(\n context: &Context,\n added_member_addr: &str,\n by_contact: ContactId,\n) -> String {\n let addr = added_member_addr;\n let whom = &match Contact::lookup_id_by_addr(context, addr, Origin::Unknown).await {\n Ok(Some(contact_id)) => Contact::get_by_id(context, contact_id)\n .await\n .map(|contact| contact.get_name_n_addr())\n .unwrap_or_else(|_| addr.to_string()),\n _ => addr.to_string(),\n };\n if by_contact == ContactId::UNDEFINED {\n translated(context, StockMessage::MsgAddMember)\n .await\n .replace1(whom)\n } else if by_contact == ContactId::SELF {\n translated(context, StockMessage::MsgYouAddMember)\n .await\n .replace1(whom)\n } else {\n translated(context, StockMessage::MsgAddMemberBy)\n .await\n .replace1(whom)\n .replace2(&by_contact.get_stock_name_n_addr(context).await)\n }\n}\n\npub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result {\n let mut chat = context\n .sql\n .query_row(\n \"SELECT c.type, c.name, c.grpid, c.param, c.archived,\n c.blocked, c.locations_send_until, c.muted_until, c.protected\n FROM chats c\n WHERE c.id=?;\",\n (chat_id,),\n |row| {\n let c = Chat {\n id: chat_id,\n typ: row.get(0)?,\n name: row.get::<_, String>(1)?,\n grpid: row.get::<_, String>(2)?,\n param: row.get::<_, String>(3)?.parse().unwrap_or_default(),\n visibility: row.get(4)?,\n blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),\n is_sending_locations: row.get(6)?,\n mute_duration: row.get(7)?,\n protected: row.get(8)?,\n };\n Ok(c)\n },\n )\n .await\n .context(format!(\"Failed loading chat {chat_id} from database\"))?;\n\n if chat.id.is_archived_link() {\n chat.name = stock_str::archived_chats(context).await;\n } else {\n if chat.typ == Chattype::Single && chat.name.is_empty() {\n // chat.name is set to contact.display_name on changes,\n // however, if things went wrong somehow, we do this here explicitly.\n let mut chat_name = \"Err [Name not found]\".to_owned();\n match get_chat_contacts(context, chat.id).await {\n Ok(contacts) => {\n if let Some(contact_id) = contacts.first() {\n if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {\n contact.get_display_name().clone_into(&mut chat_name);\n }\n }\n }\n Err(err) => {\n error!(\n context,\n \"Failed to load contacts for {}: {:#}.\", chat.id, err\n );\n }\n }\n chat.name = chat_name;\n }\n if chat.param.exists(Param::Selftalk) {\n chat.name = stock_str::saved_messages(context).await;\n } else if chat.param.exists(Param::Devicetalk) {\n chat.name = stock_str::device_messages(context).await;\n }\n }\n\n Ok(chat)\n }\n\npub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> {\n context\n .sql\n .execute(\n \"UPDATE chats SET param=? WHERE id=?\",\n (self.param.to_string(), self.id),\n )\n .await?;\n Ok(())\n }\n\npub fn set_int(&mut self, key: Param, value: i32) -> &mut Self {\n self.set(key, format!(\"{value}\"));\n self\n }\n\npub fn is_protected(&self) -> bool {\n self.protected == ProtectionStatus::Protected\n }\n\npub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result {\n if chat_id.is_unset() {\n let forwards = msg.param.get(Param::PrepForwards);\n if let Some(forwards) = forwards {\n for forward in forwards.split(' ') {\n if let Ok(msg_id) = forward.parse::().map(MsgId::new) {\n if let Ok(mut msg) = Message::load_from_db(context, msg_id).await {\n send_msg_inner(context, chat_id, &mut msg).await?;\n };\n }\n }\n msg.param.remove(Param::PrepForwards);\n msg.update_param(context).await?;\n }\n return send_msg_inner(context, chat_id, msg).await;\n }\n\n if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing {\n msg.param.remove(Param::GuaranteeE2ee);\n msg.param.remove(Param::ForcePlaintext);\n msg.update_param(context).await?;\n }\n send_msg_inner(context, chat_id, msg).await\n}\n\npub async fn is_contact_in_chat(\n context: &Context,\n chat_id: ChatId,\n contact_id: ContactId,\n) -> Result {\n // this function works for group and for normal chats, however, it is more useful\n // for group chats.\n // ContactId::SELF may be used to check, if the user itself is in a group\n // chat (ContactId::SELF is not added to normal chats)\n\n let exists = context\n .sql\n .exists(\n \"SELECT COUNT(*) FROM chats_contacts WHERE chat_id=? AND contact_id=?;\",\n (chat_id, contact_id),\n )\n .await?;\n Ok(exists)\n}\n\npub(crate) async fn sync_contacts(&self, context: &Context) -> Result<()> {\n let addrs = context\n .sql\n .query_map(\n \"SELECT c.addr \\\n FROM contacts c INNER JOIN chats_contacts cc \\\n ON c.id=cc.contact_id \\\n WHERE cc.chat_id=?\",\n (self.id,),\n |row| row.get::<_, String>(0),\n |addrs| addrs.collect::, _>>().map_err(Into::into),\n )\n .await?;\n self.sync(context, SyncAction::SetContacts(addrs)).await\n }\n\npub(crate) async fn sync_qr_code_tokens(&self, chat_id: Option) -> Result<()> {\n if !self.get_config_bool(Config::SyncMsgs).await? {\n return Ok(());\n }\n\n if let (Some(invitenumber), Some(auth)) = (\n token::lookup(self, Namespace::InviteNumber, chat_id).await?,\n token::lookup(self, Namespace::Auth, chat_id).await?,\n ) {\n let grpid = if let Some(chat_id) = chat_id {\n let chat = Chat::load_from_db(self, chat_id).await?;\n if !chat.is_promoted() {\n info!(\n self,\n \"group '{}' not yet promoted, do not sync tokens yet.\", chat.grpid\n );\n return Ok(());\n }\n Some(chat.grpid)\n } else {\n None\n };\n self.add_sync_item(SyncData::AddQrToken(QrTokenData {\n invitenumber,\n auth,\n grpid,\n }))\n .await?;\n }\n Ok(())\n }\n\npub fn remove(&mut self, key: Param) -> &mut Self {\n self.inner.remove(&key);\n self\n }\n\npub fn set_cmd(&mut self, value: SystemMessage) {\n self.set_int(Param::Cmd, value as i32);\n }\n\npub fn is_promoted(&self) -> bool {\n !self.is_unpromoted()\n }\n\npub fn get_int(&self, key: Param) -> Option {\n self.get(key).and_then(|s| s.parse().ok())\n }\n\npub(crate) async fn add_to_chat_contacts_table(\n context: &Context,\n chat_id: ChatId,\n contact_ids: &[ContactId],\n) -> Result<()> {\n context\n .sql\n .transaction(move |transaction| {\n for contact_id in contact_ids {\n transaction.execute(\n \"INSERT OR IGNORE INTO chats_contacts (chat_id, contact_id) VALUES(?, ?)\",\n (chat_id, contact_id),\n )?;\n }\n Ok(())\n })\n .await?;\n\n Ok(())\n}\n\npub(crate) async fn reset_gossiped_timestamp(self, context: &Context) -> Result<()> {\n self.set_gossiped_timestamp(context, 0).await\n }\n\npub(crate) async fn is_self_in_chat(&self, context: &Context) -> Result {\n match self.typ {\n Chattype::Single | Chattype::Broadcast | Chattype::Mailinglist => Ok(true),\n Chattype::Group => is_contact_in_chat(context, self.id, ContactId::SELF).await,\n }\n }\n\npub(crate) async fn is_self_addr(&self, addr: &str) -> Result {\n Ok(self\n .get_config(Config::ConfiguredAddr)\n .await?\n .iter()\n .any(|a| addr_cmp(addr, a))\n || self\n .get_secondary_self_addrs()\n .await?\n .iter()\n .any(|a| addr_cmp(addr, a)))\n }\n\npub async fn is_verified(&self, context: &Context) -> Result {\n // We're always sort of secured-verified as we could verify the key on this device any time with the key\n // on this device\n if self.id == ContactId::SELF {\n return Ok(true);\n }\n\n let Some(peerstate) = Peerstate::from_addr(context, &self.addr).await? else {\n return Ok(false);\n };\n\n let forward_verified = peerstate.is_using_verified_key();\n let backward_verified = peerstate.is_backward_verified(context).await?;\n Ok(forward_verified && backward_verified)\n }\n\nfn log_err(self, context: &Context) -> Result {\n if let Err(e) = &self {\n let location = std::panic::Location::caller();\n\n // We are using Anyhow's .context() and to show the inner error, too, we need the {:#}:\n let full = format!(\n \"{file}:{line}: {e:#}\",\n file = location.file(),\n line = location.line(),\n e = e\n );\n // We can't use the warn!() macro here as the file!() and line!() macros\n // don't work with #[track_caller]\n context.emit_event(crate::EventType::Warning(full));\n };\n self\n }\n\npub async fn send_sync_msg(&self) -> Result> {\n if let Some((json, ids)) = self.build_sync_json().await? {\n let chat_id =\n ChatId::create_for_contact_with_blocked(self, ContactId::SELF, Blocked::Yes)\n .await?;\n let mut msg = Message {\n chat_id,\n viewtype: Viewtype::Text,\n text: stock_str::sync_msg_body(self).await,\n hidden: true,\n subject: stock_str::sync_msg_subject(self).await,\n ..Default::default()\n };\n msg.param.set_cmd(SystemMessage::MultiDeviceSync);\n msg.param.set(Param::Arg, json);\n msg.param.set(Param::Arg2, ids);\n msg.param.set_int(Param::GuaranteeE2ee, 1);\n Ok(Some(chat::send_msg(self, chat_id, &mut msg).await?))\n } else {\n Ok(None)\n }\n }\n\npub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self {\n self.inner.insert(key, value.to_string());\n self\n }\n\npub fn emit_event(&self, event: EventType) {\n {\n let lock = self.debug_logging.read().expect(\"RwLock is poisoned\");\n if let Some(debug_logging) = &*lock {\n debug_logging.log_event(event.clone());\n }\n }\n self.events.emit(Event {\n id: self.id,\n typ: event,\n });\n }\n\nmacro_rules! warn {\n ($ctx:expr, $msg:expr) => {\n warn!($ctx, $msg,)\n };\n ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{\n let formatted = format!($msg, $($args),*);\n let full = format!(\"{file}:{line}: {msg}\",\n file = file!(),\n line = line!(),\n msg = &formatted);\n $ctx.emit_event($crate::EventType::Warning(full));\n }};\n}\n\npub fn get_addr(&self) -> &str {\n &self.addr\n }\n\npub fn error(&self) -> Option {\n self.error.clone()\n }\n\npub async fn real_exists_by_id(context: &Context, contact_id: ContactId) -> Result {\n if contact_id.is_special() {\n return Ok(false);\n }\n\n let exists = context\n .sql\n .exists(\"SELECT COUNT(*) FROM contacts WHERE id=?;\", (contact_id,))\n .await?;\n Ok(exists)\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ChatId(u32);\n\npub struct ContactId(u32);\n\npub enum Chattype {\n /// 1:1 chat.\n Single = 100,\n\n /// Group chat.\n Group = 120,\n\n /// Mailing list.\n Mailinglist = 140,\n\n /// Broadcast list.\n Broadcast = 160,\n}\n\nimpl ContactId {\n /// The owner of the account.\n ///\n /// The email-address is set by `set_config` using \"addr\".\n pub const SELF: ContactId = ContactId::new(1);\n}\n\npub enum EventType {\n /// The library-user may write an informational string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Info(String),\n\n /// Emitted when SMTP connection is established and login was successful.\n SmtpConnected(String),\n\n /// Emitted when IMAP connection is established and login was successful.\n ImapConnected(String),\n\n /// Emitted when a message was successfully sent to the SMTP server.\n SmtpMessageSent(String),\n\n /// Emitted when an IMAP message has been marked as deleted\n ImapMessageDeleted(String),\n\n /// Emitted when an IMAP message has been moved\n ImapMessageMoved(String),\n\n /// Emitted before going into IDLE on the Inbox folder.\n ImapInboxIdle,\n\n /// Emitted when an new file in the $BLOBDIR was created\n NewBlobFile(String),\n\n /// Emitted when an file in the $BLOBDIR was deleted\n DeletedBlobFile(String),\n\n /// The library-user should write a warning string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Warning(String),\n\n /// The library-user should report an error to the end-user.\n ///\n /// As most things are asynchronous, things may go wrong at any time and the user\n /// should not be disturbed by a dialog or so. Instead, use a bubble or so.\n ///\n /// However, for ongoing processes (eg. configure())\n /// or for functions that are expected to fail (eg. dc_continue_key_transfer())\n /// it might be better to delay showing these events until the function has really\n /// failed (returned false). It should be sufficient to report only the *last* error\n /// in a messasge box then.\n Error(String),\n\n /// An action cannot be performed because the user is not in the group.\n /// Reported eg. after a call to\n /// dc_set_chat_name(), dc_set_chat_profile_image(),\n /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(),\n /// dc_send_text_msg() or another sending function.\n ErrorSelfNotInGroup(String),\n\n /// Messages or chats changed. One or more messages or chats changed for various\n /// reasons in the database:\n /// - Messages sent, received or removed\n /// - Chats created, deleted or archived\n /// - A draft has been set\n ///\n MsgsChanged {\n /// Set if only a single chat is affected by the changes, otherwise 0.\n chat_id: ChatId,\n\n /// Set if only a single message is affected by the changes, otherwise 0.\n msg_id: MsgId,\n },\n\n /// Reactions for the message changed.\n ReactionsChanged {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message for which reactions were changed.\n msg_id: MsgId,\n\n /// ID of the contact whose reaction set is changed.\n contact_id: ContactId,\n },\n\n /// There is a fresh message. Typically, the user will show an notification\n /// when receiving this message.\n ///\n /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event.\n IncomingMsg {\n /// ID of the chat where the message is assigned.\n chat_id: ChatId,\n\n /// ID of the message.\n msg_id: MsgId,\n },\n\n /// Downloading a bunch of messages just finished.\n IncomingMsgBunch,\n\n /// Messages were seen or noticed.\n /// chat id is always set.\n MsgsNoticed(ChatId),\n\n /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to\n /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state().\n MsgDelivered {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was successfully sent.\n msg_id: MsgId,\n },\n\n /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_FAILED, see dc_msg_get_state().\n MsgFailed {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that could not be sent.\n msg_id: MsgId,\n },\n\n /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state().\n MsgRead {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was read.\n msg_id: MsgId,\n },\n\n /// A single message was deleted.\n ///\n /// This event means that the message will no longer appear in the messagelist.\n /// UI should remove the message from the messagelist\n /// in response to this event if the message is currently displayed.\n ///\n /// The message may have been explicitly deleted by the user or expired.\n /// Internally the message may have been removed from the database,\n /// moved to the trash chat or hidden.\n ///\n /// This event does not indicate the message\n /// deletion from the server.\n MsgDeleted {\n /// ID of the chat where the message was prior to deletion.\n /// Never 0 or trash chat.\n chat_id: ChatId,\n\n /// ID of the deleted message. Never 0.\n msg_id: MsgId,\n },\n\n /// Chat changed. The name or the image of a chat group was changed or members were added or removed.\n /// Or the verify state of a chat has changed.\n /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat()\n /// and dc_remove_contact_from_chat().\n ///\n /// This event does not include ephemeral timer modification, which\n /// is a separate event.\n ChatModified(ChatId),\n\n /// Chat ephemeral timer changed.\n ChatEphemeralTimerModified {\n /// Chat ID.\n chat_id: ChatId,\n\n /// New ephemeral timer value.\n timer: EphemeralTimer,\n },\n\n /// Contact(s) created, renamed, blocked, deleted or changed their \"recently seen\" status.\n ///\n /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected.\n ContactsChanged(Option),\n\n /// Location of one or more contact has changed.\n ///\n /// @param data1 (u32) contact_id of the contact for which the location has changed.\n /// If the locations of several contacts have been changed,\n /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`.\n LocationChanged(Option),\n\n /// Inform about the configuration progress started by configure().\n ConfigureProgress {\n /// Progress.\n ///\n /// 0=error, 1-999=progress in permille, 1000=success and done\n progress: usize,\n\n /// Progress comment or error, something to display to the user.\n comment: Option,\n },\n\n /// Inform about the import/export progress started by imex().\n ///\n /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done\n /// @param data2 0\n ImexProgress(usize),\n\n /// A file has been exported. A file has been written by imex().\n /// This event may be sent multiple times by a single call to imex().\n ///\n /// A typical purpose for a handler of this event may be to make the file public to some system\n /// services.\n ///\n /// @param data2 0\n ImexFileWritten(PathBuf),\n\n /// Progress information of a secure-join handshake from the view of the inviter\n /// (Alice, the person who shows the QR code).\n ///\n /// These events are typically sent after a joiner has scanned the QR code\n /// generated by dc_get_securejoin_qr().\n SecurejoinInviterProgress {\n /// ID of the contact that wants to join.\n contact_id: ContactId,\n\n /// Progress as:\n /// 300=vg-/vc-request received, typically shown as \"bob@addr joins\".\n /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as \"bob@addr verified\".\n /// 800=contact added to chat, shown as \"bob@addr securely joined GROUP\". Only for the verified-group-protocol.\n /// 1000=Protocol finished for this contact.\n progress: usize,\n },\n\n /// Progress information of a secure-join handshake from the view of the joiner\n /// (Bob, the person who scans the QR code).\n /// The events are typically sent while dc_join_securejoin(), which\n /// may take some time, is executed.\n SecurejoinJoinerProgress {\n /// ID of the inviting contact.\n contact_id: ContactId,\n\n /// Progress as:\n /// 400=vg-/vc-request-with-auth sent, typically shown as \"alice@addr verified, introducing myself.\"\n /// (Bob has verified alice and waits until Alice does the same for him)\n /// 1000=vg-member-added/vc-contact-confirm received\n progress: usize,\n },\n\n /// The connectivity to the server changed.\n /// This means that you should refresh the connectivity view\n /// and possibly the connectivtiy HTML; see dc_get_connectivity() and\n /// dc_get_connectivity_html() for details.\n ConnectivityChanged,\n\n /// The user's avatar changed.\n /// Deprecated by `ConfigSynced`.\n SelfavatarChanged,\n\n /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For\n /// uniformity this is emitted on the source device too. The value isn't here, otherwise it\n /// would be logged which might not be good for privacy.\n ConfigSynced {\n /// Configuration key.\n key: Config,\n },\n\n /// Webxdc status update received.\n WebxdcStatusUpdate {\n /// Message ID.\n msg_id: MsgId,\n\n /// Status update ID.\n status_update_serial: StatusUpdateSerial,\n },\n\n /// Data received over an ephemeral peer channel.\n WebxdcRealtimeData {\n /// Message ID.\n msg_id: MsgId,\n\n /// Realtime data.\n data: Vec,\n },\n\n /// Inform that a message containing a webxdc instance has been deleted.\n WebxdcInstanceDeleted {\n /// ID of the deleted message.\n msg_id: MsgId,\n },\n\n /// Tells that the Background fetch was completed (or timed out).\n /// This event acts as a marker, when you reach this event you can be sure\n /// that all events emitted during the background fetch were processed.\n ///\n /// This event is only emitted by the account manager\n AccountsBackgroundFetchDone,\n /// Inform that set of chats or the order of the chats in the chatlist has changed.\n ///\n /// Sometimes this is emitted together with `UIChatlistItemChanged`.\n ChatlistChanged,\n\n /// Inform that a single chat list item changed and needs to be rerendered.\n /// 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.\n ChatlistItemChanged {\n /// ID of the changed chat\n chat_id: Option,\n },\n\n /// Event for using in tests, e.g. as a fence between normally generated events.\n #[cfg(test)]\n Test,\n\n /// Inform than some events have been skipped due to event channel overflow.\n EventChannelOverflow {\n /// Number of events skipped.\n n: u64,\n },\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}\n\npub enum SystemMessage {\n /// Unknown type of system message.\n #[default]\n Unknown = 0,\n\n /// Group name changed.\n GroupNameChanged = 2,\n\n /// Group avatar changed.\n GroupImageChanged = 3,\n\n /// Member was added to the group.\n MemberAddedToGroup = 4,\n\n /// Member was removed from the group.\n MemberRemovedFromGroup = 5,\n\n /// Autocrypt Setup Message.\n AutocryptSetupMessage = 6,\n\n /// Secure-join message.\n SecurejoinMessage = 7,\n\n /// Location streaming is enabled.\n LocationStreamingEnabled = 8,\n\n /// Location-only message.\n LocationOnly = 9,\n\n /// Chat ephemeral message timer is changed.\n EphemeralTimerChanged = 10,\n\n /// \"Messages are guaranteed to be end-to-end encrypted from now on.\"\n ChatProtectionEnabled = 11,\n\n /// \"%1$s sent a message from another device.\"\n ChatProtectionDisabled = 12,\n\n /// Message can't be sent because of `Invalid unencrypted mail to <>`\n /// which is sent by chatmail servers.\n InvalidUnencryptedMail = 13,\n\n /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it\n /// to complete.\n SecurejoinWait = 14,\n\n /// 1:1 chats info message telling that SecureJoin is still running, but the user may already\n /// send messages.\n SecurejoinWaitTimeout = 15,\n\n /// Self-sent-message that contains only json used for multi-device-sync;\n /// if possible, we attach that to other messages as for locations.\n MultiDeviceSync = 20,\n\n /// Sync message that contains a json payload\n /// sent to the other webxdc instances\n /// These messages are not shown in the chat.\n WebxdcStatusUpdate = 30,\n\n /// Webxdc info added with `info` set in `send_webxdc_status_update()`.\n WebxdcInfoMessage = 32,\n\n /// This message contains a users iroh node address.\n IrohNodeAddr = 40,\n}\n\npub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__127.txt"} {"c_path": "projects/deltachat-core/c/dc_securejoin.c", "c_func": "uint32_t dc_join_securejoin(dc_context_t* context, const char* qr)\n{\n\t/* ==========================================================\n\t ==== Bob - the joiner's side =====\n\t ==== Step 2 in \"Setup verified contact\" protocol =====\n\t ========================================================== */\n\n\tint ret_chat_id = 0;\n\tint ongoing_allocated = 0;\n\tuint32_t contact_chat_id = 0;\n\tint join_vg = 0;\n\tdc_lot_t* qr_scan = NULL;\n\tint qr_locked = 0;\n\t#define LOCK_QR { pthread_mutex_lock(&context->bobs_qr_critical); qr_locked = 1; }\n\t#define UNLOCK_QR if (qr_locked) { pthread_mutex_unlock(&context->bobs_qr_critical); qr_locked = 0; }\n\t#define CHECK_EXIT if (context->shall_stop_ongoing) { goto cleanup; }\n\n\tdc_log_info(context, 0, \"Requesting secure-join ...\");\n\n\tdc_ensure_secret_key_exists(context);\n\n\tif ((ongoing_allocated=dc_alloc_ongoing(context))==0) {\n\t\tgoto cleanup;\n\t}\n\n\tif (((qr_scan=dc_check_qr(context, qr))==NULL)\n\t || (qr_scan->state!=DC_QR_ASK_VERIFYCONTACT && qr_scan->state!=DC_QR_ASK_VERIFYGROUP)) {\n\t\tdc_log_error(context, 0, \"Unknown QR code.\");\n\t\tgoto cleanup;\n\t}\n\n\tif ((contact_chat_id=dc_create_chat_by_contact_id(context, qr_scan->id))==0) {\n\t\tdc_log_error(context, 0, \"Unknown contact.\");\n\t\tgoto cleanup;\n\t}\n\n\tCHECK_EXIT\n\n\tjoin_vg = (qr_scan->state==DC_QR_ASK_VERIFYGROUP);\n\n\tcontext->bobs_status = 0;\n\tLOCK_QR\n\t\tcontext->bobs_qr_scan = qr_scan;\n\tUNLOCK_QR\n\n\tif (fingerprint_equals_sender(context, qr_scan->fingerprint, contact_chat_id)) {\n\t\t// the scanned fingerprint matches Alice's key, we can proceed to step 4b) directly and save two mails\n\t\tdc_log_info(context, 0, \"Taking protocol shortcut.\");\n\t\tcontext->bob_expects = DC_VC_CONTACT_CONFIRM;\n\t\tcontext->cb(context, DC_EVENT_SECUREJOIN_JOINER_PROGRESS, chat_id_2_contact_id(context, contact_chat_id), 400);\n\t\tchar* own_fingerprint = get_self_fingerprint(context);\n\t\tsend_handshake_msg(context, contact_chat_id, join_vg? \"vg-request-with-auth\" : \"vc-request-with-auth\",\n\t\t\tqr_scan->auth, own_fingerprint, join_vg? qr_scan->text2 : NULL); // Bob -> Alice\n\t\tfree(own_fingerprint);\n\t}\n\telse {\n\t\tcontext->bob_expects = DC_VC_AUTH_REQUIRED;\n\t\tsend_handshake_msg(context, contact_chat_id, join_vg? \"vg-request\" : \"vc-request\",\n\t\t\tqr_scan->invitenumber, NULL, NULL); // Bob -> Alice\n\t}\n\n\twhile (1) {\n\t\tCHECK_EXIT\n\n\t\tusleep(300*1000); // 0.3 seconds\n\t}\n\ncleanup:\n\tcontext->bob_expects = 0;\n\n\tif (context->bobs_status==DC_BOB_SUCCESS) {\n\t\tif (join_vg) {\n\t\t\tret_chat_id = dc_get_chat_id_by_grpid(context, qr_scan->text2, NULL, NULL);\n\t\t}\n\t\telse {\n\t\t\tret_chat_id = contact_chat_id;\n\t\t}\n\t}\n\n\tLOCK_QR\n\t\tcontext->bobs_qr_scan = NULL;\n\tUNLOCK_QR\n\n\tdc_lot_unref(qr_scan);\n\n\tif (ongoing_allocated) { dc_free_ongoing(context); }\n\treturn ret_chat_id;\n}", "rust_path": "projects/deltachat-core/rust/securejoin.rs", "rust_func": "pub async fn join_securejoin(context: &Context, qr: &str) -> Result {\n securejoin(context, qr).await.map_err(|err| {\n warn!(context, \"Fatal joiner error: {:#}\", err);\n // The user just scanned this QR code so has context on what failed.\n error!(context, \"QR process failed\");\n err\n })\n}", "rust_context": "pub fn error(&self) -> Option {\n self.error.clone()\n }\n\nasync fn securejoin(context: &Context, qr: &str) -> Result {\n /*========================================================\n ==== Bob - the joiner's side =====\n ==== Step 2 in \"Setup verified contact\" protocol =====\n ========================================================*/\n\n info!(context, \"Requesting secure-join ...\",);\n let qr_scan = check_qr(context, qr).await?;\n\n let invite = QrInvite::try_from(qr_scan)?;\n\n bob::start_protocol(context, invite).await\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}", "rust_imports": "use anyhow::{bail, Context as _, Error, Result};\nuse percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};\nuse crate::aheader::EncryptPreference;\nuse crate::chat::{self, Chat, ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::Blocked;\nuse crate::contact::{Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::e2ee::ensure_secret_key_exists;\nuse crate::events::EventType;\nuse crate::headerdef::HeaderDef;\nuse crate::key::{load_self_public_key, DcKey, Fingerprint};\nuse crate::message::{Message, Viewtype};\nuse crate::mimeparser::{MimeMessage, SystemMessage};\nuse crate::param::Param;\nuse crate::peerstate::Peerstate;\nuse crate::qr::check_qr;\nuse crate::securejoin::bob::JoinerProgress;\nuse crate::stock_str;\nuse crate::sync::Sync::*;\nuse crate::token;\nuse crate::tools::time;\nuse bobstate::BobState;\nuse qrinvite::QrInvite;\nuse crate::token::Namespace;\nuse deltachat_contact_tools::{ContactAddress, EmailAddress};\nuse super::*;\nuse crate::chat::{remove_contact_from_chat, CantSendReason};\nuse crate::chatlist::Chatlist;\nuse crate::constants::{self, Chattype};\nuse crate::imex::{imex, ImexMode};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::{self, chat_protection_enabled};\nuse crate::test_utils::get_chat_msg;\nuse crate::test_utils::{TestContext, TestContextManager};\nuse crate::tools::SystemTime;\nuse std::collections::HashSet;\nuse std::time::Duration;", "rustrepotrans_file": "projects__deltachat-core__rust__securejoin__.rs__function__4.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "uint32_t dc_contact_get_color(const dc_contact_t* contact)\n{\n\tif (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) {\n\t\treturn 0x000000;\n\t}\n\n\treturn dc_str_to_color(contact->addr);\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub fn get_color(&self) -> u32 {\n str_to_color(&self.addr.to_lowercase())\n }", "rust_context": "pub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}\n\npub fn str_to_color(s: &str) -> u32 {\n rgb_to_u32(hsluv_to_rgb((str_to_angle(s), 100.0, 50.0)))\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__44.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* If the group is already _promoted_ (any message was sent to the group),\n * all group members are informed by a special status message that is sent automatically by this function.\n *\n * If the group is a verified group, only verified contacts can be added to the group.\n *\n * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent.\n *\n * @memberof dc_context_t\n * @param context The context as created by dc_context_new().\n * @param chat_id The chat ID to add the contact to. Must be a group chat.\n * @param contact_id The contact ID to add to the chat.\n * @return 1=member added to group, 0=error\n */\nint dc_add_contact_to_chat(dc_context_t* context, uint32_t chat_id, uint32_t contact_id /*may be DC_CONTACT_ID_SELF*/)\n{\n\treturn dc_add_contact_to_chat_ex(context, chat_id, contact_id, 0);\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn add_contact_to_chat(\n context: &Context,\n chat_id: ChatId,\n contact_id: ContactId,\n) -> Result<()> {\n add_contact_to_chat_ex(context, Sync, chat_id, contact_id, false).await?;\n Ok(())\n}", "rust_context": "pub(crate) async fn add_contact_to_chat_ex(\n context: &Context,\n mut sync: sync::Sync,\n chat_id: ChatId,\n contact_id: ContactId,\n from_handshake: bool,\n) -> Result {\n ensure!(!chat_id.is_special(), \"can not add member to special chats\");\n let contact = Contact::get_by_id(context, contact_id).await?;\n let mut msg = Message::default();\n\n chat_id.reset_gossiped_timestamp(context).await?;\n\n // this also makes sure, no contacts are added to special or normal chats\n let mut chat = Chat::load_from_db(context, chat_id).await?;\n ensure!(\n chat.typ == Chattype::Group || chat.typ == Chattype::Broadcast,\n \"{} is not a group/broadcast where one can add members\",\n chat_id\n );\n ensure!(\n Contact::real_exists_by_id(context, contact_id).await? || contact_id == ContactId::SELF,\n \"invalid contact_id {} for adding to group\",\n contact_id\n );\n ensure!(!chat.is_mailing_list(), \"Mailing lists can't be changed\");\n ensure!(\n chat.typ != Chattype::Broadcast || contact_id != ContactId::SELF,\n \"Cannot add SELF to broadcast.\"\n );\n\n if !chat.is_self_in_chat(context).await? {\n context.emit_event(EventType::ErrorSelfNotInGroup(\n \"Cannot add contact to group; self not in group.\".into(),\n ));\n bail!(\"can not add contact because the account is not part of the group/broadcast\");\n }\n\n if from_handshake && chat.param.get_int(Param::Unpromoted).unwrap_or_default() == 1 {\n chat.param.remove(Param::Unpromoted);\n chat.update_param(context).await?;\n let _ = context\n .sync_qr_code_tokens(Some(chat_id))\n .await\n .log_err(context)\n .is_ok()\n && context.send_sync_msg().await.log_err(context).is_ok();\n }\n\n if context.is_self_addr(contact.get_addr()).await? {\n // ourself is added using ContactId::SELF, do not add this address explicitly.\n // if SELF is not in the group, members cannot be added at all.\n warn!(\n context,\n \"Invalid attempt to add self e-mail address to group.\"\n );\n return Ok(false);\n }\n\n if is_contact_in_chat(context, chat_id, contact_id).await? {\n if !from_handshake {\n return Ok(true);\n }\n } else {\n // else continue and send status mail\n if chat.is_protected() && !contact.is_verified(context).await? {\n error!(\n context,\n \"Cannot add non-bidirectionally verified contact {contact_id} to protected chat {chat_id}.\"\n );\n return Ok(false);\n }\n if is_contact_in_chat(context, chat_id, contact_id).await? {\n return Ok(false);\n }\n add_to_chat_contacts_table(context, chat_id, &[contact_id]).await?;\n }\n if chat.typ == Chattype::Group && chat.is_promoted() {\n msg.viewtype = Viewtype::Text;\n\n let contact_addr = contact.get_addr().to_lowercase();\n msg.text = stock_str::msg_add_member_local(context, &contact_addr, ContactId::SELF).await;\n msg.param.set_cmd(SystemMessage::MemberAddedToGroup);\n msg.param.set(Param::Arg, contact_addr);\n msg.param.set_int(Param::Arg2, from_handshake.into());\n msg.id = send_msg(context, chat_id, &mut msg).await?;\n sync = Nosync;\n }\n context.emit_event(EventType::ChatModified(chat_id));\n if sync.into() {\n chat.sync_contacts(context).await.log_err(context).ok();\n }\n Ok(true)\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ContactId(u32);\n\npub struct ChatId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__126.txt"} {"c_path": "projects/deltachat-core/c/dc_param.c", "c_func": "void dc_param_set_int(dc_param_t* param, int key, int32_t value)\n{\n\tif (param==NULL || key==0) {\n\t\treturn;\n\t}\n\n char* value_str = dc_mprintf(\"%i\", (int)value);\n if (value_str==NULL) {\n\t\treturn;\n }\n dc_param_set(param, key, value_str);\n free(value_str);\n}", "rust_path": "projects/deltachat-core/rust/param.rs", "rust_func": "pub fn set_int(&mut self, key: Param, value: i32) -> &mut Self {\n self.set(key, format!(\"{value}\"));\n self\n }", "rust_context": "pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self {\n self.inner.insert(key, value.to_string());\n self\n }\n\npub struct Params {\n inner: BTreeMap,\n}", "rust_imports": "use std::collections::BTreeMap;\nuse std::fmt;\nuse std::path::PathBuf;\nuse std::str;\nuse anyhow::{bail, Error, Result};\nuse num_traits::FromPrimitive;\nuse serde::{Deserialize, Serialize};\nuse crate::blob::BlobObject;\nuse crate::context::Context;\nuse crate::mimeparser::SystemMessage;\nuse std::path::Path;\nuse std::str::FromStr;\nuse tokio::fs;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__param__.rs__function__20.txt"} {"c_path": "projects/deltachat-core/c/dc_param.c", "c_func": "char* dc_param_get(const dc_param_t* param, int key, const char* def)\n{\n\tchar* p1 = NULL;\n\tchar* p2 = NULL;\n\tchar bak = 0;\n\tchar* ret = NULL;\n\n\tif (param==NULL || key==0) {\n\t\treturn def? dc_strdup(def) : NULL;\n\t}\n\n\tp1 = find_param(param->packed, key, &p2);\n\tif (p1==NULL) {\n\t\treturn def? dc_strdup(def) : NULL;\n\t}\n\n\tp1 += 2; /* skip key and \"=\" (safe as find_param checks for its existance) */\n\n\tbak = *p2;\n\t*p2 = 0;\n\tret = dc_strdup(p1);\n\tdc_rtrim(ret); /* to be safe with '\\r' characters ... */\n\t*p2 = bak;\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/param.rs", "rust_func": "pub fn get(&self, key: Param) -> Option<&str> {\n self.inner.get(&key).map(|s| s.as_str())\n }", "rust_context": "pub struct Params {\n inner: BTreeMap,\n}", "rust_imports": "use std::collections::BTreeMap;\nuse std::fmt;\nuse std::path::PathBuf;\nuse std::str;\nuse anyhow::{bail, Error, Result};\nuse num_traits::FromPrimitive;\nuse serde::{Deserialize, Serialize};\nuse crate::blob::BlobObject;\nuse crate::context::Context;\nuse crate::mimeparser::SystemMessage;\nuse std::path::Path;\nuse std::str::FromStr;\nuse tokio::fs;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__param__.rs__function__4.txt"} {"c_path": "projects/deltachat-core/c/dc_oauth2.c", "c_func": "static void replace_in_uri(char** uri, const char* key, const char* value)\n{\n\tif (uri && key && value) {\n\t\tchar* value_urlencoded = dc_urlencode(value);\n\t\tdc_str_replace(uri, key, value_urlencoded);\n\t\tfree(value_urlencoded);\n\t}\n}", "rust_path": "projects/deltachat-core/rust/oauth2.rs", "rust_func": "fn replace_in_uri(uri: &str, key: &str, value: &str) -> String {\n let value_urlencoded = utf8_percent_encode(value, NON_ALPHANUMERIC).to_string();\n uri.replace(key, &value_urlencoded)\n}", "rust_context": "", "rust_imports": "use std::collections::HashMap;\nuse anyhow::Result;\nuse percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};\nuse serde::Deserialize;\nuse crate::config::Config;\nuse crate::context::Context;\nuse crate::provider;\nuse crate::provider::Oauth2Authorizer;\nuse crate::socks::Socks5Config;\nuse crate::tools::time;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__oauth2__.rs__function__7.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "uint32_t dc_msg_get_id(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn msg->id;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn get_id(&self) -> MsgId {\n self.id\n }", "rust_context": "pub struct MsgId(u32);\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__30.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "int dc_get_msg_cnt(dc_context_t* context, uint32_t chat_id)\n{\n\tint ret = 0;\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT COUNT(*) FROM msgs WHERE chat_id=?;\");\n\tsqlite3_bind_int(stmt, 1, chat_id);\n\tif (sqlite3_step(stmt)!=SQLITE_ROW) {\n\t\tgoto cleanup;\n\t}\n\n\tret = sqlite3_column_int(stmt, 0);\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn get_msg_cnt(self, context: &Context) -> Result {\n let count = context\n .sql\n .count(\n \"SELECT COUNT(*) FROM msgs WHERE hidden=0 AND chat_id=?\",\n (self,),\n )\n .await?;\n Ok(count)\n }", "rust_context": "pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result {\n let count: isize = self.query_row(query, params, |row| row.get(0)).await?;\n Ok(usize::try_from(count)?)\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result {\n let count: isize = self.query_row(query, params, |row| row.get(0)).await?;\n Ok(usize::try_from(count)?)\n }\n \npub struct ChatId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__36.txt"} {"c_path": "projects/deltachat-core/c/dc_configure.c", "c_func": "static int get_folder_meaning_by_name(const char* folder_name)\n{\n\t// try to get the folder meaning by the name of the folder.\n\t// only used if the server does not support XLIST.\n\tint ret_meaning = MEANING_UNKNOWN;\n\n\t// TODO: lots languages missing - maybe there is a list somewhere on other MUAs?\n\t// however, if we fail to find out the sent-folder,\n\t// only watching this folder is not working. at least, this is no show stopper.\n\t// CAVE: if possible, take care not to add a name here that is \"sent\" in one language\n\t// but sth. different in others - a hard job.\n static const char* sent_names =\n \"sent,sentmail,sent objects,gesendet,Sent Mail,Sendte e-mails,Enviados,\"\n \"Messages envoy\u00e9s,Messages envoyes,Posta inviata,Verzonden berichten,\"\n \"Wyslane,E-mails enviados,Correio enviado,Enviada,Enviado,G\u00f6nderildi,\"\n \"Inviati,Odeslan\u00e1 po\u0161ta,Sendt,Skickat,Verzonden,Wys\u0142ane,\u00c9l\u00e9ments envoy\u00e9s,\"\n \"\u0391\u03c0\u03b5\u03c3\u03c4\u03b1\u03bb\u03bc\u03ad\u03bd\u03b1,\u041e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0435,\u5bc4\u4ef6\u5099\u4efd,\u5df2\u53d1\u9001\u90ae\u4ef6,\u9001\u4fe1\u6e08\u307f,\ubcf4\ub0b8\ud3b8\uc9c0\ud568\";\n\n static const char* spam_names =\n \"spam,junk,Correio electr\u00f3nico n\u00e3o solicitado,Correo basura,Lixo,Netts\u00f8ppel,\"\n \"Nevy\u017e\u00e1dan\u00e1 po\u0161ta,No solicitado,Ongewenst,Posta indesiderata,Skr\u00e4p,\"\n \"Wiadomo\u015bci-\u015bmieci,\u00d6nemsiz,\u0391\u03bd\u03b5\u03c0\u03b9\u03b8\u03cd\u03bc\u03b7\u03c4\u03b1,\u0421\u043f\u0430\u043c,\u5783\u573e\u90ae\u4ef6,\u5783\u573e\u90f5\u4ef6,\u8ff7\u60d1\u30e1\u30fc\u30eb,\uc2a4\ud338\";\n\n static const char* draft_names =\n \"Drafts,Kladder,Entw?rfe,Borradores,Brouillons,Bozze,Concepten,\"\n \"Wersje robocze,Rascunhos,Entw\u00fcrfe,Koncepty,Kopie robocze,Taslaklar,\"\n \"Utkast,\u03a0\u03c1\u03cc\u03c7\u03b5\u03b9\u03c1\u03b1,\u0427\u0435\u0440\u043d\u043e\u0432\u0438\u043a\u0438,\u4e0b\u66f8\u304d,\u8349\u7a3f,\uc784\uc2dc\ubcf4\uad00\ud568\";\n\n static const char* trash_names =\n \"Trash,Bin,Caixote do lixo,Cestino,Corbeille,Papelera,Papierkorb,\"\n \"Papirkurv,Papperskorgen,Prullenbak,Rubujo,\u039a\u03ac\u03b4\u03bf\u03c2 \u03b1\u03c0\u03bf\u03c1\u03c1\u03b9\u03bc\u03bc\u03ac\u03c4\u03c9\u03bd,\u041a\u043e\u0440\u0437\u0438\u043d\u0430,\"\n \"\u041a\u043e\u0448\u0438\u043a,\u30b4\u30df\u7bb1,\u5783\u573e\u6876,\u5df2\u5220\u9664\u90ae\u4ef6,\ud734\uc9c0\ud1b5\";\n \n\tchar* lower = dc_mprintf(\",%s,\", folder_name);\n\tdc_strlower_in_place(lower);\n\tif (strstr(sent_names, lower)!=NULL) {\n\t\tret_meaning = MEANING_SENT_OBJECTS;\n\t} else if (strstr(spam_names, lower)!=NULL) {\n\t\tret_meaning = MEANING_SPAM;\n\t} else if (strstr(draft_names, lower)!=NULL) {\n\t\tret_meaning = MEANING_DRAFT;\n\t} else if (strstr(trash_names, lower)!=NULL) {\n\t\tret_meaning = MEANING_TRASH;\n\t}\n\n\tfree(lower);\n\treturn ret_meaning;\n}", "rust_path": "projects/deltachat-core/rust/imap.rs", "rust_func": "fn get_folder_meaning_by_name(folder_name: &str) -> FolderMeaning {\n // source: \n const SENT_NAMES: &[&str] = &[\n \"sent\",\n \"sentmail\",\n \"sent objects\",\n \"gesendet\",\n \"Sent Mail\",\n \"Sendte e-mails\",\n \"Enviados\",\n \"Messages envoy\u00e9s\",\n \"Messages envoyes\",\n \"Posta inviata\",\n \"Verzonden berichten\",\n \"Wyslane\",\n \"E-mails enviados\",\n \"Correio enviado\",\n \"Enviada\",\n \"Enviado\",\n \"G\u00f6nderildi\",\n \"Inviati\",\n \"Odeslan\u00e1 po\u0161ta\",\n \"Sendt\",\n \"Skickat\",\n \"Verzonden\",\n \"Wys\u0142ane\",\n \"\u00c9l\u00e9ments envoy\u00e9s\",\n \"\u0391\u03c0\u03b5\u03c3\u03c4\u03b1\u03bb\u03bc\u03ad\u03bd\u03b1\",\n \"\u041e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0435\",\n \"\u5bc4\u4ef6\u5099\u4efd\",\n \"\u5df2\u53d1\u9001\u90ae\u4ef6\",\n \"\u9001\u4fe1\u6e08\u307f\",\n \"\ubcf4\ub0b8\ud3b8\uc9c0\ud568\",\n ];\n const SPAM_NAMES: &[&str] = &[\n \"spam\",\n \"junk\",\n \"Correio electr\u00f3nico n\u00e3o solicitado\",\n \"Correo basura\",\n \"Lixo\",\n \"Netts\u00f8ppel\",\n \"Nevy\u017e\u00e1dan\u00e1 po\u0161ta\",\n \"No solicitado\",\n \"Ongewenst\",\n \"Posta indesiderata\",\n \"Skr\u00e4p\",\n \"Wiadomo\u015bci-\u015bmieci\",\n \"\u00d6nemsiz\",\n \"\u0391\u03bd\u03b5\u03c0\u03b9\u03b8\u03cd\u03bc\u03b7\u03c4\u03b1\",\n \"\u0421\u043f\u0430\u043c\",\n \"\u5783\u573e\u90ae\u4ef6\",\n \"\u5783\u573e\u90f5\u4ef6\",\n \"\u8ff7\u60d1\u30e1\u30fc\u30eb\",\n \"\uc2a4\ud338\",\n ];\n const DRAFT_NAMES: &[&str] = &[\n \"Drafts\",\n \"Kladder\",\n \"Entw?rfe\",\n \"Borradores\",\n \"Brouillons\",\n \"Bozze\",\n \"Concepten\",\n \"Wersje robocze\",\n \"Rascunhos\",\n \"Entw\u00fcrfe\",\n \"Koncepty\",\n \"Kopie robocze\",\n \"Taslaklar\",\n \"Utkast\",\n \"\u03a0\u03c1\u03cc\u03c7\u03b5\u03b9\u03c1\u03b1\",\n \"\u0427\u0435\u0440\u043d\u043e\u0432\u0438\u043a\u0438\",\n \"\u4e0b\u66f8\u304d\",\n \"\u8349\u7a3f\",\n \"\uc784\uc2dc\ubcf4\uad00\ud568\",\n ];\n const TRASH_NAMES: &[&str] = &[\n \"Trash\",\n \"Bin\",\n \"Caixote do lixo\",\n \"Cestino\",\n \"Corbeille\",\n \"Papelera\",\n \"Papierkorb\",\n \"Papirkurv\",\n \"Papperskorgen\",\n \"Prullenbak\",\n \"Rubujo\",\n \"\u039a\u03ac\u03b4\u03bf\u03c2 \u03b1\u03c0\u03bf\u03c1\u03c1\u03b9\u03bc\u03bc\u03ac\u03c4\u03c9\u03bd\",\n \"\u041a\u043e\u0440\u0437\u0438\u043d\u0430\",\n \"\u041a\u043e\u0448\u0438\u043a\",\n \"\u30b4\u30df\u7bb1\",\n \"\u5783\u573e\u6876\",\n \"\u5df2\u5220\u9664\u90ae\u4ef6\",\n \"\ud734\uc9c0\ud1b5\",\n ];\n let lower = folder_name.to_lowercase();\n\n if SENT_NAMES.iter().any(|s| s.to_lowercase() == lower) {\n FolderMeaning::Sent\n } else if SPAM_NAMES.iter().any(|s| s.to_lowercase() == lower) {\n FolderMeaning::Spam\n } else if DRAFT_NAMES.iter().any(|s| s.to_lowercase() == lower) {\n FolderMeaning::Drafts\n } else if TRASH_NAMES.iter().any(|s| s.to_lowercase() == lower) {\n FolderMeaning::Trash\n } else {\n FolderMeaning::Unknown\n }\n}", "rust_context": "pub enum FolderMeaning {\n Unknown,\n\n /// Spam folder.\n Spam,\n Inbox,\n Mvbox,\n Sent,\n Trash,\n Drafts,\n\n /// Virtual folders.\n ///\n /// On Gmail there are virtual folders marked as \\\\All, \\\\Important and \\\\Flagged.\n /// Delta Chat ignores these folders because the same messages can be fetched\n /// from the real folder and the result of moving and deleting messages via\n /// virtual folder is unclear.\n Virtual,\n}", "rust_imports": "use std::{\n cmp::max,\n cmp::min,\n collections::{BTreeMap, BTreeSet, HashMap},\n iter::Peekable,\n mem::take,\n sync::atomic::Ordering,\n time::{Duration, UNIX_EPOCH},\n};\nuse anyhow::{bail, format_err, Context as _, Result};\nuse async_channel::Receiver;\nuse async_imap::types::{Fetch, Flag, Name, NameAttribute, UnsolicitedResponse};\nuse deltachat_contact_tools::{normalize_name, ContactAddress};\nuse futures::{FutureExt as _, StreamExt, TryStreamExt};\nuse futures_lite::FutureExt;\nuse num_traits::FromPrimitive;\nuse rand::Rng;\nuse ratelimit::Ratelimit;\nuse url::Url;\nuse crate::chat::{self, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{self, Blocked, Chattype, ShowEmails};\nuse crate::contact::{Contact, ContactId, Modifier, Origin};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::headerdef::{HeaderDef, HeaderDefMap};\nuse crate::login_param::{CertificateChecks, LoginParam, ServerLoginParam};\nuse crate::message::{self, Message, MessageState, MessengerMessage, MsgId, Viewtype};\nuse crate::mimeparser;\nuse crate::oauth2::get_oauth2_access_token;\nuse crate::provider::Socket;\nuse crate::receive_imf::{\n from_field_to_contact_id, get_prefetch_parent_message, receive_imf_inner, ReceivedMsg,\n};\nuse crate::scheduler::connectivity::ConnectivityStore;\nuse crate::socks::Socks5Config;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{self, create_id, duration_to_str};\nuse client::Client;\nuse mailparse::SingleInfo;\nuse session::Session;\nuse async_imap::imap_proto::Response;\nuse async_imap::imap_proto::ResponseCode;\nuse UnsolicitedResponse::*;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__imap__.rs__function__32.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "char* dc_chat_get_name(const dc_chat_t* chat)\n{\n\tif (chat==NULL || chat->magic!=DC_CHAT_MAGIC) {\n\t\treturn dc_strdup(\"Err\");\n\t}\n\n\treturn dc_strdup(chat->name);\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub fn get_name(&self) -> &str {\n &self.name\n }", "rust_context": "pub struct Chat {\n /// Database ID.\n pub id: ChatId,\n\n /// Chat type, e.g. 1:1 chat, group chat, mailing list.\n pub typ: Chattype,\n\n /// Chat name.\n pub name: String,\n\n /// Whether the chat is archived or pinned.\n pub visibility: ChatVisibility,\n\n /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and\n /// ad-hoc groups.\n pub grpid: String,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n\n /// Additional chat parameters stored in the database.\n pub param: Params,\n\n /// If location streaming is enabled in the chat.\n is_sending_locations: bool,\n\n /// Duration of the chat being muted.\n pub mute_duration: MuteDuration,\n\n /// If the chat is protected (verified).\n pub(crate) protected: ProtectionStatus,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__71.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "int dc_get_fresh_msg_cnt(dc_context_t* context, uint32_t chat_id)\n{\n\tint ret = 0;\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n if (chat_id == DC_CHAT_ID_ARCHIVED_LINK){\n stmt = dc_sqlite3_prepare(context->sql, \n \"SELECT COUNT(DISTINCT(m.chat_id))\"\n \"FROM msgs m\"\n \"LEFT JOIN chats c ON m.chat_id=c.id\"\n \"WHERE m.state=10\"\n \"and m.hidden=0\"\n \"AND m.chat_id>9\"\n \"AND c.blocked=0\"\n \"AND c.archived=1;\");\n }\n else{\n stmt = dc_sqlite3_prepare(context->sql,\n \"SELECT COUNT(*) FROM msgs \"\n \" WHERE state=\" DC_STRINGIFY(DC_STATE_IN_FRESH)\n \" AND hidden=0 \"\n \" AND chat_id=?;\"); /* we have an index over the state-column, this should be sufficient as there are typically only few fresh messages */\n sqlite3_bind_int(stmt, 1, chat_id);\n }\n \n\n\tif (sqlite3_step(stmt)!=SQLITE_ROW) {\n\t\tgoto cleanup;\n\t}\n\n\tret = sqlite3_column_int(stmt, 0);\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn get_fresh_msg_cnt(self, context: &Context) -> Result {\n // this function is typically used to show a badge counter beside _each_ chatlist item.\n // to make this as fast as possible, esp. on older devices, we added an combined index over the rows used for querying.\n // so if you alter the query here, you may want to alter the index over `(state, hidden, chat_id)` in `sql.rs`.\n //\n // the impact of the index is significant once the database grows:\n // - on an older android4 with 18k messages, query-time decreased from 110ms to 2ms\n // - on an mid-class moto-g or iphone7 with 50k messages, query-time decreased from 26ms or 6ms to 0-1ms\n // the times are average, no matter if there are fresh messages or not -\n // and have to be multiplied by the number of items shown at once on the chatlist,\n // so savings up to 2 seconds are possible on older devices - newer ones will feel \"snappier\" :)\n let count = if self.is_archived_link() {\n context\n .sql\n .count(\n \"SELECT COUNT(DISTINCT(m.chat_id))\n FROM msgs m\n LEFT JOIN chats c ON m.chat_id=c.id\n WHERE m.state=10\n and m.hidden=0\n AND m.chat_id>9\n AND c.blocked=0\n AND c.archived=1\n \",\n (),\n )\n .await?\n } else {\n context\n .sql\n .count(\n \"SELECT COUNT(*)\n FROM msgs\n WHERE state=?\n AND hidden=0\n AND chat_id=?;\",\n (MessageState::InFresh, self),\n )\n .await?\n };\n Ok(count)\n }", "rust_context": "pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result {\n let count: isize = self.query_row(query, params, |row| row.get(0)).await?;\n Ok(usize::try_from(count)?)\n }\n\npub fn is_archived_link(self) -> bool {\n self == DC_CHAT_ID_ARCHIVED_LINK\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result {\n let count: isize = self.query_row(query, params, |row| row.get(0)).await?;\n Ok(usize::try_from(count)?)\n }\n \npub struct ChatId(u32);\n\npub enum MessageState {\n /// Undefined message state.\n #[default]\n Undefined = 0,\n\n /// Incoming *fresh* message. Fresh messages are neither noticed\n /// nor seen and are typically shown in notifications.\n InFresh = 10,\n\n /// Incoming *noticed* message. E.g. chat opened but message not\n /// yet read - noticed messages are not counted as unread but did\n /// not marked as read nor resulted in MDNs.\n InNoticed = 13,\n\n /// Incoming message, really *seen* by the user. Marked as read on\n /// IMAP and MDN may be sent.\n InSeen = 16,\n\n /// For files which need time to be prepared before they can be\n /// sent, the message enters this state before\n /// OutPending.\n OutPreparing = 18,\n\n /// Message saved as draft.\n OutDraft = 19,\n\n /// The user has pressed the \"send\" button but the message is not\n /// yet sent and is pending in some way. Maybe we're offline (no\n /// checkmark).\n OutPending = 20,\n\n /// *Unrecoverable* error (*recoverable* errors result in pending\n /// messages).\n OutFailed = 24,\n\n /// Outgoing message successfully delivered to server (one\n /// checkmark). Note, that already delivered messages may get into\n /// the OutFailed state if we get such a hint from the server.\n OutDelivered = 26,\n\n /// Outgoing message read by the recipient (two checkmarks; this\n /// requires goodwill on the receiver's side)\n OutMdnRcvd = 28,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__37.txt"} {"c_path": "projects/deltachat-core/c/dc_apeerstate.c", "c_func": "void dc_apeerstate_apply_header(dc_apeerstate_t* peerstate, const dc_aheader_t* header, time_t message_time)\n{\n\tif (peerstate==NULL || header==NULL\n\t || peerstate->addr==NULL\n\t || header->addr==NULL || header->public_key->binary==NULL\n\t || strcasecmp(peerstate->addr, header->addr)!=0) {\n\t\treturn;\n\t}\n\n\tif (message_time > peerstate->last_seen_autocrypt)\n\t{\n\t\tpeerstate->last_seen = message_time;\n\t\tpeerstate->last_seen_autocrypt = message_time;\n\n\t\tif ((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 */\n\t\t && header->prefer_encrypt!=peerstate->prefer_encrypt)\n\t\t{\n\t\t\tpeerstate->prefer_encrypt = header->prefer_encrypt;\n\t\t}\n\n\t\tif (peerstate->public_key==NULL) {\n\t\t\tpeerstate->public_key = dc_key_new();\n\t\t}\n\n\t\tif (!dc_key_equals(peerstate->public_key, header->public_key))\n\t\t{\n\t\t\tdc_key_set_from_key(peerstate->public_key, header->public_key);\n\t\t\tdc_apeerstate_recalc_fingerprint(peerstate);\n\t\t}\n\t}\n}", "rust_path": "projects/deltachat-core/rust/peerstate.rs", "rust_func": "pub fn apply_header(&mut self, header: &Aheader, message_time: i64) {\n if !addr_cmp(&self.addr, &header.addr) {\n return;\n }\n\n if message_time >= self.last_seen {\n self.last_seen = message_time;\n self.last_seen_autocrypt = message_time;\n if (header.prefer_encrypt == EncryptPreference::Mutual\n || header.prefer_encrypt == EncryptPreference::NoPreference)\n && header.prefer_encrypt != self.prefer_encrypt\n {\n self.prefer_encrypt = header.prefer_encrypt;\n }\n\n if self.public_key.as_ref() != Some(&header.public_key) {\n self.public_key = Some(header.public_key.clone());\n self.recalc_fingerprint();\n }\n }\n }", "rust_context": "pub fn recalc_fingerprint(&mut self) {\n if let Some(ref public_key) = self.public_key {\n let old_public_fingerprint = self.public_key_fingerprint.take();\n self.public_key_fingerprint = Some(public_key.fingerprint());\n\n if old_public_fingerprint.is_some()\n && old_public_fingerprint != self.public_key_fingerprint\n {\n self.fingerprint_changed = true;\n }\n }\n\n if let Some(ref gossip_key) = self.gossip_key {\n let old_gossip_fingerprint = self.gossip_key_fingerprint.take();\n self.gossip_key_fingerprint = Some(gossip_key.fingerprint());\n\n if old_gossip_fingerprint.is_none()\n || self.gossip_key_fingerprint.is_none()\n || old_gossip_fingerprint != self.gossip_key_fingerprint\n {\n // Warn about gossip key change only if there is no public key obtained from\n // Autocrypt header, which overrides gossip key.\n if old_gossip_fingerprint.is_some() && self.public_key_fingerprint.is_none() {\n self.fingerprint_changed = true;\n }\n }\n }\n }\n\npub struct Aheader {\n pub addr: String,\n pub public_key: SignedPublicKey,\n pub prefer_encrypt: EncryptPreference,\n}\n\npub enum EncryptPreference {\n #[default]\n NoPreference = 0,\n Mutual = 1,\n Reset = 20,\n}\n\npub struct Peerstate {\n /// E-mail address of the contact.\n pub addr: String,\n\n /// Timestamp of the latest peerstate update.\n ///\n /// Updated when a message is received from a contact,\n /// either with or without `Autocrypt` header.\n pub last_seen: i64,\n\n /// Timestamp of the latest `Autocrypt` header reception.\n pub last_seen_autocrypt: i64,\n\n /// Encryption preference of the contact.\n pub prefer_encrypt: EncryptPreference,\n\n /// Public key of the contact received in `Autocrypt` header.\n pub public_key: Option,\n\n /// Fingerprint of the contact public key.\n pub public_key_fingerprint: Option,\n\n /// Public key of the contact received in `Autocrypt-Gossip` header.\n pub gossip_key: Option,\n\n /// Timestamp of the latest `Autocrypt-Gossip` header reception.\n ///\n /// It is stored to avoid applying outdated gossiped key\n /// from delayed or reordered messages.\n pub gossip_timestamp: i64,\n\n /// Fingerprint of the contact gossip key.\n pub gossip_key_fingerprint: Option,\n\n /// Public key of the contact at the time it was verified,\n /// either directly or via gossip from the verified contact.\n pub verified_key: Option,\n\n /// Fingerprint of the verified public key.\n pub verified_key_fingerprint: Option,\n\n /// The address that introduced this verified key.\n pub verifier: Option,\n\n /// Secondary public verified key of the contact.\n /// It could be a contact gossiped by another verified contact in a shared group\n /// or a key that was previously used as a verified key.\n pub secondary_verified_key: Option,\n\n /// Fingerprint of the secondary verified public key.\n pub secondary_verified_key_fingerprint: Option,\n\n /// The address that introduced secondary verified key.\n pub secondary_verifier: Option,\n\n /// Row ID of the key in the `keypairs` table\n /// that we think the peer knows as verified.\n pub backward_verified_key_id: Option,\n\n /// True if it was detected\n /// that the fingerprint of the key used in chats with\n /// opportunistic encryption was changed after Peerstate creation.\n pub fingerprint_changed: bool,\n}", "rust_imports": "use std::mem;\nuse anyhow::{Context as _, Error, Result};\nuse deltachat_contact_tools::{addr_cmp, ContactAddress};\nuse num_traits::FromPrimitive;\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::chat::{self, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::constants::Chattype;\nuse crate::contact::{Contact, Origin};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{DcKey, Fingerprint, SignedPublicKey};\nuse crate::message::Message;\nuse crate::mimeparser::SystemMessage;\nuse crate::sql::Sql;\nuse crate::{chatlist_events, stock_str};\nuse super::*;\nuse crate::test_utils::alice_keypair;", "rustrepotrans_file": "projects__deltachat-core__rust__peerstate__.rs__function__10.txt"} {"c_path": "projects/deltachat-core/c/dc_param.c", "c_func": "void dc_param_set(dc_param_t* param, int key, const char* value)\n{\n\tchar* old1 = NULL;\n\tchar* old2 = NULL;\n\tchar* new1 = NULL;\n\n\tif (param==NULL || key==0) {\n\t\treturn;\n\t}\n\n\told1 = param->packed;\n\told2 = NULL;\n\n\t/* remove existing parameter from packed string, if any */\n\tif (old1) {\n\t\tchar *p1, *p2;\n\t\tp1 = find_param(old1, key, &p2);\n\t\tif (p1 != NULL) {\n\t\t\t*p1 = 0;\n\t\t\told2 = p2;\n\t\t}\n\t\telse if (value==NULL) {\n\t\t\treturn; /* parameter does not exist and should be cleared -> done. */\n\t\t}\n\t}\n\n\tdc_rtrim(old1); /* trim functions are null-pointer-safe */\n\tdc_ltrim(old2);\n\n\tif (old1 && old1[0]==0) { old1 = NULL; }\n\tif (old2 && old2[0]==0) { old2 = NULL; }\n\n\t/* create new string */\n\tif (value) {\n\t\tnew1 = dc_mprintf(\"%s%s%c=%s%s%s\",\n\t\t\told1? old1 : \"\",\n\t\t\told1? \"\\n\" : \"\",\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\told2? \"\\n\" : \"\",\n\t\t\told2? old2 : \"\");\n\t}\n\telse {\n\t\tnew1 = dc_mprintf(\"%s%s%s\",\n\t\t\told1? old1 : \"\",\n\t\t\t(old1&&old2)? \"\\n\" : \"\",\n\t\t\told2? old2 : \"\");\n\t}\n\n\tfree(param->packed);\n\tparam->packed = new1;\n}", "rust_path": "projects/deltachat-core/rust/param.rs", "rust_func": "pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self {\n self.inner.insert(key, value.to_string());\n self\n }", "rust_context": "pub struct Params {\n inner: BTreeMap,\n}", "rust_imports": "use std::collections::BTreeMap;\nuse std::fmt;\nuse std::path::PathBuf;\nuse std::str;\nuse anyhow::{bail, Error, Result};\nuse num_traits::FromPrimitive;\nuse serde::{Deserialize, Serialize};\nuse crate::blob::BlobObject;\nuse crate::context::Context;\nuse crate::mimeparser::SystemMessage;\nuse std::path::Path;\nuse std::str::FromStr;\nuse tokio::fs;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__param__.rs__function__6.txt"} {"c_path": "projects/deltachat-core/c/dc_sqlite3.c", "c_func": "int dc_sqlite3_table_exists(dc_sqlite3_t* sql, const char* name)\n{\n\tint ret = 0;\n\tchar* querystr = NULL;\n\tsqlite3_stmt* stmt = NULL;\n\tint sqlState = 0;\n\n\tif ((querystr=sqlite3_mprintf(\"PRAGMA table_info(%s)\", name))==NULL) { /* this statement cannot be used with binded variables */\n\t\tdc_log_error(sql->context, 0, \"dc_sqlite3_table_exists_(): Out of memory.\");\n\t\tgoto cleanup;\n\t}\n\n\tif ((stmt=dc_sqlite3_prepare(sql, querystr))==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tsqlState = sqlite3_step(stmt);\n\tif (sqlState==SQLITE_ROW) {\n\t\tret = 1; /* the table exists. Other states are SQLITE_DONE or SQLITE_ERROR in both cases we return 0. */\n\t}\n\n\t/* success - fall through to free allocated objects */\n\t;\n\n\t/* error/cleanup */\ncleanup:\n\tif (stmt) {\n\t\tsqlite3_finalize(stmt);\n\t}\n\n\tif (querystr) {\n\t\tsqlite3_free(querystr);\n\t}\n\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/sql.rs", "rust_func": "pub async fn table_exists(&self, name: &str) -> Result {\n self.call(move |conn| {\n let mut exists = false;\n conn.pragma(None, \"table_info\", name.to_string(), |_row| {\n // will only be executed if the info was found\n exists = true;\n Ok(())\n })?;\n\n Ok(exists)\n })\n .await\n }", "rust_context": "async fn call<'a, F, R>(&'a self, function: F) -> Result\n where\n F: 'a + FnOnce(&mut Connection) -> Result + Send,\n R: Send + 'static,\n {\n let lock = self.pool.read().await;\n let pool = lock.as_ref().context(\"no SQL connection\")?;\n let mut conn = pool.get().await?;\n let res = tokio::task::block_in_place(move || function(&mut conn))?;\n Ok(res)\n }\n\npub struct Sql {\n /// Database file path\n pub(crate) dbfile: PathBuf,\n\n /// Write transactions mutex.\n ///\n /// See [`Self::write_lock`].\n write_mtx: Mutex<()>,\n\n /// SQL connection pool.\n pool: RwLock>,\n\n /// None if the database is not open, true if it is open with passphrase and false if it is\n /// open without a passphrase.\n is_encrypted: RwLock>,\n\n /// Cache of `config` table.\n pub(crate) config_cache: RwLock>>,\n}", "rust_imports": "use std::collections::{HashMap, HashSet};\nuse std::path::{Path, PathBuf};\nuse anyhow::{bail, Context as _, Result};\nuse rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row};\nuse tokio::sync::{Mutex, MutexGuard, RwLock};\nuse crate::blob::BlobObject;\nuse crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon};\nuse crate::config::Config;\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::ephemeral::start_ephemeral_timers;\nuse crate::imex::BLOBS_BACKUP_NAME;\nuse crate::location::delete_orphaned_poi_locations;\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::stock_str;\nuse crate::tools::{delete_file, time, SystemTime};\nuse pool::Pool;\nuse super::*;\nuse crate::{test_utils::TestContext, EventType};\nuse tempfile::tempdir;\nuse tempfile::tempdir;\nuse tempfile::tempdir;", "rustrepotrans_file": "projects__deltachat-core__rust__sql__.rs__function__23.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "void dc_forward_msgs(dc_context_t* context, const uint32_t* msg_ids, int msg_cnt, uint32_t chat_id)\n{\n\tdc_msg_t* msg = dc_msg_new_untyped(context);\n\tdc_chat_t* chat = dc_chat_new(context);\n\tdc_contact_t* contact = dc_contact_new(context);\n\tint transaction_pending = 0;\n\tcarray* created_db_entries = carray_new(16);\n\tchar* idsstr = NULL;\n\tchar* q3 = NULL;\n\tsqlite3_stmt* stmt = NULL;\n\ttime_t curr_timestamp = 0;\n\tdc_param_t* original_param = dc_param_new();\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_ids==NULL || msg_cnt<=0 || chat_id<=DC_CHAT_ID_LAST_SPECIAL) {\n\t\tgoto cleanup;\n\t}\n\n\tdc_sqlite3_begin_transaction(context->sql);\n\ttransaction_pending = 1;\n\n\t\tdc_unarchive_chat(context, chat_id);\n\n\t\tcontext->smtp->log_connect_errors = 1;\n\n\t\tif (!dc_chat_load_from_db(chat, chat_id)) {\n\t\t\tgoto cleanup;\n\t\t}\n\n\t\tcurr_timestamp = dc_create_smeared_timestamps(context, msg_cnt);\n\n\t\tidsstr = dc_arr_to_string(msg_ids, msg_cnt);\n\t\tq3 = sqlite3_mprintf(\"SELECT id FROM msgs WHERE id IN(%s) ORDER BY timestamp,id\", idsstr);\n\t\tstmt = dc_sqlite3_prepare(context->sql, q3);\n\t\twhile (sqlite3_step(stmt)==SQLITE_ROW)\n\t\t{\n\t\t\tint src_msg_id = sqlite3_column_int(stmt, 0);\n\t\t\tif (!dc_msg_load_from_db(msg, context, src_msg_id)) {\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\n\t\t\tdc_param_set_packed(original_param, msg->param->packed);\n\n\t\t\t// do not mark own messages as being forwarded.\n\t\t\t// this allows sort of broadcasting\n\t\t\t// by just forwarding messages to other chats.\n\t\t\tif (msg->from_id!=DC_CONTACT_ID_SELF) {\n\t\t\t\tdc_param_set_int(msg->param, DC_PARAM_FORWARDED, 1);\n\t\t\t}\n\n\t\t\tdc_param_set(msg->param, DC_PARAM_GUARANTEE_E2EE, NULL);\n\t\t\tdc_param_set(msg->param, DC_PARAM_FORCE_PLAINTEXT, NULL);\n\t\t\tdc_param_set(msg->param, DC_PARAM_CMD, NULL);\n\n\t\t\tuint32_t new_msg_id;\n\t\t\t// PREPARING messages can't be forwarded immediately\n\t\t\tif (msg->state==DC_STATE_OUT_PREPARING) {\n\t\t\t\tnew_msg_id = prepare_msg_raw(context, chat, msg, curr_timestamp++);\n\n\t\t\t\t// to update the original message, perform in-place surgery\n\t\t\t\t// on msg to avoid copying the entire structure, text, etc.\n\t\t\t\tdc_param_t* save_param = msg->param;\n\t\t\t\tmsg->param = original_param;\n\t\t\t\tmsg->id = src_msg_id;\n\t\t\t\t{\n\t\t\t\t\t// append new id to the original's param.\n\t\t\t\t\tchar* old_fwd = dc_param_get(msg->param, DC_PARAM_PREP_FORWARDS, \"\");\n\t\t\t\t\tchar* new_fwd = dc_mprintf(\"%s %d\", old_fwd, new_msg_id);\n\t\t\t\t\tdc_param_set(msg->param, DC_PARAM_PREP_FORWARDS, new_fwd);\n\t\t\t\t\tdc_msg_save_param_to_disk(msg);\n\t\t\t\t\tfree(new_fwd);\n\t\t\t\t\tfree(old_fwd);\n\t\t\t\t}\n\t\t\t\tmsg->param = save_param;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmsg->state = DC_STATE_OUT_PENDING;\n\t\t\t\tnew_msg_id = prepare_msg_raw(context, chat, msg, curr_timestamp++);\n\t\t\t\tdc_job_send_msg(context, new_msg_id);\n\t\t\t}\n\n\t\t\tcarray_add(created_db_entries, (void*)(uintptr_t)chat_id, NULL);\n\t\t\tcarray_add(created_db_entries, (void*)(uintptr_t)new_msg_id, NULL);\n\t\t}\n\n\tdc_sqlite3_commit(context->sql);\n\ttransaction_pending = 0;\n\ncleanup:\n\tif (transaction_pending) { dc_sqlite3_rollback(context->sql); }\n\tif (created_db_entries) {\n\t\tsize_t i, icnt = carray_count(created_db_entries);\n\t\tfor (i = 0; i < icnt; i += 2) {\n\t\t\tcontext->cb(context, DC_EVENT_MSGS_CHANGED, (uintptr_t)carray_get(created_db_entries, i), (uintptr_t)carray_get(created_db_entries, i+1));\n\t\t}\n\t\tcarray_free(created_db_entries);\n\t}\n\tdc_contact_unref(contact);\n\tdc_msg_unref(msg);\n\tdc_chat_unref(chat);\n\tsqlite3_finalize(stmt);\n\tfree(idsstr);\n\tsqlite3_free(q3);\n\tdc_param_unref(original_param);\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn forward_msgs(context: &Context, msg_ids: &[MsgId], chat_id: ChatId) -> Result<()> {\n ensure!(!msg_ids.is_empty(), \"empty msgs_ids: nothing to forward\");\n ensure!(!chat_id.is_special(), \"can not forward to special chat\");\n\n let mut created_chats: Vec = Vec::new();\n let mut created_msgs: Vec = Vec::new();\n let mut curr_timestamp: i64;\n\n chat_id\n .unarchive_if_not_muted(context, MessageState::Undefined)\n .await?;\n let mut chat = Chat::load_from_db(context, chat_id).await?;\n if let Some(reason) = chat.why_cant_send(context).await? {\n bail!(\"cannot send to {}: {}\", chat_id, reason);\n }\n curr_timestamp = create_smeared_timestamps(context, msg_ids.len());\n let ids = context\n .sql\n .query_map(\n &format!(\n \"SELECT id FROM msgs WHERE id IN({}) ORDER BY timestamp,id\",\n sql::repeat_vars(msg_ids.len())\n ),\n rusqlite::params_from_iter(msg_ids),\n |row| row.get::<_, MsgId>(0),\n |ids| ids.collect::, _>>().map_err(Into::into),\n )\n .await?;\n\n for id in ids {\n let src_msg_id: MsgId = id;\n let mut msg = Message::load_from_db(context, src_msg_id).await?;\n if msg.state == MessageState::OutDraft {\n bail!(\"cannot forward drafts.\");\n }\n\n let original_param = msg.param.clone();\n\n // we tested a sort of broadcast\n // by not marking own forwarded messages as such,\n // however, this turned out to be to confusing and unclear.\n\n if msg.get_viewtype() != Viewtype::Sticker {\n msg.param\n .set_int(Param::Forwarded, src_msg_id.to_u32() as i32);\n }\n\n msg.param.remove(Param::GuaranteeE2ee);\n msg.param.remove(Param::ForcePlaintext);\n msg.param.remove(Param::Cmd);\n msg.param.remove(Param::OverrideSenderDisplayname);\n msg.param.remove(Param::WebxdcDocument);\n msg.param.remove(Param::WebxdcDocumentTimestamp);\n msg.param.remove(Param::WebxdcSummary);\n msg.param.remove(Param::WebxdcSummaryTimestamp);\n msg.in_reply_to = None;\n\n // do not leak data as group names; a default subject is generated by mimefactory\n msg.subject = \"\".to_string();\n\n let new_msg_id: MsgId;\n if msg.state == MessageState::OutPreparing {\n new_msg_id = chat\n .prepare_msg_raw(context, &mut msg, None, curr_timestamp)\n .await?;\n curr_timestamp += 1;\n msg.param = original_param;\n msg.id = src_msg_id;\n\n if let Some(old_fwd) = msg.param.get(Param::PrepForwards) {\n let new_fwd = format!(\"{} {}\", old_fwd, new_msg_id.to_u32());\n msg.param.set(Param::PrepForwards, new_fwd);\n } else {\n msg.param\n .set(Param::PrepForwards, new_msg_id.to_u32().to_string());\n }\n\n msg.update_param(context).await?;\n } else {\n msg.state = MessageState::OutPending;\n new_msg_id = chat\n .prepare_msg_raw(context, &mut msg, None, curr_timestamp)\n .await?;\n curr_timestamp += 1;\n if !create_send_msg_jobs(context, &mut msg).await?.is_empty() {\n context.scheduler.interrupt_smtp().await;\n }\n }\n created_chats.push(chat_id);\n created_msgs.push(new_msg_id);\n }\n for (chat_id, msg_id) in created_chats.iter().zip(created_msgs.iter()) {\n context.emit_msgs_changed(*chat_id, *msg_id);\n }\n Ok(())\n}", "rust_context": "pub(crate) async fn update_param(&mut self, context: &Context) -> Result<()> {\n context\n .sql\n .execute(\n \"UPDATE chats SET param=? WHERE id=?\",\n (self.param.to_string(), self.id),\n )\n .await?;\n Ok(())\n }\n\npub fn get_viewtype(&self) -> Viewtype {\n self.viewtype\n }\n\npub(crate) async fn create_send_msg_jobs(context: &Context, msg: &mut Message) -> Result> {\n let needs_encryption = msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default();\n let mimefactory = MimeFactory::from_msg(context, msg).await?;\n let attach_selfavatar = mimefactory.attach_selfavatar;\n let mut recipients = mimefactory.recipients();\n\n let from = context.get_primary_self_addr().await?;\n let lowercase_from = from.to_lowercase();\n\n // Send BCC to self if it is enabled.\n //\n // Previous versions of Delta Chat did not send BCC self\n // if DeleteServerAfter was set to immediately delete messages\n // from the server. This is not the case anymore\n // because BCC-self messages are also used to detect\n // that message was sent if SMTP server is slow to respond\n // and connection is frequently lost\n // before receiving status line.\n //\n // `from` must be the last addr, see `receive_imf_inner()` why.\n if context.get_config_bool(Config::BccSelf).await?\n && !recipients\n .iter()\n .any(|x| x.to_lowercase() == lowercase_from)\n {\n recipients.push(from);\n }\n\n // Webxdc integrations are messages, however, shipped with main app and must not be sent out\n if msg.param.get_int(Param::WebxdcIntegration).is_some() {\n recipients.clear();\n }\n\n if recipients.is_empty() {\n // may happen eg. for groups with only SELF and bcc_self disabled\n info!(\n context,\n \"Message {} has no recipient, skipping smtp-send.\", msg.id\n );\n msg.id.set_delivered(context).await?;\n msg.state = MessageState::OutDelivered;\n return Ok(Vec::new());\n }\n\n let rendered_msg = match mimefactory.render(context).await {\n Ok(res) => Ok(res),\n Err(err) => {\n message::set_msg_failed(context, msg, &err.to_string()).await?;\n Err(err)\n }\n }?;\n\n if needs_encryption && !rendered_msg.is_encrypted {\n /* unrecoverable */\n message::set_msg_failed(\n context,\n msg,\n \"End-to-end-encryption unavailable unexpectedly.\",\n )\n .await?;\n bail!(\n \"e2e encryption unavailable {} - {:?}\",\n msg.id,\n needs_encryption\n );\n }\n\n let now = smeared_time(context);\n\n if rendered_msg.is_gossiped {\n msg.chat_id.set_gossiped_timestamp(context, now).await?;\n }\n\n if msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {\n // Reject member list synchronisation from older messages. See also\n // `receive_imf::apply_group_changes()`.\n msg.chat_id\n .update_timestamp(\n context,\n Param::MemberListTimestamp,\n now.saturating_add(constants::TIMESTAMP_SENT_TOLERANCE),\n )\n .await?;\n }\n\n if rendered_msg.last_added_location_id.is_some() {\n if let Err(err) = location::set_kml_sent_timestamp(context, msg.chat_id, now).await {\n error!(context, \"Failed to set kml sent_timestamp: {err:#}.\");\n }\n }\n\n if let Some(sync_ids) = rendered_msg.sync_ids_to_delete {\n if let Err(err) = context.delete_sync_ids(sync_ids).await {\n error!(context, \"Failed to delete sync ids: {err:#}.\");\n }\n }\n\n if attach_selfavatar {\n if let Err(err) = msg.chat_id.set_selfavatar_timestamp(context, now).await {\n error!(context, \"Failed to set selfavatar timestamp: {err:#}.\");\n }\n }\n\n if rendered_msg.is_encrypted && !needs_encryption {\n msg.param.set_int(Param::GuaranteeE2ee, 1);\n msg.update_param(context).await?;\n }\n\n msg.subject.clone_from(&rendered_msg.subject);\n msg.update_subject(context).await?;\n let chunk_size = context.get_max_smtp_rcpt_to().await?;\n let trans_fn = |t: &mut rusqlite::Transaction| {\n let mut row_ids = Vec::::new();\n for recipients_chunk in recipients.chunks(chunk_size) {\n let recipients_chunk = recipients_chunk.join(\" \");\n let row_id = t.execute(\n \"INSERT INTO smtp (rfc724_mid, recipients, mime, msg_id) \\\n VALUES (?1, ?2, ?3, ?4)\",\n (\n &rendered_msg.rfc724_mid,\n recipients_chunk,\n &rendered_msg.message,\n msg.id,\n ),\n )?;\n row_ids.push(row_id.try_into()?);\n }\n Ok(row_ids)\n };\n context.sql.transaction(trans_fn).await\n}\n\nasync fn prepare_msg_raw(\n &mut self,\n context: &Context,\n msg: &mut Message,\n update_msg_id: Option,\n timestamp: i64,\n ) -> Result {\n let mut to_id = 0;\n let mut location_id = 0;\n\n let new_rfc724_mid = create_outgoing_rfc724_mid();\n\n if self.typ == Chattype::Single {\n if let Some(id) = context\n .sql\n .query_get_value(\n \"SELECT contact_id FROM chats_contacts WHERE chat_id=?;\",\n (self.id,),\n )\n .await?\n {\n to_id = id;\n } else {\n error!(\n context,\n \"Cannot send message, contact for {} not found.\", self.id,\n );\n bail!(\"Cannot set message, contact for {} not found.\", self.id);\n }\n } else if self.typ == Chattype::Group\n && self.param.get_int(Param::Unpromoted).unwrap_or_default() == 1\n {\n msg.param.set_int(Param::AttachGroupImage, 1);\n self.param.remove(Param::Unpromoted);\n self.update_param(context).await?;\n // send_sync_msg() is called (usually) a moment later at send_msg_to_smtp()\n // when the group-creation message is actually sent though SMTP -\n // this makes sure, the other devices are aware of grpid that is used in the sync-message.\n context\n .sync_qr_code_tokens(Some(self.id))\n .await\n .log_err(context)\n .ok();\n }\n\n // reset encrypt error state eg. for forwarding\n msg.param.remove(Param::ErroneousE2ee);\n\n let is_bot = context.get_config_bool(Config::Bot).await?;\n msg.param\n .set_optional(Param::Bot, Some(\"1\").filter(|_| is_bot));\n\n // Set \"In-Reply-To:\" to identify the message to which the composed message is a reply.\n // Set \"References:\" to identify the \"thread\" of the conversation.\n // Both according to [RFC 5322 3.6.4, page 25](https://www.rfc-editor.org/rfc/rfc5322#section-3.6.4).\n let new_references;\n if self.is_self_talk() {\n // As self-talks are mainly used to transfer data between devices,\n // we do not set In-Reply-To/References in this case.\n new_references = String::new();\n } else if let Some((parent_rfc724_mid, parent_in_reply_to, parent_references)) =\n // We don't filter `OutPending` and `OutFailed` messages because the new message for\n // which `parent_query()` is done may assume that it will be received in a context\n // affected by those messages, e.g. they could add new members to a group and the\n // new message will contain them in \"To:\". Anyway recipients must be prepared to\n // orphaned references.\n self\n .id\n .get_parent_mime_headers(context, MessageState::OutPending)\n .await?\n {\n // \"In-Reply-To:\" is not changed if it is set manually.\n // This does not affect \"References:\" header, it will contain \"default parent\" (the\n // latest message in the thread) anyway.\n if msg.in_reply_to.is_none() && !parent_rfc724_mid.is_empty() {\n msg.in_reply_to = Some(parent_rfc724_mid.clone());\n }\n\n // Use parent `In-Reply-To` as a fallback\n // in case parent message has no `References` header\n // as specified in RFC 5322:\n // > If the parent message does not contain\n // > a \"References:\" field but does have an \"In-Reply-To:\" field\n // > containing a single message identifier, then the \"References:\" field\n // > will contain the contents of the parent's \"In-Reply-To:\" field\n // > followed by the contents of the parent's \"Message-ID:\" field (if\n // > any).\n let parent_references = if parent_references.is_empty() {\n parent_in_reply_to\n } else {\n parent_references\n };\n\n // The whole list of messages referenced may be huge.\n // Only take 2 recent references and add third from `In-Reply-To`.\n let mut references_vec: Vec<&str> = parent_references.rsplit(' ').take(2).collect();\n references_vec.reverse();\n\n if !parent_rfc724_mid.is_empty()\n && !references_vec.contains(&parent_rfc724_mid.as_str())\n {\n references_vec.push(&parent_rfc724_mid)\n }\n\n if references_vec.is_empty() {\n // As a fallback, use our Message-ID,\n // same as in the case of top-level message.\n new_references = new_rfc724_mid.clone();\n } else {\n new_references = references_vec.join(\" \");\n }\n } else {\n // This is a top-level message.\n // Add our Message-ID as first references.\n // This allows us to identify replies to our message even if\n // email server such as Outlook changes `Message-ID:` header.\n // MUAs usually keep the first Message-ID in `References:` header unchanged.\n new_references = new_rfc724_mid.clone();\n }\n\n // add independent location to database\n if msg.param.exists(Param::SetLatitude) {\n if let Ok(row_id) = context\n .sql\n .insert(\n \"INSERT INTO locations \\\n (timestamp,from_id,chat_id, latitude,longitude,independent)\\\n VALUES (?,?,?, ?,?,1);\",\n (\n timestamp,\n ContactId::SELF,\n self.id,\n msg.param.get_float(Param::SetLatitude).unwrap_or_default(),\n msg.param.get_float(Param::SetLongitude).unwrap_or_default(),\n ),\n )\n .await\n {\n location_id = row_id;\n }\n }\n\n let ephemeral_timer = if msg.param.get_cmd() == SystemMessage::EphemeralTimerChanged {\n EphemeralTimer::Disabled\n } else {\n self.id.get_ephemeral_timer(context).await?\n };\n let ephemeral_timestamp = match ephemeral_timer {\n EphemeralTimer::Disabled => 0,\n EphemeralTimer::Enabled { duration } => time().saturating_add(duration.into()),\n };\n\n let new_mime_headers = if msg.has_html() {\n let html = if msg.param.exists(Param::Forwarded) {\n msg.get_id().get_html(context).await?\n } else {\n msg.param.get(Param::SendHtml).map(|s| s.to_string())\n };\n match html {\n Some(html) => Some(tokio::task::block_in_place(move || {\n buf_compress(new_html_mimepart(html).build().as_string().as_bytes())\n })?),\n None => None,\n }\n } else {\n None\n };\n\n msg.chat_id = self.id;\n msg.from_id = ContactId::SELF;\n msg.rfc724_mid = new_rfc724_mid;\n msg.timestamp_sort = timestamp;\n\n // add message to the database\n if let Some(update_msg_id) = update_msg_id {\n context\n .sql\n .execute(\n \"UPDATE msgs\n SET rfc724_mid=?, chat_id=?, from_id=?, to_id=?, timestamp=?, type=?,\n state=?, txt=?, subject=?, param=?,\n hidden=?, mime_in_reply_to=?, mime_references=?, mime_modified=?,\n mime_headers=?, mime_compressed=1, location_id=?, ephemeral_timer=?,\n ephemeral_timestamp=?\n WHERE id=?;\",\n params_slice![\n msg.rfc724_mid,\n msg.chat_id,\n msg.from_id,\n to_id,\n msg.timestamp_sort,\n msg.viewtype,\n msg.state,\n msg.text,\n &msg.subject,\n msg.param.to_string(),\n msg.hidden,\n msg.in_reply_to.as_deref().unwrap_or_default(),\n new_references,\n new_mime_headers.is_some(),\n new_mime_headers.unwrap_or_default(),\n location_id as i32,\n ephemeral_timer,\n ephemeral_timestamp,\n update_msg_id\n ],\n )\n .await?;\n msg.id = update_msg_id;\n } else {\n let raw_id = context\n .sql\n .insert(\n \"INSERT INTO msgs (\n rfc724_mid,\n chat_id,\n from_id,\n to_id,\n timestamp,\n type,\n state,\n txt,\n subject,\n param,\n hidden,\n mime_in_reply_to,\n mime_references,\n mime_modified,\n mime_headers,\n mime_compressed,\n location_id,\n ephemeral_timer,\n ephemeral_timestamp)\n VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?,?);\",\n params_slice![\n msg.rfc724_mid,\n msg.chat_id,\n msg.from_id,\n to_id,\n msg.timestamp_sort,\n msg.viewtype,\n msg.state,\n msg.text,\n &msg.subject,\n msg.param.to_string(),\n msg.hidden,\n msg.in_reply_to.as_deref().unwrap_or_default(),\n new_references,\n new_mime_headers.is_some(),\n new_mime_headers.unwrap_or_default(),\n location_id as i32,\n ephemeral_timer,\n ephemeral_timestamp\n ],\n )\n .await?;\n context.new_msgs_notify.notify_one();\n msg.id = MsgId::new(u32::try_from(raw_id)?);\n\n maybe_set_logging_xdc(context, msg, self.id).await?;\n context.update_webxdc_integration_database(msg).await?;\n }\n context.scheduler.interrupt_ephemeral_task().await;\n Ok(msg.id)\n }\n\npub fn emit_msgs_changed(&self, chat_id: ChatId, msg_id: MsgId) {\n self.emit_event(EventType::MsgsChanged { chat_id, msg_id });\n chatlist_events::emit_chatlist_changed(self);\n chatlist_events::emit_chatlist_item_changed(self, chat_id);\n }\n\npub fn set_int(&mut self, key: Param, value: i32) -> &mut Self {\n self.set(key, format!(\"{value}\"));\n self\n }\n\npub async fn query_map(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n mut g: G,\n ) -> Result\n where\n F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result,\n G: Send + FnMut(rusqlite::MappedRows) -> Result,\n H: Send + 'static,\n {\n self.call(move |conn| {\n let mut stmt = conn.prepare(sql)?;\n let res = stmt.query_map(params, f)?;\n g(res)\n })\n .await\n }\n\npub(crate) fn iter(&self) -> BlobDirIter<'_> {\n BlobDirIter::new(self.context, self.inner.iter())\n }\n\npub fn remove(&mut self, key: Param) -> &mut Self {\n self.inner.remove(&key);\n self\n }\n\npub fn is_empty(&self) -> bool {\n self.inner.is_empty()\n }\n\npub fn is_special(self) -> bool {\n (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)\n }\n\npub fn to_u32(self) -> u32 {\n self.0\n }\n\npub(crate) async fn why_cant_send(&self, context: &Context) -> Result> {\n use CantSendReason::*;\n\n // NB: Don't forget to update Chatlist::try_load() when changing this function!\n let reason = if self.id.is_special() {\n Some(SpecialChat)\n } else if self.is_device_talk() {\n Some(DeviceChat)\n } else if self.is_contact_request() {\n Some(ContactRequest)\n } else if self.is_protection_broken() {\n Some(ProtectionBroken)\n } else if self.is_mailing_list() && self.get_mailinglist_addr().is_none_or_empty() {\n Some(ReadOnlyMailingList)\n } else if !self.is_self_in_chat(context).await? {\n Some(NotAMember)\n } else if self\n .check_securejoin_wait(context, constants::SECUREJOIN_WAIT_TIMEOUT)\n .await?\n > 0\n {\n Some(SecurejoinWait)\n } else {\n None\n };\n Ok(reason)\n }\n\npub async fn unarchive_if_not_muted(\n self,\n context: &Context,\n msg_state: MessageState,\n ) -> Result<()> {\n if msg_state != MessageState::InFresh {\n context\n .sql\n .execute(\n \"UPDATE chats SET archived=0 WHERE id=? AND archived=1 \\\n AND NOT(muted_until=-1 OR muted_until>?)\",\n (self, time()),\n )\n .await?;\n return Ok(());\n }\n let chat = Chat::load_from_db(context, self).await?;\n if chat.visibility != ChatVisibility::Archived {\n return Ok(());\n }\n if chat.is_muted() {\n let unread_cnt = context\n .sql\n .count(\n \"SELECT COUNT(*)\n FROM msgs\n WHERE state=?\n AND hidden=0\n AND chat_id=?\",\n (MessageState::InFresh, self),\n )\n .await?;\n if unread_cnt == 1 {\n // Added the first unread message in the chat.\n context.emit_msgs_changed(DC_CHAT_ID_ARCHIVED_LINK, MsgId::new(0));\n }\n return Ok(());\n }\n context\n .sql\n .execute(\"UPDATE chats SET archived=0 WHERE id=?\", (self,))\n .await?;\n Ok(())\n }\n\npub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result {\n let mut chat = context\n .sql\n .query_row(\n \"SELECT c.type, c.name, c.grpid, c.param, c.archived,\n c.blocked, c.locations_send_until, c.muted_until, c.protected\n FROM chats c\n WHERE c.id=?;\",\n (chat_id,),\n |row| {\n let c = Chat {\n id: chat_id,\n typ: row.get(0)?,\n name: row.get::<_, String>(1)?,\n grpid: row.get::<_, String>(2)?,\n param: row.get::<_, String>(3)?.parse().unwrap_or_default(),\n visibility: row.get(4)?,\n blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),\n is_sending_locations: row.get(6)?,\n mute_duration: row.get(7)?,\n protected: row.get(8)?,\n };\n Ok(c)\n },\n )\n .await\n .context(format!(\"Failed loading chat {chat_id} from database\"))?;\n\n if chat.id.is_archived_link() {\n chat.name = stock_str::archived_chats(context).await;\n } else {\n if chat.typ == Chattype::Single && chat.name.is_empty() {\n // chat.name is set to contact.display_name on changes,\n // however, if things went wrong somehow, we do this here explicitly.\n let mut chat_name = \"Err [Name not found]\".to_owned();\n match get_chat_contacts(context, chat.id).await {\n Ok(contacts) => {\n if let Some(contact_id) = contacts.first() {\n if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {\n contact.get_display_name().clone_into(&mut chat_name);\n }\n }\n }\n Err(err) => {\n error!(\n context,\n \"Failed to load contacts for {}: {:#}.\", chat.id, err\n );\n }\n }\n chat.name = chat_name;\n }\n if chat.param.exists(Param::Selftalk) {\n chat.name = stock_str::saved_messages(context).await;\n } else if chat.param.exists(Param::Devicetalk) {\n chat.name = stock_str::device_messages(context).await;\n }\n }\n\n Ok(chat)\n }\n\npub async fn query_map(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n mut g: G,\n ) -> Result\n where\n F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result,\n G: Send + FnMut(rusqlite::MappedRows) -> Result,\n H: Send + 'static,\n {\n self.call(move |conn| {\n let mut stmt = conn.prepare(sql)?;\n let res = stmt.query_map(params, f)?;\n g(res)\n })\n .await\n }\n\npub fn params_from_iter(iter: I) -> ParamsFromIter\nwhere\n I: IntoIterator,\n I::Item: ToSql,\n{\n ParamsFromIter(iter)\n}\n\npub(crate) fn create_smeared_timestamps(context: &Context, count: usize) -> i64 {\n let now = time();\n context.smeared_timestamp.create_n(now, count as i64)\n}\n\npub fn repeat_vars(count: usize) -> String {\n let mut s = \"?,\".repeat(count);\n s.pop(); // Remove trailing comma\n s\n}\n\npub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self {\n self.inner.insert(key, value.to_string());\n self\n }\n\npub fn len(&self) -> usize {\n self.inner.len()\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct MsgId(u32);\n\npub struct ChatId(u32);\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}\n\n\npub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}\n\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\n\npub enum MessageState {\n /// Undefined message state.\n #[default]\n Undefined = 0,\n\n /// Incoming *fresh* message. Fresh messages are neither noticed\n /// nor seen and are typically shown in notifications.\n InFresh = 10,\n\n /// Incoming *noticed* message. E.g. chat opened but message not\n /// yet read - noticed messages are not counted as unread but did\n /// not marked as read nor resulted in MDNs.\n InNoticed = 13,\n\n /// Incoming message, really *seen* by the user. Marked as read on\n /// IMAP and MDN may be sent.\n InSeen = 16,\n\n /// For files which need time to be prepared before they can be\n /// sent, the message enters this state before\n /// OutPending.\n OutPreparing = 18,\n\n /// Message saved as draft.\n OutDraft = 19,\n\n /// The user has pressed the \"send\" button but the message is not\n /// yet sent and is pending in some way. Maybe we're offline (no\n /// checkmark).\n OutPending = 20,\n\n /// *Unrecoverable* error (*recoverable* errors result in pending\n /// messages).\n OutFailed = 24,\n\n /// Outgoing message successfully delivered to server (one\n /// checkmark). Note, that already delivered messages may get into\n /// the OutFailed state if we get such a hint from the server.\n OutDelivered = 26,\n\n /// Outgoing message read by the recipient (two checkmarks; this\n /// requires goodwill on the receiver's side)\n OutMdnRcvd = 28,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__139.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "int dc_delete_contact(dc_context_t* context, uint32_t contact_id)\n{\n\tint success = 0;\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || contact_id<=DC_CONTACT_ID_LAST_SPECIAL) {\n\t\tgoto cleanup;\n\t}\n\n\t/* we can only delete contacts that are not in use anywhere; this function is mainly for the user who has just\n\tcreated an contact manually and wants to delete it a moment later */\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT COUNT(*) FROM chats_contacts WHERE contact_id=?;\");\n\tsqlite3_bind_int(stmt, 1, contact_id);\n\tif (sqlite3_step(stmt)!=SQLITE_ROW || sqlite3_column_int(stmt, 0) >= 1) {\n\t\tgoto cleanup;\n\t}\n\tsqlite3_finalize(stmt);\n\tstmt = NULL;\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT COUNT(*) FROM msgs WHERE from_id=? OR to_id=?;\");\n\tsqlite3_bind_int(stmt, 1, contact_id);\n\tsqlite3_bind_int(stmt, 2, contact_id);\n\tif (sqlite3_step(stmt)!=SQLITE_ROW || sqlite3_column_int(stmt, 0) >= 1) {\n\t\tgoto cleanup;\n\t}\n\tsqlite3_finalize(stmt);\n\tstmt = NULL;\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"DELETE FROM contacts WHERE id=?;\");\n\tsqlite3_bind_int(stmt, 1, contact_id);\n\tif (sqlite3_step(stmt)!=SQLITE_DONE) {\n\t\tgoto cleanup;\n\t}\n\n\tcontext->cb(context, DC_EVENT_CONTACTS_CHANGED, 0, 0);\n\n\tsuccess = 1;\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub async fn delete(context: &Context, contact_id: ContactId) -> Result<()> {\n ensure!(!contact_id.is_special(), \"Can not delete special contact\");\n\n context\n .sql\n .transaction(move |transaction| {\n // make sure, the transaction starts with a write command and becomes EXCLUSIVE by that -\n // upgrading later may be impossible by races.\n let deleted_contacts = transaction.execute(\n \"DELETE FROM contacts WHERE id=?\n AND (SELECT COUNT(*) FROM chats_contacts WHERE contact_id=?)=0;\",\n (contact_id, contact_id),\n )?;\n if deleted_contacts == 0 {\n transaction.execute(\n \"UPDATE contacts SET origin=? WHERE id=?;\",\n (Origin::Hidden, contact_id),\n )?;\n }\n Ok(())\n })\n .await?;\n\n context.emit_event(EventType::ContactsChanged(None));\n Ok(())\n }", "rust_context": "pub fn emit_event(&self, event: EventType) {\n {\n let lock = self.debug_logging.read().expect(\"RwLock is poisoned\");\n if let Some(debug_logging) = &*lock {\n debug_logging.log_event(event.clone());\n }\n }\n self.events.emit(Event {\n id: self.id,\n typ: event,\n });\n }\n\npub fn is_special(&self) -> bool {\n self.0 <= Self::LAST_SPECIAL.0\n }\n\npub async fn transaction(&self, callback: G) -> Result\n where\n H: Send + 'static,\n G: Send + FnOnce(&mut rusqlite::Transaction<'_>) -> Result,\n {\n self.call_write(move |conn| {\n let mut transaction = conn.transaction()?;\n let ret = callback(&mut transaction);\n\n match ret {\n Ok(ret) => {\n transaction.commit()?;\n Ok(ret)\n }\n Err(err) => {\n transaction.rollback()?;\n Err(err)\n }\n }\n })\n .await\n } \n\npub struct ContactId(u32);\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub enum Origin {\n /// Unknown origin. Can be used as a minimum origin to specify that the caller does not care\n /// about origin of the contact.\n #[default]\n Unknown = 0,\n\n /// The contact is a mailing list address, needed to unblock mailing lists\n MailinglistAddress = 0x2,\n\n /// Hidden on purpose, e.g. addresses with the word \"noreply\" in it\n Hidden = 0x8,\n\n /// From: of incoming messages of unknown sender\n IncomingUnknownFrom = 0x10,\n\n /// Cc: of incoming messages of unknown sender\n IncomingUnknownCc = 0x20,\n\n /// To: of incoming messages of unknown sender\n IncomingUnknownTo = 0x40,\n\n /// address scanned but not verified\n UnhandledQrScan = 0x80,\n\n /// Reply-To: of incoming message of known sender\n /// Contacts with at least this origin value are shown in the contact list.\n IncomingReplyTo = 0x100,\n\n /// Cc: of incoming message of known sender\n IncomingCc = 0x200,\n\n /// additional To:'s of incoming message of known sender\n IncomingTo = 0x400,\n\n /// a chat was manually created for this user, but no message yet sent\n CreateChat = 0x800,\n\n /// message sent by us\n OutgoingBcc = 0x1000,\n\n /// message sent by us\n OutgoingCc = 0x2000,\n\n /// message sent by us\n OutgoingTo = 0x4000,\n\n /// internal use\n Internal = 0x40000,\n\n /// address is in our address book\n AddressBook = 0x80000,\n\n /// 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() !\n SecurejoinInvited = 0x0100_0000,\n\n /// 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() !\n SecurejoinJoined = 0x0200_0000,\n\n /// contact added manually by create_contact(), this should be the largest origin as otherwise the user cannot modify the names\n ManuallyCreated = 0x0400_0000,\n}\n\npub enum EventType {\n /// The library-user may write an informational string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Info(String),\n\n /// Emitted when SMTP connection is established and login was successful.\n SmtpConnected(String),\n\n /// Emitted when IMAP connection is established and login was successful.\n ImapConnected(String),\n\n /// Emitted when a message was successfully sent to the SMTP server.\n SmtpMessageSent(String),\n\n /// Emitted when an IMAP message has been marked as deleted\n ImapMessageDeleted(String),\n\n /// Emitted when an IMAP message has been moved\n ImapMessageMoved(String),\n\n /// Emitted before going into IDLE on the Inbox folder.\n ImapInboxIdle,\n\n /// Emitted when an new file in the $BLOBDIR was created\n NewBlobFile(String),\n\n /// Emitted when an file in the $BLOBDIR was deleted\n DeletedBlobFile(String),\n\n /// The library-user should write a warning string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Warning(String),\n\n /// The library-user should report an error to the end-user.\n ///\n /// As most things are asynchronous, things may go wrong at any time and the user\n /// should not be disturbed by a dialog or so. Instead, use a bubble or so.\n ///\n /// However, for ongoing processes (eg. configure())\n /// or for functions that are expected to fail (eg. dc_continue_key_transfer())\n /// it might be better to delay showing these events until the function has really\n /// failed (returned false). It should be sufficient to report only the *last* error\n /// in a messasge box then.\n Error(String),\n\n /// An action cannot be performed because the user is not in the group.\n /// Reported eg. after a call to\n /// dc_set_chat_name(), dc_set_chat_profile_image(),\n /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(),\n /// dc_send_text_msg() or another sending function.\n ErrorSelfNotInGroup(String),\n\n /// Messages or chats changed. One or more messages or chats changed for various\n /// reasons in the database:\n /// - Messages sent, received or removed\n /// - Chats created, deleted or archived\n /// - A draft has been set\n ///\n MsgsChanged {\n /// Set if only a single chat is affected by the changes, otherwise 0.\n chat_id: ChatId,\n\n /// Set if only a single message is affected by the changes, otherwise 0.\n msg_id: MsgId,\n },\n\n /// Reactions for the message changed.\n ReactionsChanged {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message for which reactions were changed.\n msg_id: MsgId,\n\n /// ID of the contact whose reaction set is changed.\n contact_id: ContactId,\n },\n\n /// There is a fresh message. Typically, the user will show an notification\n /// when receiving this message.\n ///\n /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event.\n IncomingMsg {\n /// ID of the chat where the message is assigned.\n chat_id: ChatId,\n\n /// ID of the message.\n msg_id: MsgId,\n },\n\n /// Downloading a bunch of messages just finished.\n IncomingMsgBunch,\n\n /// Messages were seen or noticed.\n /// chat id is always set.\n MsgsNoticed(ChatId),\n\n /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to\n /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state().\n MsgDelivered {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was successfully sent.\n msg_id: MsgId,\n },\n\n /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_FAILED, see dc_msg_get_state().\n MsgFailed {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that could not be sent.\n msg_id: MsgId,\n },\n\n /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state().\n MsgRead {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was read.\n msg_id: MsgId,\n },\n\n /// A single message was deleted.\n ///\n /// This event means that the message will no longer appear in the messagelist.\n /// UI should remove the message from the messagelist\n /// in response to this event if the message is currently displayed.\n ///\n /// The message may have been explicitly deleted by the user or expired.\n /// Internally the message may have been removed from the database,\n /// moved to the trash chat or hidden.\n ///\n /// This event does not indicate the message\n /// deletion from the server.\n MsgDeleted {\n /// ID of the chat where the message was prior to deletion.\n /// Never 0 or trash chat.\n chat_id: ChatId,\n\n /// ID of the deleted message. Never 0.\n msg_id: MsgId,\n },\n\n /// Chat changed. The name or the image of a chat group was changed or members were added or removed.\n /// Or the verify state of a chat has changed.\n /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat()\n /// and dc_remove_contact_from_chat().\n ///\n /// This event does not include ephemeral timer modification, which\n /// is a separate event.\n ChatModified(ChatId),\n\n /// Chat ephemeral timer changed.\n ChatEphemeralTimerModified {\n /// Chat ID.\n chat_id: ChatId,\n\n /// New ephemeral timer value.\n timer: EphemeralTimer,\n },\n\n /// Contact(s) created, renamed, blocked, deleted or changed their \"recently seen\" status.\n ///\n /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected.\n ContactsChanged(Option),\n\n /// Location of one or more contact has changed.\n ///\n /// @param data1 (u32) contact_id of the contact for which the location has changed.\n /// If the locations of several contacts have been changed,\n /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`.\n LocationChanged(Option),\n\n /// Inform about the configuration progress started by configure().\n ConfigureProgress {\n /// Progress.\n ///\n /// 0=error, 1-999=progress in permille, 1000=success and done\n progress: usize,\n\n /// Progress comment or error, something to display to the user.\n comment: Option,\n },\n\n /// Inform about the import/export progress started by imex().\n ///\n /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done\n /// @param data2 0\n ImexProgress(usize),\n\n /// A file has been exported. A file has been written by imex().\n /// This event may be sent multiple times by a single call to imex().\n ///\n /// A typical purpose for a handler of this event may be to make the file public to some system\n /// services.\n ///\n /// @param data2 0\n ImexFileWritten(PathBuf),\n\n /// Progress information of a secure-join handshake from the view of the inviter\n /// (Alice, the person who shows the QR code).\n ///\n /// These events are typically sent after a joiner has scanned the QR code\n /// generated by dc_get_securejoin_qr().\n SecurejoinInviterProgress {\n /// ID of the contact that wants to join.\n contact_id: ContactId,\n\n /// Progress as:\n /// 300=vg-/vc-request received, typically shown as \"bob@addr joins\".\n /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as \"bob@addr verified\".\n /// 800=contact added to chat, shown as \"bob@addr securely joined GROUP\". Only for the verified-group-protocol.\n /// 1000=Protocol finished for this contact.\n progress: usize,\n },\n\n /// Progress information of a secure-join handshake from the view of the joiner\n /// (Bob, the person who scans the QR code).\n /// The events are typically sent while dc_join_securejoin(), which\n /// may take some time, is executed.\n SecurejoinJoinerProgress {\n /// ID of the inviting contact.\n contact_id: ContactId,\n\n /// Progress as:\n /// 400=vg-/vc-request-with-auth sent, typically shown as \"alice@addr verified, introducing myself.\"\n /// (Bob has verified alice and waits until Alice does the same for him)\n /// 1000=vg-member-added/vc-contact-confirm received\n progress: usize,\n },\n\n /// The connectivity to the server changed.\n /// This means that you should refresh the connectivity view\n /// and possibly the connectivtiy HTML; see dc_get_connectivity() and\n /// dc_get_connectivity_html() for details.\n ConnectivityChanged,\n\n /// The user's avatar changed.\n /// Deprecated by `ConfigSynced`.\n SelfavatarChanged,\n\n /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For\n /// uniformity this is emitted on the source device too. The value isn't here, otherwise it\n /// would be logged which might not be good for privacy.\n ConfigSynced {\n /// Configuration key.\n key: Config,\n },\n\n /// Webxdc status update received.\n WebxdcStatusUpdate {\n /// Message ID.\n msg_id: MsgId,\n\n /// Status update ID.\n status_update_serial: StatusUpdateSerial,\n },\n\n /// Data received over an ephemeral peer channel.\n WebxdcRealtimeData {\n /// Message ID.\n msg_id: MsgId,\n\n /// Realtime data.\n data: Vec,\n },\n\n /// Inform that a message containing a webxdc instance has been deleted.\n WebxdcInstanceDeleted {\n /// ID of the deleted message.\n msg_id: MsgId,\n },\n\n /// Tells that the Background fetch was completed (or timed out).\n /// This event acts as a marker, when you reach this event you can be sure\n /// that all events emitted during the background fetch were processed.\n ///\n /// This event is only emitted by the account manager\n AccountsBackgroundFetchDone,\n /// Inform that set of chats or the order of the chats in the chatlist has changed.\n ///\n /// Sometimes this is emitted together with `UIChatlistItemChanged`.\n ChatlistChanged,\n\n /// Inform that a single chat list item changed and needs to be rerendered.\n /// 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.\n ChatlistItemChanged {\n /// ID of the changed chat\n chat_id: Option,\n },\n\n /// Event for using in tests, e.g. as a fence between normally generated events.\n #[cfg(test)]\n Test,\n\n /// Inform than some events have been skipped due to event channel overflow.\n EventChannelOverflow {\n /// Number of events skipped.\n n: u64,\n },\n}\n\npub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__33.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* After the creation with dc_create_group_chat() the chat is usually unpromoted\n * until the first call to dc_send_text_msg() or another sending function.\n *\n * With unpromoted chats, members can be added\n * and settings can be modified without the need of special status messages being sent.\n *\n * While the core takes care of the unpromoted state on its own,\n * checking the state from the UI side may be useful to decide whether a hint as\n * \"Send the first message to allow others to reply within the group\"\n * should be shown to the user or not.\n *\n * @memberof dc_chat_t\n * @param chat The chat object.\n * @return 1=chat is still unpromoted, no message was ever send to the chat,\n * 0=chat is not unpromoted, messages were send and/or received\n * or the chat is not group chat.\n */\nint dc_chat_is_unpromoted(const dc_chat_t* chat)\n{\n\tif (chat==NULL || chat->magic!=DC_CHAT_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0);\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub(crate) async fn is_unpromoted(self, context: &Context) -> Result {\n let param = self.get_param(context).await?;\n let unpromoted = param.get_bool(Param::Unpromoted).unwrap_or_default();\n Ok(unpromoted)\n }", "rust_context": "pub fn get_bool(&self, key: Param) -> Option {\n self.get_int(key).map(|v| v != 0)\n }\n\npub(crate) async fn get_param(self, context: &Context) -> Result {\n let res: Option = context\n .sql\n .query_get_value(\"SELECT param FROM chats WHERE id=?\", (self,))\n .await?;\n Ok(res\n .map(|s| s.parse().unwrap_or_default())\n .unwrap_or_default())\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct Chat {\n /// Database ID.\n pub id: ChatId,\n\n /// Chat type, e.g. 1:1 chat, group chat, mailing list.\n pub typ: Chattype,\n\n /// Chat name.\n pub name: String,\n\n /// Whether the chat is archived or pinned.\n pub visibility: ChatVisibility,\n\n /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and\n /// ad-hoc groups.\n pub grpid: String,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n\n /// Additional chat parameters stored in the database.\n pub param: Params,\n\n /// If location streaming is enabled in the chat.\n is_sending_locations: bool,\n\n /// Duration of the chat being muted.\n pub mute_duration: MuteDuration,\n\n /// If the chat is protected (verified).\n pub(crate) protected: ProtectionStatus,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}\n\npub struct ChatId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__42.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* If the group is already _promoted_ (any message was sent to the group),\n * all group members are informed by a special status message that is sent automatically by this function.\n *\n * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent.\n *\n * @memberof dc_context_t\n * @param chat_id The chat ID to set the name for. Must be a group chat.\n * @param new_name New name of the group.\n * @param context The context as created by dc_context_new().\n * @return 1=success, 0=error\n */\nint dc_set_chat_name(dc_context_t* context, uint32_t chat_id, const char* new_name)\n{\n\t/* the function only sets the names of group chats; normal chats get their names from the contacts */\n\tint success = 0;\n\tdc_chat_t* chat = dc_chat_new(context);\n\tdc_msg_t* msg = dc_msg_new_untyped(context);\n\tchar* q3 = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || new_name==NULL || new_name[0]==0 || chat_id<=DC_CHAT_ID_LAST_SPECIAL) {\n\t\tgoto cleanup;\n\t}\n\n\tif (0==real_group_exists(context, chat_id)\n\t || 0==dc_chat_load_from_db(chat, chat_id)) {\n\t\tgoto cleanup;\n\t}\n\n\tif (strcmp(chat->name, new_name)==0) {\n\t\tsuccess = 1;\n\t\tgoto cleanup; /* name not modified */\n\t}\n\n\tif (!IS_SELF_IN_GROUP) {\n\t\tdc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0,\n\t\t \"Cannot set chat name; self not in group\");\n\t\tgoto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */\n\t}\n\n\tq3 = sqlite3_mprintf(\"UPDATE chats SET name=%Q WHERE id=%i;\", new_name, chat_id);\n\tif (!dc_sqlite3_execute(context->sql, q3)) {\n\t\tgoto cleanup;\n\t}\n\n\t/* send a status mail to all group members, also needed for outself to allow multi-client */\n\tif (DO_SEND_STATUS_MAILS)\n\t{\n\t\tmsg->type = DC_MSG_TEXT;\n\t\tmsg->text = dc_stock_system_msg(context, DC_STR_MSGGRPNAME, chat->name, new_name, DC_CONTACT_ID_SELF);\n\t\tdc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_GROUPNAME_CHANGED);\n\t\tdc_param_set (msg->param, DC_PARAM_CMD_ARG, chat->name);\n\t\tmsg->id = dc_send_msg(context, chat_id, msg);\n\t\tcontext->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, msg->id);\n\t}\n\tcontext->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0);\n\n\tsuccess = 1;\n\ncleanup:\n\tsqlite3_free(q3);\n\tdc_chat_unref(chat);\n\tdc_msg_unref(msg);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn set_chat_name(context: &Context, chat_id: ChatId, new_name: &str) -> Result<()> {\n rename_ex(context, Sync, chat_id, new_name).await\n}", "rust_context": "async fn rename_ex(\n context: &Context,\n mut sync: sync::Sync,\n chat_id: ChatId,\n new_name: &str,\n) -> Result<()> {\n let new_name = improve_single_line_input(new_name);\n /* the function only sets the names of group chats; normal chats get their names from the contacts */\n let mut success = false;\n\n ensure!(!new_name.is_empty(), \"Invalid name\");\n ensure!(!chat_id.is_special(), \"Invalid chat ID\");\n\n let chat = Chat::load_from_db(context, chat_id).await?;\n let mut msg = Message::default();\n\n if chat.typ == Chattype::Group\n || chat.typ == Chattype::Mailinglist\n || chat.typ == Chattype::Broadcast\n {\n if chat.name == new_name {\n success = true;\n } else if !chat.is_self_in_chat(context).await? {\n context.emit_event(EventType::ErrorSelfNotInGroup(\n \"Cannot set chat name; self not in group\".into(),\n ));\n } else {\n context\n .sql\n .execute(\n \"UPDATE chats SET name=? WHERE id=?;\",\n (new_name.to_string(), chat_id),\n )\n .await?;\n if chat.is_promoted()\n && !chat.is_mailing_list()\n && chat.typ != Chattype::Broadcast\n && improve_single_line_input(&chat.name) != new_name\n {\n msg.viewtype = Viewtype::Text;\n msg.text =\n stock_str::msg_grp_name(context, &chat.name, &new_name, ContactId::SELF).await;\n msg.param.set_cmd(SystemMessage::GroupNameChanged);\n if !chat.name.is_empty() {\n msg.param.set(Param::Arg, &chat.name);\n }\n msg.id = send_msg(context, chat_id, &mut msg).await?;\n context.emit_msgs_changed(chat_id, msg.id);\n sync = Nosync;\n }\n context.emit_event(EventType::ChatModified(chat_id));\n chatlist_events::emit_chatlist_item_changed(context, chat_id);\n success = true;\n }\n }\n\n if !success {\n bail!(\"Failed to set name\");\n }\n if sync.into() && chat.name != new_name {\n let sync_name = new_name.to_string();\n chat.sync(context, SyncAction::Rename(sync_name))\n .await\n .log_err(context)\n .ok();\n }\n Ok(())\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ChatId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__136.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* See dc_set_draft() for more details about drafts.\n *\n * @memberof dc_context_t\n * @param context The context as created by dc_context_new().\n * @param chat_id The chat ID to get the draft for.\n * @return Message object.\n * Can be passed directly to dc_send_msg().\n * Must be freed using dc_msg_unref() after usage.\n * If there is no draft, NULL is returned.\n */\ndc_msg_t* dc_get_draft(dc_context_t* context, uint32_t chat_id)\n{\n\tuint32_t draft_msg_id = 0;\n\tdc_msg_t* draft_msg = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC\n\t || chat_id<=DC_CHAT_ID_LAST_SPECIAL) {\n\t\treturn NULL;\n\t}\n\n\tdraft_msg_id = get_draft_msg_id(context, chat_id);\n\tif (draft_msg_id==0) {\n\t\treturn NULL;\n\t}\n\n\tdraft_msg = dc_msg_new_untyped(context);\n\tif (!dc_msg_load_from_db(draft_msg, context, draft_msg_id)) {\n\t\tdc_msg_unref(draft_msg);\n\t\treturn NULL;\n\t}\n\n\treturn draft_msg;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn get_draft(self, context: &Context) -> Result> {\n if self.is_special() {\n return Ok(None);\n }\n match self.get_draft_msg_id(context).await? {\n Some(draft_msg_id) => {\n let msg = Message::load_from_db(context, draft_msg_id).await?;\n Ok(Some(msg))\n }\n None => Ok(None),\n }\n }", "rust_context": "async fn get_draft_msg_id(self, context: &Context) -> Result> {\n let msg_id: Option = context\n .sql\n .query_get_value(\n \"SELECT id FROM msgs WHERE chat_id=? AND state=?;\",\n (self, MessageState::OutDraft),\n )\n .await?;\n Ok(msg_id)\n }\n\npub fn is_special(self) -> bool {\n (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ChatId(u32);\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub async fn load_from_db(context: &Context, id: MsgId) -> Result {\n let message = Self::load_from_db_optional(context, id)\n .await?\n .with_context(|| format!(\"Message {id} does not exist\"))?;\n Ok(message)\n }", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__33.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "* using dc_set_config(context, \"selfavatar\", image).\n *\n * @memberof dc_contact_t\n * @param contact The contact object.\n * @return Path and file if the profile image, if any.\n * NULL otherwise.\n * Must be free()'d after usage.\n */\nchar* dc_contact_get_profile_image(const dc_contact_t* contact)\n{\n\tchar* selfavatar = NULL;\n\tchar* image_abs = NULL;\n\n\tif (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tif (contact->id==DC_CONTACT_ID_SELF) {\n\t\tselfavatar = dc_get_config(contact->context, \"selfavatar\");\n\t\tif (selfavatar && selfavatar[0]) {\n\t\t\timage_abs = dc_strdup(selfavatar);\n\t\t}\n\t}\n\telse {\n\t\timage_rel = dc_param_get(chat->param, DC_PARAM_PROFILE_IMAGE, NULL);\n\t\tif (image_rel && image_rel[0]) {\n\t\t\timage_abs = dc_get_abs_path(chat->context, image_rel);\n\t\t}\n\t}\n\ncleanup:\n\tfree(selfavatar);\n\treturn image_abs;\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub async fn get_profile_image(&self, context: &Context) -> Result> {\n if self.id == ContactId::SELF {\n if let Some(p) = context.get_config(Config::Selfavatar).await? {\n return Ok(Some(PathBuf::from(p)));\n }\n } else if let Some(image_rel) = self.param.get(Param::ProfileImage) {\n if !image_rel.is_empty() {\n return Ok(Some(get_abs_path(context, Path::new(image_rel))));\n }\n }\n Ok(None)\n }", "rust_context": "pub fn get(&self, key: Param) -> Option<&str> {\n self.inner.get(&key).map(|s| s.as_str())\n }\n\npub async fn get_config(&self, key: Config) -> Result> {\n let env_key = format!(\"DELTACHAT_{}\", key.as_ref().to_uppercase());\n if let Ok(value) = env::var(env_key) {\n return Ok(Some(value));\n }\n\n let value = match key {\n Config::Selfavatar => {\n let rel_path = self.sql.get_raw_config(key.as_ref()).await?;\n rel_path.map(|p| {\n get_abs_path(self, Path::new(&p))\n .to_string_lossy()\n .into_owned()\n })\n }\n Config::SysVersion => Some((*DC_VERSION_STR).clone()),\n Config::SysMsgsizeMaxRecommended => Some(format!(\"{RECOMMENDED_FILE_SIZE}\")),\n Config::SysConfigKeys => Some(get_config_keys_string()),\n _ => self.sql.get_raw_config(key.as_ref()).await?,\n };\n\n if value.is_some() {\n return Ok(value);\n }\n\n // Default values\n match key {\n Config::ConfiguredInboxFolder => Ok(Some(\"INBOX\".to_owned())),\n _ => Ok(key.get_str(\"default\").map(|s| s.to_string())),\n }\n }\n\npub fn is_empty(&self) -> bool {\n self.inner.is_empty()\n }\n\npub(crate) fn get_abs_path(context: &Context, path: &Path) -> PathBuf {\n if let Ok(p) = path.strip_prefix(\"$BLOBDIR\") {\n context.get_blobdir().join(p)\n } else {\n path.into()\n }\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ContactId(u32);\n\nimpl ContactId {\n /// Undefined contact. Used as a placeholder for trashed messages.\n pub const UNDEFINED: ContactId = ContactId::new(0);\n\n /// The owner of the account.\n ///\n /// The email-address is set by `set_config` using \"addr\".\n pub const SELF: ContactId = ContactId::new(1);\n\n /// ID of the contact for info messages.\n pub const INFO: ContactId = ContactId::new(2);\n\n /// ID of the contact for device messages.\n pub const DEVICE: ContactId = ContactId::new(5);\n pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9);\n\n /// Address to go with [`ContactId::DEVICE`].\n ///\n /// This is used by APIs which need to return an email address for this contact.\n pub const DEVICE_ADDR: &'static str = \"device@localhost\";\n}\n\npub enum Config {\n /// Email address, used in the `From:` field.\n Addr,\n\n /// IMAP server hostname.\n MailServer,\n\n /// IMAP server username.\n MailUser,\n\n /// IMAP server password.\n MailPw,\n\n /// IMAP server port.\n MailPort,\n\n /// IMAP server security (e.g. TLS, STARTTLS).\n MailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ImapCertificateChecks,\n\n /// SMTP server hostname.\n SendServer,\n\n /// SMTP server username.\n SendUser,\n\n /// SMTP server password.\n SendPw,\n\n /// SMTP server port.\n SendPort,\n\n /// SMTP server security (e.g. TLS, STARTTLS).\n SendSecurity,\n\n /// How to check SMTP server TLS certificates.\n SmtpCertificateChecks,\n\n /// Whether to use OAuth 2.\n ///\n /// Historically contained other bitflags, which are now deprecated.\n /// Should not be extended in the future, create new config keys instead.\n ServerFlags,\n\n /// True if SOCKS5 is enabled.\n ///\n /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.\n Socks5Enabled,\n\n /// SOCKS5 proxy server hostname or address.\n Socks5Host,\n\n /// SOCKS5 proxy server port.\n Socks5Port,\n\n /// SOCKS5 proxy server username.\n Socks5User,\n\n /// SOCKS5 proxy server password.\n Socks5Password,\n\n /// Own name to use in the `From:` field when sending messages.\n Displayname,\n\n /// Own status to display, sent in message footer.\n Selfstatus,\n\n /// Own avatar filename.\n Selfavatar,\n\n /// Send BCC copy to self.\n ///\n /// Should be enabled for multidevice setups.\n #[strum(props(default = \"1\"))]\n BccSelf,\n\n /// True if encryption is preferred according to Autocrypt standard.\n #[strum(props(default = \"1\"))]\n E2eeEnabled,\n\n /// True if Message Delivery Notifications (read receipts) should\n /// be sent and requested.\n #[strum(props(default = \"1\"))]\n MdnsEnabled,\n\n /// True if \"Sent\" folder should be watched for changes.\n #[strum(props(default = \"0\"))]\n SentboxWatch,\n\n /// True if chat messages should be moved to a separate folder.\n #[strum(props(default = \"1\"))]\n MvboxMove,\n\n /// Watch for new messages in the \"Mvbox\" (aka DeltaChat folder) only.\n ///\n /// This will not entirely disable other folders, e.g. the spam folder will also still\n /// be watched for new messages.\n #[strum(props(default = \"0\"))]\n OnlyFetchMvbox,\n\n /// Whether to show classic emails or only chat messages.\n #[strum(props(default = \"2\"))] // also change ShowEmails.default() on changes\n ShowEmails,\n\n /// Quality of the media files to send.\n #[strum(props(default = \"0\"))] // also change MediaQuality.default() on changes\n MediaQuality,\n\n /// If set to \"1\", on the first time `start_io()` is called after configuring,\n /// the newest existing messages are fetched.\n /// Existing recipients are added to the contact database regardless of this setting.\n #[strum(props(default = \"0\"))]\n FetchExistingMsgs,\n\n /// If set to \"1\", then existing messages are considered to be already fetched.\n /// This flag is reset after successful configuration.\n #[strum(props(default = \"1\"))]\n FetchedExistingMsgs,\n\n /// Type of the OpenPGP key to generate.\n #[strum(props(default = \"0\"))]\n KeyGenType,\n\n /// Timer in seconds after which the message is deleted from the\n /// server.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n ///\n /// Value 1 is treated as \"delete at once\": messages are deleted\n /// immediately, without moving to DeltaChat folder.\n #[strum(props(default = \"0\"))]\n DeleteServerAfter,\n\n /// Timer in seconds after which the message is deleted from the\n /// device.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n #[strum(props(default = \"0\"))]\n DeleteDeviceAfter,\n\n /// Move messages to the Trash folder instead of marking them \"\\Deleted\". Overrides\n /// `ProviderOptions::delete_to_trash`.\n DeleteToTrash,\n\n /// Save raw MIME messages with headers in the database if true.\n SaveMimeHeaders,\n\n /// The primary email address. Also see `SecondaryAddrs`.\n ConfiguredAddr,\n\n /// Configured IMAP server hostname.\n ConfiguredMailServer,\n\n /// Configured IMAP server username.\n ConfiguredMailUser,\n\n /// Configured IMAP server password.\n ConfiguredMailPw,\n\n /// Configured IMAP server port.\n ConfiguredMailPort,\n\n /// Configured IMAP server security (e.g. TLS, STARTTLS).\n ConfiguredMailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ConfiguredImapCertificateChecks,\n\n /// Configured SMTP server hostname.\n ConfiguredSendServer,\n\n /// Configured SMTP server username.\n ConfiguredSendUser,\n\n /// Configured SMTP server password.\n ConfiguredSendPw,\n\n /// Configured SMTP server port.\n ConfiguredSendPort,\n\n /// How to check SMTP server TLS certificates.\n ConfiguredSmtpCertificateChecks,\n\n /// Whether OAuth 2 is used with configured provider.\n ConfiguredServerFlags,\n\n /// Configured SMTP server security (e.g. TLS, STARTTLS).\n ConfiguredSendSecurity,\n\n /// Configured folder for incoming messages.\n ConfiguredInboxFolder,\n\n /// Configured folder for chat messages.\n ConfiguredMvboxFolder,\n\n /// Configured \"Sent\" folder.\n ConfiguredSentboxFolder,\n\n /// Configured \"Trash\" folder.\n ConfiguredTrashFolder,\n\n /// Unix timestamp of the last successful configuration.\n ConfiguredTimestamp,\n\n /// ID of the configured provider from the provider database.\n ConfiguredProvider,\n\n /// True if account is configured.\n Configured,\n\n /// True if account is a chatmail account.\n IsChatmail,\n\n /// All secondary self addresses separated by spaces\n /// (`addr1@example.org addr2@example.org addr3@example.org`)\n SecondaryAddrs,\n\n /// Read-only core version string.\n #[strum(serialize = \"sys.version\")]\n SysVersion,\n\n /// Maximal recommended attachment size in bytes.\n #[strum(serialize = \"sys.msgsize_max_recommended\")]\n SysMsgsizeMaxRecommended,\n\n /// Space separated list of all config keys available.\n #[strum(serialize = \"sys.config_keys\")]\n SysConfigKeys,\n\n /// True if it is a bot account.\n Bot,\n\n /// True when to skip initial start messages in groups.\n #[strum(props(default = \"0\"))]\n SkipStartMessages,\n\n /// Whether we send a warning if the password is wrong (set to false when we send a warning\n /// because we do not want to send a second warning)\n #[strum(props(default = \"0\"))]\n NotifyAboutWrongPw,\n\n /// If a warning about exceeding quota was shown recently,\n /// this is the percentage of quota at the time the warning was given.\n /// Unset, when quota falls below minimal warning threshold again.\n QuotaExceeding,\n\n /// address to webrtc instance to use for videochats\n WebrtcInstance,\n\n /// Timestamp of the last time housekeeping was run\n LastHousekeeping,\n\n /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.\n LastCantDecryptOutgoingMsgs,\n\n /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.\n #[strum(props(default = \"60\"))]\n ScanAllFoldersDebounceSecs,\n\n /// Whether to avoid using IMAP IDLE even if the server supports it.\n ///\n /// This is a developer option for testing \"fake idle\".\n #[strum(props(default = \"0\"))]\n DisableIdle,\n\n /// Defines the max. size (in bytes) of messages downloaded automatically.\n /// 0 = no limit.\n #[strum(props(default = \"0\"))]\n DownloadLimit,\n\n /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.\n #[strum(props(default = \"1\"))]\n SyncMsgs,\n\n /// Space-separated list of all the authserv-ids which we believe\n /// may be the one of our email server.\n ///\n /// See `crate::authres::update_authservid_candidates`.\n AuthservIdCandidates,\n\n /// Make all outgoing messages with Autocrypt header \"multipart/signed\".\n SignUnencrypted,\n\n /// Let the core save all events to the database.\n /// This value is used internally to remember the MsgId of the logging xdc\n #[strum(props(default = \"0\"))]\n DebugLogging,\n\n /// Last message processed by the bot.\n LastMsgId,\n\n /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by\n /// default.\n ///\n /// This is not supposed to be changed by UIs and only used for testing.\n #[strum(props(default = \"172800\"))]\n GossipPeriod,\n\n /// Feature flag for verified 1:1 chats; the UI should set it\n /// to 1 if it supports verified 1:1 chats.\n /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,\n /// and when the key changes, an info message is posted into the chat.\n /// 0=Nothing else happens when the key changes.\n /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true\n /// until `chat_id.accept()` is called.\n #[strum(props(default = \"0\"))]\n VerifiedOneOnOneChats,\n\n /// Row ID of the key in the `keypairs` table\n /// used for signatures, encryption to self and included in `Autocrypt` header.\n KeyId,\n\n /// This key is sent to the self_reporting bot so that the bot can recognize the user\n /// without storing the email address\n SelfReportingId,\n\n /// MsgId of webxdc map integration.\n WebxdcIntegration,\n\n /// Iroh secret key.\n IrohSecretKey,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}\n\npub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__43.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_is_increation(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->context==NULL) {\n\t\treturn 0;\n\t}\n\n\treturn DC_MSG_NEEDS_ATTACHMENT(msg->type) && msg->state==DC_STATE_OUT_PREPARING;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn is_increation(&self) -> bool {\n self.viewtype.has_file() && self.state == MessageState::OutPreparing\n }", "rust_context": "pub fn has_file(&self) -> bool {\n match self {\n Viewtype::Unknown => false,\n Viewtype::Text => false,\n Viewtype::Image => true,\n Viewtype::Gif => true,\n Viewtype::Sticker => true,\n Viewtype::Audio => true,\n Viewtype::Voice => true,\n Viewtype::Video => true,\n Viewtype::File => true,\n Viewtype::VideochatInvitation => false,\n Viewtype::Webxdc => true,\n Viewtype::Vcard => true,\n }\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum MessageState {\n /// Undefined message state.\n #[default]\n Undefined = 0,\n\n /// Incoming *fresh* message. Fresh messages are neither noticed\n /// nor seen and are typically shown in notifications.\n InFresh = 10,\n\n /// Incoming *noticed* message. E.g. chat opened but message not\n /// yet read - noticed messages are not counted as unread but did\n /// not marked as read nor resulted in MDNs.\n InNoticed = 13,\n\n /// Incoming message, really *seen* by the user. Marked as read on\n /// IMAP and MDN may be sent.\n InSeen = 16,\n\n /// For files which need time to be prepared before they can be\n /// sent, the message enters this state before\n /// OutPending.\n OutPreparing = 18,\n\n /// Message saved as draft.\n OutDraft = 19,\n\n /// The user has pressed the \"send\" button but the message is not\n /// yet sent and is pending in some way. Maybe we're offline (no\n /// checkmark).\n OutPending = 20,\n\n /// *Unrecoverable* error (*recoverable* errors result in pending\n /// messages).\n OutFailed = 24,\n\n /// Outgoing message successfully delivered to server (one\n /// checkmark). Note, that already delivered messages may get into\n /// the OutFailed state if we get such a hint from the server.\n OutDelivered = 26,\n\n /// Outgoing message read by the recipient (two checkmarks; this\n /// requires goodwill on the receiver's side)\n OutMdnRcvd = 28,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__59.txt"} {"c_path": "projects/deltachat-core/c/dc_location.c", "c_func": "char* dc_get_message_kml(dc_context_t* context, time_t timestamp, double latitude, double longitude)\n{\n\tchar* timestamp_str = NULL;\n\tchar* latitude_str = NULL;\n\tchar* longitude_str = NULL;\n\tchar* ret = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\ttimestamp_str = get_kml_timestamp(timestamp);\n\tlatitude_str = dc_ftoa(latitude);\n\tlongitude_str = dc_ftoa(longitude);\n\n\tret = dc_mprintf(\n\t\t\"\\n\"\n\t\t\"\\n\"\n\t\t\t\"\\n\"\n\t\t\t\t\"\"\n\t\t\t\t\t\"%s\"\n\t\t\t\t\t\"%s,%s\"\n\t\t\t\t\"\\n\"\n\t\t\t\"\\n\"\n\t\t\"\",\n\t\ttimestamp_str,\n\t\tlongitude_str, // reverse order!\n\t\tlatitude_str);\n\ncleanup:\n\tfree(latitude_str);\n\tfree(longitude_str);\n\tfree(timestamp_str);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/location.rs", "rust_func": "pub fn get_message_kml(timestamp: i64, latitude: f64, longitude: f64) -> String {\n format!(\n \"\\n\\\n \\n\\\n \\n\\\n \\\n {}\\\n {},{}\\\n \\n\\\n \\n\\\n \",\n get_kml_timestamp(timestamp),\n longitude,\n latitude,\n )\n}", "rust_context": "", "rust_imports": "use std::time::Duration;\nuse anyhow::{ensure, Context as _, Result};\nuse async_channel::Receiver;\nuse quick_xml::events::{BytesEnd, BytesStart, BytesText};\nuse tokio::time::timeout;\nuse crate::chat::{self, ChatId};\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::tools::{duration_to_str, time};\nuse crate::{chatlist_events, stock_str};\nuse super::*;\nuse crate::config::Config;\nuse crate::message::MessageState;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{TestContext, TestContextManager};\nuse crate::tools::SystemTime;", "rustrepotrans_file": "projects__deltachat-core__rust__location__.rs__function__18.txt"} {"c_path": "projects/deltachat-core/c/dc_location.c", "c_func": "void dc_send_locations_to_chat(dc_context_t* context, uint32_t chat_id,\n int seconds)\n{\n\tsqlite3_stmt* stmt = NULL;\n\ttime_t now = time(NULL);\n\tdc_msg_t* msg = NULL;\n\tchar* stock_str = NULL;\n\tint is_sending_locations_before = 0;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || seconds<0\n\t || chat_id<=DC_CHAT_ID_LAST_SPECIAL) {\n\t\tgoto cleanup;\n\t}\n\n\tis_sending_locations_before = dc_is_sending_locations_to_chat(context, chat_id);\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"UPDATE chats \"\n\t\t\" SET locations_send_begin=?, \"\n\t\t\" locations_send_until=? \"\n\t\t\" WHERE id=?\");\n\tsqlite3_bind_int64(stmt, 1, seconds? now : 0);\n\tsqlite3_bind_int64(stmt, 2, seconds? now+seconds : 0);\n\tsqlite3_bind_int (stmt, 3, chat_id);\n\tsqlite3_step(stmt);\n\n\t// add/sent status message.\n\t// as disable also happens after a timeout, this is not sent explicitly.\n\tif (seconds && !is_sending_locations_before) {\n\t\tmsg = dc_msg_new(context, DC_MSG_TEXT);\n\t\tmsg->text = dc_stock_system_msg(context, DC_STR_MSGLOCATIONENABLED, NULL, NULL, 0);\n\t\tdc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_LOCATION_STREAMING_ENABLED);\n\t\tdc_send_msg(context, chat_id, msg);\n\t}\n\telse if(!seconds && is_sending_locations_before) {\n\t\tstock_str = dc_stock_system_msg(context, DC_STR_MSGLOCATIONDISABLED, NULL, NULL, 0);\n\t\tdc_add_device_msg(context, chat_id, stock_str);\n\t}\n\n\t// update eg. the \"location-sending\"-icon\n\tcontext->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0);\n\n\tif (seconds) {\n\t\tschedule_MAYBE_SEND_LOCATIONS(context, 0);\n\t\tdc_job_add(context, DC_JOB_MAYBE_SEND_LOC_ENDED, chat_id, NULL, seconds+1);\n\t}\n\ncleanup:\n\tfree(stock_str);\n\tdc_msg_unref(msg);\n\tsqlite3_finalize(stmt);\n}", "rust_path": "projects/deltachat-core/rust/location.rs", "rust_func": "pub async fn send_locations_to_chat(\n context: &Context,\n chat_id: ChatId,\n seconds: i64,\n) -> Result<()> {\n ensure!(seconds >= 0);\n ensure!(!chat_id.is_special());\n let now = time();\n let is_sending_locations_before = is_sending_locations_to_chat(context, Some(chat_id)).await?;\n context\n .sql\n .execute(\n \"UPDATE chats \\\n SET locations_send_begin=?, \\\n locations_send_until=? \\\n WHERE id=?\",\n (\n if 0 != seconds { now } else { 0 },\n if 0 != seconds { now + seconds } else { 0 },\n chat_id,\n ),\n )\n .await?;\n if 0 != seconds && !is_sending_locations_before {\n let mut msg = Message::new(Viewtype::Text);\n msg.text = stock_str::msg_location_enabled(context).await;\n msg.param.set_cmd(SystemMessage::LocationStreamingEnabled);\n chat::send_msg(context, chat_id, &mut msg)\n .await\n .unwrap_or_default();\n } else if 0 == seconds && is_sending_locations_before {\n let stock_str = stock_str::msg_location_disabled(context).await;\n chat::add_info_msg(context, chat_id, &stock_str, now).await?;\n }\n context.emit_event(EventType::ChatModified(chat_id));\n chatlist_events::emit_chatlist_item_changed(context, chat_id);\n if 0 != seconds {\n context.scheduler.interrupt_location().await;\n }\n Ok(())\n}", "rust_context": "pub fn emit_event(&self, event: EventType) {\n {\n let lock = self.debug_logging.read().expect(\"RwLock is poisoned\");\n if let Some(debug_logging) = &*lock {\n debug_logging.log_event(event.clone());\n }\n }\n self.events.emit(Event {\n id: self.id,\n typ: event,\n });\n }\n\npub fn is_special(self) -> bool {\n (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)\n }\n\npub async fn is_sending_locations_to_chat(\n context: &Context,\n chat_id: Option,\n) -> Result {\n let exists = match chat_id {\n Some(chat_id) => {\n context\n .sql\n .exists(\n \"SELECT COUNT(id) FROM chats WHERE id=? AND locations_send_until>?;\",\n (chat_id, time()),\n )\n .await?\n }\n None => {\n context\n .sql\n .exists(\n \"SELECT COUNT(id) FROM chats WHERE locations_send_until>?;\",\n (time(),),\n )\n .await?\n }\n };\n Ok(exists)\n}\n\npub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result {\n if chat_id.is_unset() {\n let forwards = msg.param.get(Param::PrepForwards);\n if let Some(forwards) = forwards {\n for forward in forwards.split(' ') {\n if let Ok(msg_id) = forward.parse::().map(MsgId::new) {\n if let Ok(mut msg) = Message::load_from_db(context, msg_id).await {\n send_msg_inner(context, chat_id, &mut msg).await?;\n };\n }\n }\n msg.param.remove(Param::PrepForwards);\n msg.update_param(context).await?;\n }\n return send_msg_inner(context, chat_id, msg).await;\n }\n\n if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing {\n msg.param.remove(Param::GuaranteeE2ee);\n msg.param.remove(Param::ForcePlaintext);\n msg.update_param(context).await?;\n }\n send_msg_inner(context, chat_id, msg).await\n}\n\npub async fn execute(\n &self,\n query: &str,\n params: impl rusqlite::Params + Send,\n ) -> Result {\n self.call_write(move |conn| {\n let res = conn.execute(query, params)?;\n Ok(res)\n })\n .await\n }\n\npub(crate) fn time() -> i64 {\n SystemTime::now()\n .duration_since(SystemTime::UNIX_EPOCH)\n .unwrap_or_default()\n .as_secs() as i64\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\nimpl Message {\n /// Creates a new message with given view type.\n pub fn new(viewtype: Viewtype) -> Self {\n Message {\n viewtype,\n ..Default::default()\n }\n }\n}\n\npub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}\n\npub(crate) async fn msg_location_enabled(context: &Context) -> String {\n translated(context, StockMessage::MsgLocationEnabled).await\n}\n\npub enum EventType {\n /// The library-user may write an informational string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Info(String),\n\n /// Emitted when SMTP connection is established and login was successful.\n SmtpConnected(String),\n\n /// Emitted when IMAP connection is established and login was successful.\n ImapConnected(String),\n\n /// Emitted when a message was successfully sent to the SMTP server.\n SmtpMessageSent(String),\n\n /// Emitted when an IMAP message has been marked as deleted\n ImapMessageDeleted(String),\n\n /// Emitted when an IMAP message has been moved\n ImapMessageMoved(String),\n\n /// Emitted before going into IDLE on the Inbox folder.\n ImapInboxIdle,\n\n /// Emitted when an new file in the $BLOBDIR was created\n NewBlobFile(String),\n\n /// Emitted when an file in the $BLOBDIR was deleted\n DeletedBlobFile(String),\n\n /// The library-user should write a warning string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Warning(String),\n\n /// The library-user should report an error to the end-user.\n ///\n /// As most things are asynchronous, things may go wrong at any time and the user\n /// should not be disturbed by a dialog or so. Instead, use a bubble or so.\n ///\n /// However, for ongoing processes (eg. configure())\n /// or for functions that are expected to fail (eg. dc_continue_key_transfer())\n /// it might be better to delay showing these events until the function has really\n /// failed (returned false). It should be sufficient to report only the *last* error\n /// in a messasge box then.\n Error(String),\n\n /// An action cannot be performed because the user is not in the group.\n /// Reported eg. after a call to\n /// dc_set_chat_name(), dc_set_chat_profile_image(),\n /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(),\n /// dc_send_text_msg() or another sending function.\n ErrorSelfNotInGroup(String),\n\n /// Messages or chats changed. One or more messages or chats changed for various\n /// reasons in the database:\n /// - Messages sent, received or removed\n /// - Chats created, deleted or archived\n /// - A draft has been set\n ///\n MsgsChanged {\n /// Set if only a single chat is affected by the changes, otherwise 0.\n chat_id: ChatId,\n\n /// Set if only a single message is affected by the changes, otherwise 0.\n msg_id: MsgId,\n },\n\n /// Reactions for the message changed.\n ReactionsChanged {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message for which reactions were changed.\n msg_id: MsgId,\n\n /// ID of the contact whose reaction set is changed.\n contact_id: ContactId,\n },\n\n /// There is a fresh message. Typically, the user will show an notification\n /// when receiving this message.\n ///\n /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event.\n IncomingMsg {\n /// ID of the chat where the message is assigned.\n chat_id: ChatId,\n\n /// ID of the message.\n msg_id: MsgId,\n },\n\n /// Downloading a bunch of messages just finished.\n IncomingMsgBunch,\n\n /// Messages were seen or noticed.\n /// chat id is always set.\n MsgsNoticed(ChatId),\n\n /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to\n /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state().\n MsgDelivered {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was successfully sent.\n msg_id: MsgId,\n },\n\n /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_FAILED, see dc_msg_get_state().\n MsgFailed {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that could not be sent.\n msg_id: MsgId,\n },\n\n /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state().\n MsgRead {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was read.\n msg_id: MsgId,\n },\n\n /// A single message was deleted.\n ///\n /// This event means that the message will no longer appear in the messagelist.\n /// UI should remove the message from the messagelist\n /// in response to this event if the message is currently displayed.\n ///\n /// The message may have been explicitly deleted by the user or expired.\n /// Internally the message may have been removed from the database,\n /// moved to the trash chat or hidden.\n ///\n /// This event does not indicate the message\n /// deletion from the server.\n MsgDeleted {\n /// ID of the chat where the message was prior to deletion.\n /// Never 0 or trash chat.\n chat_id: ChatId,\n\n /// ID of the deleted message. Never 0.\n msg_id: MsgId,\n },\n\n /// Chat changed. The name or the image of a chat group was changed or members were added or removed.\n /// Or the verify state of a chat has changed.\n /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat()\n /// and dc_remove_contact_from_chat().\n ///\n /// This event does not include ephemeral timer modification, which\n /// is a separate event.\n ChatModified(ChatId),\n\n /// Chat ephemeral timer changed.\n ChatEphemeralTimerModified {\n /// Chat ID.\n chat_id: ChatId,\n\n /// New ephemeral timer value.\n timer: EphemeralTimer,\n },\n\n /// Contact(s) created, renamed, blocked, deleted or changed their \"recently seen\" status.\n ///\n /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected.\n ContactsChanged(Option),\n\n /// Location of one or more contact has changed.\n ///\n /// @param data1 (u32) contact_id of the contact for which the location has changed.\n /// If the locations of several contacts have been changed,\n /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`.\n LocationChanged(Option),\n\n /// Inform about the configuration progress started by configure().\n ConfigureProgress {\n /// Progress.\n ///\n /// 0=error, 1-999=progress in permille, 1000=success and done\n progress: usize,\n\n /// Progress comment or error, something to display to the user.\n comment: Option,\n },\n\n /// Inform about the import/export progress started by imex().\n ///\n /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done\n /// @param data2 0\n ImexProgress(usize),\n\n /// A file has been exported. A file has been written by imex().\n /// This event may be sent multiple times by a single call to imex().\n ///\n /// A typical purpose for a handler of this event may be to make the file public to some system\n /// services.\n ///\n /// @param data2 0\n ImexFileWritten(PathBuf),\n\n /// Progress information of a secure-join handshake from the view of the inviter\n /// (Alice, the person who shows the QR code).\n ///\n /// These events are typically sent after a joiner has scanned the QR code\n /// generated by dc_get_securejoin_qr().\n SecurejoinInviterProgress {\n /// ID of the contact that wants to join.\n contact_id: ContactId,\n\n /// Progress as:\n /// 300=vg-/vc-request received, typically shown as \"bob@addr joins\".\n /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as \"bob@addr verified\".\n /// 800=contact added to chat, shown as \"bob@addr securely joined GROUP\". Only for the verified-group-protocol.\n /// 1000=Protocol finished for this contact.\n progress: usize,\n },\n\n /// Progress information of a secure-join handshake from the view of the joiner\n /// (Bob, the person who scans the QR code).\n /// The events are typically sent while dc_join_securejoin(), which\n /// may take some time, is executed.\n SecurejoinJoinerProgress {\n /// ID of the inviting contact.\n contact_id: ContactId,\n\n /// Progress as:\n /// 400=vg-/vc-request-with-auth sent, typically shown as \"alice@addr verified, introducing myself.\"\n /// (Bob has verified alice and waits until Alice does the same for him)\n /// 1000=vg-member-added/vc-contact-confirm received\n progress: usize,\n },\n\n /// The connectivity to the server changed.\n /// This means that you should refresh the connectivity view\n /// and possibly the connectivtiy HTML; see dc_get_connectivity() and\n /// dc_get_connectivity_html() for details.\n ConnectivityChanged,\n\n /// The user's avatar changed.\n /// Deprecated by `ConfigSynced`.\n SelfavatarChanged,\n\n /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For\n /// uniformity this is emitted on the source device too. The value isn't here, otherwise it\n /// would be logged which might not be good for privacy.\n ConfigSynced {\n /// Configuration key.\n key: Config,\n },\n\n /// Webxdc status update received.\n WebxdcStatusUpdate {\n /// Message ID.\n msg_id: MsgId,\n\n /// Status update ID.\n status_update_serial: StatusUpdateSerial,\n },\n\n /// Data received over an ephemeral peer channel.\n WebxdcRealtimeData {\n /// Message ID.\n msg_id: MsgId,\n\n /// Realtime data.\n data: Vec,\n },\n\n /// Inform that a message containing a webxdc instance has been deleted.\n WebxdcInstanceDeleted {\n /// ID of the deleted message.\n msg_id: MsgId,\n },\n\n /// Tells that the Background fetch was completed (or timed out).\n /// This event acts as a marker, when you reach this event you can be sure\n /// that all events emitted during the background fetch were processed.\n ///\n /// This event is only emitted by the account manager\n AccountsBackgroundFetchDone,\n /// Inform that set of chats or the order of the chats in the chatlist has changed.\n ///\n /// Sometimes this is emitted together with `UIChatlistItemChanged`.\n ChatlistChanged,\n\n /// Inform that a single chat list item changed and needs to be rerendered.\n /// 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.\n ChatlistItemChanged {\n /// ID of the changed chat\n chat_id: Option,\n },\n\n /// Event for using in tests, e.g. as a fence between normally generated events.\n #[cfg(test)]\n Test,\n\n /// Inform than some events have been skipped due to event channel overflow.\n EventChannelOverflow {\n /// Number of events skipped.\n n: u64,\n },\n}\n\npub(crate) fn emit_chatlist_item_changed(context: &Context, chat_id: ChatId) {\n context.emit_event(EventType::ChatlistItemChanged {\n chat_id: Some(chat_id),\n });\n}\n\npub(crate) async fn interrupt_location(&self) {\n let inner = self.inner.read().await;\n if let InnerSchedulerState::Started(ref scheduler) = *inner {\n scheduler.interrupt_location();\n }\n }\n\npub(crate) async fn add_info_msg(\n context: &Context,\n chat_id: ChatId,\n text: &str,\n timestamp: i64,\n) -> Result {\n add_info_msg_with_cmd(\n context,\n chat_id,\n text,\n SystemMessage::Unknown,\n timestamp,\n None,\n None,\n None,\n )\n .await\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}", "rust_imports": "use std::time::Duration;\nuse anyhow::{ensure, Context as _, Result};\nuse async_channel::Receiver;\nuse quick_xml::events::{BytesEnd, BytesStart, BytesText};\nuse tokio::time::timeout;\nuse crate::chat::{self, ChatId};\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::tools::{duration_to_str, time};\nuse crate::{chatlist_events, stock_str};\nuse super::*;\nuse crate::config::Config;\nuse crate::message::MessageState;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{TestContext, TestContextManager};\nuse crate::tools::SystemTime;", "rustrepotrans_file": "projects__deltachat-core__rust__location__.rs__function__7.txt"} {"c_path": "projects/deltachat-core/c/dc_location.c", "c_func": "dc_array_t* dc_get_locations(dc_context_t* context,\n uint32_t chat_id, uint32_t contact_id,\n time_t timestamp_from, time_t timestamp_to)\n{\n\tdc_array_t* ret = dc_array_new_typed(context, DC_ARRAY_LOCATIONS, 500);\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tif (timestamp_to==0) {\n\t\ttimestamp_to = time(NULL) + 10/*messages may be inserted by another thread just now*/;\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\t\"SELECT l.id, l.latitude, l.longitude, l.accuracy, l.timestamp, l.independent, \"\n\t\t\t\" m.id, l.from_id, l.chat_id, m.txt \"\n\t\t\t\" FROM locations l \"\n\t\t\t\" LEFT JOIN msgs m ON l.id=m.location_id \"\n\t\t\t\" WHERE (? OR l.chat_id=?) \"\n\t\t\t\" AND (? OR l.from_id=?) \"\n\t\t\t\" AND (l.independent=1 OR (l.timestamp>=? AND l.timestamp<=?)) \"\n\t\t\t\" ORDER BY l.timestamp DESC, l.id DESC, m.id DESC;\");\n\tsqlite3_bind_int(stmt, 1, chat_id==0? 1 : 0);\n\tsqlite3_bind_int(stmt, 2, chat_id);\n\tsqlite3_bind_int(stmt, 3, contact_id==0? 1 : 0);\n\tsqlite3_bind_int(stmt, 4, contact_id);\n\tsqlite3_bind_int(stmt, 5, timestamp_from);\n\tsqlite3_bind_int(stmt, 6, timestamp_to);\n\n\twhile (sqlite3_step(stmt)==SQLITE_ROW) {\n struct _dc_location* loc = calloc(1, sizeof(struct _dc_location));\n if (loc==NULL) {\n\t\t\tgoto cleanup;\n }\n\n\t\tloc->location_id = sqlite3_column_double(stmt, 0);\n\t\tloc->latitude = sqlite3_column_double(stmt, 1);\n\t\tloc->longitude = sqlite3_column_double(stmt, 2);\n\t\tloc->accuracy = sqlite3_column_double(stmt, 3);\n\t\tloc->timestamp = sqlite3_column_int64 (stmt, 4);\n\t\tloc->independent = sqlite3_column_int (stmt, 5);\n\t\tloc->msg_id = sqlite3_column_int (stmt, 6);\n\t\tloc->contact_id = sqlite3_column_int (stmt, 7);\n\t\tloc->chat_id = sqlite3_column_int (stmt, 8);\n\t\tif (loc->msg_id) {\n\t\t\tconst char* txt = (const char*)sqlite3_column_text(stmt, 9);\n\t\t\tif (is_marker(txt)) {\n\t\t\t\tloc->marker = strdup(txt);\n\t\t\t}\n\t\t}\n\n\t\tdc_array_add_ptr(ret, loc);\n\t}\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/location.rs", "rust_func": "pub async fn get_range(\n context: &Context,\n chat_id: Option,\n contact_id: Option,\n timestamp_from: i64,\n mut timestamp_to: i64,\n) -> Result> {\n if timestamp_to == 0 {\n timestamp_to = time() + 10;\n }\n\n let (disable_chat_id, chat_id) = match chat_id {\n Some(chat_id) => (0, chat_id),\n None => (1, ChatId::new(0)), // this ChatId is unused\n };\n let (disable_contact_id, contact_id) = match contact_id {\n Some(contact_id) => (0, contact_id),\n None => (1, 0), // this contact_id is unused\n };\n let list = context\n .sql\n .query_map(\n \"SELECT l.id, l.latitude, l.longitude, l.accuracy, l.timestamp, l.independent, \\\n COALESCE(m.id, 0) AS msg_id, l.from_id, l.chat_id, COALESCE(m.txt, '') AS txt \\\n FROM locations l LEFT JOIN msgs m ON l.id=m.location_id WHERE (? OR l.chat_id=?) \\\n AND (? OR l.from_id=?) \\\n AND (l.independent=1 OR (l.timestamp>=? AND l.timestamp<=?)) \\\n ORDER BY l.timestamp DESC, l.id DESC, msg_id DESC;\",\n (\n disable_chat_id,\n chat_id,\n disable_contact_id,\n contact_id as i32,\n timestamp_from,\n timestamp_to,\n ),\n |row| {\n let msg_id = row.get(6)?;\n let txt: String = row.get(9)?;\n let marker = if msg_id != 0 && is_marker(&txt) {\n Some(txt)\n } else {\n None\n };\n let loc = Location {\n location_id: row.get(0)?,\n latitude: row.get(1)?,\n longitude: row.get(2)?,\n accuracy: row.get(3)?,\n timestamp: row.get(4)?,\n independent: row.get(5)?,\n msg_id,\n contact_id: row.get(7)?,\n chat_id: row.get(8)?,\n marker,\n };\n Ok(loc)\n },\n |locations| {\n let mut ret = Vec::new();\n\n for location in locations {\n ret.push(location?);\n }\n Ok(ret)\n },\n )\n .await?;\n Ok(list)\n}", "rust_context": "fn is_marker(txt: &str) -> bool {\n let mut chars = txt.chars();\n if let Some(c) = chars.next() {\n !c.is_whitespace() && chars.next().is_none()\n } else {\n false\n }\n}\n\npub(crate) fn time() -> i64 {\n SystemTime::now()\n .duration_since(SystemTime::UNIX_EPOCH)\n .unwrap_or_default()\n .as_secs() as i64\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub async fn query_map(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n mut g: G,\n ) -> Result\n where\n F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result,\n G: Send + FnMut(rusqlite::MappedRows) -> Result,\n H: Send + 'static,\n {\n self.call(move |conn| {\n let mut stmt = conn.prepare(sql)?;\n let res = stmt.query_map(params, f)?;\n g(res)\n })\n .await\n }\n\npub const fn new(id: u32) -> ChatId {\n ChatId(id)\n }\n \npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub struct Location {\n /// Row ID of the location.\n pub location_id: u32,\n\n /// Location latitude.\n pub latitude: f64,\n\n /// Location longitude.\n pub longitude: f64,\n\n /// Nonstandard `accuracy` attribute of the `coordinates` tag.\n pub accuracy: f64,\n\n /// Location timestamp in seconds.\n pub timestamp: i64,\n\n /// Contact ID.\n pub contact_id: ContactId,\n\n /// Message ID.\n pub msg_id: u32,\n\n /// Chat ID.\n pub chat_id: ChatId,\n\n /// A marker string, such as an emoji, to be displayed on top of the location.\n pub marker: Option,\n\n /// Whether location is independent, i.e. not part of the path.\n pub independent: u32,\n}", "rust_imports": "use std::time::Duration;\nuse anyhow::{ensure, Context as _, Result};\nuse async_channel::Receiver;\nuse quick_xml::events::{BytesEnd, BytesStart, BytesText};\nuse tokio::time::timeout;\nuse crate::chat::{self, ChatId};\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::tools::{duration_to_str, time};\nuse crate::{chatlist_events, stock_str};\nuse super::*;\nuse crate::config::Config;\nuse crate::message::MessageState;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{TestContext, TestContextManager};\nuse crate::tools::SystemTime;", "rustrepotrans_file": "projects__deltachat-core__rust__location__.rs__function__10.txt"} {"c_path": "projects/deltachat-core/c/dc_location.c", "c_func": "static int is_marker(const char* txt)\n{\n\tif (txt) {\n\t\tint len = dc_utf8_strlen(txt);\n\t\tif (len==1 && !isspace(txt[0])) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}", "rust_path": "projects/deltachat-core/rust/location.rs", "rust_func": "fn is_marker(txt: &str) -> bool {\n let mut chars = txt.chars();\n if let Some(c) = chars.next() {\n !c.is_whitespace() && chars.next().is_none()\n } else {\n false\n }\n}", "rust_context": "", "rust_imports": "use std::time::Duration;\nuse anyhow::{ensure, Context as _, Result};\nuse async_channel::Receiver;\nuse quick_xml::events::{BytesEnd, BytesStart, BytesText};\nuse tokio::time::timeout;\nuse crate::chat::{self, ChatId};\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::tools::{duration_to_str, time};\nuse crate::{chatlist_events, stock_str};\nuse super::*;\nuse crate::config::Config;\nuse crate::message::MessageState;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{TestContext, TestContextManager};\nuse crate::tools::SystemTime;", "rustrepotrans_file": "projects__deltachat-core__rust__location__.rs__function__11.txt"} {"c_path": "projects/deltachat-core/c/dc_configure.c", "c_func": "* function not under the control of the core (eg. #DC_EVENT_HTTP_GET). Another\n * reason for dc_stop_ongoing_process() not to wait is that otherwise it\n * would be GUI-blocking and should be started in another thread then; this\n * would make things even more complicated.\n *\n * Typical ongoing processes are started by dc_configure(),\n * dc_initiate_key_transfer() or dc_imex(). As there is always at most only\n * one onging process at the same time, there is no need to define _which_ process to exit.\n *\n * @memberof dc_context_t\n * @param context The context object.\n * @return None.\n */\nvoid dc_stop_ongoing_process(dc_context_t* context)\n{\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\treturn;\n\t}\n\n\tif (context->ongoing_running && context->shall_stop_ongoing==0)\n\t{\n\t\tdc_log_info(context, 0, \"Signaling the ongoing process to stop ASAP.\");\n\t\tcontext->shall_stop_ongoing = 1;\n\t}\n\telse\n\t{\n\t\tdc_log_info(context, 0, \"No ongoing process to stop.\");\n\t}\n}", "rust_path": "projects/deltachat-core/rust/context.rs", "rust_func": "pub async fn stop_ongoing(&self) {\n let mut s = self.running_state.write().await;\n match &*s {\n RunningState::Running { cancel_sender } => {\n if let Err(err) = cancel_sender.send(()).await {\n warn!(self, \"could not cancel ongoing: {:#}\", err);\n }\n info!(self, \"Signaling the ongoing process to stop ASAP.\",);\n *s = RunningState::ShallStop {\n request: tools::Time::now(),\n };\n }\n RunningState::ShallStop { .. } | RunningState::Stopped => {\n info!(self, \"No ongoing process to stop.\",);\n }\n }\n }", "rust_context": "macro_rules! info {\n ($ctx:expr, $msg:expr) => {\n info!($ctx, $msg,)\n };\n ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{\n let formatted = format!($msg, $($args),*);\n let full = format!(\"{file}:{line}: {msg}\",\n file = file!(),\n line = line!(),\n msg = &formatted);\n $ctx.emit_event($crate::EventType::Info(full));\n }};\n}\n\nmacro_rules! warn {\n ($ctx:expr, $msg:expr) => {\n warn!($ctx, $msg,)\n };\n ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{\n let formatted = format!($msg, $($args),*);\n let full = format!(\"{file}:{line}: {msg}\",\n file = file!(),\n line = line!(),\n msg = &formatted);\n $ctx.emit_event($crate::EventType::Warning(full));\n }};\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\nenum RunningState {\n /// Ongoing process is allocated.\n Running { cancel_sender: Sender<()> },\n\n /// Cancel signal has been sent, waiting for ongoing process to be freed.\n ShallStop { request: tools::Time },\n\n /// There is no ongoing process, a new one can be allocated.\n Stopped,\n}", "rust_imports": "use std::collections::{BTreeMap, HashMap};\nuse std::ffi::OsString;\nuse std::ops::Deref;\nuse std::path::{Path, PathBuf};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\nuse std::time::Duration;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse pgp::SignedPublicKey;\nuse ratelimit::Ratelimit;\nuse tokio::sync::{Mutex, Notify, OnceCell, RwLock};\nuse crate::aheader::EncryptPreference;\nuse crate::chat::{get_chat_cnt, ChatId, ProtectionStatus};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::debug_logging::DebugLogging;\nuse crate::download::DownloadState;\nuse crate::events::{Event, EventEmitter, EventType, Events};\nuse crate::imap::{FolderMeaning, Imap, ServerMetadata};\nuse crate::key::{load_self_public_key, load_self_secret_key, DcKey as _};\nuse crate::login_param::LoginParam;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peer_channels::Iroh;\nuse crate::peerstate::Peerstate;\nuse crate::push::PushSubscriber;\nuse crate::quota::QuotaInfo;\nuse crate::scheduler::{convert_folder_meaning, SchedulerState};\nuse crate::sql::Sql;\nuse crate::stock_str::StockStrings;\nuse crate::timesmearing::SmearedTimestamp;\nuse crate::tools::{self, create_id, duration_to_str, time, time_elapsed};\nuse anyhow::Context as _;\nuse strum::IntoEnumIterator;\nuse tempfile::tempdir;\nuse super::*;\nuse crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration};\nuse crate::chatlist::Chatlist;\nuse crate::constants::Chattype;\nuse crate::mimeparser::SystemMessage;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{get_chat_msg, TestContext};\nuse crate::tools::{create_outgoing_rfc724_mid, SystemTime};", "rustrepotrans_file": "projects__deltachat-core__rust__context__.rs__function__39.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "void dc_msg_set_location(dc_msg_t* msg, double latitude, double longitude)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC || (latitude==0.0 && longitude==0.0)) {\n\t\treturn;\n\t}\n\n\tdc_param_set_float(msg->param, DC_PARAM_SET_LATITUDE, latitude);\n\tdc_param_set_float(msg->param, DC_PARAM_SET_LONGITUDE, longitude);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn set_location(&mut self, latitude: f64, longitude: f64) {\n if latitude == 0.0 && longitude == 0.0 {\n return;\n }\n\n self.param.set_float(Param::SetLatitude, latitude);\n self.param.set_float(Param::SetLongitude, longitude);\n }", "rust_context": "pub fn set_float(&mut self, key: Param, value: f64) -> &mut Self {\n self.set(key, format!(\"{value}\"));\n self\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__28.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "void dc_block_contact(dc_context_t* context, uint32_t contact_id, int new_blocking)\n{\n\tint send_event = 0;\n\tdc_contact_t* contact = dc_contact_new(context);\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || contact_id<=DC_CONTACT_ID_LAST_SPECIAL) {\n\t\tgoto cleanup;\n\t}\n\n\t\tif (dc_contact_load_from_db(contact, context->sql, contact_id)\n\t\t && contact->blocked!=new_blocking)\n\t\t{\n\t\t\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\t\t\"UPDATE contacts SET blocked=? WHERE id=?;\");\n\t\t\tsqlite3_bind_int(stmt, 1, new_blocking);\n\t\t\tsqlite3_bind_int(stmt, 2, contact_id);\n\t\t\tif (sqlite3_step(stmt)!=SQLITE_DONE) {\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\t\t\tsqlite3_finalize(stmt);\n\t\t\tstmt = NULL;\n\n\t\t\t/* also (un)block all chats with _only_ this contact - we do not delete them to allow a non-destructive blocking->unblocking.\n\t\t\t(Maybe, beside normal chats (type=100) we should also block group chats with only this user.\n\t\t\tHowever, I'm not sure about this point; it may be confusing if the user wants to add other people;\n\t\t\tthis would result in recreating the same group...) */\n\t\t\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\t\t\"UPDATE chats SET blocked=? WHERE type=? AND id IN (SELECT chat_id FROM chats_contacts WHERE contact_id=?);\");\n\t\t\tsqlite3_bind_int(stmt, 1, new_blocking);\n\t\t\tsqlite3_bind_int(stmt, 2, DC_CHAT_TYPE_SINGLE);\n\t\t\tsqlite3_bind_int(stmt, 3, contact_id);\n\t\t\tif (sqlite3_step(stmt)!=SQLITE_DONE) {\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\n\t\t\t/* mark all messages from the blocked contact as being noticed (this is to remove the deaddrop popup) */\n\t\t\tdc_marknoticed_contact(context, contact_id);\n\n\t\t\tsend_event = 1;\n\t\t}\n\n\tif (send_event) {\n\t\tcontext->cb(context, DC_EVENT_CONTACTS_CHANGED, 0, 0);\n\t}\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\tdc_contact_unref(contact);\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub async fn block(context: &Context, id: ContactId) -> Result<()> {\n set_blocked(context, Sync, id, true).await\n }", "rust_context": "pub(crate) async fn set_blocked(\n context: &Context,\n sync: sync::Sync,\n contact_id: ContactId,\n new_blocking: bool,\n) -> Result<()> {\n ensure!(\n !contact_id.is_special(),\n \"Can't block special contact {}\",\n contact_id\n );\n let contact = Contact::get_by_id(context, contact_id).await?;\n\n if contact.blocked != new_blocking {\n context\n .sql\n .execute(\n \"UPDATE contacts SET blocked=? WHERE id=?;\",\n (i32::from(new_blocking), contact_id),\n )\n .await?;\n\n // also (un)block all chats with _only_ this contact - we do not delete them to allow a\n // non-destructive blocking->unblocking.\n // (Maybe, beside normal chats (type=100) we should also block group chats with only this user.\n // However, I'm not sure about this point; it may be confusing if the user wants to add other people;\n // this would result in recreating the same group...)\n if context\n .sql\n .execute(\n r#\"\nUPDATE chats\nSET blocked=?\nWHERE type=? AND id IN (\n SELECT chat_id FROM chats_contacts WHERE contact_id=?\n);\n\"#,\n (new_blocking, Chattype::Single, contact_id),\n )\n .await\n .is_ok()\n {\n Contact::mark_noticed(context, contact_id).await?;\n context.emit_event(EventType::ContactsChanged(Some(contact_id)));\n }\n\n // also unblock mailinglist\n // if the contact is a mailinglist address explicitly created to allow unblocking\n if !new_blocking && contact.origin == Origin::MailinglistAddress {\n if let Some((chat_id, _, _)) =\n chat::get_chat_id_by_grpid(context, &contact.addr).await?\n {\n chat_id.unblock_ex(context, Nosync).await?;\n }\n }\n\n if sync.into() {\n let action = match new_blocking {\n true => chat::SyncAction::Block,\n false => chat::SyncAction::Unblock,\n };\n chat::sync(\n context,\n chat::SyncId::ContactAddr(contact.addr.clone()),\n action,\n )\n .await\n .log_err(context)\n .ok();\n }\n }\n\n chatlist_events::emit_chatlist_changed(context);\n Ok(())\n}\n\npub struct ContactId(u32);\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__18.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_get_showpadlock(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->context==NULL) {\n\t\treturn 0;\n\t}\n\n\tif (dc_param_get_int(msg->param, DC_PARAM_GUARANTEE_E2EE, 0)!=0) {\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn get_showpadlock(&self) -> bool {\n self.param.get_int(Param::GuaranteeE2ee).unwrap_or_default() != 0\n }", "rust_context": "pub fn get_int(&self, key: Param) -> Option {\n self.get(key).and_then(|s| s.parse().ok())\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__46.txt"} {"c_path": "projects/deltachat-core/c/dc_location.c", "c_func": "int dc_set_location(dc_context_t* context,\n double latitude, double longitude, double accuracy)\n{\n\tsqlite3_stmt* stmt_chats = NULL;\n\tsqlite3_stmt* stmt_insert = NULL;\n\tint continue_streaming = 0;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC\n\t || (latitude==0.0 && longitude==0.0)) {\n\t\tcontinue_streaming = 1;\n\t\tgoto cleanup;\n\t}\n\n\tstmt_chats = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT id FROM chats WHERE locations_send_until>?;\");\n\tsqlite3_bind_int64(stmt_chats, 1, time(NULL));\n\twhile (sqlite3_step(stmt_chats)==SQLITE_ROW)\n\t{\n\t\tuint32_t chat_id = sqlite3_column_int(stmt_chats, 0);\n\n\t\tstmt_insert = dc_sqlite3_prepare(context->sql,\n\t\t\t\t\"INSERT INTO locations \"\n\t\t\t\t\" (latitude, longitude, accuracy, timestamp, chat_id, from_id)\"\n\t\t\t\t\" VALUES (?,?,?,?,?,?);\");\n\t\tsqlite3_bind_double(stmt_insert, 1, latitude);\n\t\tsqlite3_bind_double(stmt_insert, 2, longitude);\n\t\tsqlite3_bind_double(stmt_insert, 3, accuracy);\n\t\tsqlite3_bind_int64 (stmt_insert, 4, time(NULL));\n\t\tsqlite3_bind_int (stmt_insert, 5, chat_id);\n\t\tsqlite3_bind_int (stmt_insert, 6, DC_CONTACT_ID_SELF);\n\t\tsqlite3_step(stmt_insert);\n\n\t\tcontinue_streaming = 1;\n\t}\n\n\tif (continue_streaming) {\n\t\tcontext->cb(context, DC_EVENT_LOCATION_CHANGED, DC_CONTACT_ID_SELF, 0);\n\t\tschedule_MAYBE_SEND_LOCATIONS(context, 0);\n\t}\n\ncleanup:\n\tsqlite3_finalize(stmt_chats);\n\tsqlite3_finalize(stmt_insert);\n\treturn continue_streaming;\n}", "rust_path": "projects/deltachat-core/rust/location.rs", "rust_func": "pub async fn set(context: &Context, latitude: f64, longitude: f64, accuracy: f64) -> Result {\n if latitude == 0.0 && longitude == 0.0 {\n return Ok(true);\n }\n let mut continue_streaming = false;\n let now = time();\n\n let chats = context\n .sql\n .query_map(\n \"SELECT id FROM chats WHERE locations_send_until>?;\",\n (now,),\n |row| row.get::<_, i32>(0),\n |chats| {\n chats\n .collect::, _>>()\n .map_err(Into::into)\n },\n )\n .await?;\n\n let mut stored_location = false;\n for chat_id in chats {\n context.sql.execute(\n \"INSERT INTO locations \\\n (latitude, longitude, accuracy, timestamp, chat_id, from_id) VALUES (?,?,?,?,?,?);\",\n (\n latitude,\n longitude,\n accuracy,\n now,\n chat_id,\n ContactId::SELF,\n )).await.context(\"Failed to store location\")?;\n stored_location = true;\n\n info!(context, \"Stored location for chat {chat_id}.\");\n continue_streaming = true;\n }\n if continue_streaming {\n context.emit_location_changed(Some(ContactId::SELF)).await?;\n };\n if stored_location {\n // Interrupt location loop so it may send a location-only message.\n context.scheduler.interrupt_location().await;\n }\n\n Ok(continue_streaming)\n}", "rust_context": "pub(crate) fn time() -> i64 {\n SystemTime::now()\n .duration_since(SystemTime::UNIX_EPOCH)\n .unwrap_or_default()\n .as_secs() as i64\n}\n\npub async fn query_map(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n mut g: G,\n ) -> Result\n where\n F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result,\n G: Send + FnMut(rusqlite::MappedRows) -> Result,\n H: Send + 'static,\n {\n self.call(move |conn| {\n let mut stmt = conn.prepare(sql)?;\n let res = stmt.query_map(params, f)?;\n g(res)\n })\n .await\n }\n\npub async fn execute(\n &self,\n query: &str,\n params: impl rusqlite::Params + Send,\n ) -> Result {\n self.call_write(move |conn| {\n let res = conn.execute(query, params)?;\n Ok(res)\n })\n .await\n }\n\npub async fn emit_location_changed(&self, contact_id: Option) -> Result<()> {\n self.emit_event(EventType::LocationChanged(contact_id));\n\n if let Some(msg_id) = self\n .get_config_parsed::(Config::WebxdcIntegration)\n .await?\n {\n self.emit_event(EventType::WebxdcStatusUpdate {\n msg_id: MsgId::new(msg_id),\n status_update_serial: Default::default(),\n })\n }\n\n Ok(())\n }\n\npub(crate) async fn interrupt_location(&self) {\n let inner = self.inner.read().await;\n if let InnerSchedulerState::Started(ref scheduler) = *inner {\n scheduler.interrupt_location();\n }\n }\n \npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub struct ContactId(u32);\n\nimpl ContactId {\n /// Undefined contact. Used as a placeholder for trashed messages.\n pub const UNDEFINED: ContactId = ContactId::new(0);\n\n /// The owner of the account.\n ///\n /// The email-address is set by `set_config` using \"addr\".\n pub const SELF: ContactId = ContactId::new(1);\n\n /// ID of the contact for info messages.\n pub const INFO: ContactId = ContactId::new(2);\n\n /// ID of the contact for device messages.\n pub const DEVICE: ContactId = ContactId::new(5);\n pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9);\n\n /// Address to go with [`ContactId::DEVICE`].\n ///\n /// This is used by APIs which need to return an email address for this contact.\n pub const DEVICE_ADDR: &'static str = \"device@localhost\";\n}", "rust_imports": "use std::time::Duration;\nuse anyhow::{ensure, Context as _, Result};\nuse async_channel::Receiver;\nuse quick_xml::events::{BytesEnd, BytesStart, BytesText};\nuse tokio::time::timeout;\nuse crate::chat::{self, ChatId};\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::tools::{duration_to_str, time};\nuse crate::{chatlist_events, stock_str};\nuse super::*;\nuse crate::config::Config;\nuse crate::message::MessageState;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{TestContext, TestContextManager};\nuse crate::tools::SystemTime;", "rustrepotrans_file": "projects__deltachat-core__rust__location__.rs__function__9.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "void dc_msg_guess_msgtype_from_suffix(const char* pathNfilename, int* ret_msgtype, char** ret_mime)\n{\n\tchar* suffix = NULL;\n\tint dummy_msgtype = 0;\n\tchar* dummy_buf = NULL;\n\n\tif (pathNfilename==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tif (ret_msgtype==NULL) { ret_msgtype = &dummy_msgtype; }\n\tif (ret_mime==NULL) { ret_mime = &dummy_buf; }\n\n\t*ret_msgtype = 0;\n\t*ret_mime = NULL;\n\n\tsuffix = dc_get_filesuffix_lc(pathNfilename);\n\tif (suffix==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tif (strcmp(suffix, \"mp3\")==0) {\n\t\t*ret_msgtype = DC_MSG_AUDIO;\n\t\t*ret_mime = dc_strdup(\"audio/mpeg\");\n\t}\n\telse if (strcmp(suffix, \"aac\")==0) {\n\t\t*ret_msgtype = DC_MSG_AUDIO;\n\t\t*ret_mime = dc_strdup(\"audio/aac\");\n\t}\n\telse if (strcmp(suffix, \"mp4\")==0) {\n\t\t*ret_msgtype = DC_MSG_VIDEO;\n\t\t*ret_mime = dc_strdup(\"video/mp4\");\n\t}\n\telse if (strcmp(suffix, \"jpg\")==0 || strcmp(suffix, \"jpeg\")==0) {\n\t\t*ret_msgtype = DC_MSG_IMAGE;\n\t\t*ret_mime = dc_strdup(\"image/jpeg\");\n\t}\n\telse if (strcmp(suffix, \"png\")==0) {\n\t\t*ret_msgtype = DC_MSG_IMAGE;\n\t\t*ret_mime = dc_strdup(\"image/png\");\n\t}\n\telse if (strcmp(suffix, \"webp\")==0) {\n\t\t*ret_msgtype = DC_MSG_IMAGE;\n\t\t*ret_mime = dc_strdup(\"image/webp\");\n\t}\n\telse if (strcmp(suffix, \"gif\")==0) {\n\t\t*ret_msgtype = DC_MSG_GIF;\n\t\t*ret_mime = dc_strdup(\"image/gif\");\n\t}\n\telse if (strcmp(suffix, \"vcf\")==0 || strcmp(suffix, \"vcard\")==0) {\n\t\t*ret_msgtype = DC_MSG_FILE;\n\t\t*ret_mime = dc_strdup(\"text/vcard\");\n\t}\n\ncleanup:\n\tfree(suffix);\n\tfree(dummy_buf);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub(crate) fn guess_msgtype_from_suffix(path: &Path) -> Option<(Viewtype, &str)> {\n let extension: &str = &path.extension()?.to_str()?.to_lowercase();\n let info = match extension {\n // before using viewtype other than Viewtype::File,\n // make sure, all target UIs support that type in the context of the used viewer/player.\n // if in doubt, it is better to default to Viewtype::File that passes handing to an external app.\n // (cmp. )\n \"3gp\" => (Viewtype::Video, \"video/3gpp\"),\n \"aac\" => (Viewtype::Audio, \"audio/aac\"),\n \"avi\" => (Viewtype::Video, \"video/x-msvideo\"),\n \"avif\" => (Viewtype::File, \"image/avif\"), // supported since Android 12 / iOS 16\n \"doc\" => (Viewtype::File, \"application/msword\"),\n \"docx\" => (\n Viewtype::File,\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n ),\n \"epub\" => (Viewtype::File, \"application/epub+zip\"),\n \"flac\" => (Viewtype::Audio, \"audio/flac\"),\n \"gif\" => (Viewtype::Gif, \"image/gif\"),\n \"heic\" => (Viewtype::File, \"image/heic\"), // supported since Android 10 / iOS 11\n \"heif\" => (Viewtype::File, \"image/heif\"), // supported since Android 10 / iOS 11\n \"html\" => (Viewtype::File, \"text/html\"),\n \"htm\" => (Viewtype::File, \"text/html\"),\n \"ico\" => (Viewtype::File, \"image/vnd.microsoft.icon\"),\n \"jar\" => (Viewtype::File, \"application/java-archive\"),\n \"jpeg\" => (Viewtype::Image, \"image/jpeg\"),\n \"jpe\" => (Viewtype::Image, \"image/jpeg\"),\n \"jpg\" => (Viewtype::Image, \"image/jpeg\"),\n \"json\" => (Viewtype::File, \"application/json\"),\n \"mov\" => (Viewtype::Video, \"video/quicktime\"),\n \"m4a\" => (Viewtype::Audio, \"audio/m4a\"),\n \"mp3\" => (Viewtype::Audio, \"audio/mpeg\"),\n \"mp4\" => (Viewtype::Video, \"video/mp4\"),\n \"odp\" => (\n Viewtype::File,\n \"application/vnd.oasis.opendocument.presentation\",\n ),\n \"ods\" => (\n Viewtype::File,\n \"application/vnd.oasis.opendocument.spreadsheet\",\n ),\n \"odt\" => (Viewtype::File, \"application/vnd.oasis.opendocument.text\"),\n \"oga\" => (Viewtype::Audio, \"audio/ogg\"),\n \"ogg\" => (Viewtype::Audio, \"audio/ogg\"),\n \"ogv\" => (Viewtype::File, \"video/ogg\"),\n \"opus\" => (Viewtype::File, \"audio/ogg\"), // supported since Android 10\n \"otf\" => (Viewtype::File, \"font/otf\"),\n \"pdf\" => (Viewtype::File, \"application/pdf\"),\n \"png\" => (Viewtype::Image, \"image/png\"),\n \"ppt\" => (Viewtype::File, \"application/vnd.ms-powerpoint\"),\n \"pptx\" => (\n Viewtype::File,\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n ),\n \"rar\" => (Viewtype::File, \"application/vnd.rar\"),\n \"rtf\" => (Viewtype::File, \"application/rtf\"),\n \"spx\" => (Viewtype::File, \"audio/ogg\"), // Ogg Speex Profile\n \"svg\" => (Viewtype::File, \"image/svg+xml\"),\n \"tgs\" => (Viewtype::Sticker, \"application/x-tgsticker\"),\n \"tiff\" => (Viewtype::File, \"image/tiff\"),\n \"tif\" => (Viewtype::File, \"image/tiff\"),\n \"ttf\" => (Viewtype::File, \"font/ttf\"),\n \"txt\" => (Viewtype::File, \"text/plain\"),\n \"vcard\" => (Viewtype::Vcard, \"text/vcard\"),\n \"vcf\" => (Viewtype::Vcard, \"text/vcard\"),\n \"wav\" => (Viewtype::Audio, \"audio/wav\"),\n \"weba\" => (Viewtype::File, \"audio/webm\"),\n \"webm\" => (Viewtype::Video, \"video/webm\"),\n \"webp\" => (Viewtype::Image, \"image/webp\"), // iOS via SDWebImage, Android since 4.0\n \"wmv\" => (Viewtype::Video, \"video/x-ms-wmv\"),\n \"xdc\" => (Viewtype::Webxdc, \"application/webxdc+zip\"),\n \"xhtml\" => (Viewtype::File, \"application/xhtml+xml\"),\n \"xls\" => (Viewtype::File, \"application/vnd.ms-excel\"),\n \"xlsx\" => (\n Viewtype::File,\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n ),\n \"xml\" => (Viewtype::File, \"application/xml\"),\n \"zip\" => (Viewtype::File, \"application/zip\"),\n _ => {\n return None;\n }\n };\n Some(info)\n}", "rust_context": "pub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__87.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_is_forwarded(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn dc_param_get_int(msg->param, DC_PARAM_FORWARDED, 0)? 1 : 0;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn is_forwarded(&self) -> bool {\n 0 != self.param.get_int(Param::Forwarded).unwrap_or_default()\n }", "rust_context": "pub fn get_int(&self, key: Param) -> Option {\n self.get(key).and_then(|s| s.parse().ok())\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__55.txt"} {"c_path": "projects/deltachat-core/c/dc_sqlite3.c", "c_func": "static void maybe_add_file(dc_hash_t* files_in_use, const char* file)\n{\n\t#define PREFIX \"$BLOBDIR/\"\n\t#define PREFIX_LEN 9\n\tif (strncmp(file, PREFIX, PREFIX_LEN)!=0) {\n\t\treturn;\n\t}\n\n\tconst char* raw_name = &file[PREFIX_LEN];\n dc_hash_insert_str(files_in_use, raw_name, (void*)1);\n}", "rust_path": "projects/deltachat-core/rust/sql.rs", "rust_func": "fn maybe_add_file(files_in_use: &mut HashSet, file: &str) {\n if let Some(file) = file.strip_prefix(\"$BLOBDIR/\") {\n files_in_use.insert(file.to_string());\n }\n}", "rust_context": "", "rust_imports": "use std::collections::{HashMap, HashSet};\nuse std::path::{Path, PathBuf};\nuse anyhow::{bail, Context as _, Result};\nuse rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row};\nuse tokio::sync::{Mutex, MutexGuard, RwLock};\nuse crate::blob::BlobObject;\nuse crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon};\nuse crate::config::Config;\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::ephemeral::start_ephemeral_timers;\nuse crate::imex::BLOBS_BACKUP_NAME;\nuse crate::location::delete_orphaned_poi_locations;\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::stock_str;\nuse crate::tools::{delete_file, time, SystemTime};\nuse pool::Pool;\nuse super::*;\nuse crate::{test_utils::TestContext, EventType};\nuse tempfile::tempdir;\nuse tempfile::tempdir;\nuse tempfile::tempdir;", "rustrepotrans_file": "projects__deltachat-core__rust__sql__.rs__function__42.txt"} {"c_path": "projects/deltachat-core/c/dc_tools.c", "c_func": "time_t dc_smeared_time(dc_context_t* context)\n{\n\t/* function returns a corrected time(NULL) */\n\ttime_t now = time(NULL);\n\tSMEAR_LOCK\n\t\tif (context->last_smeared_timestamp >= now) {\n\t\t\tnow = context->last_smeared_timestamp+1;\n\t\t}\n\tSMEAR_UNLOCK\n\treturn now;\n}", "rust_path": "projects/deltachat-core/rust/tools.rs", "rust_func": "pub(crate) fn smeared_time(context: &Context) -> i64 {\n let now = time();\n let ts = context.smeared_timestamp.current();\n std::cmp::max(ts, now)\n}", "rust_context": "pub(crate) fn time() -> i64 {\n SystemTime::now()\n .duration_since(SystemTime::UNIX_EPOCH)\n .unwrap_or_default()\n .as_secs() as i64\n}\n\npub fn current(&self) -> i64 {\n self.smeared_timestamp.load(Ordering::Relaxed)\n }\n \npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}", "rust_imports": "use std::borrow::Cow;\nuse std::io::{Cursor, Write};\nuse std::mem;\nuse std::path::{Path, PathBuf};\nuse std::str::from_utf8;\nuse std::time::Duration;\nuse std::time::SystemTime as Time;\nuse std::time::SystemTime;\nuse anyhow::{bail, Context as _, Result};\nuse base64::Engine as _;\nuse chrono::{Local, NaiveDateTime, NaiveTime, TimeZone};\nuse deltachat_contact_tools::{strip_rtlo_characters, EmailAddress};\nuse deltachat_time::SystemTimeTools as SystemTime;\nuse futures::{StreamExt, TryStreamExt};\nuse mailparse::dateparse;\nuse mailparse::headers::Headers;\nuse mailparse::MailHeaderMap;\nuse rand::{thread_rng, Rng};\nuse tokio::{fs, io};\nuse url::Url;\nuse crate::chat::{add_device_msg, add_device_msg_with_importance};\nuse crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, Viewtype};\nuse crate::stock_str;\nuse chrono::NaiveDate;\nuse proptest::prelude::*;\nuse super::*;\nuse crate::chatlist::Chatlist;\nuse crate::{chat, test_utils};\nuse crate::{receive_imf::receive_imf, test_utils::TestContext};\nuse super::*;", "rustrepotrans_file": "projects__deltachat-core__rust__tools__.rs__function__6.txt"} {"c_path": "projects/deltachat-core/c/dc_oauth2.c", "c_func": "char* dc_get_oauth2_access_token(dc_context_t* context, const char* addr,\n const char* code, int flags)\n{\n\toauth2_t* oauth2 = NULL;\n\tchar* access_token = NULL;\n\tchar* refresh_token = NULL;\n\tchar* refresh_token_for = NULL;\n\tchar* redirect_uri = NULL;\n\tint update_redirect_uri_on_success = 0;\n\tchar* token_url = NULL;\n\ttime_t expires_in = 0;\n\tchar* error = NULL;\n\tchar* error_description = NULL;\n\tchar* json = NULL;\n\tjsmn_parser parser;\n\tjsmntok_t tok[128]; // we do not expect nor read more tokens\n\tint tok_cnt = 0;\n\tint locked = 0;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC\n\t || code==NULL || code[0]==0) {\n\t\tdc_log_warning(context, 0, \"Internal OAuth2 error\");\n\t\tgoto cleanup;\n\t}\n\n\tif ((oauth2=get_info(addr))==NULL) {\n\t\tdc_log_warning(context, 0, \"Internal OAuth2 error: 2\");\n\t\tgoto cleanup;\n\t}\n\n\tpthread_mutex_lock(&context->oauth2_critical);\n\tlocked = 1;\n\n\t// read generated token\n\tif ( !(flags&DC_REGENERATE) && !is_expired(context) ) {\n\t\taccess_token = dc_sqlite3_get_config(context->sql, \"oauth2_access_token\", NULL);\n\t\tif (access_token!=NULL) {\n\t\t\tgoto cleanup; // success\n\t\t}\n\t}\n\n\t// generate new token: build & call auth url\n\trefresh_token = dc_sqlite3_get_config(context->sql, \"oauth2_refresh_token\", NULL);\n\trefresh_token_for = dc_sqlite3_get_config(context->sql, \"oauth2_refresh_token_for\", \"unset\");\n\tif (refresh_token==NULL || strcmp(refresh_token_for, code)!=0)\n\t{\n\t\tdc_log_info(context, 0, \"Generate OAuth2 refresh_token and access_token...\");\n\t\tredirect_uri = dc_sqlite3_get_config(context->sql, \"oauth2_pending_redirect_uri\", \"unset\");\n\t\tupdate_redirect_uri_on_success = 1;\n\t\ttoken_url = dc_strdup(oauth2->init_token);\n\t}\n\telse\n\t{\n\t\tdc_log_info(context, 0, \"Regenerate OAuth2 access_token by refresh_token...\");\n\t\tredirect_uri = dc_sqlite3_get_config(context->sql, \"oauth2_redirect_uri\", \"unset\");\n\t\ttoken_url = dc_strdup(oauth2->refresh_token);\n\t}\n\n\treplace_in_uri(&token_url, \"$CLIENT_ID\", oauth2->client_id);\n\treplace_in_uri(&token_url, \"$REDIRECT_URI\", redirect_uri);\n\treplace_in_uri(&token_url, \"$CODE\", code);\n\treplace_in_uri(&token_url, \"$REFRESH_TOKEN\", refresh_token);\n\n\tjson = (char*)context->cb(context, DC_EVENT_HTTP_POST, (uintptr_t)token_url, 0);\n\tif (json==NULL) {\n\t\tdc_log_warning(context, 0, \"Error calling OAuth2 at %s\", token_url);\n\t\tgoto cleanup;\n\t}\n\n\t// generate new token: parse returned json\n\tjsmn_init(&parser);\n\ttok_cnt = jsmn_parse(&parser, json, strlen(json), tok, sizeof(tok)/sizeof(tok[0]));\n\tif (tok_cnt<2 || tok[0].type!=JSMN_OBJECT) {\n\t\tdc_log_warning(context, 0, \"Failed to parse OAuth2 json from %s\", token_url);\n\t\tgoto cleanup;\n\t}\n\n\tfor (int i = 1; i < tok_cnt; i++) {\n\t\tif (access_token==NULL && jsoneq(json, &tok[i], \"access_token\")==0) {\n\t\t\taccess_token = jsondup(json, &tok[i+1]);\n\t\t}\n\t\telse if (refresh_token==NULL && jsoneq(json, &tok[i], \"refresh_token\")==0) {\n\t\t\trefresh_token = jsondup(json, &tok[i+1]);\n\t\t}\n\t\telse if (jsoneq(json, &tok[i], \"expires_in\")==0) {\n\t\t\tchar* expires_in_str = jsondup(json, &tok[i+1]);\n\t\t\tif (expires_in_str) {\n\t\t\t\ttime_t val = atol(expires_in_str);\n\t\t\t\t// val should be reasonable, maybe between 20 seconds and 5 years.\n\t\t\t\t// if out of range, we re-create when the token gets invalid,\n\t\t\t\t// which may create some additional load and requests wrt threads.\n\t\t\t\tif (val>20 && val<(60*60*24*365*5)) {\n\t\t\t\t\texpires_in = val;\n\t\t\t\t}\n\t\t\t\tfree(expires_in_str);\n\t\t\t}\n\t\t}\n\t\telse if (error==NULL && jsoneq(json, &tok[i], \"error\")==0) {\n\t\t\terror = jsondup(json, &tok[i+1]);\n\t\t}\n\t\telse if (error_description==NULL && jsoneq(json, &tok[i], \"error_description\")==0) {\n\t\t\terror_description = jsondup(json, &tok[i+1]);\n\t\t}\n\t}\n\n\tif (error || error_description) {\n\t\tdc_log_warning(context, 0, \"OAuth error: %s: %s\",\n\t\t\terror? error : \"unknown\",\n\t\t\terror_description? error_description : \"no details\");\n\t\t// continue, errors do not imply everything went wrong\n\t}\n\n\t// update refresh_token if given, typically on the first round, but we update it later as well.\n\tif (refresh_token && refresh_token[0]) {\n\t\tdc_sqlite3_set_config(context->sql, \"oauth2_refresh_token\", refresh_token);\n\t\tdc_sqlite3_set_config(context->sql, \"oauth2_refresh_token_for\", code);\n\t}\n\n\t// after that, save the access token.\n\t// if it's unset, we may get it in the next round as we have the refresh_token now.\n\tif (access_token==NULL || access_token[0]==0) {\n\t\tdc_log_warning(context, 0, \"Failed to find OAuth2 access token\");\n\t\tgoto cleanup;\n\t}\n\n\tdc_sqlite3_set_config(context->sql, \"oauth2_access_token\", access_token);\n\tdc_sqlite3_set_config_int64(context->sql, \"oauth2_timestamp_expires\",\n\t\texpires_in? time(NULL)+expires_in-5/*refresh a bet before*/ : 0);\n\n\tif (update_redirect_uri_on_success) {\n\t\tdc_sqlite3_set_config(context->sql, \"oauth2_redirect_uri\", redirect_uri);\n\t}\n\ncleanup:\n\tif (locked) { pthread_mutex_unlock(&context->oauth2_critical); }\n\tfree(refresh_token);\n\tfree(refresh_token_for);\n\tfree(redirect_uri);\n\tfree(token_url);\n\tfree(json);\n\tfree(error);\n\tfree(error_description);\n\tfree(oauth2);\n\treturn access_token? access_token : dc_strdup(NULL);\n}", "rust_path": "projects/deltachat-core/rust/oauth2.rs", "rust_func": "pub(crate) async fn get_oauth2_access_token(\n context: &Context,\n addr: &str,\n code: &str,\n regenerate: bool,\n) -> Result> {\n let socks5_enabled = context.get_config_bool(Config::Socks5Enabled).await?;\n if let Some(oauth2) = Oauth2::from_address(context, addr, socks5_enabled).await {\n let lock = context.oauth2_mutex.lock().await;\n\n // read generated token\n if !regenerate && !is_expired(context).await? {\n let access_token = context.sql.get_raw_config(\"oauth2_access_token\").await?;\n if access_token.is_some() {\n // success\n return Ok(access_token);\n }\n }\n\n // generate new token: build & call auth url\n let refresh_token = context.sql.get_raw_config(\"oauth2_refresh_token\").await?;\n let refresh_token_for = context\n .sql\n .get_raw_config(\"oauth2_refresh_token_for\")\n .await?\n .unwrap_or_else(|| \"unset\".into());\n\n let (redirect_uri, token_url, update_redirect_uri_on_success) =\n if refresh_token.is_none() || refresh_token_for != code {\n info!(context, \"Generate OAuth2 refresh_token and access_token...\",);\n (\n context\n .sql\n .get_raw_config(\"oauth2_pending_redirect_uri\")\n .await?\n .unwrap_or_else(|| \"unset\".into()),\n oauth2.init_token,\n true,\n )\n } else {\n info!(\n context,\n \"Regenerate OAuth2 access_token by refresh_token...\",\n );\n (\n context\n .sql\n .get_raw_config(\"oauth2_redirect_uri\")\n .await?\n .unwrap_or_else(|| \"unset\".into()),\n oauth2.refresh_token,\n false,\n )\n };\n\n // to allow easier specification of different configurations,\n // token_url is in GET-method-format, sth. as -\n // convert this to POST-format ...\n let mut parts = token_url.splitn(2, '?');\n let post_url = parts.next().unwrap_or_default();\n let post_args = parts.next().unwrap_or_default();\n let mut post_param = HashMap::new();\n for key_value_pair in post_args.split('&') {\n let mut parts = key_value_pair.splitn(2, '=');\n let key = parts.next().unwrap_or_default();\n let mut value = parts.next().unwrap_or_default();\n\n if value == \"$CLIENT_ID\" {\n value = oauth2.client_id;\n } else if value == \"$REDIRECT_URI\" {\n value = &redirect_uri;\n } else if value == \"$CODE\" {\n value = code;\n } else if value == \"$REFRESH_TOKEN\" {\n if let Some(refresh_token) = refresh_token.as_ref() {\n value = refresh_token;\n }\n }\n\n post_param.insert(key, value);\n }\n\n // ... and POST\n let socks5_config = Socks5Config::from_database(&context.sql).await?;\n let client = crate::net::http::get_client(socks5_config)?;\n\n let response: Response = match client.post(post_url).form(&post_param).send().await {\n Ok(resp) => match resp.json().await {\n Ok(response) => response,\n Err(err) => {\n warn!(\n context,\n \"Failed to parse OAuth2 JSON response from {}: error: {}\", token_url, err\n );\n return Ok(None);\n }\n },\n Err(err) => {\n warn!(context, \"Error calling OAuth2 at {}: {:?}\", token_url, err);\n return Ok(None);\n }\n };\n\n // update refresh_token if given, typically on the first round, but we update it later as well.\n if let Some(ref token) = response.refresh_token {\n context\n .sql\n .set_raw_config(\"oauth2_refresh_token\", Some(token))\n .await?;\n context\n .sql\n .set_raw_config(\"oauth2_refresh_token_for\", Some(code))\n .await?;\n }\n\n // after that, save the access token.\n // if it's unset, we may get it in the next round as we have the refresh_token now.\n if let Some(ref token) = response.access_token {\n context\n .sql\n .set_raw_config(\"oauth2_access_token\", Some(token))\n .await?;\n let expires_in = response\n .expires_in\n // refresh a bit before\n .map(|t| time() + t as i64 - 5)\n .unwrap_or_else(|| 0);\n context\n .sql\n .set_raw_config_int64(\"oauth2_timestamp_expires\", expires_in)\n .await?;\n\n if update_redirect_uri_on_success {\n context\n .sql\n .set_raw_config(\"oauth2_redirect_uri\", Some(redirect_uri.as_ref()))\n .await?;\n }\n } else {\n warn!(context, \"Failed to find OAuth2 access token\");\n }\n\n drop(lock);\n\n Ok(response.access_token)\n } else {\n warn!(context, \"Internal OAuth2 error: 2\");\n\n Ok(None)\n }\n}", "rust_context": "pub async fn get_config_bool(&self, key: Config) -> Result {\n Ok(self.get_config_bool_opt(key).await?.unwrap_or_default())\n }\n\npub(crate) fn time() -> i64 {\n SystemTime::now()\n .duration_since(SystemTime::UNIX_EPOCH)\n .unwrap_or_default()\n .as_secs() as i64\n}\n\npub async fn get_raw_config(&self, key: &str) -> Result> {\n let lock = self.config_cache.read().await;\n let cached = lock.get(key).cloned();\n drop(lock);\n\n if let Some(c) = cached {\n return Ok(c);\n }\n\n let mut lock = self.config_cache.write().await;\n let value = self\n .query_get_value(\"SELECT value FROM config WHERE keyname=?\", (key,))\n .await\n .context(format!(\"failed to fetch raw config: {key}\"))?;\n lock.insert(key.to_string(), value.clone());\n drop(lock);\n\n Ok(value)\n }\n\npub(crate) fn get_client(socks5_config: Option) -> Result {\n let builder = reqwest::ClientBuilder::new()\n .timeout(HTTP_TIMEOUT)\n .add_root_certificate(LETSENCRYPT_ROOT.clone());\n\n let builder = if let Some(socks5_config) = socks5_config {\n let proxy = reqwest::Proxy::all(socks5_config.to_url())?;\n builder.proxy(proxy)\n } else {\n // Disable usage of \"system\" proxy configured via environment variables.\n // It is enabled by default in `reqwest`, see\n // \n // for documentation.\n builder.no_proxy()\n };\n Ok(builder.build()?)\n}\n\n\npub async fn from_database(sql: &Sql) -> Result> {\n let enabled = sql.get_raw_config_bool(\"socks5_enabled\").await?;\n if enabled {\n let host = sql.get_raw_config(\"socks5_host\").await?.unwrap_or_default();\n let port: u16 = sql\n .get_raw_config_int(\"socks5_port\")\n .await?\n .unwrap_or_default() as u16;\n let user = sql.get_raw_config(\"socks5_user\").await?.unwrap_or_default();\n let password = sql\n .get_raw_config(\"socks5_password\")\n .await?\n .unwrap_or_default();\n\n let socks5_config = Self {\n host,\n port,\n user_password: if !user.is_empty() {\n Some((user, password))\n } else {\n None\n },\n };\n Ok(Some(socks5_config))\n } else {\n Ok(None)\n }\n }\n\nasync fn is_expired(context: &Context) -> Result {\n let expire_timestamp = context\n .sql\n .get_raw_config_int64(\"oauth2_timestamp_expires\")\n .await?\n .unwrap_or_default();\n\n if expire_timestamp <= 0 {\n return Ok(false);\n }\n if expire_timestamp > time() {\n return Ok(false);\n }\n\n Ok(true)\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\nstruct Response {\n // Should always be there according to: \n // but previous code handled its abscense.\n access_token: Option,\n token_type: String,\n /// Duration of time the token is granted for, in seconds\n expires_in: Option,\n refresh_token: Option,\n scope: Option,\n}\n\nasync fn from_address(context: &Context, addr: &str, skip_mx: bool) -> Option {\n let addr_normalized = normalize_addr(addr);\n if let Some(domain) = addr_normalized\n .find('@')\n .map(|index| addr_normalized.split_at(index + 1).1)\n {\n if let Some(oauth2_authorizer) = provider::get_provider_info(context, domain, skip_mx)\n .await\n .and_then(|provider| provider.oauth2_authorizer.as_ref())\n {\n return Some(match oauth2_authorizer {\n Oauth2Authorizer::Gmail => OAUTH2_GMAIL,\n Oauth2Authorizer::Yandex => OAUTH2_YANDEX,\n });\n }\n }\n None\n }\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub enum Config {\n /// Email address, used in the `From:` field.\n Addr,\n\n /// IMAP server hostname.\n MailServer,\n\n /// IMAP server username.\n MailUser,\n\n /// IMAP server password.\n MailPw,\n\n /// IMAP server port.\n MailPort,\n\n /// IMAP server security (e.g. TLS, STARTTLS).\n MailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ImapCertificateChecks,\n\n /// SMTP server hostname.\n SendServer,\n\n /// SMTP server username.\n SendUser,\n\n /// SMTP server password.\n SendPw,\n\n /// SMTP server port.\n SendPort,\n\n /// SMTP server security (e.g. TLS, STARTTLS).\n SendSecurity,\n\n /// How to check SMTP server TLS certificates.\n SmtpCertificateChecks,\n\n /// Whether to use OAuth 2.\n ///\n /// Historically contained other bitflags, which are now deprecated.\n /// Should not be extended in the future, create new config keys instead.\n ServerFlags,\n\n /// True if SOCKS5 is enabled.\n ///\n /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.\n Socks5Enabled,\n\n /// SOCKS5 proxy server hostname or address.\n Socks5Host,\n\n /// SOCKS5 proxy server port.\n Socks5Port,\n\n /// SOCKS5 proxy server username.\n Socks5User,\n\n /// SOCKS5 proxy server password.\n Socks5Password,\n\n /// Own name to use in the `From:` field when sending messages.\n Displayname,\n\n /// Own status to display, sent in message footer.\n Selfstatus,\n\n /// Own avatar filename.\n Selfavatar,\n\n /// Send BCC copy to self.\n ///\n /// Should be enabled for multidevice setups.\n #[strum(props(default = \"1\"))]\n BccSelf,\n\n /// True if encryption is preferred according to Autocrypt standard.\n #[strum(props(default = \"1\"))]\n E2eeEnabled,\n\n /// True if Message Delivery Notifications (read receipts) should\n /// be sent and requested.\n #[strum(props(default = \"1\"))]\n MdnsEnabled,\n\n /// True if \"Sent\" folder should be watched for changes.\n #[strum(props(default = \"0\"))]\n SentboxWatch,\n\n /// True if chat messages should be moved to a separate folder.\n #[strum(props(default = \"1\"))]\n MvboxMove,\n\n /// Watch for new messages in the \"Mvbox\" (aka DeltaChat folder) only.\n ///\n /// This will not entirely disable other folders, e.g. the spam folder will also still\n /// be watched for new messages.\n #[strum(props(default = \"0\"))]\n OnlyFetchMvbox,\n\n /// Whether to show classic emails or only chat messages.\n #[strum(props(default = \"2\"))] // also change ShowEmails.default() on changes\n ShowEmails,\n\n /// Quality of the media files to send.\n #[strum(props(default = \"0\"))] // also change MediaQuality.default() on changes\n MediaQuality,\n\n /// If set to \"1\", on the first time `start_io()` is called after configuring,\n /// the newest existing messages are fetched.\n /// Existing recipients are added to the contact database regardless of this setting.\n #[strum(props(default = \"0\"))]\n FetchExistingMsgs,\n\n /// If set to \"1\", then existing messages are considered to be already fetched.\n /// This flag is reset after successful configuration.\n #[strum(props(default = \"1\"))]\n FetchedExistingMsgs,\n\n /// Type of the OpenPGP key to generate.\n #[strum(props(default = \"0\"))]\n KeyGenType,\n\n /// Timer in seconds after which the message is deleted from the\n /// server.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n ///\n /// Value 1 is treated as \"delete at once\": messages are deleted\n /// immediately, without moving to DeltaChat folder.\n #[strum(props(default = \"0\"))]\n DeleteServerAfter,\n\n /// Timer in seconds after which the message is deleted from the\n /// device.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n #[strum(props(default = \"0\"))]\n DeleteDeviceAfter,\n\n /// Move messages to the Trash folder instead of marking them \"\\Deleted\". Overrides\n /// `ProviderOptions::delete_to_trash`.\n DeleteToTrash,\n\n /// Save raw MIME messages with headers in the database if true.\n SaveMimeHeaders,\n\n /// The primary email address. Also see `SecondaryAddrs`.\n ConfiguredAddr,\n\n /// Configured IMAP server hostname.\n ConfiguredMailServer,\n\n /// Configured IMAP server username.\n ConfiguredMailUser,\n\n /// Configured IMAP server password.\n ConfiguredMailPw,\n\n /// Configured IMAP server port.\n ConfiguredMailPort,\n\n /// Configured IMAP server security (e.g. TLS, STARTTLS).\n ConfiguredMailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ConfiguredImapCertificateChecks,\n\n /// Configured SMTP server hostname.\n ConfiguredSendServer,\n\n /// Configured SMTP server username.\n ConfiguredSendUser,\n\n /// Configured SMTP server password.\n ConfiguredSendPw,\n\n /// Configured SMTP server port.\n ConfiguredSendPort,\n\n /// How to check SMTP server TLS certificates.\n ConfiguredSmtpCertificateChecks,\n\n /// Whether OAuth 2 is used with configured provider.\n ConfiguredServerFlags,\n\n /// Configured SMTP server security (e.g. TLS, STARTTLS).\n ConfiguredSendSecurity,\n\n /// Configured folder for incoming messages.\n ConfiguredInboxFolder,\n\n /// Configured folder for chat messages.\n ConfiguredMvboxFolder,\n\n /// Configured \"Sent\" folder.\n ConfiguredSentboxFolder,\n\n /// Configured \"Trash\" folder.\n ConfiguredTrashFolder,\n\n /// Unix timestamp of the last successful configuration.\n ConfiguredTimestamp,\n\n /// ID of the configured provider from the provider database.\n ConfiguredProvider,\n\n /// True if account is configured.\n Configured,\n\n /// True if account is a chatmail account.\n IsChatmail,\n\n /// All secondary self addresses separated by spaces\n /// (`addr1@example.org addr2@example.org addr3@example.org`)\n SecondaryAddrs,\n\n /// Read-only core version string.\n #[strum(serialize = \"sys.version\")]\n SysVersion,\n\n /// Maximal recommended attachment size in bytes.\n #[strum(serialize = \"sys.msgsize_max_recommended\")]\n SysMsgsizeMaxRecommended,\n\n /// Space separated list of all config keys available.\n #[strum(serialize = \"sys.config_keys\")]\n SysConfigKeys,\n\n /// True if it is a bot account.\n Bot,\n\n /// True when to skip initial start messages in groups.\n #[strum(props(default = \"0\"))]\n SkipStartMessages,\n\n /// Whether we send a warning if the password is wrong (set to false when we send a warning\n /// because we do not want to send a second warning)\n #[strum(props(default = \"0\"))]\n NotifyAboutWrongPw,\n\n /// If a warning about exceeding quota was shown recently,\n /// this is the percentage of quota at the time the warning was given.\n /// Unset, when quota falls below minimal warning threshold again.\n QuotaExceeding,\n\n /// address to webrtc instance to use for videochats\n WebrtcInstance,\n\n /// Timestamp of the last time housekeeping was run\n LastHousekeeping,\n\n /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.\n LastCantDecryptOutgoingMsgs,\n\n /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.\n #[strum(props(default = \"60\"))]\n ScanAllFoldersDebounceSecs,\n\n /// Whether to avoid using IMAP IDLE even if the server supports it.\n ///\n /// This is a developer option for testing \"fake idle\".\n #[strum(props(default = \"0\"))]\n DisableIdle,\n\n /// Defines the max. size (in bytes) of messages downloaded automatically.\n /// 0 = no limit.\n #[strum(props(default = \"0\"))]\n DownloadLimit,\n\n /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.\n #[strum(props(default = \"1\"))]\n SyncMsgs,\n\n /// Space-separated list of all the authserv-ids which we believe\n /// may be the one of our email server.\n ///\n /// See `crate::authres::update_authservid_candidates`.\n AuthservIdCandidates,\n\n /// Make all outgoing messages with Autocrypt header \"multipart/signed\".\n SignUnencrypted,\n\n /// Let the core save all events to the database.\n /// This value is used internally to remember the MsgId of the logging xdc\n #[strum(props(default = \"0\"))]\n DebugLogging,\n\n /// Last message processed by the bot.\n LastMsgId,\n\n /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by\n /// default.\n ///\n /// This is not supposed to be changed by UIs and only used for testing.\n #[strum(props(default = \"172800\"))]\n GossipPeriod,\n\n /// Feature flag for verified 1:1 chats; the UI should set it\n /// to 1 if it supports verified 1:1 chats.\n /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,\n /// and when the key changes, an info message is posted into the chat.\n /// 0=Nothing else happens when the key changes.\n /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true\n /// until `chat_id.accept()` is called.\n #[strum(props(default = \"0\"))]\n VerifiedOneOnOneChats,\n\n /// Row ID of the key in the `keypairs` table\n /// used for signatures, encryption to self and included in `Autocrypt` header.\n KeyId,\n\n /// This key is sent to the self_reporting bot so that the bot can recognize the user\n /// without storing the email address\n SelfReportingId,\n\n /// MsgId of webxdc map integration.\n WebxdcIntegration,\n\n /// Iroh secret key.\n IrohSecretKey,\n}", "rust_imports": "use std::collections::HashMap;\nuse anyhow::Result;\nuse percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};\nuse serde::Deserialize;\nuse crate::config::Config;\nuse crate::context::Context;\nuse crate::provider;\nuse crate::provider::Oauth2Authorizer;\nuse crate::socks::Socks5Config;\nuse crate::tools::time;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__oauth2__.rs__function__2.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "int dc_chat_get_type(const dc_chat_t* chat)\n{\n\tif (chat==NULL || chat->magic!=DC_CHAT_MAGIC) {\n\t\treturn DC_CHAT_TYPE_UNDEFINED;\n\t}\n\treturn chat->type;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub fn get_type(&self) -> Chattype {\n self.typ\n }", "rust_context": "pub struct Chat {\n /// Database ID.\n pub id: ChatId,\n\n /// Chat type, e.g. 1:1 chat, group chat, mailing list.\n pub typ: Chattype,\n\n /// Chat name.\n pub name: String,\n\n /// Whether the chat is archived or pinned.\n pub visibility: ChatVisibility,\n\n /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and\n /// ad-hoc groups.\n pub grpid: String,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n\n /// Additional chat parameters stored in the database.\n pub param: Params,\n\n /// If location streaming is enabled in the chat.\n is_sending_locations: bool,\n\n /// Duration of the chat being muted.\n pub mute_duration: MuteDuration,\n\n /// If the chat is protected (verified).\n pub(crate) protected: ProtectionStatus,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__70.txt"} {"c_path": "projects/deltachat-core/c/dc_imex.c", "c_func": "char* dc_decrypt_setup_file(dc_context_t* context, const char* passphrase, const char* filecontent)\n{\n\tchar* binary = NULL;\n\tsize_t binary_bytes = 0;\n\tsize_t indx = 0;\n\tvoid* plain = NULL;\n\tsize_t plain_bytes = 0;\n\tchar* payload = NULL;\n\n\t/* decrypt symmetrically */\n\tif (!dc_pgp_symm_decrypt(context, passphrase, binary, binary_bytes, &plain, &plain_bytes)) {\n\t\tgoto cleanup;\n\t}\n\tpayload = strndup((const char*)plain, plain_bytes);\n\ncleanup:\n\tfree(plain);\n\tif (binary) { mmap_string_unref(binary); }\n\treturn payload;\n}", "rust_path": "projects/deltachat-core/rust/imex.rs", "rust_func": "async fn decrypt_setup_file(\n passphrase: &str,\n file: T,\n) -> Result {\n let plain_bytes = pgp::symm_decrypt(passphrase, file).await?;\n let plain_text = std::string::String::from_utf8(plain_bytes)?;\n\n Ok(plain_text)\n}", "rust_context": "pub async fn symm_decrypt(\n passphrase: &str,\n ctext: T,\n) -> Result> {\n let (enc_msg, _) = Message::from_armor_single(ctext)?;\n\n let passphrase = passphrase.to_string();\n tokio::task::spawn_blocking(move || {\n let decryptor = enc_msg.decrypt_with_password(|| passphrase)?;\n\n let msgs = decryptor.collect::>>()?;\n if let Some(msg) = msgs.first() {\n match msg.get_content()? {\n Some(content) => Ok(content),\n None => bail!(\"Decrypted message is empty\"),\n }\n } else {\n bail!(\"No valid messages found\")\n }\n })\n .await?\n}", "rust_imports": "use std::any::Any;\nuse std::ffi::OsStr;\nuse std::path::{Path, PathBuf};\nuse ::pgp::types::KeyTrait;\nuse anyhow::{bail, ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse futures::StreamExt;\nuse futures_lite::FutureExt;\nuse rand::{thread_rng, Rng};\nuse tokio::fs::{self, File};\nuse tokio_tar::Archive;\nuse crate::blob::{BlobDirContents, BlobObject};\nuse crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};\nuse crate::config::Config;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::e2ee;\nuse crate::events::EventType;\nuse crate::key::{\n self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,\n};\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::param::Param;\nuse crate::pgp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{\n create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,\n};\nuse transfer::{get_backup, BackupProvider};\nuse std::time::Duration;\nuse ::pgp::armor::BlockType;\nuse tokio::task;\nuse super::*;\nuse crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::{alice_keypair, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__imex__.rs__function__9.txt"} {"c_path": "projects/deltachat-core/c/dc_imex.c", "c_func": "char* dc_normalize_setup_code(dc_context_t* context, const char* in)\n{\n\tif (in==NULL) {\n\t\treturn NULL;\n\t}\n\n\tdc_strbuilder_t out;\n\tdc_strbuilder_init(&out, 0);\n\tint outlen = 0;\n\n\tconst char* p1 = in;\n\twhile (*p1) {\n\t\tif (*p1 >= '0' && *p1 <= '9') {\n\t\t\tdc_strbuilder_catf(&out, \"%c\", *p1);\n\t\t\toutlen = strlen(out.buf);\n\t\t\tif (outlen==4 || outlen==9 || outlen==14 || outlen==19 || outlen==24 || outlen==29 || outlen==34 || outlen==39) {\n\t\t\t\tdc_strbuilder_cat(&out, \"-\");\n\t\t\t}\n\t\t}\n\t\tp1++;\n\t}\n\n\treturn out.buf;\n}", "rust_path": "projects/deltachat-core/rust/imex.rs", "rust_func": "fn normalize_setup_code(s: &str) -> String {\n let mut out = String::new();\n for c in s.chars() {\n if c.is_ascii_digit() {\n out.push(c);\n if let 4 | 9 | 14 | 19 | 24 | 29 | 34 | 39 = out.len() {\n out += \"-\"\n }\n }\n }\n out\n}", "rust_context": "", "rust_imports": "use std::any::Any;\nuse std::ffi::OsStr;\nuse std::path::{Path, PathBuf};\nuse ::pgp::types::KeyTrait;\nuse anyhow::{bail, ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse futures::StreamExt;\nuse futures_lite::FutureExt;\nuse rand::{thread_rng, Rng};\nuse tokio::fs::{self, File};\nuse tokio_tar::Archive;\nuse crate::blob::{BlobDirContents, BlobObject};\nuse crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};\nuse crate::config::Config;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::e2ee;\nuse crate::events::EventType;\nuse crate::key::{\n self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,\n};\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::param::Param;\nuse crate::pgp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{\n create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,\n};\nuse transfer::{get_backup, BackupProvider};\nuse std::time::Duration;\nuse ::pgp::armor::BlockType;\nuse tokio::task;\nuse super::*;\nuse crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::{alice_keypair, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__imex__.rs__function__10.txt"} {"c_path": "projects/deltachat-core/c/dc_aheader.c", "c_func": "int dc_aheader_set_from_string(dc_aheader_t* aheader, const char* header_str__)\n{\n\t/* according to RFC 5322 (Internet Message Format), the given string may contain `\\r\\n` before any whitespace.\n\twe can ignore this issue as\n\t(a) no key or value is expected to contain spaces,\n\t(b) for the key, non-base64-characters are ignored and\n\t(c) for parsing, we ignore `\\r\\n` as well as tabs for spaces */\n\t#define AHEADER_WS \"\\t\\r\\n \"\n\tchar* header_str = NULL;\n\tchar* p = NULL;\n\tchar* beg_attr_name = NULL;\n\tchar* after_attr_name = NULL;\n\tchar* beg_attr_value = NULL;\n\tint success = 0;\n\n\tdc_aheader_empty(aheader);\n\n\tif (aheader==NULL || header_str__==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\taheader->prefer_encrypt = DC_PE_NOPREFERENCE; /* value to use if the prefer-encrypted header is missing */\n\n\theader_str = dc_strdup(header_str__);\n\tp = header_str;\n\twhile (*p)\n\t{\n\t\tp += strspn(p, AHEADER_WS \"=;\"); /* forward to first attribute name beginning */\n\t\tbeg_attr_name = p;\n\t\tbeg_attr_value = NULL;\n\t\tp += strcspn(p, AHEADER_WS \"=;\"); /* get end of attribute name (an attribute may have no value) */\n\t\tif (p!=beg_attr_name)\n\t\t{\n\t\t\t/* attribute found */\n\t\t\tafter_attr_name = p;\n\t\t\tp += strspn(p, AHEADER_WS); /* skip whitespace between attribute name and possible `=` */\n\t\t\tif (*p=='=')\n\t\t\t{\n\t\t\t\tp += strspn(p, AHEADER_WS \"=\"); /* skip spaces and equal signs */\n\n\t\t\t\t/* read unquoted attribute value until the first semicolon */\n\t\t\t\tbeg_attr_value = p;\n\t\t\t\tp += strcspn(p, \";\");\n\t\t\t\tif (*p!='\\0') {\n\t\t\t\t\t*p = '\\0';\n\t\t\t\t\tp++;\n\t\t\t\t}\n\t\t\t\tdc_trim(beg_attr_value);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tp += strspn(p, AHEADER_WS \";\");\n\t\t\t}\n\t\t\t*after_attr_name = '\\0';\n\t\t\tif (!add_attribute(aheader, beg_attr_name, beg_attr_value)) {\n\t\t\t\tgoto cleanup; /* a bad attribute makes the whole header invalid */\n\t\t\t}\n\t\t}\n\t}\n\n\t/* all needed data found? */\n\tif (aheader->addr && aheader->public_key->binary) {\n\t\tsuccess = 1;\n\t}\n\ncleanup:\n\tfree(header_str);\n\tif (!success) { dc_aheader_empty(aheader); }\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/aheader.rs", "rust_func": "fn from_str(s: &str) -> Result {\n let mut attributes: BTreeMap = s\n .split(';')\n .filter_map(|a| {\n let attribute: Vec<&str> = a.trim().splitn(2, '=').collect();\n match &attribute[..] {\n [key, value] => Some((key.trim().to_string(), value.trim().to_string())),\n _ => None,\n }\n })\n .collect();\n\n let addr = match attributes.remove(\"addr\") {\n Some(addr) => addr,\n None => bail!(\"Autocrypt header has no addr\"),\n };\n let public_key: SignedPublicKey = attributes\n .remove(\"keydata\")\n .context(\"keydata attribute is not found\")\n .and_then(|raw| {\n SignedPublicKey::from_base64(&raw).context(\"autocrypt key cannot be decoded\")\n })\n .and_then(|key| {\n key.verify()\n .and(Ok(key))\n .context(\"autocrypt key cannot be verified\")\n })?;\n\n let prefer_encrypt = attributes\n .remove(\"prefer-encrypt\")\n .and_then(|raw| raw.parse().ok())\n .unwrap_or_default();\n\n // Autocrypt-Level0: unknown attributes starting with an underscore can be safely ignored\n // Autocrypt-Level0: unknown attribute, treat the header as invalid\n if attributes.keys().any(|k| !k.starts_with('_')) {\n bail!(\"Unknown Autocrypt attribute found\");\n }\n\n Ok(Aheader {\n addr,\n public_key,\n prefer_encrypt,\n })\n }", "rust_context": "pub struct Aheader {\n pub addr: String,\n pub public_key: SignedPublicKey,\n pub prefer_encrypt: EncryptPreference,\n}\n\nfn from_base64(data: &str) -> Result {\n // strip newlines and other whitespace\n let cleaned: String = data.split_whitespace().collect();\n let bytes = base64::engine::general_purpose::STANDARD.decode(cleaned.as_bytes())?;\n Self::from_slice(&bytes)\n }", "rust_imports": "use std::collections::BTreeMap;\nuse std::fmt;\nuse std::str::FromStr;\nuse anyhow::{bail, Context as _, Error, Result};\nuse crate::key::{DcKey, SignedPublicKey};\nuse super::*;", "rustrepotrans_file": "projects__deltachat-core__rust__aheader__.rs__function__5.txt"} {"c_path": "projects/deltachat-core/c/dc_param.c", "c_func": "dc_param_t* dc_param_new()\n{\n\tdc_param_t* param = NULL;\n\n\tif ((param=calloc(1, sizeof(dc_param_t)))==NULL) {\n\t\texit(28); /* cannot allocate little memory, unrecoverable error */\n\t}\n\n\tparam->packed = calloc(1, 1);\n\n return param;\n}", "rust_path": "projects/deltachat-core/rust/param.rs", "rust_func": "pub fn new() -> Self {\n Default::default()\n }", "rust_context": "pub struct Params {\n inner: BTreeMap,\n}", "rust_imports": "use std::collections::BTreeMap;\nuse std::fmt;\nuse std::path::PathBuf;\nuse std::str;\nuse anyhow::{bail, Error, Result};\nuse num_traits::FromPrimitive;\nuse serde::{Deserialize, Serialize};\nuse crate::blob::BlobObject;\nuse crate::context::Context;\nuse crate::mimeparser::SystemMessage;\nuse std::path::Path;\nuse std::str::FromStr;\nuse tokio::fs;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__param__.rs__function__3.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "int dc_contact_is_blocked(const dc_contact_t* contact)\n{\n\tif (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn contact->blocked;\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub fn is_blocked(&self) -> bool {\n self.blocked\n }", "rust_context": "pub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__14.txt"} {"c_path": "projects/deltachat-core/c/dc_context.c", "c_func": "dc_array_t* dc_get_fresh_msgs(dc_context_t* context)\n{\n\tint show_deaddrop = 0;\n\tdc_array_t* ret = dc_array_new(context, 128);\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || ret==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT m.id\"\n\t\t\" FROM msgs m\"\n\t\t\" LEFT JOIN contacts ct ON m.from_id=ct.id\"\n\t\t\" LEFT JOIN chats c ON m.chat_id=c.id\"\n\t\t\" WHERE m.state=?\"\n\t\t\" AND m.hidden=0\"\n\t\t\" AND m.chat_id>?\"\n\t\t\" AND ct.blocked=0\"\n \" AND c.blocked=0\"\n\t\t\" AND NOT(c.muted_until=-1 OR c.muted_until>?)\"\n\t\t\" ORDER BY m.timestamp DESC,m.id DESC;\");\n\tsqlite3_bind_int(stmt, 1, DC_STATE_IN_FRESH);\n\tsqlite3_bind_int(stmt, 2, DC_CHAT_ID_LAST_SPECIAL);\n\tsqlite3_bind_int(stmt, 3, show_deaddrop? DC_CHAT_DEADDROP_BLOCKED : 0);\n\n\twhile (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\tdc_array_add_id(ret, sqlite3_column_int(stmt, 0));\n\t}\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/context.rs", "rust_func": "pub async fn get_fresh_msgs(&self) -> Result> {\n let list = self\n .sql\n .query_map(\n concat!(\n \"SELECT m.id\",\n \" FROM msgs m\",\n \" LEFT JOIN contacts ct\",\n \" ON m.from_id=ct.id\",\n \" LEFT JOIN chats c\",\n \" ON m.chat_id=c.id\",\n \" WHERE m.state=?\",\n \" AND m.hidden=0\",\n \" AND m.chat_id>9\",\n \" AND ct.blocked=0\",\n \" AND c.blocked=0\",\n \" AND NOT(c.muted_until=-1 OR c.muted_until>?)\",\n \" ORDER BY m.timestamp DESC,m.id DESC;\"\n ),\n (MessageState::InFresh, time()),\n |row| row.get::<_, MsgId>(0),\n |rows| {\n let mut list = Vec::new();\n for row in rows {\n list.push(row?);\n }\n Ok(list)\n },\n )\n .await?;\n Ok(list)\n }", "rust_context": "pub(crate) fn time() -> i64 {\n SystemTime::now()\n .duration_since(SystemTime::UNIX_EPOCH)\n .unwrap_or_default()\n .as_secs() as i64\n}\n\npub async fn query_map(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n mut g: G,\n ) -> Result\n where\n F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result,\n G: Send + FnMut(rusqlite::MappedRows) -> Result,\n H: Send + 'static,\n {\n self.call(move |conn| {\n let mut stmt = conn.prepare(sql)?;\n let res = stmt.query_map(params, f)?;\n g(res)\n })\n .await\n }\n\npub struct MsgId(u32);\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub enum MessageState {\n /// Undefined message state.\n #[default]\n Undefined = 0,\n\n /// Incoming *fresh* message. Fresh messages are neither noticed\n /// nor seen and are typically shown in notifications.\n InFresh = 10,\n\n /// Incoming *noticed* message. E.g. chat opened but message not\n /// yet read - noticed messages are not counted as unread but did\n /// not marked as read nor resulted in MDNs.\n InNoticed = 13,\n\n /// Incoming message, really *seen* by the user. Marked as read on\n /// IMAP and MDN may be sent.\n InSeen = 16,\n\n /// For files which need time to be prepared before they can be\n /// sent, the message enters this state before\n /// OutPending.\n OutPreparing = 18,\n\n /// Message saved as draft.\n OutDraft = 19,\n\n /// The user has pressed the \"send\" button but the message is not\n /// yet sent and is pending in some way. Maybe we're offline (no\n /// checkmark).\n OutPending = 20,\n\n /// *Unrecoverable* error (*recoverable* errors result in pending\n /// messages).\n OutFailed = 24,\n\n /// Outgoing message successfully delivered to server (one\n /// checkmark). Note, that already delivered messages may get into\n /// the OutFailed state if we get such a hint from the server.\n OutDelivered = 26,\n\n /// Outgoing message read by the recipient (two checkmarks; this\n /// requires goodwill on the receiver's side)\n OutMdnRcvd = 28,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}", "rust_imports": "use std::collections::{BTreeMap, HashMap};\nuse std::ffi::OsString;\nuse std::ops::Deref;\nuse std::path::{Path, PathBuf};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\nuse std::time::Duration;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse pgp::SignedPublicKey;\nuse ratelimit::Ratelimit;\nuse tokio::sync::{Mutex, Notify, OnceCell, RwLock};\nuse crate::aheader::EncryptPreference;\nuse crate::chat::{get_chat_cnt, ChatId, ProtectionStatus};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::debug_logging::DebugLogging;\nuse crate::download::DownloadState;\nuse crate::events::{Event, EventEmitter, EventType, Events};\nuse crate::imap::{FolderMeaning, Imap, ServerMetadata};\nuse crate::key::{load_self_public_key, load_self_secret_key, DcKey as _};\nuse crate::login_param::LoginParam;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peer_channels::Iroh;\nuse crate::peerstate::Peerstate;\nuse crate::push::PushSubscriber;\nuse crate::quota::QuotaInfo;\nuse crate::scheduler::{convert_folder_meaning, SchedulerState};\nuse crate::sql::Sql;\nuse crate::stock_str::StockStrings;\nuse crate::timesmearing::SmearedTimestamp;\nuse crate::tools::{self, create_id, duration_to_str, time, time_elapsed};\nuse anyhow::Context as _;\nuse strum::IntoEnumIterator;\nuse tempfile::tempdir;\nuse super::*;\nuse crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration};\nuse crate::chatlist::Chatlist;\nuse crate::constants::Chattype;\nuse crate::mimeparser::SystemMessage;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{get_chat_msg, TestContext};\nuse crate::tools::{create_outgoing_rfc724_mid, SystemTime};", "rustrepotrans_file": "projects__deltachat-core__rust__context__.rs__function__44.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_is_setupmessage(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->type!=DC_MSG_FILE) {\n\t\treturn 0;\n\t}\n\n\treturn dc_param_get_int(msg->param, DC_PARAM_CMD, 0)==DC_CMD_AUTOCRYPT_SETUP_MESSAGE? 1 : 0;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn is_setupmessage(&self) -> bool {\n if self.viewtype != Viewtype::File {\n return false;\n }\n\n self.param.get_cmd() == SystemMessage::AutocryptSetupMessage\n }", "rust_context": "pub fn get_cmd(&self) -> SystemMessage {\n self.get_int(Param::Cmd)\n .and_then(SystemMessage::from_i32)\n .unwrap_or_default()\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}\n\npub enum SystemMessage {\n /// Unknown type of system message.\n #[default]\n Unknown = 0,\n\n /// Group name changed.\n GroupNameChanged = 2,\n\n /// Group avatar changed.\n GroupImageChanged = 3,\n\n /// Member was added to the group.\n MemberAddedToGroup = 4,\n\n /// Member was removed from the group.\n MemberRemovedFromGroup = 5,\n\n /// Autocrypt Setup Message.\n AutocryptSetupMessage = 6,\n\n /// Secure-join message.\n SecurejoinMessage = 7,\n\n /// Location streaming is enabled.\n LocationStreamingEnabled = 8,\n\n /// Location-only message.\n LocationOnly = 9,\n\n /// Chat ephemeral message timer is changed.\n EphemeralTimerChanged = 10,\n\n /// \"Messages are guaranteed to be end-to-end encrypted from now on.\"\n ChatProtectionEnabled = 11,\n\n /// \"%1$s sent a message from another device.\"\n ChatProtectionDisabled = 12,\n\n /// Message can't be sent because of `Invalid unencrypted mail to <>`\n /// which is sent by chatmail servers.\n InvalidUnencryptedMail = 13,\n\n /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it\n /// to complete.\n SecurejoinWait = 14,\n\n /// 1:1 chats info message telling that SecureJoin is still running, but the user may already\n /// send messages.\n SecurejoinWaitTimeout = 15,\n\n /// Self-sent-message that contains only json used for multi-device-sync;\n /// if possible, we attach that to other messages as for locations.\n MultiDeviceSync = 20,\n\n /// Sync message that contains a json payload\n /// sent to the other webxdc instances\n /// These messages are not shown in the chat.\n WebxdcStatusUpdate = 30,\n\n /// Webxdc info added with `info` set in `send_webxdc_status_update()`.\n WebxdcInfoMessage = 32,\n\n /// This message contains a users iroh node address.\n IrohNodeAddr = 40,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__60.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "dc_array_t* dc_get_contacts(dc_context_t* context, uint32_t listflags, const char* query)\n{\n\tchar* self_addr = NULL;\n\tchar* self_name = NULL;\n\tchar* self_name2 = NULL;\n\tint add_self = 0;\n\tdc_array_t* ret = dc_array_new(context, 100);\n\tchar* s3strLikeCmd = NULL;\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tself_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 */\n\n\tif ((listflags&DC_GCL_VERIFIED_ONLY) || query)\n\t{\n\t\tif ((s3strLikeCmd=sqlite3_mprintf(\"%%%s%%\", query? query : \"\"))==NULL) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\t// see comments in dc_search_msgs() about the LIKE operator\n\t\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\t\"SELECT c.id FROM contacts c\"\n\t\t\t\t\" LEFT JOIN acpeerstates ps ON c.addr=ps.addr \"\n\t\t\t\t\" WHERE c.addr!=?1 AND c.id>?2 AND c.origin>=?3\"\n\t\t\t\t\" AND c.blocked=0 AND (c.name LIKE ?4 OR c.addr LIKE ?5)\"\n\t\t\t\t\" AND (1=?6 OR LENGTH(ps.verified_key_fingerprint)!=0) \"\n\t\t\t\t\" ORDER BY LOWER(c.name||c.addr),c.id;\");\n\t\tsqlite3_bind_text(stmt, 1, self_addr, -1, SQLITE_STATIC);\n\t\tsqlite3_bind_int (stmt, 2, DC_CONTACT_ID_LAST_SPECIAL);\n\t\tsqlite3_bind_int (stmt, 3, DC_ORIGIN_MIN_CONTACT_LIST);\n\t\tsqlite3_bind_text(stmt, 4, s3strLikeCmd, -1, SQLITE_STATIC);\n\t\tsqlite3_bind_text(stmt, 5, s3strLikeCmd, -1, SQLITE_STATIC);\n\t\tsqlite3_bind_int (stmt, 6, (listflags&DC_GCL_VERIFIED_ONLY)? 0/*force checking for verified_key*/ : 1/*force statement being always true*/);\n\n\t\tself_name = dc_sqlite3_get_config(context->sql, \"displayname\", \"\");\n\t\tself_name2 = dc_stock_str(context, DC_STR_SELF);\n\t\tif (query==NULL || dc_str_contains(self_addr, query) || dc_str_contains(self_name, query) || dc_str_contains(self_name2, query)) {\n\t\t\tadd_self = 1;\n\t\t}\n\t}\n\telse\n\t{\n\t\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\t\"SELECT id FROM contacts\"\n\t\t\t\t\" WHERE addr!=?1 AND id>?2 AND origin>=?3 AND blocked=0\"\n\t\t\t\t\" ORDER BY LOWER(name||addr),id;\");\n\t\tsqlite3_bind_text(stmt, 1, self_addr, -1, SQLITE_STATIC);\n\t\tsqlite3_bind_int (stmt, 2, DC_CONTACT_ID_LAST_SPECIAL);\n\t\tsqlite3_bind_int (stmt, 3, DC_ORIGIN_MIN_CONTACT_LIST);\n\n\t\tadd_self = 1;\n\t}\n\n\twhile (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\tdc_array_add_id(ret, sqlite3_column_int(stmt, 0));\n\t}\n\n\t/* 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 */\n\tif ((listflags&DC_GCL_ADD_SELF) && add_self) {\n\t\tdc_array_add_id(ret, DC_CONTACT_ID_SELF);\n\t}\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\tsqlite3_free(s3strLikeCmd);\n\tfree(self_addr);\n\tfree(self_name);\n\tfree(self_name2);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub async fn get_all(\n context: &Context,\n listflags: u32,\n query: Option<&str>,\n ) -> Result> {\n let self_addrs = context.get_all_self_addrs().await?;\n let mut add_self = false;\n let mut ret = Vec::new();\n let flag_verified_only = (listflags & DC_GCL_VERIFIED_ONLY) != 0;\n let flag_add_self = (listflags & DC_GCL_ADD_SELF) != 0;\n let minimal_origin = if context.get_config_bool(Config::Bot).await? {\n Origin::Unknown\n } else {\n Origin::IncomingReplyTo\n };\n if flag_verified_only || query.is_some() {\n let s3str_like_cmd = format!(\"%{}%\", query.unwrap_or(\"\"));\n context\n .sql\n .query_map(\n &format!(\n \"SELECT c.id FROM contacts c \\\n LEFT JOIN acpeerstates ps ON c.addr=ps.addr \\\n WHERE c.addr NOT IN ({})\n AND c.id>? \\\n AND c.origin>=? \\\n AND c.blocked=0 \\\n AND (iif(c.name='',c.authname,c.name) LIKE ? OR c.addr LIKE ?) \\\n AND (1=? OR LENGTH(ps.verified_key_fingerprint)!=0) \\\n ORDER BY c.last_seen DESC, c.id DESC;\",\n sql::repeat_vars(self_addrs.len())\n ),\n rusqlite::params_from_iter(params_iter(&self_addrs).chain(params_slice![\n ContactId::LAST_SPECIAL,\n minimal_origin,\n s3str_like_cmd,\n s3str_like_cmd,\n if flag_verified_only { 0i32 } else { 1i32 }\n ])),\n |row| row.get::<_, ContactId>(0),\n |ids| {\n for id in ids {\n ret.push(id?);\n }\n Ok(())\n },\n )\n .await?;\n\n if let Some(query) = query {\n let self_addr = context\n .get_config(Config::ConfiguredAddr)\n .await?\n .unwrap_or_default();\n let self_name = context\n .get_config(Config::Displayname)\n .await?\n .unwrap_or_default();\n let self_name2 = stock_str::self_msg(context);\n\n if self_addr.contains(query)\n || self_name.contains(query)\n || self_name2.await.contains(query)\n {\n add_self = true;\n }\n } else {\n add_self = true;\n }\n } else {\n add_self = true;\n\n context\n .sql\n .query_map(\n &format!(\n \"SELECT id FROM contacts\n WHERE addr NOT IN ({})\n AND id>?\n AND origin>=?\n AND blocked=0\n ORDER BY last_seen DESC, id DESC;\",\n sql::repeat_vars(self_addrs.len())\n ),\n rusqlite::params_from_iter(\n params_iter(&self_addrs)\n .chain(params_slice![ContactId::LAST_SPECIAL, minimal_origin]),\n ),\n |row| row.get::<_, ContactId>(0),\n |ids| {\n for id in ids {\n ret.push(id?);\n }\n Ok(())\n },\n )\n .await?;\n }\n\n if flag_add_self && add_self {\n ret.push(ContactId::SELF);\n }\n\n Ok(ret)\n }", "rust_context": "pub async fn get_config_bool(&self, key: Config) -> Result {\n Ok(self.get_config_bool_opt(key).await?.unwrap_or_default())\n }\n\nmacro_rules! params_slice {\n ($($param:expr),+) => {\n [$(&$param as &dyn $crate::sql::ToSql),+]\n };\n}\n\npub(crate) fn params_iter(\n iter: &[impl crate::sql::ToSql],\n) -> impl Iterator {\n iter.iter().map(|item| item as &dyn crate::sql::ToSql)\n}\n\npub async fn query_map(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n mut g: G,\n ) -> Result\n where\n F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result,\n G: Send + FnMut(rusqlite::MappedRows) -> Result,\n H: Send + 'static,\n {\n self.call(move |conn| {\n let mut stmt = conn.prepare(sql)?;\n let res = stmt.query_map(params, f)?;\n g(res)\n })\n .await\n }\n\npub async fn get_config(&self, key: Config) -> Result> {\n let env_key = format!(\"DELTACHAT_{}\", key.as_ref().to_uppercase());\n if let Ok(value) = env::var(env_key) {\n return Ok(Some(value));\n }\n\n let value = match key {\n Config::Selfavatar => {\n let rel_path = self.sql.get_raw_config(key.as_ref()).await?;\n rel_path.map(|p| {\n get_abs_path(self, Path::new(&p))\n .to_string_lossy()\n .into_owned()\n })\n }\n Config::SysVersion => Some((*DC_VERSION_STR).clone()),\n Config::SysMsgsizeMaxRecommended => Some(format!(\"{RECOMMENDED_FILE_SIZE}\")),\n Config::SysConfigKeys => Some(get_config_keys_string()),\n _ => self.sql.get_raw_config(key.as_ref()).await?,\n };\n\n if value.is_some() {\n return Ok(value);\n }\n\n // Default values\n match key {\n Config::ConfiguredInboxFolder => Ok(Some(\"INBOX\".to_owned())),\n _ => Ok(key.get_str(\"default\").map(|s| s.to_string())),\n }\n }\n\npub(crate) async fn get_all_self_addrs(&self) -> Result> {\n let primary_addrs = self.get_config(Config::ConfiguredAddr).await?.into_iter();\n let secondary_addrs = self.get_secondary_self_addrs().await?.into_iter();\n\n Ok(primary_addrs.chain(secondary_addrs).collect())\n }\n\npub fn repeat_vars(count: usize) -> String {\n let mut s = \"?,\".repeat(count);\n s.pop(); // Remove trailing comma\n s\n}\n\npub(crate) async fn self_msg(context: &Context) -> String {\n translated(context, StockMessage::SelfMsg).await\n}\n\npub fn params_from_iter(iter: I) -> ParamsFromIter\nwhere\n I: IntoIterator,\n I::Item: ToSql,\n{\n ParamsFromIter(iter)\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\n\npub struct ContactId(u32);\n\nimpl ContactId {\n /// The owner of the account.\n ///\n /// The email-address is set by `set_config` using \"addr\".\n pub const SELF: ContactId = ContactId::new(1);\n\n\n /// ID of the contact for device messages.\n pub const DEVICE: ContactId = ContactId::new(5);\n pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9);\n}\n\npub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}\n\npub enum Config {\n /// Email address, used in the `From:` field.\n Addr,\n\n /// IMAP server hostname.\n MailServer,\n\n /// IMAP server username.\n MailUser,\n\n /// IMAP server password.\n MailPw,\n\n /// IMAP server port.\n MailPort,\n\n /// IMAP server security (e.g. TLS, STARTTLS).\n MailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ImapCertificateChecks,\n\n /// SMTP server hostname.\n SendServer,\n\n /// SMTP server username.\n SendUser,\n\n /// SMTP server password.\n SendPw,\n\n /// SMTP server port.\n SendPort,\n\n /// SMTP server security (e.g. TLS, STARTTLS).\n SendSecurity,\n\n /// How to check SMTP server TLS certificates.\n SmtpCertificateChecks,\n\n /// Whether to use OAuth 2.\n ///\n /// Historically contained other bitflags, which are now deprecated.\n /// Should not be extended in the future, create new config keys instead.\n ServerFlags,\n\n /// True if SOCKS5 is enabled.\n ///\n /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.\n Socks5Enabled,\n\n /// SOCKS5 proxy server hostname or address.\n Socks5Host,\n\n /// SOCKS5 proxy server port.\n Socks5Port,\n\n /// SOCKS5 proxy server username.\n Socks5User,\n\n /// SOCKS5 proxy server password.\n Socks5Password,\n\n /// Own name to use in the `From:` field when sending messages.\n Displayname,\n\n /// Own status to display, sent in message footer.\n Selfstatus,\n\n /// Own avatar filename.\n Selfavatar,\n\n /// Send BCC copy to self.\n ///\n /// Should be enabled for multidevice setups.\n #[strum(props(default = \"1\"))]\n BccSelf,\n\n /// True if encryption is preferred according to Autocrypt standard.\n #[strum(props(default = \"1\"))]\n E2eeEnabled,\n\n /// True if Message Delivery Notifications (read receipts) should\n /// be sent and requested.\n #[strum(props(default = \"1\"))]\n MdnsEnabled,\n\n /// True if \"Sent\" folder should be watched for changes.\n #[strum(props(default = \"0\"))]\n SentboxWatch,\n\n /// True if chat messages should be moved to a separate folder.\n #[strum(props(default = \"1\"))]\n MvboxMove,\n\n /// Watch for new messages in the \"Mvbox\" (aka DeltaChat folder) only.\n ///\n /// This will not entirely disable other folders, e.g. the spam folder will also still\n /// be watched for new messages.\n #[strum(props(default = \"0\"))]\n OnlyFetchMvbox,\n\n /// Whether to show classic emails or only chat messages.\n #[strum(props(default = \"2\"))] // also change ShowEmails.default() on changes\n ShowEmails,\n\n /// Quality of the media files to send.\n #[strum(props(default = \"0\"))] // also change MediaQuality.default() on changes\n MediaQuality,\n\n /// If set to \"1\", on the first time `start_io()` is called after configuring,\n /// the newest existing messages are fetched.\n /// Existing recipients are added to the contact database regardless of this setting.\n #[strum(props(default = \"0\"))]\n FetchExistingMsgs,\n\n /// If set to \"1\", then existing messages are considered to be already fetched.\n /// This flag is reset after successful configuration.\n #[strum(props(default = \"1\"))]\n FetchedExistingMsgs,\n\n /// Type of the OpenPGP key to generate.\n #[strum(props(default = \"0\"))]\n KeyGenType,\n\n /// Timer in seconds after which the message is deleted from the\n /// server.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n ///\n /// Value 1 is treated as \"delete at once\": messages are deleted\n /// immediately, without moving to DeltaChat folder.\n #[strum(props(default = \"0\"))]\n DeleteServerAfter,\n\n /// Timer in seconds after which the message is deleted from the\n /// device.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n #[strum(props(default = \"0\"))]\n DeleteDeviceAfter,\n\n /// Move messages to the Trash folder instead of marking them \"\\Deleted\". Overrides\n /// `ProviderOptions::delete_to_trash`.\n DeleteToTrash,\n\n /// Save raw MIME messages with headers in the database if true.\n SaveMimeHeaders,\n\n /// The primary email address. Also see `SecondaryAddrs`.\n ConfiguredAddr,\n\n /// Configured IMAP server hostname.\n ConfiguredMailServer,\n\n /// Configured IMAP server username.\n ConfiguredMailUser,\n\n /// Configured IMAP server password.\n ConfiguredMailPw,\n\n /// Configured IMAP server port.\n ConfiguredMailPort,\n\n /// Configured IMAP server security (e.g. TLS, STARTTLS).\n ConfiguredMailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ConfiguredImapCertificateChecks,\n\n /// Configured SMTP server hostname.\n ConfiguredSendServer,\n\n /// Configured SMTP server username.\n ConfiguredSendUser,\n\n /// Configured SMTP server password.\n ConfiguredSendPw,\n\n /// Configured SMTP server port.\n ConfiguredSendPort,\n\n /// How to check SMTP server TLS certificates.\n ConfiguredSmtpCertificateChecks,\n\n /// Whether OAuth 2 is used with configured provider.\n ConfiguredServerFlags,\n\n /// Configured SMTP server security (e.g. TLS, STARTTLS).\n ConfiguredSendSecurity,\n\n /// Configured folder for incoming messages.\n ConfiguredInboxFolder,\n\n /// Configured folder for chat messages.\n ConfiguredMvboxFolder,\n\n /// Configured \"Sent\" folder.\n ConfiguredSentboxFolder,\n\n /// Configured \"Trash\" folder.\n ConfiguredTrashFolder,\n\n /// Unix timestamp of the last successful configuration.\n ConfiguredTimestamp,\n\n /// ID of the configured provider from the provider database.\n ConfiguredProvider,\n\n /// True if account is configured.\n Configured,\n\n /// True if account is a chatmail account.\n IsChatmail,\n\n /// All secondary self addresses separated by spaces\n /// (`addr1@example.org addr2@example.org addr3@example.org`)\n SecondaryAddrs,\n\n /// Read-only core version string.\n #[strum(serialize = \"sys.version\")]\n SysVersion,\n\n /// Maximal recommended attachment size in bytes.\n #[strum(serialize = \"sys.msgsize_max_recommended\")]\n SysMsgsizeMaxRecommended,\n\n /// Space separated list of all config keys available.\n #[strum(serialize = \"sys.config_keys\")]\n SysConfigKeys,\n\n /// True if it is a bot account.\n Bot,\n\n /// True when to skip initial start messages in groups.\n #[strum(props(default = \"0\"))]\n SkipStartMessages,\n\n /// Whether we send a warning if the password is wrong (set to false when we send a warning\n /// because we do not want to send a second warning)\n #[strum(props(default = \"0\"))]\n NotifyAboutWrongPw,\n\n /// If a warning about exceeding quota was shown recently,\n /// this is the percentage of quota at the time the warning was given.\n /// Unset, when quota falls below minimal warning threshold again.\n QuotaExceeding,\n\n /// address to webrtc instance to use for videochats\n WebrtcInstance,\n\n /// Timestamp of the last time housekeeping was run\n LastHousekeeping,\n\n /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.\n LastCantDecryptOutgoingMsgs,\n\n /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.\n #[strum(props(default = \"60\"))]\n ScanAllFoldersDebounceSecs,\n\n /// Whether to avoid using IMAP IDLE even if the server supports it.\n ///\n /// This is a developer option for testing \"fake idle\".\n #[strum(props(default = \"0\"))]\n DisableIdle,\n\n /// Defines the max. size (in bytes) of messages downloaded automatically.\n /// 0 = no limit.\n #[strum(props(default = \"0\"))]\n DownloadLimit,\n\n /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.\n #[strum(props(default = \"1\"))]\n SyncMsgs,\n\n /// Space-separated list of all the authserv-ids which we believe\n /// may be the one of our email server.\n ///\n /// See `crate::authres::update_authservid_candidates`.\n AuthservIdCandidates,\n\n /// Make all outgoing messages with Autocrypt header \"multipart/signed\".\n SignUnencrypted,\n\n /// Let the core save all events to the database.\n /// This value is used internally to remember the MsgId of the logging xdc\n #[strum(props(default = \"0\"))]\n DebugLogging,\n\n /// Last message processed by the bot.\n LastMsgId,\n\n /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by\n /// default.\n ///\n /// This is not supposed to be changed by UIs and only used for testing.\n #[strum(props(default = \"172800\"))]\n GossipPeriod,\n\n /// Feature flag for verified 1:1 chats; the UI should set it\n /// to 1 if it supports verified 1:1 chats.\n /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,\n /// and when the key changes, an info message is posted into the chat.\n /// 0=Nothing else happens when the key changes.\n /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true\n /// until `chat_id.accept()` is called.\n #[strum(props(default = \"0\"))]\n VerifiedOneOnOneChats,\n\n /// Row ID of the key in the `keypairs` table\n /// used for signatures, encryption to self and included in `Autocrypt` header.\n KeyId,\n\n /// This key is sent to the self_reporting bot so that the bot can recognize the user\n /// without storing the email address\n SelfReportingId,\n\n /// MsgId of webxdc map integration.\n WebxdcIntegration,\n\n /// Iroh secret key.\n IrohSecretKey,\n}\n\npub enum Origin {\n /// Unknown origin. Can be used as a minimum origin to specify that the caller does not care\n /// about origin of the contact.\n #[default]\n Unknown = 0,\n\n /// The contact is a mailing list address, needed to unblock mailing lists\n MailinglistAddress = 0x2,\n\n /// Hidden on purpose, e.g. addresses with the word \"noreply\" in it\n Hidden = 0x8,\n\n /// From: of incoming messages of unknown sender\n IncomingUnknownFrom = 0x10,\n\n /// Cc: of incoming messages of unknown sender\n IncomingUnknownCc = 0x20,\n\n /// To: of incoming messages of unknown sender\n IncomingUnknownTo = 0x40,\n\n /// address scanned but not verified\n UnhandledQrScan = 0x80,\n\n /// Reply-To: of incoming message of known sender\n /// Contacts with at least this origin value are shown in the contact list.\n IncomingReplyTo = 0x100,\n\n /// Cc: of incoming message of known sender\n IncomingCc = 0x200,\n\n /// additional To:'s of incoming message of known sender\n IncomingTo = 0x400,\n\n /// a chat was manually created for this user, but no message yet sent\n CreateChat = 0x800,\n\n /// message sent by us\n OutgoingBcc = 0x1000,\n\n /// message sent by us\n OutgoingCc = 0x2000,\n\n /// message sent by us\n OutgoingTo = 0x4000,\n\n /// internal use\n Internal = 0x40000,\n\n /// address is in our address book\n AddressBook = 0x80000,\n\n /// 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() !\n SecurejoinInvited = 0x0100_0000,\n\n /// 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() !\n SecurejoinJoined = 0x0200_0000,\n\n /// contact added manually by create_contact(), this should be the largest origin as otherwise the user cannot modify the names\n ManuallyCreated = 0x0400_0000,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__28.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "dc_array_t* dc_get_chat_contacts(dc_context_t* context, uint32_t chat_id)\n{\n\t/* Normal chats do not include SELF. Group chats do (as it may happen that one is deleted from a\n\tgroupchat but the chats stays visible, moreover, this makes displaying lists easier) */\n\tdc_array_t* ret = dc_array_new(context, 100);\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT cc.contact_id FROM chats_contacts cc\"\n\t\t\t\" LEFT JOIN contacts c ON c.id=cc.contact_id\"\n\t\t\t\" WHERE cc.chat_id=?\"\n\t\t\t\" ORDER BY c.id=1, c.last_seen DESC, c.id DESC;\");\n\tsqlite3_bind_int(stmt, 1, chat_id);\n\twhile (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\tdc_array_add_id(ret, sqlite3_column_int(stmt, 0));\n\t}\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn get_chat_contacts(context: &Context, chat_id: ChatId) -> Result> {\n // Normal chats do not include SELF. Group chats do (as it may happen that one is deleted from a\n // groupchat but the chats stays visible, moreover, this makes displaying lists easier)\n\n let list = context\n .sql\n .query_map(\n \"SELECT cc.contact_id\n FROM chats_contacts cc\n LEFT JOIN contacts c\n ON c.id=cc.contact_id\n WHERE cc.chat_id=?\n ORDER BY c.id=1, c.last_seen DESC, c.id DESC;\",\n (chat_id,),\n |row| row.get::<_, ContactId>(0),\n |ids| ids.collect::, _>>().map_err(Into::into),\n )\n .await?;\n\n Ok(list)\n}", "rust_context": "pub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub async fn query_map(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n mut g: G,\n ) -> Result\n where\n F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result,\n G: Send + FnMut(rusqlite::MappedRows) -> Result,\n H: Send + 'static,\n {\n self.call(move |conn| {\n let mut stmt = conn.prepare(sql)?;\n let res = stmt.query_map(params, f)?;\n g(res)\n })\n .await\n }\n \npub struct ChatId(u32);\n\npub struct ContactId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__118.txt"} {"c_path": "projects/deltachat-core/c/dc_imex.c", "c_func": "char* dc_create_setup_code(dc_context_t* context)\n{\n\t#define CODE_ELEMS 9\n\tuint16_t random_val = 0;\n\tint i = 0;\n\tdc_strbuilder_t ret;\n\tdc_strbuilder_init(&ret, 0);\n\n\tfor (i = 0; i < CODE_ELEMS; i++)\n\t{\n\t\tdo\n\t\t{\n\t\t\tif (!RAND_bytes((unsigned char*)&random_val, sizeof(uint16_t))) {\n\t\t\t\tdc_log_warning(context, 0, \"Falling back to pseudo-number generation for the setup code.\");\n\t\t\t\tRAND_pseudo_bytes((unsigned char*)&random_val, sizeof(uint16_t));\n\t\t\t}\n\t\t}\n\t\twhile (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) */\n\n\t\trandom_val = random_val % 10000; /* force all blocks into the range 0..9999 */\n\n\t\tdc_strbuilder_catf(&ret, \"%s%04i\", i?\"-\":\"\", (int)random_val);\n\t}\n\n\treturn ret.buf;\n}", "rust_path": "projects/deltachat-core/rust/imex.rs", "rust_func": "pub fn create_setup_code(_context: &Context) -> String {\n let mut random_val: u16;\n let mut rng = thread_rng();\n let mut ret = String::new();\n\n for i in 0..9 {\n loop {\n random_val = rng.gen();\n if random_val as usize <= 60000 {\n break;\n }\n }\n random_val = (random_val as usize % 10000) as u16;\n ret += &format!(\n \"{}{:04}\",\n if 0 != i { \"-\" } else { \"\" },\n random_val as usize\n );\n }\n\n ret\n}", "rust_context": "pub struct Context {\n pub(crate) inner: Arc,\n}", "rust_imports": "use std::any::Any;\nuse std::ffi::OsStr;\nuse std::path::{Path, PathBuf};\nuse ::pgp::types::KeyTrait;\nuse anyhow::{bail, ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse futures::StreamExt;\nuse futures_lite::FutureExt;\nuse rand::{thread_rng, Rng};\nuse tokio::fs::{self, File};\nuse tokio_tar::Archive;\nuse crate::blob::{BlobDirContents, BlobObject};\nuse crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};\nuse crate::config::Config;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::e2ee;\nuse crate::events::EventType;\nuse crate::key::{\n self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,\n};\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::param::Param;\nuse crate::pgp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{\n create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,\n};\nuse transfer::{get_backup, BackupProvider};\nuse std::time::Duration;\nuse ::pgp::armor::BlockType;\nuse tokio::task;\nuse super::*;\nuse crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::{alice_keypair, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__imex__.rs__function__5.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "char* dc_contact_get_name(const dc_contact_t* contact)\n{\n\tif (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) {\n\t\treturn dc_strdup(NULL);\n\t}\n\n\treturn dc_strdup(contact->name);\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub fn get_name(&self) -> &str {\n &self.name\n }", "rust_context": "pub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__39.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* See also dc_send_msg().\n *\n * @memberof dc_context_t\n * @param context The context object as returned from dc_context_new().\n * @param chat_id Chat ID to send the text message to.\n * @param text_to_send Text to send to the chat defined by the chat ID.\n * Passing an empty text here causes an empty text to be sent,\n * it's up to the caller to handle this if undesired.\n * Passing NULL as the text causes the function to return 0.\n * @return The ID of the message that is about being sent.\n */\nuint32_t dc_send_text_msg(dc_context_t* context, uint32_t chat_id, const char* text_to_send)\n{\n\tdc_msg_t* msg = dc_msg_new(context, DC_MSG_TEXT);\n\tuint32_t ret = 0;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL || text_to_send==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tmsg->text = dc_strdup(text_to_send);\n\n\tret = dc_send_msg(context, chat_id, msg);\n\ncleanup:\n\tdc_msg_unref(msg);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn send_text_msg(\n context: &Context,\n chat_id: ChatId,\n text_to_send: String,\n) -> Result {\n ensure!(\n !chat_id.is_special(),\n \"bad chat_id, can not be a special chat: {}\",\n chat_id\n );\n\n let mut msg = Message::new(Viewtype::Text);\n msg.text = text_to_send;\n send_msg(context, chat_id, &mut msg).await\n}", "rust_context": "pub async fn send_msg(context: &Context, chat_id: ChatId, msg: &mut Message) -> Result {\n if chat_id.is_unset() {\n let forwards = msg.param.get(Param::PrepForwards);\n if let Some(forwards) = forwards {\n for forward in forwards.split(' ') {\n if let Ok(msg_id) = forward.parse::().map(MsgId::new) {\n if let Ok(mut msg) = Message::load_from_db(context, msg_id).await {\n send_msg_inner(context, chat_id, &mut msg).await?;\n };\n }\n }\n msg.param.remove(Param::PrepForwards);\n msg.update_param(context).await?;\n }\n return send_msg_inner(context, chat_id, msg).await;\n }\n\n if msg.state != MessageState::Undefined && msg.state != MessageState::OutPreparing {\n msg.param.remove(Param::GuaranteeE2ee);\n msg.param.remove(Param::ForcePlaintext);\n msg.update_param(context).await?;\n }\n send_msg_inner(context, chat_id, msg).await\n}\n\npub fn is_special(self) -> bool {\n (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct MsgId(u32);\n\npub struct ChatId(u32);\n\nimpl Message {\n /// Creates a new message with given view type.\n pub fn new(viewtype: Viewtype) -> Self {\n Message {\n viewtype,\n ..Default::default()\n }\n }\n}\n\npub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__109.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "char* dc_contact_get_addr(const dc_contact_t* contact)\n{\n\tif (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) {\n\t\treturn dc_strdup(NULL);\n\t}\n\n\treturn dc_strdup(contact->addr);\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub fn get_addr(&self) -> &str {\n &self.addr\n }", "rust_context": "pub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__37.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "* unless it was edited manually by dc_create_contact() before.\n * @return The number of modified or added contacts.\n */\nint dc_add_address_book(dc_context_t* context, const char* adr_book)\n{\n\tcarray* lines = NULL;\n\tsize_t i = 0;\n\tsize_t iCnt = 0;\n\tint sth_modified = 0;\n\tint modify_cnt = 0;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || adr_book==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tif ((lines=dc_split_into_lines(adr_book))==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tdc_sqlite3_begin_transaction(context->sql);\n\n\t\tiCnt = carray_count(lines);\n\t\tfor (i = 0; i+1 < iCnt; i += 2) {\n\t\t\tchar* name = (char*)carray_get(lines, i);\n\t\t\tchar* addr = (char*)carray_get(lines, i+1);\n\t\t\tdc_normalize_name(name);\n dc_normalize_addr(addr);\n\t\t\tdc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_ADRESS_BOOK, &sth_modified);\n\t\t\tif (sth_modified) {\n\t\t\t\tmodify_cnt++;\n\t\t\t}\n\t\t}\n\n\tdc_sqlite3_commit(context->sql);\n\n\tif (modify_cnt) {\n\t\tcontext->cb(context, DC_EVENT_CONTACTS_CHANGED, 0, 0);\n\t}\n\ncleanup:\n\tdc_free_splitted_lines(lines);\n\n\treturn modify_cnt;\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub async fn add_address_book(context: &Context, addr_book: &str) -> Result {\n let mut modify_cnt = 0;\n\n for (name, addr) in split_address_book(addr_book) {\n let (name, addr) = sanitize_name_and_addr(name, addr);\n match ContactAddress::new(&addr) {\n Ok(addr) => {\n match Contact::add_or_lookup(context, &name, &addr, Origin::AddressBook).await {\n Ok((_, modified)) => {\n if modified != Modifier::None {\n modify_cnt += 1\n }\n }\n Err(err) => {\n warn!(\n context,\n \"Failed to add address {} from address book: {}\", addr, err\n );\n }\n }\n }\n Err(err) => {\n warn!(context, \"{:#}.\", err);\n }\n }\n }\n if modify_cnt > 0 {\n context.emit_event(EventType::ContactsChanged(None));\n }\n\n Ok(modify_cnt)\n }", "rust_context": "fn split_address_book(book: &str) -> Vec<(&str, &str)> {\n book.lines()\n .collect::>()\n .chunks(2)\n .filter_map(|chunk| {\n let name = chunk.first()?;\n let addr = chunk.get(1)?;\n Some((*name, *addr))\n })\n .collect()\n}\n\npub(crate) async fn add_or_lookup(\n context: &Context,\n name: &str,\n addr: &ContactAddress,\n mut origin: Origin,\n ) -> Result<(ContactId, Modifier)> {\n let mut sth_modified = Modifier::None;\n\n ensure!(!addr.is_empty(), \"Can not add_or_lookup empty address\");\n ensure!(origin != Origin::Unknown, \"Missing valid origin\");\n\n if context.is_self_addr(addr).await? {\n return Ok((ContactId::SELF, sth_modified));\n }\n\n let mut name = strip_rtlo_characters(name);\n #[allow(clippy::collapsible_if)]\n if origin <= Origin::OutgoingTo {\n // The user may accidentally have written to a \"noreply\" address with another MUA:\n if addr.contains(\"noreply\")\n || addr.contains(\"no-reply\")\n || addr.starts_with(\"notifications@\")\n // Filter out use-once addresses (like reply+AEJDGPOECLAP...@reply.github.com):\n || (addr.len() > 50 && addr.contains('+'))\n {\n info!(context, \"hiding contact {}\", addr);\n origin = Origin::Hidden;\n // For these kind of email addresses, sender and address often don't belong together\n // (like hocuri ). In this example, hocuri shouldn't\n // be saved as the displayname for notifications@github.com.\n name = \"\".to_string();\n }\n }\n\n // If the origin indicates that user entered the contact manually, from the address book or\n // from the QR-code scan (potentially from the address book of their other phone), then name\n // should go into the \"name\" column and never into \"authname\" column, to avoid leaking it\n // into the network.\n let manual = matches!(\n origin,\n Origin::ManuallyCreated | Origin::AddressBook | Origin::UnhandledQrScan\n );\n\n let mut update_addr = false;\n\n let row_id = context.sql.transaction(|transaction| {\n let row = transaction.query_row(\n \"SELECT id, name, addr, origin, authname\n FROM contacts WHERE addr=? COLLATE NOCASE\",\n [addr.to_string()],\n |row| {\n let row_id: isize = row.get(0)?;\n let row_name: String = row.get(1)?;\n let row_addr: String = row.get(2)?;\n let row_origin: Origin = row.get(3)?;\n let row_authname: String = row.get(4)?;\n\n Ok((row_id, row_name, row_addr, row_origin, row_authname))\n }).optional()?;\n\n let row_id;\n if let Some((id, row_name, row_addr, row_origin, row_authname)) = row {\n let update_name = manual && name != row_name;\n let update_authname = !manual\n && name != row_authname\n && !name.is_empty()\n && (origin >= row_origin\n || origin == Origin::IncomingUnknownFrom\n || row_authname.is_empty());\n\n row_id = u32::try_from(id)?;\n if origin >= row_origin && addr.as_ref() != row_addr {\n update_addr = true;\n }\n if update_name || update_authname || update_addr || origin > row_origin {\n let new_name = if update_name {\n name.to_string()\n } else {\n row_name\n };\n\n transaction\n .execute(\n \"UPDATE contacts SET name=?, addr=?, origin=?, authname=? WHERE id=?;\",\n (\n new_name,\n if update_addr {\n addr.to_string()\n } else {\n row_addr\n },\n if origin > row_origin {\n origin\n } else {\n row_origin\n },\n if update_authname {\n name.to_string()\n } else {\n row_authname\n },\n row_id\n ),\n )?;\n\n if update_name || update_authname {\n // Update the contact name also if it is used as a group name.\n // This is one of the few duplicated data, however, getting the chat list is easier this way.\n let chat_id: Option = transaction.query_row(\n \"SELECT id FROM chats WHERE type=? AND id IN(SELECT chat_id FROM chats_contacts WHERE contact_id=?)\",\n (Chattype::Single, isize::try_from(row_id)?),\n |row| {\n let chat_id: ChatId = row.get(0)?;\n Ok(chat_id)\n }\n ).optional()?;\n\n if let Some(chat_id) = chat_id {\n let contact_id = ContactId::new(row_id);\n let (addr, name, authname) =\n transaction.query_row(\n \"SELECT addr, name, authname\n FROM contacts\n WHERE id=?\",\n (contact_id,),\n |row| {\n let addr: String = row.get(0)?;\n let name: String = row.get(1)?;\n let authname: String = row.get(2)?;\n Ok((addr, name, authname))\n })?;\n\n let chat_name = if !name.is_empty() {\n name\n } else if !authname.is_empty() {\n authname\n } else {\n addr\n };\n\n let count = transaction.execute(\n \"UPDATE chats SET name=?1 WHERE id=?2 AND name!=?1\",\n (chat_name, chat_id))?;\n\n if count > 0 {\n // Chat name updated\n context.emit_event(EventType::ChatModified(chat_id));\n chatlist_events::emit_chatlist_items_changed_for_contact(context, contact_id);\n }\n }\n }\n sth_modified = Modifier::Modified;\n }\n } else {\n let update_name = manual;\n let update_authname = !manual;\n\n transaction\n .execute(\n \"INSERT INTO contacts (name, addr, origin, authname)\n VALUES (?, ?, ?, ?);\",\n (\n if update_name {\n name.to_string()\n } else {\n \"\".to_string()\n },\n &addr,\n origin,\n if update_authname {\n name.to_string()\n } else {\n \"\".to_string()\n }\n ),\n )?;\n\n sth_modified = Modifier::Created;\n row_id = u32::try_from(transaction.last_insert_rowid())?;\n info!(context, \"Added contact id={row_id} addr={addr}.\");\n }\n Ok(row_id)\n }).await?;\n\n let contact_id = ContactId::new(row_id);\n\n Ok((contact_id, sth_modified))\n }\n\nimpl ContactAddress {\n /// Constructs a new contact address from string,\n /// normalizing and validating it.\n pub fn new(s: &str) -> Result {\n let addr = addr_normalize(s);\n if !may_be_valid_addr(&addr) {\n bail!(\"invalid address {:?}\", s);\n }\n Ok(Self(addr.to_string()))\n }\n} \n\nmacro_rules! warn {\n ($ctx:expr, $msg:expr) => {\n warn!($ctx, $msg,)\n };\n ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{\n let formatted = format!($msg, $($args),*);\n let full = format!(\"{file}:{line}: {msg}\",\n file = file!(),\n line = line!(),\n msg = &formatted);\n $ctx.emit_event($crate::EventType::Warning(full));\n }};\n}\n\npub fn emit_event(&self, event: EventType) {\n {\n let lock = self.debug_logging.read().expect(\"RwLock is poisoned\");\n if let Some(debug_logging) = &*lock {\n debug_logging.log_event(event.clone());\n }\n }\n self.events.emit(Event {\n id: self.id,\n typ: event,\n });\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub enum Origin {\n /// Unknown origin. Can be used as a minimum origin to specify that the caller does not care\n /// about origin of the contact.\n #[default]\n Unknown = 0,\n\n /// The contact is a mailing list address, needed to unblock mailing lists\n MailinglistAddress = 0x2,\n\n /// Hidden on purpose, e.g. addresses with the word \"noreply\" in it\n Hidden = 0x8,\n\n /// From: of incoming messages of unknown sender\n IncomingUnknownFrom = 0x10,\n\n /// Cc: of incoming messages of unknown sender\n IncomingUnknownCc = 0x20,\n\n /// To: of incoming messages of unknown sender\n IncomingUnknownTo = 0x40,\n\n /// address scanned but not verified\n UnhandledQrScan = 0x80,\n\n /// Reply-To: of incoming message of known sender\n /// Contacts with at least this origin value are shown in the contact list.\n IncomingReplyTo = 0x100,\n\n /// Cc: of incoming message of known sender\n IncomingCc = 0x200,\n\n /// additional To:'s of incoming message of known sender\n IncomingTo = 0x400,\n\n /// a chat was manually created for this user, but no message yet sent\n CreateChat = 0x800,\n\n /// message sent by us\n OutgoingBcc = 0x1000,\n\n /// message sent by us\n OutgoingCc = 0x2000,\n\n /// message sent by us\n OutgoingTo = 0x4000,\n\n /// internal use\n Internal = 0x40000,\n\n /// address is in our address book\n AddressBook = 0x80000,\n\n /// 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() !\n SecurejoinInvited = 0x0100_0000,\n\n /// 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() !\n SecurejoinJoined = 0x0200_0000,\n\n /// contact added manually by create_contact(), this should be the largest origin as otherwise the user cannot modify the names\n ManuallyCreated = 0x0400_0000,\n}\n\npub enum EventType {\n /// The library-user may write an informational string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Info(String),\n\n /// Emitted when SMTP connection is established and login was successful.\n SmtpConnected(String),\n\n /// Emitted when IMAP connection is established and login was successful.\n ImapConnected(String),\n\n /// Emitted when a message was successfully sent to the SMTP server.\n SmtpMessageSent(String),\n\n /// Emitted when an IMAP message has been marked as deleted\n ImapMessageDeleted(String),\n\n /// Emitted when an IMAP message has been moved\n ImapMessageMoved(String),\n\n /// Emitted before going into IDLE on the Inbox folder.\n ImapInboxIdle,\n\n /// Emitted when an new file in the $BLOBDIR was created\n NewBlobFile(String),\n\n /// Emitted when an file in the $BLOBDIR was deleted\n DeletedBlobFile(String),\n\n /// The library-user should write a warning string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Warning(String),\n\n /// The library-user should report an error to the end-user.\n ///\n /// As most things are asynchronous, things may go wrong at any time and the user\n /// should not be disturbed by a dialog or so. Instead, use a bubble or so.\n ///\n /// However, for ongoing processes (eg. configure())\n /// or for functions that are expected to fail (eg. dc_continue_key_transfer())\n /// it might be better to delay showing these events until the function has really\n /// failed (returned false). It should be sufficient to report only the *last* error\n /// in a messasge box then.\n Error(String),\n\n /// An action cannot be performed because the user is not in the group.\n /// Reported eg. after a call to\n /// dc_set_chat_name(), dc_set_chat_profile_image(),\n /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(),\n /// dc_send_text_msg() or another sending function.\n ErrorSelfNotInGroup(String),\n\n /// Messages or chats changed. One or more messages or chats changed for various\n /// reasons in the database:\n /// - Messages sent, received or removed\n /// - Chats created, deleted or archived\n /// - A draft has been set\n ///\n MsgsChanged {\n /// Set if only a single chat is affected by the changes, otherwise 0.\n chat_id: ChatId,\n\n /// Set if only a single message is affected by the changes, otherwise 0.\n msg_id: MsgId,\n },\n\n /// Reactions for the message changed.\n ReactionsChanged {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message for which reactions were changed.\n msg_id: MsgId,\n\n /// ID of the contact whose reaction set is changed.\n contact_id: ContactId,\n },\n\n /// There is a fresh message. Typically, the user will show an notification\n /// when receiving this message.\n ///\n /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event.\n IncomingMsg {\n /// ID of the chat where the message is assigned.\n chat_id: ChatId,\n\n /// ID of the message.\n msg_id: MsgId,\n },\n\n /// Downloading a bunch of messages just finished.\n IncomingMsgBunch,\n\n /// Messages were seen or noticed.\n /// chat id is always set.\n MsgsNoticed(ChatId),\n\n /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to\n /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state().\n MsgDelivered {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was successfully sent.\n msg_id: MsgId,\n },\n\n /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_FAILED, see dc_msg_get_state().\n MsgFailed {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that could not be sent.\n msg_id: MsgId,\n },\n\n /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state().\n MsgRead {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was read.\n msg_id: MsgId,\n },\n\n /// A single message was deleted.\n ///\n /// This event means that the message will no longer appear in the messagelist.\n /// UI should remove the message from the messagelist\n /// in response to this event if the message is currently displayed.\n ///\n /// The message may have been explicitly deleted by the user or expired.\n /// Internally the message may have been removed from the database,\n /// moved to the trash chat or hidden.\n ///\n /// This event does not indicate the message\n /// deletion from the server.\n MsgDeleted {\n /// ID of the chat where the message was prior to deletion.\n /// Never 0 or trash chat.\n chat_id: ChatId,\n\n /// ID of the deleted message. Never 0.\n msg_id: MsgId,\n },\n\n /// Chat changed. The name or the image of a chat group was changed or members were added or removed.\n /// Or the verify state of a chat has changed.\n /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat()\n /// and dc_remove_contact_from_chat().\n ///\n /// This event does not include ephemeral timer modification, which\n /// is a separate event.\n ChatModified(ChatId),\n\n /// Chat ephemeral timer changed.\n ChatEphemeralTimerModified {\n /// Chat ID.\n chat_id: ChatId,\n\n /// New ephemeral timer value.\n timer: EphemeralTimer,\n },\n\n /// Contact(s) created, renamed, blocked, deleted or changed their \"recently seen\" status.\n ///\n /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected.\n ContactsChanged(Option),\n\n /// Location of one or more contact has changed.\n ///\n /// @param data1 (u32) contact_id of the contact for which the location has changed.\n /// If the locations of several contacts have been changed,\n /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`.\n LocationChanged(Option),\n\n /// Inform about the configuration progress started by configure().\n ConfigureProgress {\n /// Progress.\n ///\n /// 0=error, 1-999=progress in permille, 1000=success and done\n progress: usize,\n\n /// Progress comment or error, something to display to the user.\n comment: Option,\n },\n\n /// Inform about the import/export progress started by imex().\n ///\n /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done\n /// @param data2 0\n ImexProgress(usize),\n\n /// A file has been exported. A file has been written by imex().\n /// This event may be sent multiple times by a single call to imex().\n ///\n /// A typical purpose for a handler of this event may be to make the file public to some system\n /// services.\n ///\n /// @param data2 0\n ImexFileWritten(PathBuf),\n\n /// Progress information of a secure-join handshake from the view of the inviter\n /// (Alice, the person who shows the QR code).\n ///\n /// These events are typically sent after a joiner has scanned the QR code\n /// generated by dc_get_securejoin_qr().\n SecurejoinInviterProgress {\n /// ID of the contact that wants to join.\n contact_id: ContactId,\n\n /// Progress as:\n /// 300=vg-/vc-request received, typically shown as \"bob@addr joins\".\n /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as \"bob@addr verified\".\n /// 800=contact added to chat, shown as \"bob@addr securely joined GROUP\". Only for the verified-group-protocol.\n /// 1000=Protocol finished for this contact.\n progress: usize,\n },\n\n /// Progress information of a secure-join handshake from the view of the joiner\n /// (Bob, the person who scans the QR code).\n /// The events are typically sent while dc_join_securejoin(), which\n /// may take some time, is executed.\n SecurejoinJoinerProgress {\n /// ID of the inviting contact.\n contact_id: ContactId,\n\n /// Progress as:\n /// 400=vg-/vc-request-with-auth sent, typically shown as \"alice@addr verified, introducing myself.\"\n /// (Bob has verified alice and waits until Alice does the same for him)\n /// 1000=vg-member-added/vc-contact-confirm received\n progress: usize,\n },\n\n /// The connectivity to the server changed.\n /// This means that you should refresh the connectivity view\n /// and possibly the connectivtiy HTML; see dc_get_connectivity() and\n /// dc_get_connectivity_html() for details.\n ConnectivityChanged,\n\n /// The user's avatar changed.\n /// Deprecated by `ConfigSynced`.\n SelfavatarChanged,\n\n /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For\n /// uniformity this is emitted on the source device too. The value isn't here, otherwise it\n /// would be logged which might not be good for privacy.\n ConfigSynced {\n /// Configuration key.\n key: Config,\n },\n\n /// Webxdc status update received.\n WebxdcStatusUpdate {\n /// Message ID.\n msg_id: MsgId,\n\n /// Status update ID.\n status_update_serial: StatusUpdateSerial,\n },\n\n /// Data received over an ephemeral peer channel.\n WebxdcRealtimeData {\n /// Message ID.\n msg_id: MsgId,\n\n /// Realtime data.\n data: Vec,\n },\n\n /// Inform that a message containing a webxdc instance has been deleted.\n WebxdcInstanceDeleted {\n /// ID of the deleted message.\n msg_id: MsgId,\n },\n\n /// Tells that the Background fetch was completed (or timed out).\n /// This event acts as a marker, when you reach this event you can be sure\n /// that all events emitted during the background fetch were processed.\n ///\n /// This event is only emitted by the account manager\n AccountsBackgroundFetchDone,\n /// Inform that set of chats or the order of the chats in the chatlist has changed.\n ///\n /// Sometimes this is emitted together with `UIChatlistItemChanged`.\n ChatlistChanged,\n\n /// Inform that a single chat list item changed and needs to be rerendered.\n /// 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.\n ChatlistItemChanged {\n /// ID of the changed chat\n chat_id: Option,\n },\n\n /// Event for using in tests, e.g. as a fence between normally generated events.\n #[cfg(test)]\n Test,\n\n /// Inform than some events have been skipped due to event channel overflow.\n EventChannelOverflow {\n /// Number of events skipped.\n n: u64,\n },\n}\n\n\npub(crate) enum Modifier {\n None,\n Modified,\n Created,\n}\n\npub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__27.txt"} {"c_path": "projects/deltachat-core/c/dc_sqlite3.c", "c_func": "int dc_sqlite3_execute(dc_sqlite3_t* sql, const char* querystr)\n{\n\tint success = 0;\n\tsqlite3_stmt* stmt = NULL;\n\tint sqlState = 0;\n\n\tstmt = dc_sqlite3_prepare(sql, querystr);\n\tif (stmt==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tsqlState = sqlite3_step(stmt);\n\tif (sqlState != SQLITE_DONE && sqlState != SQLITE_ROW) {\n\t\tdc_sqlite3_log_error(sql, \"Cannot execute \\\"%s\\\".\", querystr);\n\t\tgoto cleanup;\n\t}\n\n\tsuccess = 1;\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/sql.rs", "rust_func": "pub async fn execute(\n &self,\n query: &str,\n params: impl rusqlite::Params + Send,\n ) -> Result {\n self.call_write(move |conn| {\n let res = conn.execute(query, params)?;\n Ok(res)\n })\n .await\n }", "rust_context": "pub async fn call_write<'a, F, R>(&'a self, function: F) -> Result\n where\n F: 'a + FnOnce(&mut Connection) -> Result + Send,\n R: Send + 'static,\n {\n let _lock = self.write_lock().await;\n self.call(function).await\n }\n\npub struct Params {\n inner: BTreeMap,\n}\n\npub struct Sql {\n /// Database file path\n pub(crate) dbfile: PathBuf,\n\n /// Write transactions mutex.\n ///\n /// See [`Self::write_lock`].\n write_mtx: Mutex<()>,\n\n /// SQL connection pool.\n pool: RwLock>,\n\n /// None if the database is not open, true if it is open with passphrase and false if it is\n /// open without a passphrase.\n is_encrypted: RwLock>,\n\n /// Cache of `config` table.\n pub(crate) config_cache: RwLock>>,\n}", "rust_imports": "use std::collections::{HashMap, HashSet};\nuse std::path::{Path, PathBuf};\nuse anyhow::{bail, Context as _, Result};\nuse rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row};\nuse tokio::sync::{Mutex, MutexGuard, RwLock};\nuse crate::blob::BlobObject;\nuse crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon};\nuse crate::config::Config;\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::ephemeral::start_ephemeral_timers;\nuse crate::imex::BLOBS_BACKUP_NAME;\nuse crate::location::delete_orphaned_poi_locations;\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::stock_str;\nuse crate::tools::{delete_file, time, SystemTime};\nuse pool::Pool;\nuse super::*;\nuse crate::{test_utils::TestContext, EventType};\nuse tempfile::tempdir;\nuse tempfile::tempdir;\nuse tempfile::tempdir;", "rustrepotrans_file": "projects__deltachat-core__rust__sql__.rs__function__16.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "* normalize() is _not_ called for the name. If the contact is blocked, it is unblocked.\n *\n * To add a number of contacts, see dc_add_address_book() which is much faster for adding\n * a bunch of addresses.\n *\n * May result in a #DC_EVENT_CONTACTS_CHANGED event.\n *\n * @memberof dc_context_t\n * @param context The context object as created by dc_context_new().\n * @param name Name of the contact to add. If you do not know the name belonging\n * to the address, you can give NULL here.\n * @param addr E-mail-address of the contact to add. If the email address\n * already exists, the name is updated and the origin is increased to\n * \"manually created\".\n * @return Contact ID of the created or reused contact.\n */\nuint32_t dc_create_contact(dc_context_t* context, const char* name, const char* addr)\n{\n\tuint32_t contact_id = 0;\n\tint sth_modified = 0;\n\tint blocked = 0;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || addr==NULL || addr[0]==0) {\n\t\tgoto cleanup;\n\t}\n\n\tcontact_id = dc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_MANUALLY_CREATED, &sth_modified);\n\n\tblocked = dc_is_contact_blocked(context, contact_id);\n\n\tcontext->cb(context, DC_EVENT_CONTACTS_CHANGED, sth_modified==CONTACT_CREATED? contact_id : 0, 0);\n\n\tif (blocked) {\n\t\tdc_block_contact(context, contact_id, 0);\n\t}\n\ncleanup:\n\treturn contact_id;\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub async fn create(context: &Context, name: &str, addr: &str) -> Result {\n Self::create_ex(context, Sync, name, addr).await\n }", "rust_context": "pub(crate) async fn create_ex(\n context: &Context,\n sync: sync::Sync,\n name: &str,\n addr: &str,\n ) -> Result {\n let name = improve_single_line_input(name);\n\n let (name, addr) = sanitize_name_and_addr(&name, addr);\n let addr = ContactAddress::new(&addr)?;\n\n let (contact_id, sth_modified) =\n Contact::add_or_lookup(context, &name, &addr, Origin::ManuallyCreated)\n .await\n .context(\"add_or_lookup\")?;\n let blocked = Contact::is_blocked_load(context, contact_id).await?;\n match sth_modified {\n Modifier::None => {}\n Modifier::Modified | Modifier::Created => {\n context.emit_event(EventType::ContactsChanged(Some(contact_id)))\n }\n }\n if blocked {\n set_blocked(context, Nosync, contact_id, false).await?;\n }\n\n if sync.into() {\n chat::sync(\n context,\n chat::SyncId::ContactAddr(addr.to_string()),\n chat::SyncAction::Rename(name.to_string()),\n )\n .await\n .log_err(context)\n .ok();\n }\n Ok(contact_id)\n }\n \npub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ContactId(u32);", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__20.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_get_state(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn DC_STATE_UNDEFINED;\n\t}\n\treturn msg->state;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn get_state(&self) -> MessageState {\n self.state\n }", "rust_context": "pub struct MsgId(u32);\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__36.txt"} {"c_path": "projects/deltachat-core/c/dc_chatlist.c", "c_func": "* 0 and dc_chatlist_get_cnt()-1.\n */\nuint32_t dc_chatlist_get_chat_id(const dc_chatlist_t* chatlist, size_t index)\n{\n\tif (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC || chatlist->chatNlastmsg_ids==NULL || index>=chatlist->cnt) {\n\t\treturn 0;\n\t}\n\n\treturn dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT);\n}", "rust_path": "projects/deltachat-core/rust/chatlist.rs", "rust_func": "pub fn get_chat_id(&self, index: usize) -> Result {\n let (chat_id, _msg_id) = self\n .ids\n .get(index)\n .context(\"chatlist index is out of range\")?;\n Ok(*chat_id)\n }", "rust_context": "pub struct Chatlist {\n /// Stores pairs of `chat_id, message_id`\n ids: Vec<(ChatId, Option)>,\n}", "rust_imports": "use anyhow::{ensure, Context as _, Result};\nuse once_cell::sync::Lazy;\nuse crate::chat::{update_special_chat_names, Chat, ChatId, ChatVisibility};\nuse crate::constants::{\n Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK, DC_GCL_ADD_ALLDONE_HINT,\n DC_GCL_ARCHIVED_ONLY, DC_GCL_FOR_FORWARDING, DC_GCL_NO_SPECIALS,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::message::{Message, MessageState, MsgId};\nuse crate::param::{Param, Params};\nuse crate::stock_str;\nuse crate::summary::Summary;\nuse crate::tools::IsNoneOrEmpty;\nuse super::*;\nuse crate::chat::{\n add_contact_to_chat, create_group_chat, get_chat_contacts, remove_contact_from_chat,\n send_text_msg, ProtectionStatus,\n };\nuse crate::message::Viewtype;\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__chatlist__.rs__function__5.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_has_location(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn 0;\n\t}\n\n\treturn (msg->location_id!=0);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn has_location(&self) -> bool {\n self.location_id != 0\n }", "rust_context": "pub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__27.txt"} {"c_path": "projects/deltachat-core/c/dc_sqlite3.c", "c_func": "static int is_file_in_use(dc_hash_t* files_in_use, const char* namespc, const char* name)\n{\n\tchar* name_to_check = dc_strdup(name);\n\n\tif (namespc) {\n\t\tint name_len = strlen(name);\n\t\tint namespc_len = strlen(namespc);\n\t\tif (name_len<=namespc_len\n\t\t || strcmp(&name[name_len-namespc_len], namespc)!=0) {\n\t\t\treturn 0;\n\t\t}\n\t\tname_to_check[name_len-namespc_len] = 0;\n\t}\n\n\tint ret = (dc_hash_find_str(files_in_use, name_to_check)!=NULL);\n\n\tfree(name_to_check);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/sql.rs", "rust_func": "fn is_file_in_use(files_in_use: &HashSet, namespc_opt: Option<&str>, name: &str) -> bool {\n let name_to_check = if let Some(namespc) = namespc_opt {\n let name_len = name.len();\n let namespc_len = namespc.len();\n if name_len <= namespc_len || !name.ends_with(namespc) {\n return false;\n }\n &name[..name_len - namespc_len]\n } else {\n name\n };\n files_in_use.contains(name_to_check)\n}", "rust_context": "", "rust_imports": "use std::collections::{HashMap, HashSet};\nuse std::path::{Path, PathBuf};\nuse anyhow::{bail, Context as _, Result};\nuse rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row};\nuse tokio::sync::{Mutex, MutexGuard, RwLock};\nuse crate::blob::BlobObject;\nuse crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon};\nuse crate::config::Config;\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::ephemeral::start_ephemeral_timers;\nuse crate::imex::BLOBS_BACKUP_NAME;\nuse crate::location::delete_orphaned_poi_locations;\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::stock_str;\nuse crate::tools::{delete_file, time, SystemTime};\nuse pool::Pool;\nuse super::*;\nuse crate::{test_utils::TestContext, EventType};\nuse tempfile::tempdir;\nuse tempfile::tempdir;\nuse tempfile::tempdir;", "rustrepotrans_file": "projects__deltachat-core__rust__sql__.rs__function__41.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* After the creation with dc_create_group_chat() the chat is usually unpromoted\n * until the first call to dc_send_text_msg() or another sending function.\n *\n * With unpromoted chats, members can be added\n * and settings can be modified without the need of special status messages being sent.\n *\n * While the core takes care of the unpromoted state on its own,\n * checking the state from the UI side may be useful to decide whether a hint as\n * \"Send the first message to allow others to reply within the group\"\n * should be shown to the user or not.\n *\n * @memberof dc_chat_t\n * @param chat The chat object.\n * @return 1=chat is still unpromoted, no message was ever send to the chat,\n * 0=chat is not unpromoted, messages were send and/or received\n * or the chat is not group chat.\n */\nint dc_chat_is_unpromoted(const dc_chat_t* chat)\n{\n\tif (chat==NULL || chat->magic!=DC_CHAT_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0);\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub fn is_unpromoted(&self) -> bool {\n self.param.get_bool(Param::Unpromoted).unwrap_or_default()\n }", "rust_context": "pub fn get_bool(&self, key: Param) -> Option {\n self.get_int(key).map(|v| v != 0)\n }\n\npub struct Chat {\n /// Database ID.\n pub id: ChatId,\n\n /// Chat type, e.g. 1:1 chat, group chat, mailing list.\n pub typ: Chattype,\n\n /// Chat name.\n pub name: String,\n\n /// Whether the chat is archived or pinned.\n pub visibility: ChatVisibility,\n\n /// Group ID. For [`Chattype::Mailinglist`] -- mailing list address. Empty for 1:1 chats and\n /// ad-hoc groups.\n pub grpid: String,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n\n /// Additional chat parameters stored in the database.\n pub param: Params,\n\n /// If location streaming is enabled in the chat.\n is_sending_locations: bool,\n\n /// Duration of the chat being muted.\n pub mute_duration: MuteDuration,\n\n /// If the chat is protected (verified).\n pub(crate) protected: ProtectionStatus,\n}\n\npub struct ChatId(u32);\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__78.txt"} {"c_path": "projects/deltachat-core/c/dc_imex.c", "c_func": "char* dc_imex_has_backup(dc_context_t* context, const char* dir_name)\n{\n\tchar* ret = NULL;\n\tDIR* dir_handle = NULL;\n\tstruct dirent* dir_entry = NULL;\n\tint prefix_len = strlen(DC_BAK_PREFIX);\n\tint suffix_len = strlen(DC_BAK_SUFFIX);\n\tchar* curr_pathNfilename = NULL;\n\tdc_sqlite3_t* test_sql = NULL;\n char *newest_backup_name = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\treturn NULL;\n\t}\n\n\tif ((dir_handle=opendir(dir_name))==NULL) {\n\t\tdc_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 */\n\t\tgoto cleanup;\n\t}\n\n\twhile ((dir_entry=readdir(dir_handle))!=NULL) {\n\t\tconst char* name = dir_entry->d_name; /* name without path; may also be `.` or `..` */\n\t\tint name_len = strlen(name);\n free(curr_pathNfilename);\n curr_pathNfilename = dc_mprintf(\"%s/%s\", dir_name, name);\n\n\t\tif (name_len > prefix_len && strncmp(name, DC_BAK_PREFIX, prefix_len)==0\n\t\t && name_len > suffix_len && strncmp(&name[name_len-suffix_len-1], \".\" DC_BAK_SUFFIX, suffix_len)==0)\n\t\t && (newest_backup_name == NULL || strcmp(name, newest_backup_name) > 0)\n {\n\t\t\tfree(newest_backup_name); \n newest_backup_name = strdup(name);\n\n free(ret);\n ret = curr_pathNfilename;\n curr_pathNfilename = NULL;\n\t\t}\n\t}\n\ncleanup:\n\tif (dir_handle) { closedir(dir_handle); }\n\tfree(curr_pathNfilename);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/imex.rs", "rust_func": "pub async fn has_backup(_context: &Context, dir_name: &Path) -> Result {\n let mut dir_iter = tokio::fs::read_dir(dir_name).await?;\n let mut newest_backup_name = \"\".to_string();\n let mut newest_backup_path: Option = None;\n\n while let Ok(Some(dirent)) = dir_iter.next_entry().await {\n let path = dirent.path();\n let name = dirent.file_name();\n let name: String = name.to_string_lossy().into();\n if name.starts_with(\"delta-chat\")\n && name.ends_with(\".tar\")\n && (newest_backup_name.is_empty() || name > newest_backup_name)\n {\n // We just use string comparison to determine which backup is newer.\n // This works fine because the filenames have the form `delta-chat-backup-2023-10-18-00-foo@example.com.tar`\n newest_backup_path = Some(path);\n newest_backup_name = name;\n }\n }\n\n match newest_backup_path {\n Some(path) => Ok(path.to_string_lossy().into_owned()),\n None => bail!(\"no backup found in {}\", dir_name.display()),\n }\n}", "rust_context": "pub fn is_empty(&self) -> bool {\n self.inner.is_empty()\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}", "rust_imports": "use std::any::Any;\nuse std::ffi::OsStr;\nuse std::path::{Path, PathBuf};\nuse ::pgp::types::KeyTrait;\nuse anyhow::{bail, ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse futures::StreamExt;\nuse futures_lite::FutureExt;\nuse rand::{thread_rng, Rng};\nuse tokio::fs::{self, File};\nuse tokio_tar::Archive;\nuse crate::blob::{BlobDirContents, BlobObject};\nuse crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};\nuse crate::config::Config;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::e2ee;\nuse crate::events::EventType;\nuse crate::key::{\n self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,\n};\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::param::Param;\nuse crate::pgp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{\n create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,\n};\nuse transfer::{get_backup, BackupProvider};\nuse std::time::Duration;\nuse ::pgp::armor::BlockType;\nuse tokio::task;\nuse super::*;\nuse crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::{alice_keypair, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__imex__.rs__function__2.txt"} {"c_path": "projects/deltachat-core/c/dc_param.c", "c_func": "int dc_param_exists(dc_param_t* param, int key)\n{\n\tchar *p2 = NULL;\n\n\tif (param==NULL || key==0) {\n\t\treturn 0;\n\t}\n\n\treturn find_param(param->packed, key, &p2)? 1 : 0;\n}", "rust_path": "projects/deltachat-core/rust/param.rs", "rust_func": "pub fn exists(&self, key: Param) -> bool {\n self.inner.contains_key(&key)\n }", "rust_context": "pub struct Params {\n inner: BTreeMap,\n}", "rust_imports": "use std::collections::BTreeMap;\nuse std::fmt;\nuse std::path::PathBuf;\nuse std::str;\nuse anyhow::{bail, Error, Result};\nuse num_traits::FromPrimitive;\nuse serde::{Deserialize, Serialize};\nuse crate::blob::BlobObject;\nuse crate::context::Context;\nuse crate::mimeparser::SystemMessage;\nuse std::path::Path;\nuse std::str::FromStr;\nuse tokio::fs;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__param__.rs__function__5.txt"} {"c_path": "projects/deltachat-core/c/dc_imex.c", "c_func": "int dc_continue_key_transfer(dc_context_t* context, uint32_t msg_id, const char* setup_code)\n{\n\tint success = 0;\n\tdc_msg_t* msg = NULL;\n\tchar* filename = NULL;\n\tchar* filecontent = NULL;\n\tsize_t filebytes = 0;\n\tchar* armored_key = NULL;\n\tchar* norm_sc = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_id <= DC_MSG_ID_LAST_SPECIAL || setup_code==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tif ((msg=dc_get_msg(context, msg_id))==NULL || !dc_msg_is_setupmessage(msg)\n\t || (filename=dc_msg_get_file(msg))==NULL || filename[0]==0) {\n\t\tdc_log_error(context, 0, \"Message is no Autocrypt Setup Message.\");\n\t\tgoto cleanup;\n\t}\n\n\tif (!dc_read_file(context, filename, (void**)&filecontent, &filebytes) || filecontent==NULL || filebytes <= 0) {\n\t\tdc_log_error(context, 0, \"Cannot read Autocrypt Setup Message file.\");\n\t\tgoto cleanup;\n\t}\n\n\tif ((norm_sc = dc_normalize_setup_code(context, setup_code))==NULL) {\n\t\tdc_log_warning(context, 0, \"Cannot normalize Setup Code.\");\n\t\tgoto cleanup;\n\t}\n\n\tif ((armored_key=dc_decrypt_setup_file(context, norm_sc, filecontent))==NULL) {\n\t\tdc_log_warning(context, 0, \"Cannot decrypt Autocrypt Setup Message.\"); /* do not log as error - this is quite normal after entering the bad setup code */\n\t\tgoto cleanup;\n\t}\n\n\tif (!set_self_key(context, armored_key, 1/*set default*/)) {\n\t\tgoto cleanup; /* error already logged */\n\t}\n\n\tsuccess = 1;\n\ncleanup:\n\tfree(armored_key);\n\tfree(filecontent);\n\tfree(filename);\n\tdc_msg_unref(msg);\n\tfree(norm_sc);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/imex.rs", "rust_func": "pub async fn continue_key_transfer(\n context: &Context,\n msg_id: MsgId,\n setup_code: &str,\n) -> Result<()> {\n ensure!(!msg_id.is_special(), \"wrong id\");\n\n let msg = Message::load_from_db(context, msg_id).await?;\n ensure!(\n msg.is_setupmessage(),\n \"Message is no Autocrypt Setup Message.\"\n );\n\n if let Some(filename) = msg.get_file(context) {\n let file = open_file_std(context, filename)?;\n let sc = normalize_setup_code(setup_code);\n let armored_key = decrypt_setup_file(&sc, file).await?;\n set_self_key(context, &armored_key, true).await?;\n maybe_add_bcc_self_device_msg(context).await?;\n\n Ok(())\n } else {\n bail!(\"Message is no Autocrypt Setup Message.\");\n }\n}", "rust_context": "pub fn is_special(self) -> bool {\n self.0 <= DC_MSG_ID_LAST_SPECIAL\n }\n\npub async fn load_from_db(context: &Context, id: MsgId) -> Result {\n let message = Self::load_from_db_optional(context, id)\n .await?\n .with_context(|| format!(\"Message {id} does not exist\"))?;\n Ok(message)\n }\n \nfn normalize_setup_code(s: &str) -> String {\n let mut out = String::new();\n for c in s.chars() {\n if c.is_ascii_digit() {\n out.push(c);\n if let 4 | 9 | 14 | 19 | 24 | 29 | 34 | 39 = out.len() {\n out += \"-\"\n }\n }\n }\n out\n}\n\npub fn open_file_std(context: &Context, path: impl AsRef) -> Result {\n let path_abs = get_abs_path(context, path.as_ref());\n\n match std::fs::File::open(path_abs) {\n Ok(bytes) => Ok(bytes),\n Err(err) => {\n warn!(\n context,\n \"Cannot read \\\"{}\\\" or file is empty: {}\",\n path.as_ref().display(),\n err\n );\n Err(err.into())\n }\n }\n}\n\npub fn get_file(&self, context: &Context) -> Option {\n self.param.get_path(Param::File, context).unwrap_or(None)\n }\n\nasync fn set_self_key(context: &Context, armored: &str, set_default: bool) -> Result<()> {\n // try hard to only modify key-state\n let (private_key, header) = SignedSecretKey::from_asc(armored)?;\n let public_key = private_key.split_public_key()?;\n if let Some(preferencrypt) = header.get(\"Autocrypt-Prefer-Encrypt\") {\n let e2ee_enabled = match preferencrypt.as_str() {\n \"nopreference\" => 0,\n \"mutual\" => 1,\n _ => {\n bail!(\"invalid Autocrypt-Prefer-Encrypt header: {:?}\", header);\n }\n };\n context\n .sql\n .set_raw_config_int(\"e2ee_enabled\", e2ee_enabled)\n .await?;\n } else {\n // `Autocrypt-Prefer-Encrypt` is not included\n // in keys exported to file.\n //\n // `Autocrypt-Prefer-Encrypt` also SHOULD be sent\n // in Autocrypt Setup Message according to Autocrypt specification,\n // but K-9 6.802 does not include this header.\n //\n // We keep current setting in this case.\n info!(context, \"No Autocrypt-Prefer-Encrypt header.\");\n };\n\n let self_addr = context.get_primary_self_addr().await?;\n let addr = EmailAddress::new(&self_addr)?;\n let keypair = pgp::KeyPair {\n addr,\n public: public_key,\n secret: private_key,\n };\n key::store_self_keypair(\n context,\n &keypair,\n if set_default {\n key::KeyPairUse::Default\n } else {\n key::KeyPairUse::ReadOnly\n },\n )\n .await?;\n\n info!(context, \"stored self key: {:?}\", keypair.secret.key_id());\n Ok(())\n}\n\nasync fn maybe_add_bcc_self_device_msg(context: &Context) -> Result<()> {\n if !context.sql.get_raw_config_bool(\"bcc_self\").await? {\n let mut msg = Message::new(Viewtype::Text);\n // TODO: define this as a stockstring once the wording is settled.\n msg.text = \"It seems you are using multiple devices with Delta Chat. Great!\\n\\n\\\n If you also want to synchronize outgoing messages across all devices, \\\n go to \\\"Settings \u2192 Advanced\\\" and enable \\\"Send Copy to Self\\\".\"\n .to_string();\n chat::add_device_msg(context, Some(\"bcc-self-hint\"), Some(&mut msg)).await?;\n }\n Ok(())\n}\n\nasync fn decrypt_setup_file(\n passphrase: &str,\n file: T,\n) -> Result {\n let plain_bytes = pgp::symm_decrypt(passphrase, file).await?;\n let plain_text = std::string::String::from_utf8(plain_bytes)?;\n\n Ok(plain_text)\n}\n\npub struct MsgId(u32);\n\npub struct Context {\n pub(crate) inner: Arc,\n}", "rust_imports": "use std::any::Any;\nuse std::ffi::OsStr;\nuse std::path::{Path, PathBuf};\nuse ::pgp::types::KeyTrait;\nuse anyhow::{bail, ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse futures::StreamExt;\nuse futures_lite::FutureExt;\nuse rand::{thread_rng, Rng};\nuse tokio::fs::{self, File};\nuse tokio_tar::Archive;\nuse crate::blob::{BlobDirContents, BlobObject};\nuse crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};\nuse crate::config::Config;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::e2ee;\nuse crate::events::EventType;\nuse crate::key::{\n self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,\n};\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::param::Param;\nuse crate::pgp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{\n create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,\n};\nuse transfer::{get_backup, BackupProvider};\nuse std::time::Duration;\nuse ::pgp::armor::BlockType;\nuse tokio::task;\nuse super::*;\nuse crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::{alice_keypair, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__imex__.rs__function__7.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "* Known and unblocked contacts will be returned by dc_get_contacts().\n *\n * To validate an e-mail address independently of the contact database\n * use dc_may_be_valid_addr().\n *\n * @memberof dc_context_t\n * @param context The context object as created by dc_context_new().\n * @param addr The e-mail-address to check.\n * @return 1=address is a contact in use, 0=address is not a contact in use.\n */\nuint32_t dc_lookup_contact_id_by_addr(dc_context_t* context, const char* addr)\n{\n\tint contact_id = 0;\n\tchar* addr_normalized = NULL;\n\tchar* addr_self = NULL;\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || addr==NULL || addr[0]==0) {\n\t\tgoto cleanup;\n\t}\n\n\taddr_normalized = dc_addr_normalize(addr);\n\n\taddr_self = dc_sqlite3_get_config(context->sql, \"configured_addr\", \"\");\n\tif (strcasecmp(addr_normalized, addr_self)==0) {\n\t\tcontact_id = DC_CONTACT_ID_SELF;\n\t\tgoto cleanup;\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT id FROM contacts\"\n\t\t\" WHERE addr=?1 COLLATE NOCASE\"\n\t\t\" AND id>?2 AND origin>=?3 AND blocked=0;\");\n\tsqlite3_bind_text(stmt, 1, (const char*)addr_normalized, -1, SQLITE_STATIC);\n\tsqlite3_bind_int (stmt, 2, DC_CONTACT_ID_LAST_SPECIAL);\n\tsqlite3_bind_int (stmt, 3, DC_ORIGIN_MIN_CONTACT_LIST);\n\tif (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\tcontact_id = sqlite3_column_int(stmt, 0);\n\t}\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\tfree(addr_normalized);\n\tfree(addr_self);\n\treturn contact_id;\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub async fn lookup_id_by_addr(\n context: &Context,\n addr: &str,\n min_origin: Origin,\n ) -> Result> {\n Self::lookup_id_by_addr_ex(context, addr, min_origin, Some(Blocked::Not)).await\n }", "rust_context": "pub(crate) async fn lookup_id_by_addr_ex(\n context: &Context,\n addr: &str,\n min_origin: Origin,\n blocked: Option,\n ) -> Result> {\n if addr.is_empty() {\n bail!(\"lookup_id_by_addr: empty address\");\n }\n\n let addr_normalized = addr_normalize(addr);\n\n if context.is_self_addr(&addr_normalized).await? {\n return Ok(Some(ContactId::SELF));\n }\n\n let id = context\n .sql\n .query_get_value(\n \"SELECT id FROM contacts \\\n WHERE addr=?1 COLLATE NOCASE \\\n AND id>?2 AND origin>=?3 AND (? OR blocked=?)\",\n (\n &addr_normalized,\n ContactId::LAST_SPECIAL,\n min_origin as u32,\n blocked.is_none(),\n blocked.unwrap_or_default(),\n ),\n )\n .await?;\n Ok(id)\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ContactId(u32);\n\npub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__24.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_get_info_type(const dc_msg_t* msg)\n{\n\treturn dc_param_get_int(msg->param, DC_PARAM_CMD, 0);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn get_info_type(&self) -> SystemMessage {\n self.param.get_cmd()\n }", "rust_context": "pub fn get_cmd(&self) -> SystemMessage {\n self.get_int(Param::Cmd)\n .and_then(SystemMessage::from_i32)\n .unwrap_or_default()\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__57.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "void dc_update_msg_state(dc_context_t* context, uint32_t msg_id, int state)\n{\n\tsqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql,\n \"UPDATE msgs SET state=? WHERE id=? AND (?=? OR state Result<()> {\n ensure!(state != MessageState::OutFailed, \"use set_msg_failed()!\");\n let error_subst = match state >= MessageState::OutPending {\n true => \", error=''\",\n false => \"\",\n };\n context\n .sql\n .execute(\n &format!(\"UPDATE msgs SET state=?1 {error_subst} WHERE id=?2 AND (?1!=?3 OR state Result {\n self.call_write(move |conn| {\n let res = conn.execute(query, params)?;\n Ok(res)\n })\n .await\n }\n\npub struct MsgId(u32);\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\n\npub enum MessageState {\n /// Undefined message state.\n #[default]\n Undefined = 0,\n\n /// Incoming *fresh* message. Fresh messages are neither noticed\n /// nor seen and are typically shown in notifications.\n InFresh = 10,\n\n /// Incoming *noticed* message. E.g. chat opened but message not\n /// yet read - noticed messages are not counted as unread but did\n /// not marked as read nor resulted in MDNs.\n InNoticed = 13,\n\n /// Incoming message, really *seen* by the user. Marked as read on\n /// IMAP and MDN may be sent.\n InSeen = 16,\n\n /// For files which need time to be prepared before they can be\n /// sent, the message enters this state before\n /// OutPending.\n OutPreparing = 18,\n\n /// Message saved as draft.\n OutDraft = 19,\n\n /// The user has pressed the \"send\" button but the message is not\n /// yet sent and is pending in some way. Maybe we're offline (no\n /// checkmark).\n OutPending = 20,\n\n /// *Unrecoverable* error (*recoverable* errors result in pending\n /// messages).\n OutFailed = 24,\n\n /// Outgoing message successfully delivered to server (one\n /// checkmark). Note, that already delivered messages may get into\n /// the OutFailed state if we get such a hint from the server.\n OutDelivered = 26,\n\n /// Outgoing message read by the recipient (two checkmarks; this\n /// requires goodwill on the receiver's side)\n OutMdnRcvd = 28,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__91.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "size_t dc_get_chat_cnt(dc_context_t* context)\n{\n\tsize_t ret = 0;\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql->cobj==NULL) {\n\t\tgoto cleanup; /* no database, no chats - this is no error (needed eg. for information) */\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT COUNT(*) FROM chats WHERE id>\" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) \" AND blocked=0;\");\n\tif (sqlite3_step(stmt)!=SQLITE_ROW) {\n\t\tgoto cleanup;\n\t}\n\n\tret = sqlite3_column_int(stmt, 0);\n\ncleanup:\n\tsqlite3_finalize(stmt);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub(crate) async fn get_chat_cnt(context: &Context) -> Result {\n if context.sql.is_open().await {\n // no database, no chats - this is no error (needed eg. for information)\n let count = context\n .sql\n .count(\"SELECT COUNT(*) FROM chats WHERE id>9 AND blocked=0;\", ())\n .await?;\n Ok(count)\n } else {\n Ok(0)\n }\n}", "rust_context": "pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result {\n let count: isize = self.query_row(query, params, |row| row.get(0)).await?;\n Ok(usize::try_from(count)?)\n }\n\npub async fn is_open(&self) -> bool {\n self.sql.is_open().await\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__141.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "dc_lot_t* dc_msg_get_summary(const dc_msg_t* msg, const dc_chat_t* chat)\n{\n\tdc_lot_t* ret = dc_lot_new();\n\tdc_contact_t* contact = NULL;\n\tdc_chat_t* chat_to_delete = NULL;\n\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tif (chat==NULL) {\n\t\tif ((chat_to_delete=dc_get_chat(msg->context, msg->chat_id))==NULL) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\tchat = chat_to_delete;\n\t}\n\n\tif (msg->from_id!=DC_CONTACT_ID_SELF && DC_CHAT_TYPE_IS_MULTI(chat->type)) {\n\t\tcontact = dc_get_contact(chat->context, msg->from_id);\n\t}\n\n\tdc_lot_fill(ret, msg, chat, contact, msg->context);\n\ncleanup:\n\tdc_contact_unref(contact);\n\tdc_chat_unref(chat_to_delete);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub async fn get_summary(&self, context: &Context, chat: Option<&Chat>) -> Result {\n let chat_loaded: Chat;\n let chat = if let Some(chat) = chat {\n chat\n } else {\n let chat = Chat::load_from_db(context, self.chat_id).await?;\n chat_loaded = chat;\n &chat_loaded\n };\n\n let contact = if self.from_id != ContactId::SELF {\n match chat.typ {\n Chattype::Group | Chattype::Broadcast | Chattype::Mailinglist => {\n Some(Contact::get_by_id(context, self.from_id).await?)\n }\n Chattype::Single => None,\n }\n } else {\n None\n };\n\n Summary::new(context, self, chat, contact.as_ref()).await\n }", "rust_context": "pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result {\n let mut chat = context\n .sql\n .query_row(\n \"SELECT c.type, c.name, c.grpid, c.param, c.archived,\n c.blocked, c.locations_send_until, c.muted_until, c.protected\n FROM chats c\n WHERE c.id=?;\",\n (chat_id,),\n |row| {\n let c = Chat {\n id: chat_id,\n typ: row.get(0)?,\n name: row.get::<_, String>(1)?,\n grpid: row.get::<_, String>(2)?,\n param: row.get::<_, String>(3)?.parse().unwrap_or_default(),\n visibility: row.get(4)?,\n blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),\n is_sending_locations: row.get(6)?,\n mute_duration: row.get(7)?,\n protected: row.get(8)?,\n };\n Ok(c)\n },\n )\n .await\n .context(format!(\"Failed loading chat {chat_id} from database\"))?;\n\n if chat.id.is_archived_link() {\n chat.name = stock_str::archived_chats(context).await;\n } else {\n if chat.typ == Chattype::Single && chat.name.is_empty() {\n // chat.name is set to contact.display_name on changes,\n // however, if things went wrong somehow, we do this here explicitly.\n let mut chat_name = \"Err [Name not found]\".to_owned();\n match get_chat_contacts(context, chat.id).await {\n Ok(contacts) => {\n if let Some(contact_id) = contacts.first() {\n if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {\n contact.get_display_name().clone_into(&mut chat_name);\n }\n }\n }\n Err(err) => {\n error!(\n context,\n \"Failed to load contacts for {}: {:#}.\", chat.id, err\n );\n }\n }\n chat.name = chat_name;\n }\n if chat.param.exists(Param::Selftalk) {\n chat.name = stock_str::saved_messages(context).await;\n } else if chat.param.exists(Param::Devicetalk) {\n chat.name = stock_str::device_messages(context).await;\n }\n }\n\n Ok(chat)\n }\n\npub async fn new(\n context: &Context,\n msg: &Message,\n chat: &Chat,\n contact: Option<&Contact>,\n ) -> Result {\n let prefix = if msg.state == MessageState::OutDraft {\n Some(SummaryPrefix::Draft(stock_str::draft(context).await))\n } else if msg.from_id == ContactId::SELF {\n if msg.is_info() || chat.is_self_talk() {\n None\n } else {\n Some(SummaryPrefix::Me(stock_str::self_msg(context).await))\n }\n } else {\n match chat.typ {\n Chattype::Group | Chattype::Broadcast | Chattype::Mailinglist => {\n if msg.is_info() || contact.is_none() {\n None\n } else {\n msg.get_override_sender_name()\n .or_else(|| contact.map(|contact| msg.get_sender_name(contact)))\n .map(SummaryPrefix::Username)\n }\n }\n Chattype::Single => None,\n }\n };\n\n let mut text = msg.get_summary_text(context).await;\n\n if text.is_empty() && msg.quoted_text().is_some() {\n text = stock_str::reply_noun(context).await\n }\n\n let thumbnail_path = if msg.viewtype == Viewtype::Image\n || msg.viewtype == Viewtype::Gif\n || msg.viewtype == Viewtype::Sticker\n {\n msg.get_file(context)\n .and_then(|path| path.to_str().map(|p| p.to_owned()))\n } else {\n None\n };\n\n Ok(Summary {\n prefix,\n text,\n timestamp: msg.get_timestamp(),\n state: msg.state,\n thumbnail_path,\n })\n\npub async fn get_by_id(context: &Context, contact_id: ContactId) -> Result {\n let contact = Self::get_by_id_optional(context, contact_id)\n .await?\n .with_context(|| format!(\"contact {contact_id} not found\"))?;\n Ok(contact)\n }\n \npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub struct Summary {\n /// Part displayed before \":\", such as an username or a string \"Draft\".\n pub prefix: Option,\n\n /// Summary text, always present.\n pub text: String,\n\n /// Message timestamp.\n pub timestamp: i64,\n\n /// Message state.\n pub state: MessageState,\n\n /// Message preview image path\n pub thumbnail_path: Option,\n}\n\npub struct ContactId(u32);\n\nimpl ContactId {\n /// Undefined contact. Used as a placeholder for trashed messages.\n pub const UNDEFINED: ContactId = ContactId::new(0);\n\n /// The owner of the account.\n ///\n /// The email-address is set by `set_config` using \"addr\".\n pub const SELF: ContactId = ContactId::new(1);\n\n /// ID of the contact for info messages.\n pub const INFO: ContactId = ContactId::new(2);\n\n /// ID of the contact for device messages.\n pub const DEVICE: ContactId = ContactId::new(5);\n pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9);\n\n /// Address to go with [`ContactId::DEVICE`].\n ///\n /// This is used by APIs which need to return an email address for this contact.\n pub const DEVICE_ADDR: &'static str = \"device@localhost\";\n}\n\npub enum Chattype {\n /// 1:1 chat.\n Single = 100,\n\n /// Group chat.\n Group = 120,\n\n /// Mailing list.\n Mailinglist = 140,\n\n /// Broadcast list.\n Broadcast = 160,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__50.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* be unexpected as (1) deleting a normal chat also does not prevent new mails\n * from arriving, (2) leaving a group requires sending a message to\n * all group members - especially for groups not used for a longer time, this is\n * really unexpected when deletion results in contacting all members again,\n * (3) only leaving groups is also a valid usecase.\n *\n * To leave a chat explicitly, use dc_remove_contact_from_chat() with\n * chat_id=DC_CONTACT_ID_SELF)\n *\n * @memberof dc_context_t\n * @param context The context object as returned from dc_context_new().\n * @param chat_id The ID of the chat to delete.\n * @return None.\n */\nvoid dc_delete_chat(dc_context_t* context, uint32_t chat_id)\n{\n\t/* Up to 2017-11-02 deleting a group also implied leaving it, see above why we have changed this. */\n\tint pending_transaction = 0;\n\tdc_chat_t* obj = dc_chat_new(context);\n\tchar* q3 = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL) {\n\t\tgoto cleanup;\n\t}\n\n\tif (!dc_chat_load_from_db(obj, chat_id)) {\n\t\tgoto cleanup;\n\t}\n\n\tdc_sqlite3_begin_transaction(context->sql);\n\tpending_transaction = 1;\n\n\t\tq3 = sqlite3_mprintf(\"DELETE FROM msgs_mdns WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=%i);\", chat_id);\n\t\tif (!dc_sqlite3_execute(context->sql, q3)) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\tsqlite3_free(q3);\n\t\tq3 = NULL;\n\n\t\tq3 = sqlite3_mprintf(\"DELETE FROM msgs WHERE chat_id=%i;\", chat_id);\n\t\tif (!dc_sqlite3_execute(context->sql, q3)) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\tsqlite3_free(q3);\n\t\tq3 = NULL;\n\n\t\tq3 = sqlite3_mprintf(\"DELETE FROM chats_contacts WHERE chat_id=%i;\", chat_id);\n\t\tif (!dc_sqlite3_execute(context->sql, q3)) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\tsqlite3_free(q3);\n\t\tq3 = NULL;\n\n\t\tq3 = sqlite3_mprintf(\"DELETE FROM chats WHERE id=%i;\", chat_id);\n\t\tif (!dc_sqlite3_execute(context->sql, q3)) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\tsqlite3_free(q3);\n\t\tq3 = NULL;\n\n\tdc_sqlite3_commit(context->sql);\n\tpending_transaction = 0;\n\n\tcontext->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0);\n\n\tdc_job_kill_action(context, DC_JOB_HOUSEKEEPING);\n\tdc_job_add(context, DC_JOB_HOUSEKEEPING, 0, NULL, DC_HOUSEKEEPING_DELAY_SEC);\n\ncleanup:\n\tif (pending_transaction) { dc_sqlite3_rollback(context->sql); }\n\tdc_chat_unref(obj);\n\tsqlite3_free(q3);\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn delete(self, context: &Context) -> Result<()> {\n ensure!(\n !self.is_special(),\n \"bad chat_id, can not be a special chat: {}\",\n self\n );\n\n let chat = Chat::load_from_db(context, self).await?;\n context\n .sql\n .execute(\n \"DELETE FROM msgs_mdns WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=?);\",\n (self,),\n )\n .await?;\n\n context\n .sql\n .execute(\"DELETE FROM msgs WHERE chat_id=?;\", (self,))\n .await?;\n\n context\n .sql\n .execute(\"DELETE FROM chats_contacts WHERE chat_id=?;\", (self,))\n .await?;\n\n context\n .sql\n .execute(\"DELETE FROM chats WHERE id=?;\", (self,))\n .await?;\n\n context.emit_msgs_changed_without_ids();\n chatlist_events::emit_chatlist_changed(context);\n\n context\n .set_config_internal(Config::LastHousekeeping, None)\n .await?;\n context.scheduler.interrupt_inbox().await;\n\n if chat.is_self_talk() {\n let mut msg = Message::new(Viewtype::Text);\n msg.text = stock_str::self_deleted_msg_body(context).await;\n add_device_msg(context, None, Some(&mut msg)).await?;\n }\n chatlist_events::emit_chatlist_changed(context);\n\n Ok(())\n }", "rust_context": "pub(crate) async fn set_config_internal(&self, key: Config, value: Option<&str>) -> Result<()> {\n self.set_config_ex(Sync, key, value).await\n }\n\npub fn new(viewtype: Viewtype) -> Self {\n Message {\n viewtype,\n ..Default::default()\n }\n }\n\npub(crate) fn emit_chatlist_changed(context: &Context) {\n context.emit_event(EventType::ChatlistChanged);\n}\n\npub(crate) async fn self_deleted_msg_body(context: &Context) -> String {\n translated(context, StockMessage::SelfDeletedMsgBody).await\n}\n\npub async fn add_device_msg(\n context: &Context,\n label: Option<&str>,\n msg: Option<&mut Message>,\n) -> Result {\n add_device_msg_with_importance(context, label, msg, false).await\n}\n\npub fn is_self_talk(&self) -> bool {\n self.param.exists(Param::Selftalk)\n }\n\npub fn emit_msgs_changed_without_ids(&self) {\n self.emit_event(EventType::MsgsChanged {\n chat_id: ChatId::new(0),\n msg_id: MsgId::new(0),\n });\n }\n\npub fn is_special(self) -> bool {\n (0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)\n }\n\npub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result {\n let mut chat = context\n .sql\n .query_row(\n \"SELECT c.type, c.name, c.grpid, c.param, c.archived,\n c.blocked, c.locations_send_until, c.muted_until, c.protected\n FROM chats c\n WHERE c.id=?;\",\n (chat_id,),\n |row| {\n let c = Chat {\n id: chat_id,\n typ: row.get(0)?,\n name: row.get::<_, String>(1)?,\n grpid: row.get::<_, String>(2)?,\n param: row.get::<_, String>(3)?.parse().unwrap_or_default(),\n visibility: row.get(4)?,\n blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),\n is_sending_locations: row.get(6)?,\n mute_duration: row.get(7)?,\n protected: row.get(8)?,\n };\n Ok(c)\n },\n )\n .await\n .context(format!(\"Failed loading chat {chat_id} from database\"))?;\n\n if chat.id.is_archived_link() {\n chat.name = stock_str::archived_chats(context).await;\n } else {\n if chat.typ == Chattype::Single && chat.name.is_empty() {\n // chat.name is set to contact.display_name on changes,\n // however, if things went wrong somehow, we do this here explicitly.\n let mut chat_name = \"Err [Name not found]\".to_owned();\n match get_chat_contacts(context, chat.id).await {\n Ok(contacts) => {\n if let Some(contact_id) = contacts.first() {\n if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {\n contact.get_display_name().clone_into(&mut chat_name);\n }\n }\n }\n Err(err) => {\n error!(\n context,\n \"Failed to load contacts for {}: {:#}.\", chat.id, err\n );\n }\n }\n chat.name = chat_name;\n }\n if chat.param.exists(Param::Selftalk) {\n chat.name = stock_str::saved_messages(context).await;\n } else if chat.param.exists(Param::Devicetalk) {\n chat.name = stock_str::device_messages(context).await;\n }\n }\n\n Ok(chat)\n }\n\npub enum Config {\n /// Email address, used in the `From:` field.\n Addr,\n\n /// IMAP server hostname.\n MailServer,\n\n /// IMAP server username.\n MailUser,\n\n /// IMAP server password.\n MailPw,\n\n /// IMAP server port.\n MailPort,\n\n /// IMAP server security (e.g. TLS, STARTTLS).\n MailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ImapCertificateChecks,\n\n /// SMTP server hostname.\n SendServer,\n\n /// SMTP server username.\n SendUser,\n\n /// SMTP server password.\n SendPw,\n\n /// SMTP server port.\n SendPort,\n\n /// SMTP server security (e.g. TLS, STARTTLS).\n SendSecurity,\n\n /// How to check SMTP server TLS certificates.\n SmtpCertificateChecks,\n\n /// Whether to use OAuth 2.\n ///\n /// Historically contained other bitflags, which are now deprecated.\n /// Should not be extended in the future, create new config keys instead.\n ServerFlags,\n\n /// True if SOCKS5 is enabled.\n ///\n /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.\n Socks5Enabled,\n\n /// SOCKS5 proxy server hostname or address.\n Socks5Host,\n\n /// SOCKS5 proxy server port.\n Socks5Port,\n\n /// SOCKS5 proxy server username.\n Socks5User,\n\n /// SOCKS5 proxy server password.\n Socks5Password,\n\n /// Own name to use in the `From:` field when sending messages.\n Displayname,\n\n /// Own status to display, sent in message footer.\n Selfstatus,\n\n /// Own avatar filename.\n Selfavatar,\n\n /// Send BCC copy to self.\n ///\n /// Should be enabled for multidevice setups.\n #[strum(props(default = \"1\"))]\n BccSelf,\n\n /// True if encryption is preferred according to Autocrypt standard.\n #[strum(props(default = \"1\"))]\n E2eeEnabled,\n\n /// True if Message Delivery Notifications (read receipts) should\n /// be sent and requested.\n #[strum(props(default = \"1\"))]\n MdnsEnabled,\n\n /// True if \"Sent\" folder should be watched for changes.\n #[strum(props(default = \"0\"))]\n SentboxWatch,\n\n /// True if chat messages should be moved to a separate folder.\n #[strum(props(default = \"1\"))]\n MvboxMove,\n\n /// Watch for new messages in the \"Mvbox\" (aka DeltaChat folder) only.\n ///\n /// This will not entirely disable other folders, e.g. the spam folder will also still\n /// be watched for new messages.\n #[strum(props(default = \"0\"))]\n OnlyFetchMvbox,\n\n /// Whether to show classic emails or only chat messages.\n #[strum(props(default = \"2\"))] // also change ShowEmails.default() on changes\n ShowEmails,\n\n /// Quality of the media files to send.\n #[strum(props(default = \"0\"))] // also change MediaQuality.default() on changes\n MediaQuality,\n\n /// If set to \"1\", on the first time `start_io()` is called after configuring,\n /// the newest existing messages are fetched.\n /// Existing recipients are added to the contact database regardless of this setting.\n #[strum(props(default = \"0\"))]\n FetchExistingMsgs,\n\n /// If set to \"1\", then existing messages are considered to be already fetched.\n /// This flag is reset after successful configuration.\n #[strum(props(default = \"1\"))]\n FetchedExistingMsgs,\n\n /// Type of the OpenPGP key to generate.\n #[strum(props(default = \"0\"))]\n KeyGenType,\n\n /// Timer in seconds after which the message is deleted from the\n /// server.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n ///\n /// Value 1 is treated as \"delete at once\": messages are deleted\n /// immediately, without moving to DeltaChat folder.\n #[strum(props(default = \"0\"))]\n DeleteServerAfter,\n\n /// Timer in seconds after which the message is deleted from the\n /// device.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n #[strum(props(default = \"0\"))]\n DeleteDeviceAfter,\n\n /// Move messages to the Trash folder instead of marking them \"\\Deleted\". Overrides\n /// `ProviderOptions::delete_to_trash`.\n DeleteToTrash,\n\n /// Save raw MIME messages with headers in the database if true.\n SaveMimeHeaders,\n\n /// The primary email address. Also see `SecondaryAddrs`.\n ConfiguredAddr,\n\n /// Configured IMAP server hostname.\n ConfiguredMailServer,\n\n /// Configured IMAP server username.\n ConfiguredMailUser,\n\n /// Configured IMAP server password.\n ConfiguredMailPw,\n\n /// Configured IMAP server port.\n ConfiguredMailPort,\n\n /// Configured IMAP server security (e.g. TLS, STARTTLS).\n ConfiguredMailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ConfiguredImapCertificateChecks,\n\n /// Configured SMTP server hostname.\n ConfiguredSendServer,\n\n /// Configured SMTP server username.\n ConfiguredSendUser,\n\n /// Configured SMTP server password.\n ConfiguredSendPw,\n\n /// Configured SMTP server port.\n ConfiguredSendPort,\n\n /// How to check SMTP server TLS certificates.\n ConfiguredSmtpCertificateChecks,\n\n /// Whether OAuth 2 is used with configured provider.\n ConfiguredServerFlags,\n\n /// Configured SMTP server security (e.g. TLS, STARTTLS).\n ConfiguredSendSecurity,\n\n /// Configured folder for incoming messages.\n ConfiguredInboxFolder,\n\n /// Configured folder for chat messages.\n ConfiguredMvboxFolder,\n\n /// Configured \"Sent\" folder.\n ConfiguredSentboxFolder,\n\n /// Configured \"Trash\" folder.\n ConfiguredTrashFolder,\n\n /// Unix timestamp of the last successful configuration.\n ConfiguredTimestamp,\n\n /// ID of the configured provider from the provider database.\n ConfiguredProvider,\n\n /// True if account is configured.\n Configured,\n\n /// True if account is a chatmail account.\n IsChatmail,\n\n /// All secondary self addresses separated by spaces\n /// (`addr1@example.org addr2@example.org addr3@example.org`)\n SecondaryAddrs,\n\n /// Read-only core version string.\n #[strum(serialize = \"sys.version\")]\n SysVersion,\n\n /// Maximal recommended attachment size in bytes.\n #[strum(serialize = \"sys.msgsize_max_recommended\")]\n SysMsgsizeMaxRecommended,\n\n /// Space separated list of all config keys available.\n #[strum(serialize = \"sys.config_keys\")]\n SysConfigKeys,\n\n /// True if it is a bot account.\n Bot,\n\n /// True when to skip initial start messages in groups.\n #[strum(props(default = \"0\"))]\n SkipStartMessages,\n\n /// Whether we send a warning if the password is wrong (set to false when we send a warning\n /// because we do not want to send a second warning)\n #[strum(props(default = \"0\"))]\n NotifyAboutWrongPw,\n\n /// If a warning about exceeding quota was shown recently,\n /// this is the percentage of quota at the time the warning was given.\n /// Unset, when quota falls below minimal warning threshold again.\n QuotaExceeding,\n\n /// address to webrtc instance to use for videochats\n WebrtcInstance,\n\n /// Timestamp of the last time housekeeping was run\n LastHousekeeping,\n\n /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.\n LastCantDecryptOutgoingMsgs,\n\n /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.\n #[strum(props(default = \"60\"))]\n ScanAllFoldersDebounceSecs,\n\n /// Whether to avoid using IMAP IDLE even if the server supports it.\n ///\n /// This is a developer option for testing \"fake idle\".\n #[strum(props(default = \"0\"))]\n DisableIdle,\n\n /// Defines the max. size (in bytes) of messages downloaded automatically.\n /// 0 = no limit.\n #[strum(props(default = \"0\"))]\n DownloadLimit,\n\n /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.\n #[strum(props(default = \"1\"))]\n SyncMsgs,\n\n /// Space-separated list of all the authserv-ids which we believe\n /// may be the one of our email server.\n ///\n /// See `crate::authres::update_authservid_candidates`.\n AuthservIdCandidates,\n\n /// Make all outgoing messages with Autocrypt header \"multipart/signed\".\n SignUnencrypted,\n\n /// Let the core save all events to the database.\n /// This value is used internally to remember the MsgId of the logging xdc\n #[strum(props(default = \"0\"))]\n DebugLogging,\n\n /// Last message processed by the bot.\n LastMsgId,\n\n /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by\n /// default.\n ///\n /// This is not supposed to be changed by UIs and only used for testing.\n #[strum(props(default = \"172800\"))]\n GossipPeriod,\n\n /// Feature flag for verified 1:1 chats; the UI should set it\n /// to 1 if it supports verified 1:1 chats.\n /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,\n /// and when the key changes, an info message is posted into the chat.\n /// 0=Nothing else happens when the key changes.\n /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true\n /// until `chat_id.accept()` is called.\n #[strum(props(default = \"0\"))]\n VerifiedOneOnOneChats,\n\n /// Row ID of the key in the `keypairs` table\n /// used for signatures, encryption to self and included in `Autocrypt` header.\n KeyId,\n\n /// This key is sent to the self_reporting bot so that the bot can recognize the user\n /// without storing the email address\n SelfReportingId,\n\n /// MsgId of webxdc map integration.\n WebxdcIntegration,\n\n /// Iroh secret key.\n IrohSecretKey,\n}\n\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ChatId(u32);", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__30.txt"} {"c_path": "projects/deltachat-core/c/dc_sqlite3.c", "c_func": "void dc_sqlite3_close(dc_sqlite3_t* sql)\n{\n\tif (sql==NULL) {\n\t\treturn;\n\t}\n\n\tif (sql->cobj)\n\t{\n\t\tsqlite3_close(sql->cobj);\n\t\tsql->cobj = NULL;\n\t}\n\n}", "rust_path": "projects/deltachat-core/rust/sql.rs", "rust_func": "async fn close(&self) {\n let _ = self.pool.write().await.take();\n // drop closes the connection\n }", "rust_context": "pub struct Sql {\n /// Database file path\n pub(crate) dbfile: PathBuf,\n\n /// Write transactions mutex.\n ///\n /// See [`Self::write_lock`].\n write_mtx: Mutex<()>,\n\n /// SQL connection pool.\n pool: RwLock>,\n\n /// None if the database is not open, true if it is open with passphrase and false if it is\n /// open without a passphrase.\n is_encrypted: RwLock>,\n\n /// Cache of `config` table.\n pub(crate) config_cache: RwLock>>,\n}", "rust_imports": "use std::collections::{HashMap, HashSet};\nuse std::path::{Path, PathBuf};\nuse anyhow::{bail, Context as _, Result};\nuse rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row};\nuse tokio::sync::{Mutex, MutexGuard, RwLock};\nuse crate::blob::BlobObject;\nuse crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon};\nuse crate::config::Config;\nuse crate::constants::DC_CHAT_ID_TRASH;\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::ephemeral::start_ephemeral_timers;\nuse crate::imex::BLOBS_BACKUP_NAME;\nuse crate::location::delete_orphaned_poi_locations;\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::stock_str;\nuse crate::tools::{delete_file, time, SystemTime};\nuse pool::Pool;\nuse super::*;\nuse crate::{test_utils::TestContext, EventType};\nuse tempfile::tempdir;\nuse tempfile::tempdir;\nuse tempfile::tempdir;", "rustrepotrans_file": "projects__deltachat-core__rust__sql__.rs__function__6.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "char* dc_msg_get_filemime(const dc_msg_t* msg)\n{\n\tchar* ret = NULL;\n\tchar* file = NULL;\n\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tret = dc_param_get(msg->param, DC_PARAM_MIMETYPE, NULL);\n\tif (ret==NULL) {\n\t\tfile = dc_param_get(msg->param, DC_PARAM_FILE, NULL);\n\t\tif (file==NULL) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\tdc_msg_guess_msgtype_from_suffix(file, NULL, &ret);\n\n\t\tif (ret==NULL) {\n\t\t\tret = dc_strdup(\"application/octet-stream\");\n\t\t}\n\t}\n\ncleanup:\n\tfree(file);\n\treturn ret? ret : dc_strdup(NULL);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn get_filemime(&self) -> Option {\n if let Some(m) = self.param.get(Param::MimeType) {\n return Some(m.to_string());\n } else if let Some(file) = self.param.get(Param::File) {\n if let Some((_, mime)) = guess_msgtype_from_suffix(Path::new(file)) {\n return Some(mime.to_string());\n }\n // we have a file but no mimetype, let's use a generic one\n return Some(\"application/octet-stream\".to_string());\n }\n // no mimetype and no file\n None\n }", "rust_context": "pub fn get(&self, contact_id: ContactId) -> Reaction {\n self.reactions.get(&contact_id).cloned().unwrap_or_default()\n }\n\npub(crate) fn guess_msgtype_from_suffix(path: &Path) -> Option<(Viewtype, &str)> {\n let extension: &str = &path.extension()?.to_str()?.to_lowercase();\n let info = match extension {\n // before using viewtype other than Viewtype::File,\n // make sure, all target UIs support that type in the context of the used viewer/player.\n // if in doubt, it is better to default to Viewtype::File that passes handing to an external app.\n // (cmp. )\n \"3gp\" => (Viewtype::Video, \"video/3gpp\"),\n \"aac\" => (Viewtype::Audio, \"audio/aac\"),\n \"avi\" => (Viewtype::Video, \"video/x-msvideo\"),\n \"avif\" => (Viewtype::File, \"image/avif\"), // supported since Android 12 / iOS 16\n \"doc\" => (Viewtype::File, \"application/msword\"),\n \"docx\" => (\n Viewtype::File,\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n ),\n \"epub\" => (Viewtype::File, \"application/epub+zip\"),\n \"flac\" => (Viewtype::Audio, \"audio/flac\"),\n \"gif\" => (Viewtype::Gif, \"image/gif\"),\n \"heic\" => (Viewtype::File, \"image/heic\"), // supported since Android 10 / iOS 11\n \"heif\" => (Viewtype::File, \"image/heif\"), // supported since Android 10 / iOS 11\n \"html\" => (Viewtype::File, \"text/html\"),\n \"htm\" => (Viewtype::File, \"text/html\"),\n \"ico\" => (Viewtype::File, \"image/vnd.microsoft.icon\"),\n \"jar\" => (Viewtype::File, \"application/java-archive\"),\n \"jpeg\" => (Viewtype::Image, \"image/jpeg\"),\n \"jpe\" => (Viewtype::Image, \"image/jpeg\"),\n \"jpg\" => (Viewtype::Image, \"image/jpeg\"),\n \"json\" => (Viewtype::File, \"application/json\"),\n \"mov\" => (Viewtype::Video, \"video/quicktime\"),\n \"m4a\" => (Viewtype::Audio, \"audio/m4a\"),\n \"mp3\" => (Viewtype::Audio, \"audio/mpeg\"),\n \"mp4\" => (Viewtype::Video, \"video/mp4\"),\n \"odp\" => (\n Viewtype::File,\n \"application/vnd.oasis.opendocument.presentation\",\n ),\n \"ods\" => (\n Viewtype::File,\n \"application/vnd.oasis.opendocument.spreadsheet\",\n ),\n \"odt\" => (Viewtype::File, \"application/vnd.oasis.opendocument.text\"),\n \"oga\" => (Viewtype::Audio, \"audio/ogg\"),\n \"ogg\" => (Viewtype::Audio, \"audio/ogg\"),\n \"ogv\" => (Viewtype::File, \"video/ogg\"),\n \"opus\" => (Viewtype::File, \"audio/ogg\"), // supported since Android 10\n \"otf\" => (Viewtype::File, \"font/otf\"),\n \"pdf\" => (Viewtype::File, \"application/pdf\"),\n \"png\" => (Viewtype::Image, \"image/png\"),\n \"ppt\" => (Viewtype::File, \"application/vnd.ms-powerpoint\"),\n \"pptx\" => (\n Viewtype::File,\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n ),\n \"rar\" => (Viewtype::File, \"application/vnd.rar\"),\n \"rtf\" => (Viewtype::File, \"application/rtf\"),\n \"spx\" => (Viewtype::File, \"audio/ogg\"), // Ogg Speex Profile\n \"svg\" => (Viewtype::File, \"image/svg+xml\"),\n \"tgs\" => (Viewtype::Sticker, \"application/x-tgsticker\"),\n \"tiff\" => (Viewtype::File, \"image/tiff\"),\n \"tif\" => (Viewtype::File, \"image/tiff\"),\n \"ttf\" => (Viewtype::File, \"font/ttf\"),\n \"txt\" => (Viewtype::File, \"text/plain\"),\n \"vcard\" => (Viewtype::Vcard, \"text/vcard\"),\n \"vcf\" => (Viewtype::Vcard, \"text/vcard\"),\n \"wav\" => (Viewtype::Audio, \"audio/wav\"),\n \"weba\" => (Viewtype::File, \"audio/webm\"),\n \"webm\" => (Viewtype::Video, \"video/webm\"),\n \"webp\" => (Viewtype::Image, \"image/webp\"), // iOS via SDWebImage, Android since 4.0\n \"wmv\" => (Viewtype::Video, \"video/x-ms-wmv\"),\n \"xdc\" => (Viewtype::Webxdc, \"application/webxdc+zip\"),\n \"xhtml\" => (Viewtype::File, \"application/xhtml+xml\"),\n \"xls\" => (Viewtype::File, \"application/vnd.ms-excel\"),\n \"xlsx\" => (\n Viewtype::File,\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n ),\n \"xml\" => (Viewtype::File, \"application/xml\"),\n \"zip\" => (Viewtype::File, \"application/zip\"),\n _ => {\n return None;\n }\n };\n Some(info)\n}\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__22.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "void dc_lookup_real_nchat_by_contact_id(dc_context_t* context, uint32_t contact_id, uint32_t* ret_chat_id, int* ret_chat_blocked)\n{\n\t/* checks for \"real\" chats or self-chat */\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (ret_chat_id) { *ret_chat_id = 0; }\n\tif (ret_chat_blocked) { *ret_chat_blocked = 0; }\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql->cobj==NULL) {\n\t\treturn; /* no database, no chats - this is no error (needed eg. for information) */\n\t}\n\n\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\t\"SELECT c.id, c.blocked\"\n\t\t\t\" FROM chats c\"\n\t\t\t\" INNER JOIN chats_contacts j ON c.id=j.chat_id\"\n\t\t\t\" WHERE c.type=\" DC_STRINGIFY(DC_CHAT_TYPE_SINGLE) \" AND c.id>\" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) \" AND j.contact_id=?;\");\n\tsqlite3_bind_int(stmt, 1, contact_id);\n\tif (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\tif (ret_chat_id) { *ret_chat_id = sqlite3_column_int(stmt, 0); }\n\t\tif (ret_chat_blocked) { *ret_chat_blocked = sqlite3_column_int(stmt, 1); }\n\t}\n\tsqlite3_finalize(stmt);\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn lookup_by_contact(\n context: &Context,\n contact_id: ContactId,\n ) -> Result> {\n ensure!(context.sql.is_open().await, \"Database not available\");\n ensure!(\n contact_id != ContactId::UNDEFINED,\n \"Invalid contact id requested\"\n );\n\n context\n .sql\n .query_row_optional(\n \"SELECT c.id, c.blocked\n FROM chats c\n INNER JOIN chats_contacts j\n ON c.id=j.chat_id\n WHERE c.type=100 -- 100 = Chattype::Single\n AND c.id>9 -- 9 = DC_CHAT_ID_LAST_SPECIAL\n AND j.contact_id=?;\",\n (contact_id,),\n |row| {\n let id: ChatId = row.get(0)?;\n let blocked: Blocked = row.get(1)?;\n Ok(ChatIdBlocked { id, blocked })\n },\n )\n .await\n .map_err(Into::into)\n }", "rust_context": "pub async fn is_open(&self) -> bool {\n self.pool.read().await.is_some()\n }\n\npub async fn query_row_optional(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n ) -> Result>\n where\n F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result,\n T: Send + 'static,\n {\n self.call(move |conn| match conn.query_row(sql.as_ref(), params, f) {\n Ok(res) => Ok(Some(res)),\n Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),\n Err(rusqlite::Error::InvalidColumnType(_, _, rusqlite::types::Type::Null)) => Ok(None),\n Err(err) => Err(err.into()),\n })\n .await\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub struct ChatId(u32);\n\npub(crate) struct ChatIdBlocked {\n /// Chat ID.\n pub id: ChatId,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n}\n\npub struct ContactId(u32);\n\nimpl ContactId {\n /// Undefined contact. Used as a placeholder for trashed messages.\n pub const UNDEFINED: ContactId = ContactId::new(0);\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__98.txt"} {"c_path": "projects/deltachat-core/c/dc_context.c", "c_func": "* Searching can be done globally (chat_id=0) or in a specified chat only (chat_id\n * set).\n *\n * Global chat results are typically displayed using dc_msg_get_summary(), chat\n * search results may just hilite the corresponding messages and present a\n * prev/next button.\n *\n * @memberof dc_context_t\n * @param context The context object as returned from dc_context_new().\n * @param chat_id ID of the chat to search messages in.\n * Set this to 0 for a global search.\n * @param query The query to search for.\n * @return An array of message IDs. Must be freed using dc_array_unref() when no longer needed.\n * If nothing can be found, the function returns NULL.\n */\ndc_array_t* dc_search_msgs(dc_context_t* context, uint32_t chat_id, const char* query)\n{\n\t//clock_t start = clock();\n\n\tint success = 0;\n\tdc_array_t* ret = dc_array_new(context, 100);\n\tchar* strLikeInText = NULL;\n\tchar* strLikeBeg = NULL;\n\tchar* real_query = NULL;\n\tsqlite3_stmt* stmt = NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC || ret==NULL || query==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\treal_query = dc_strdup(query);\n\tdc_trim(real_query);\n\tif (real_query[0]==0) {\n\t\tsuccess = 1; /*empty result*/\n\t\tgoto cleanup;\n\t}\n\n\tstrLikeInText = dc_mprintf(\"%%%s%%\", real_query);\n\tstrLikeBeg = dc_mprintf(\"%s%%\", real_query); /*for the name search, we use \"Name%\" which is fast as it can use the index (\"%Name%\" could not). */\n\n\t/* Incremental search with \"LIKE %query%\" cannot take advantages from any index\n\t(\"query%\" could for COLLATE NOCASE indexes, see http://www.sqlite.org/optoverview.html#like_opt)\n\tAn alternative may be the FULLTEXT sqlite stuff, however, this does not really help with incremental search.\n\tAn extra table with all words and a COLLATE NOCASE indexes may help, however,\n\tthis must be updated all the time and probably consumes more time than we can save in tenthousands of searches.\n\tFor now, we just expect the following query to be fast enough :-) */\n\tif (chat_id) {\n\t\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\t\"SELECT m.id AS id\"\n\t\t\t\"FROM msgs m\"\n\t\t\t\"LEFT JOIN contacts ct ON m.from_id=ct.id\"\n\t\t\t\"WHERE m.chat_id=?\"\n\t\t\t\"AND m.hidden=0\"\n\t\t\t\"AND ct.blocked=0\"\n\t\t\t\"AND txt LIKE ?\"\n\t\t\t\"ORDER BY m.timestamp,m.id;\");/* chats starts with the oldest message*/\n\t\tsqlite3_bind_int (stmt, 1, chat_id);\n\t\tsqlite3_bind_text(stmt, 2, strLikeInText, -1, SQLITE_STATIC);\n\t\tsqlite3_bind_text(stmt, 3, strLikeBeg, -1, SQLITE_STATIC);\n\t}\n\telse {\n\t\tint show_deaddrop = 0;//dc_sqlite3_get_config_int(context->sql, \"show_deaddrop\", 0);\n\t\tstmt = dc_sqlite3_prepare(context->sql,\n\t\t\t\"SELECT m.id AS id FROM msgs m\"\n\t\t\t\"LEFT JOIN contacts ct ON m.from_id=ct.id\"\n\t\t\t\"LEFT JOIN chats c ON m.chat_id=c.id\"\n\t\t\t\"WHERE m.chat_id>9\"\n\t\t\t\"AND m.hidden=0\"\n\t\t\t\"AND c.blocked!=1\"\n\t\t\t\"AND ct.blocked=0\"\n\t\t\t\"AND m.txt LIKE ?\"\n\t\t\t\"ORDER BY m.id DESC LIMIT 1000\"); /* chat overview starts with the newest message*/\n\t\tsqlite3_bind_int (stmt, 1, show_deaddrop? DC_CHAT_DEADDROP_BLOCKED : 0);\n\t\tsqlite3_bind_text(stmt, 2, strLikeInText, -1, SQLITE_STATIC);\n\t\tsqlite3_bind_text(stmt, 3, strLikeBeg, -1, SQLITE_STATIC);\n\t}\n\n\twhile (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\tdc_array_add_id(ret, sqlite3_column_int(stmt, 0));\n\t}\n\n\tsuccess = 1;\n\ncleanup:\n\tfree(strLikeInText);\n\tfree(strLikeBeg);\n\tfree(real_query);\n\tsqlite3_finalize(stmt);\n\n\t//dc_log_info(context, 0, \"Message list for search \\\"%s\\\" in chat #%i created in %.3f ms.\", query, chat_id, (double)(clock()-start)*1000.0/CLOCKS_PER_SEC);\n\n\tif (success) {\n\t\treturn ret;\n\t}\n\telse {\n\t\tif (ret) {\n\t\t\tdc_array_unref(ret);\n\t\t}\n\t\treturn NULL;\n\t}\n}", "rust_path": "projects/deltachat-core/rust/context.rs", "rust_func": "pub async fn search_msgs(&self, chat_id: Option, query: &str) -> Result> {\n let real_query = query.trim();\n if real_query.is_empty() {\n return Ok(Vec::new());\n }\n let str_like_in_text = format!(\"%{real_query}%\");\n\n let list = if let Some(chat_id) = chat_id {\n self.sql\n .query_map(\n \"SELECT m.id AS id\n FROM msgs m\n LEFT JOIN contacts ct\n ON m.from_id=ct.id\n WHERE m.chat_id=?\n AND m.hidden=0\n AND ct.blocked=0\n AND txt LIKE ?\n ORDER BY m.timestamp,m.id;\",\n (chat_id, str_like_in_text),\n |row| row.get::<_, MsgId>(\"id\"),\n |rows| {\n let mut ret = Vec::new();\n for id in rows {\n ret.push(id?);\n }\n Ok(ret)\n },\n )\n .await?\n } else {\n // For performance reasons results are sorted only by `id`, that is in the order of\n // message reception.\n //\n // Unlike chat view, sorting by `timestamp` is not necessary but slows down the query by\n // ~25% according to benchmarks.\n //\n // To speed up incremental search, where queries for few characters usually return lots\n // of unwanted results that are discarded moments later, we added `LIMIT 1000`.\n // According to some tests, this limit speeds up eg. 2 character searches by factor 10.\n // The limit is documented and UI may add a hint when getting 1000 results.\n self.sql\n .query_map(\n \"SELECT m.id AS id\n FROM msgs m\n LEFT JOIN contacts ct\n ON m.from_id=ct.id\n LEFT JOIN chats c\n ON m.chat_id=c.id\n WHERE m.chat_id>9\n AND m.hidden=0\n AND c.blocked!=1\n AND ct.blocked=0\n AND m.txt LIKE ?\n ORDER BY m.id DESC LIMIT 1000\",\n (str_like_in_text,),\n |row| row.get::<_, MsgId>(\"id\"),\n |rows| {\n let mut ret = Vec::new();\n for id in rows {\n ret.push(id?);\n }\n Ok(ret)\n },\n )\n .await?\n };\n\n Ok(list)\n }", "rust_context": "pub fn is_empty(&self) -> bool {\n self.inner.is_empty()\n }\n\npub async fn query_map(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n mut g: G,\n ) -> Result\n where\n F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result,\n G: Send + FnMut(rusqlite::MappedRows) -> Result,\n H: Send + 'static,\n {\n self.call(move |conn| {\n let mut stmt = conn.prepare(sql)?;\n let res = stmt.query_map(params, f)?;\n g(res)\n })\n .await\n }\n \npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub struct MsgId(u32);", "rust_imports": "use std::collections::{BTreeMap, HashMap};\nuse std::ffi::OsString;\nuse std::ops::Deref;\nuse std::path::{Path, PathBuf};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\nuse std::time::Duration;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse pgp::SignedPublicKey;\nuse ratelimit::Ratelimit;\nuse tokio::sync::{Mutex, Notify, OnceCell, RwLock};\nuse crate::aheader::EncryptPreference;\nuse crate::chat::{get_chat_cnt, ChatId, ProtectionStatus};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::debug_logging::DebugLogging;\nuse crate::download::DownloadState;\nuse crate::events::{Event, EventEmitter, EventType, Events};\nuse crate::imap::{FolderMeaning, Imap, ServerMetadata};\nuse crate::key::{load_self_public_key, load_self_secret_key, DcKey as _};\nuse crate::login_param::LoginParam;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peer_channels::Iroh;\nuse crate::peerstate::Peerstate;\nuse crate::push::PushSubscriber;\nuse crate::quota::QuotaInfo;\nuse crate::scheduler::{convert_folder_meaning, SchedulerState};\nuse crate::sql::Sql;\nuse crate::stock_str::StockStrings;\nuse crate::timesmearing::SmearedTimestamp;\nuse crate::tools::{self, create_id, duration_to_str, time, time_elapsed};\nuse anyhow::Context as _;\nuse strum::IntoEnumIterator;\nuse tempfile::tempdir;\nuse super::*;\nuse crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration};\nuse crate::chatlist::Chatlist;\nuse crate::constants::Chattype;\nuse crate::mimeparser::SystemMessage;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{get_chat_msg, TestContext};\nuse crate::tools::{create_outgoing_rfc724_mid, SystemTime};", "rustrepotrans_file": "projects__deltachat-core__rust__context__.rs__function__47.txt"} {"c_path": "projects/deltachat-core/c/dc_param.c", "c_func": "int32_t dc_param_get_int(const dc_param_t* param, int key, int32_t def)\n{\n\tif (param==NULL || key==0) {\n\t\treturn def;\n\t}\n\n char* str = dc_param_get(param, key, NULL);\n if (str==NULL) {\n\t\treturn def;\n }\n int32_t ret = atol(str);\n free(str);\n return ret;\n}", "rust_path": "projects/deltachat-core/rust/param.rs", "rust_func": "pub fn get_i64(&self, key: Param) -> Option {\n self.get(key).and_then(|s| s.parse().ok())\n }", "rust_context": "pub fn get(&self, key: Param) -> Option<&str> {\n self.inner.get(&key).map(|s| s.as_str())\n }\n\npub struct Params {\n inner: BTreeMap,\n}", "rust_imports": "use std::collections::BTreeMap;\nuse std::fmt;\nuse std::path::PathBuf;\nuse std::str;\nuse anyhow::{bail, Error, Result};\nuse num_traits::FromPrimitive;\nuse serde::{Deserialize, Serialize};\nuse crate::blob::BlobObject;\nuse crate::context::Context;\nuse crate::mimeparser::SystemMessage;\nuse std::path::Path;\nuse std::str::FromStr;\nuse tokio::fs;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__param__.rs__function__12.txt"} {"c_path": "projects/deltachat-core/c/dc_apeerstate.c", "c_func": "* Typically either DC_NOT_VERIFIED (0) if there is no need for the key being verified\n * or DC_BIDIRECT_VERIFIED (2) for bidirectional verification requirement.\n * @return public_key or gossip_key, NULL if nothing is available.\n * the returned pointer MUST NOT be unref()'d.\n */\ndc_key_t* dc_apeerstate_peek_key(const dc_apeerstate_t* peerstate, int min_verified)\n{\n\tif ( peerstate==NULL\n\t || (peerstate->public_key && (peerstate->public_key->binary==NULL || peerstate->public_key->bytes<=0))\n\t || (peerstate->gossip_key && (peerstate->gossip_key->binary==NULL || peerstate->gossip_key->bytes<=0))\n\t || (peerstate->verified_key && (peerstate->verified_key->binary==NULL || peerstate->verified_key->bytes<=0))) {\n\t\treturn NULL;\n\t}\n\n\tif (min_verified)\n\t{\n\t\treturn peerstate->verified_key;\n\t}\n\n\tif (peerstate->public_key)\n\t{\n\t\treturn peerstate->public_key;\n\t}\n\n\treturn peerstate->gossip_key;\n}", "rust_path": "projects/deltachat-core/rust/peerstate.rs", "rust_func": "pub fn peek_key(&self, verified: bool) -> Option<&SignedPublicKey> {\n if verified {\n self.verified_key.as_ref()\n } else {\n self.public_key.as_ref().or(self.gossip_key.as_ref())\n }\n }", "rust_context": "pub struct Peerstate {\n /// E-mail address of the contact.\n pub addr: String,\n\n /// Timestamp of the latest peerstate update.\n ///\n /// Updated when a message is received from a contact,\n /// either with or without `Autocrypt` header.\n pub last_seen: i64,\n\n /// Timestamp of the latest `Autocrypt` header reception.\n pub last_seen_autocrypt: i64,\n\n /// Encryption preference of the contact.\n pub prefer_encrypt: EncryptPreference,\n\n /// Public key of the contact received in `Autocrypt` header.\n pub public_key: Option,\n\n /// Fingerprint of the contact public key.\n pub public_key_fingerprint: Option,\n\n /// Public key of the contact received in `Autocrypt-Gossip` header.\n pub gossip_key: Option,\n\n /// Timestamp of the latest `Autocrypt-Gossip` header reception.\n ///\n /// It is stored to avoid applying outdated gossiped key\n /// from delayed or reordered messages.\n pub gossip_timestamp: i64,\n\n /// Fingerprint of the contact gossip key.\n pub gossip_key_fingerprint: Option,\n\n /// Public key of the contact at the time it was verified,\n /// either directly or via gossip from the verified contact.\n pub verified_key: Option,\n\n /// Fingerprint of the verified public key.\n pub verified_key_fingerprint: Option,\n\n /// The address that introduced this verified key.\n pub verifier: Option,\n\n /// Secondary public verified key of the contact.\n /// It could be a contact gossiped by another verified contact in a shared group\n /// or a key that was previously used as a verified key.\n pub secondary_verified_key: Option,\n\n /// Fingerprint of the secondary verified public key.\n pub secondary_verified_key_fingerprint: Option,\n\n /// The address that introduced secondary verified key.\n pub secondary_verifier: Option,\n\n /// Row ID of the key in the `keypairs` table\n /// that we think the peer knows as verified.\n pub backward_verified_key_id: Option,\n\n /// True if it was detected\n /// that the fingerprint of the key used in chats with\n /// opportunistic encryption was changed after Peerstate creation.\n pub fingerprint_changed: bool,\n}", "rust_imports": "use std::mem;\nuse anyhow::{Context as _, Error, Result};\nuse deltachat_contact_tools::{addr_cmp, ContactAddress};\nuse num_traits::FromPrimitive;\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::chat::{self, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::constants::Chattype;\nuse crate::contact::{Contact, Origin};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{DcKey, Fingerprint, SignedPublicKey};\nuse crate::message::Message;\nuse crate::mimeparser::SystemMessage;\nuse crate::sql::Sql;\nuse crate::{chatlist_events, stock_str};\nuse super::*;\nuse crate::test_utils::alice_keypair;", "rustrepotrans_file": "projects__deltachat-core__rust__peerstate__.rs__function__14.txt"} {"c_path": "projects/deltachat-core/c/dc_configure.c", "c_func": "int dc_alloc_ongoing(dc_context_t* context)\n{\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\treturn 0;\n\t}\n\n\tif (dc_has_ongoing(context)) {\n\t\tdc_log_warning(context, 0, \"There is already another ongoing process running.\");\n\t\treturn 0;\n\t}\n\n\tcontext->ongoing_running = 1;\n\tcontext->shall_stop_ongoing = 0;\n\treturn 1;\n}", "rust_path": "projects/deltachat-core/rust/context.rs", "rust_func": "pub(crate) async fn alloc_ongoing(&self) -> Result> {\n let mut s = self.running_state.write().await;\n ensure!(\n matches!(*s, RunningState::Stopped),\n \"There is already another ongoing process running.\"\n );\n\n let (sender, receiver) = channel::bounded(1);\n *s = RunningState::Running {\n cancel_sender: sender,\n };\n\n Ok(receiver)\n }", "rust_context": "pub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\nenum RunningState {\n /// Ongoing process is allocated.\n Running { cancel_sender: Sender<()> },\n\n /// Cancel signal has been sent, waiting for ongoing process to be freed.\n ShallStop { request: tools::Time },\n\n /// There is no ongoing process, a new one can be allocated.\n Stopped,\n}", "rust_imports": "use std::collections::{BTreeMap, HashMap};\nuse std::ffi::OsString;\nuse std::ops::Deref;\nuse std::path::{Path, PathBuf};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\nuse std::time::Duration;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse pgp::SignedPublicKey;\nuse ratelimit::Ratelimit;\nuse tokio::sync::{Mutex, Notify, OnceCell, RwLock};\nuse crate::aheader::EncryptPreference;\nuse crate::chat::{get_chat_cnt, ChatId, ProtectionStatus};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::debug_logging::DebugLogging;\nuse crate::download::DownloadState;\nuse crate::events::{Event, EventEmitter, EventType, Events};\nuse crate::imap::{FolderMeaning, Imap, ServerMetadata};\nuse crate::key::{load_self_public_key, load_self_secret_key, DcKey as _};\nuse crate::login_param::LoginParam;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::param::{Param, Params};\nuse crate::peer_channels::Iroh;\nuse crate::peerstate::Peerstate;\nuse crate::push::PushSubscriber;\nuse crate::quota::QuotaInfo;\nuse crate::scheduler::{convert_folder_meaning, SchedulerState};\nuse crate::sql::Sql;\nuse crate::stock_str::StockStrings;\nuse crate::timesmearing::SmearedTimestamp;\nuse crate::tools::{self, create_id, duration_to_str, time, time_elapsed};\nuse anyhow::Context as _;\nuse strum::IntoEnumIterator;\nuse tempfile::tempdir;\nuse super::*;\nuse crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration};\nuse crate::chatlist::Chatlist;\nuse crate::constants::Chattype;\nuse crate::mimeparser::SystemMessage;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{get_chat_msg, TestContext};\nuse crate::tools::{create_outgoing_rfc724_mid, SystemTime};", "rustrepotrans_file": "projects__deltachat-core__rust__context__.rs__function__37.txt"} {"c_path": "projects/deltachat-core/c/dc_tools.c", "c_func": "char* dc_get_abs_path(dc_context_t* context, const char* pathNfilename)\n{\n\tint success = 0;\n\tchar* pathNfilename_abs = NULL;\n\n\tif (context==NULL || pathNfilename==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tpathNfilename_abs = dc_strdup(pathNfilename);\n\n\tif (strncmp(pathNfilename_abs, \"$BLOBDIR\", 8)==0) {\n\t\tif (context->blobdir==NULL) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\tdc_str_replace(&pathNfilename_abs, \"$BLOBDIR\", context->blobdir);\n\t}\n\n\tsuccess = 1;\n\ncleanup:\n\tif (!success) {\n\t\tfree(pathNfilename_abs);\n\t\tpathNfilename_abs = NULL;\n\t}\n\treturn pathNfilename_abs;\n}", "rust_path": "projects/deltachat-core/rust/blob.rs", "rust_func": "pub fn to_abs_path(&self) -> PathBuf {\n let fname = Path::new(&self.name).strip_prefix(\"$BLOBDIR/\").unwrap();\n self.blobdir.join(fname)\n }", "rust_context": "pub struct BlobObject<'a> {\n blobdir: &'a Path,\n name: String,\n}", "rust_imports": "use core::cmp::max;\nuse std::ffi::OsStr;\nuse std::fmt;\nuse std::io::Cursor;\nuse dIterator;\nuse std::mem;\nuse std::path::{Path, PathBuf};\nuse anyhow::{format_err, Context as _, Result};\nuse base64::Engine as _;\nuse futures::StreamExt;\nuse image::codecs::jpeg::JpegEncoder;\nuse image::{DynamicImage, GenericImage, GenericImageView, ImageFormat, Pixel, Rgba};\nuse num_traits::FromPrimitive;\nuse tokio::io::AsyncWriteExt;\nuse tokio::{fs, io};\nuse tokio_stream::wrappers::ReadDirStream;\nuse crate::config::Config;\nuse crate::constants::{self, MediaQuality};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::log::LogExt;\nuse fs::File;\nuse super::*;\nuse crate::chat::{self, create_group_chat, ProtectionStatus};\nuse crate::message::{Message, Viewtype};\nuse crate::test_utils::{self, TestContext};", "rustrepotrans_file": "projects__deltachat-core__rust__blob__.rs__function__7.txt"} {"c_path": "projects/deltachat-core/c/dc_tools.c", "c_func": "void dc_truncate_str(char* buf, int approx_chars)\n{\n\tif (approx_chars > 0 && strlen(buf) > approx_chars+strlen(DC_EDITORIAL_ELLIPSE))\n\t{\n\t\tchar* p = &buf[approx_chars + 1]; /* null-terminate string at the desired length */\n\t\t*p = 0;\n\n\t\tif (strchr(buf, ' ')!=NULL) {\n\t\t\twhile (p[-1]!=' ' && p[-1]!='\\n') { /* rewind to the previous space, avoid half utf-8 characters */\n\t\t\t\tp--;\n\t\t\t\t*p = 0;\n\t\t\t}\n\t\t}\n\n\t\tstrcat(p, DC_EDITORIAL_ELLIPSE);\n\t}\n}", "rust_path": "projects/deltachat-core/rust/tools.rs", "rust_func": "pub(crate) fn truncate(buf: &str, approx_chars: usize) -> Cow {\n let count = buf.chars().count();\n if count > approx_chars + DC_ELLIPSIS.len() {\n let end_pos = buf\n .char_indices()\n .nth(approx_chars)\n .map(|(n, _)| n)\n .unwrap_or_default();\n\n if let Some(index) = buf[..end_pos].rfind(|c| c == ' ' || c == '\\n') {\n Cow::Owned(format!(\"{}{}\", &buf[..=index], DC_ELLIPSIS))\n } else {\n Cow::Owned(format!(\"{}{}\", &buf[..end_pos], DC_ELLIPSIS))\n }\n } else {\n Cow::Borrowed(buf)\n }\n}", "rust_context": "pub(crate) const DC_ELLIPSIS: &str = \"[...]\";", "rust_imports": "use std::borrow::Cow;\nuse std::io::{Cursor, Write};\nuse std::mem;\nuse std::path::{Path, PathBuf};\nuse std::str::from_utf8;\nuse std::time::Duration;\nuse std::time::SystemTime as Time;\nuse std::time::SystemTime;\nuse anyhow::{bail, Context as _, Result};\nuse base64::Engine as _;\nuse chrono::{Local, NaiveDateTime, NaiveTime, TimeZone};\nuse deltachat_contact_tools::{strip_rtlo_characters, EmailAddress};\nuse deltachat_time::SystemTimeTools as SystemTime;\nuse futures::{StreamExt, TryStreamExt};\nuse mailparse::dateparse;\nuse mailparse::headers::Headers;\nuse mailparse::MailHeaderMap;\nuse rand::{thread_rng, Rng};\nuse tokio::{fs, io};\nuse url::Url;\nuse crate::chat::{add_device_msg, add_device_msg_with_importance};\nuse crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::message::{Message, Viewtype};\nuse crate::stock_str;\nuse chrono::NaiveDate;\nuse proptest::prelude::*;\nuse super::*;\nuse crate::chatlist::Chatlist;\nuse crate::{chat, test_utils};\nuse crate::{receive_imf::receive_imf, test_utils::TestContext};\nuse super::*;", "rustrepotrans_file": "projects__deltachat-core__rust__tools__.rs__function__1.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "int dc_msg_is_starred(const dc_msg_t* msg)\n{\n\treturn msg->id <= DC_MSG_ID_LAST_SPECIAL? 1 : 0;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn is_special(self) -> bool {\n self.0 <= DC_MSG_ID_LAST_SPECIAL\n }", "rust_context": "pub struct MsgId(u32);", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__3.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "* this using dc_msg_get_width() / dc_msg_get_height().\n *\n * See also dc_msg_get_duration().\n *\n * @memberof dc_msg_t\n * @param msg The message object.\n * @return Width in pixels, if applicable. 0 otherwise or if unknown.\n */\nint dc_msg_get_width(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn dc_param_get_int(msg->param, DC_PARAM_WIDTH, 0);\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn get_width(&self) -> i32 {\n self.param.get_int(Param::Width).unwrap_or_default()\n }", "rust_context": "pub fn get_int(&self, key: Param) -> Option {\n self.get(key).and_then(|s| s.parse().ok())\n }\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__43.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "* Same as dc_contact_is_verified() but allows speeding up things\n * by adding the peerstate belonging to the contact.\n * If you do not have the peerstate available, it is loaded automatically.\n *\n * @private @memberof dc_context_t\n */\nint dc_contact_is_verified_ex(dc_contact_t* contact, const dc_apeerstate_t* peerstate)\n{\n\tint contact_verified = DC_NOT_VERIFIED;\n\tdc_apeerstate_t* peerstate_to_delete = NULL;\n\n\tif (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tif (contact->id==DC_CONTACT_ID_SELF) {\n\t\tcontact_verified = DC_BIDIRECT_VERIFIED;\n\t\tgoto cleanup; // we're always sort of secured-verified as we could verify the key on this device any time with the key on this device\n\t}\n\n\tif (peerstate==NULL) {\n\t\tpeerstate_to_delete = dc_apeerstate_new(contact->context);\n\t\tif (!dc_apeerstate_load_by_addr(peerstate_to_delete, contact->context->sql, contact->addr)) {\n\t\t\tgoto cleanup;\n\t\t}\n\t\tpeerstate = peerstate_to_delete;\n\t}\n\n\tcontact_verified = peerstate->verified_key? DC_BIDIRECT_VERIFIED : 0;\n\ncleanup:\n\tdc_apeerstate_unref(peerstate_to_delete);\n\treturn contact_verified;\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub async fn is_verified(&self, context: &Context) -> Result {\n // We're always sort of secured-verified as we could verify the key on this device any time with the key\n // on this device\n if self.id == ContactId::SELF {\n return Ok(true);\n }\n\n let Some(peerstate) = Peerstate::from_addr(context, &self.addr).await? else {\n return Ok(false);\n };\n\n let forward_verified = peerstate.is_using_verified_key();\n let backward_verified = peerstate.is_backward_verified(context).await?;\n Ok(forward_verified && backward_verified)\n }", "rust_context": "pub(crate) async fn is_backward_verified(&self, context: &Context) -> Result {\n let Some(backward_verified_key_id) = self.backward_verified_key_id else {\n return Ok(false);\n };\n\n let self_key_id = context.get_config_i64(Config::KeyId).await?;\n\n let backward_verified = backward_verified_key_id == self_key_id;\n Ok(backward_verified)\n }\n\npub(crate) fn is_using_verified_key(&self) -> bool {\n let verified = self.peek_key_fingerprint(true);\n\n verified.is_some() && verified == self.peek_key_fingerprint(false)\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub async fn from_addr(context: &Context, addr: &str) -> Result> {\n if context.is_self_addr(addr).await? {\n return Ok(None);\n }\n let query = \"SELECT addr, last_seen, last_seen_autocrypt, prefer_encrypted, public_key, \\\n gossip_timestamp, gossip_key, public_key_fingerprint, gossip_key_fingerprint, \\\n verified_key, verified_key_fingerprint, \\\n verifier, \\\n secondary_verified_key, secondary_verified_key_fingerprint, \\\n secondary_verifier, \\\n backward_verified_key_id \\\n FROM acpeerstates \\\n WHERE addr=? COLLATE NOCASE LIMIT 1;\";\n Self::from_stmt(context, query, (addr,)).await\n }\n \npub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}\n\npub struct ContactId(u32);\n\nimpl ContactId {\n /// Undefined contact. Used as a placeholder for trashed messages.\n pub const UNDEFINED: ContactId = ContactId::new(0);\n\n /// The owner of the account.\n ///\n /// The email-address is set by `set_config` using \"addr\".\n pub const SELF: ContactId = ContactId::new(1);\n\n /// ID of the contact for info messages.\n pub const INFO: ContactId = ContactId::new(2);\n\n /// ID of the contact for device messages.\n pub const DEVICE: ContactId = ContactId::new(5);\n pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9);\n\n /// Address to go with [`ContactId::DEVICE`].\n ///\n /// This is used by APIs which need to return an email address for this contact.\n pub const DEVICE_ADDR: &'static str = \"device@localhost\";\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__46.txt"} {"c_path": "projects/deltachat-core/c/dc_apeerstate.c", "c_func": "void dc_apeerstate_degrade_encryption(dc_apeerstate_t* peerstate, time_t message_time)\n{\n\tif (peerstate==NULL) {\n\t\treturn 0;\n\t}\n\n\tpeerstate->prefer_encrypt = DC_PE_RESET;\n\tpeerstate->last_seen = message_time; /*last_seen_autocrypt is not updated as there was not Autocrypt:-header seen*/\n\n}", "rust_path": "projects/deltachat-core/rust/peerstate.rs", "rust_func": "pub fn degrade_encryption(&mut self, message_time: i64) {\n self.prefer_encrypt = EncryptPreference::Reset;\n self.last_seen = message_time;\n }", "rust_context": "pub struct Peerstate {\n /// E-mail address of the contact.\n pub addr: String,\n\n /// Timestamp of the latest peerstate update.\n ///\n /// Updated when a message is received from a contact,\n /// either with or without `Autocrypt` header.\n pub last_seen: i64,\n\n /// Timestamp of the latest `Autocrypt` header reception.\n pub last_seen_autocrypt: i64,\n\n /// Encryption preference of the contact.\n pub prefer_encrypt: EncryptPreference,\n\n /// Public key of the contact received in `Autocrypt` header.\n pub public_key: Option,\n\n /// Fingerprint of the contact public key.\n pub public_key_fingerprint: Option,\n\n /// Public key of the contact received in `Autocrypt-Gossip` header.\n pub gossip_key: Option,\n\n /// Timestamp of the latest `Autocrypt-Gossip` header reception.\n ///\n /// It is stored to avoid applying outdated gossiped key\n /// from delayed or reordered messages.\n pub gossip_timestamp: i64,\n\n /// Fingerprint of the contact gossip key.\n pub gossip_key_fingerprint: Option,\n\n /// Public key of the contact at the time it was verified,\n /// either directly or via gossip from the verified contact.\n pub verified_key: Option,\n\n /// Fingerprint of the verified public key.\n pub verified_key_fingerprint: Option,\n\n /// The address that introduced this verified key.\n pub verifier: Option,\n\n /// Secondary public verified key of the contact.\n /// It could be a contact gossiped by another verified contact in a shared group\n /// or a key that was previously used as a verified key.\n pub secondary_verified_key: Option,\n\n /// Fingerprint of the secondary verified public key.\n pub secondary_verified_key_fingerprint: Option,\n\n /// The address that introduced secondary verified key.\n pub secondary_verifier: Option,\n\n /// Row ID of the key in the `keypairs` table\n /// that we think the peer knows as verified.\n pub backward_verified_key_id: Option,\n\n /// True if it was detected\n /// that the fingerprint of the key used in chats with\n /// opportunistic encryption was changed after Peerstate creation.\n pub fingerprint_changed: bool,\n}\n\npub enum EncryptPreference {\n #[default]\n NoPreference = 0,\n Mutual = 1,\n Reset = 20,\n}", "rust_imports": "use std::mem;\nuse anyhow::{Context as _, Error, Result};\nuse deltachat_contact_tools::{addr_cmp, ContactAddress};\nuse num_traits::FromPrimitive;\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::chat::{self, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::constants::Chattype;\nuse crate::contact::{Contact, Origin};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{DcKey, Fingerprint, SignedPublicKey};\nuse crate::message::Message;\nuse crate::mimeparser::SystemMessage;\nuse crate::sql::Sql;\nuse crate::{chatlist_events, stock_str};\nuse super::*;\nuse crate::test_utils::alice_keypair;", "rustrepotrans_file": "projects__deltachat-core__rust__peerstate__.rs__function__9.txt"} {"c_path": "projects/deltachat-core/c/dc_imex.c", "c_func": "void dc_imex(dc_context_t* context, int what, const char* param1, const char* param2)\n{\n\tdc_param_t* param = dc_param_new();\n\n\tdc_param_set_int(param, DC_PARAM_CMD, what);\n\tdc_param_set (param, DC_PARAM_CMD_ARG, param1);\n\tdc_param_set (param, DC_PARAM_CMD_ARG2, param2);\n\n\tdc_job_kill_action(context, DC_JOB_IMEX_IMAP);\n\tdc_job_add(context, DC_JOB_IMEX_IMAP, 0, param->packed, 0); // results in a call to dc_job_do_DC_JOB_IMEX_IMAP()\n\n\tdc_param_unref(param);\n}", "rust_path": "projects/deltachat-core/rust/imex.rs", "rust_func": "pub async fn imex(\n context: &Context,\n what: ImexMode,\n path: &Path,\n passphrase: Option,\n) -> Result<()> {\n let cancel = context.alloc_ongoing().await?;\n\n let res = {\n let _guard = context.scheduler.pause(context.clone()).await?;\n imex_inner(context, what, path, passphrase)\n .race(async {\n cancel.recv().await.ok();\n Err(format_err!(\"canceled\"))\n })\n .await\n };\n context.free_ongoing().await;\n\n if let Err(err) = res.as_ref() {\n // We are using Anyhow's .context() and to show the inner error, too, we need the {:#}:\n error!(context, \"IMEX failed to complete: {:#}\", err);\n context.emit_event(EventType::ImexProgress(0));\n } else {\n info!(context, \"IMEX successfully completed\");\n context.emit_event(EventType::ImexProgress(1000));\n }\n\n res\n}", "rust_context": "pub(crate) async fn free_ongoing(&self) {\n let mut s = self.running_state.write().await;\n if let RunningState::ShallStop { request } = *s {\n info!(self, \"Ongoing stopped in {:?}\", time_elapsed(&request));\n }\n *s = RunningState::Stopped;\n }\n\nasync fn imex_inner(\n context: &Context,\n what: ImexMode,\n path: &Path,\n passphrase: Option,\n) -> Result<()> {\n info!(\n context,\n \"{} path: {}\",\n match what {\n ImexMode::ExportSelfKeys | ImexMode::ExportBackup => \"Export\",\n ImexMode::ImportSelfKeys | ImexMode::ImportBackup => \"Import\",\n },\n path.display()\n );\n ensure!(context.sql.is_open().await, \"Database not opened.\");\n context.emit_event(EventType::ImexProgress(10));\n\n if what == ImexMode::ExportBackup || what == ImexMode::ExportSelfKeys {\n // before we export anything, make sure the private key exists\n e2ee::ensure_secret_key_exists(context)\n .await\n .context(\"Cannot create private key or private key not available\")?;\n\n create_folder(context, &path).await?;\n }\n\n match what {\n ImexMode::ExportSelfKeys => export_self_keys(context, path).await,\n ImexMode::ImportSelfKeys => import_self_keys(context, path).await,\n\n ImexMode::ExportBackup => {\n export_backup(context, path, passphrase.unwrap_or_default()).await\n }\n ImexMode::ImportBackup => {\n import_backup(context, path, passphrase.unwrap_or_default()).await\n }\n }\n}\n\npub(crate) async fn alloc_ongoing(&self) -> Result> {\n let mut s = self.running_state.write().await;\n ensure!(\n matches!(*s, RunningState::Stopped),\n \"There is already another ongoing process running.\"\n );\n\n let (sender, receiver) = channel::bounded(1);\n *s = RunningState::Running {\n cancel_sender: sender,\n };\n\n Ok(receiver)\n }\n\npub async fn recv(&self) -> Option {\n let mut lock = self.0.lock().await;\n match lock.recv().await {\n Err(async_broadcast::RecvError::Overflowed(n)) => Some(Event {\n id: 0,\n typ: EventType::EventChannelOverflow { n },\n }),\n Err(async_broadcast::RecvError::Closed) => None,\n Ok(event) => Some(event),\n }\n }\n\nmacro_rules! error {\n ($ctx:expr, $msg:expr) => {\n error!($ctx, $msg,)\n };\n ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{\n let formatted = format!($msg, $($args),*);\n $ctx.set_last_error(&formatted);\n $ctx.emit_event($crate::EventType::Error(formatted));\n }};\n}\n\nmacro_rules! anyhow {\n ($msg:literal $(,)?) => {\n $crate::__private::must_use({\n let error = $crate::__private::format_err($crate::__private::format_args!($msg));\n error\n })\n };\n ($err:expr $(,)?) => {\n $crate::__private::must_use({\n use $crate::__private::kind::*;\n let error = match $err {\n error => (&error).anyhow_kind().new(error),\n };\n error\n })\n };\n ($fmt:expr, $($arg:tt)*) => {\n $crate::Error::msg($crate::__private::format!($fmt, $($arg)*))\n };\n} \n\nmacro_rules! info {\n ($ctx:expr, $msg:expr) => {\n info!($ctx, $msg,)\n };\n ($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{\n let formatted = format!($msg, $($args),*);\n let full = format!(\"{file}:{line}: {msg}\",\n file = file!(),\n line = line!(),\n msg = &formatted);\n $ctx.emit_event($crate::EventType::Info(full));\n }};\n}\n\npub fn emit_event(&self, event: EventType) {\n {\n let lock = self.debug_logging.read().expect(\"RwLock is poisoned\");\n if let Some(debug_logging) = &*lock {\n debug_logging.log_event(event.clone());\n }\n }\n self.events.emit(Event {\n id: self.id,\n typ: event,\n });\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub enum EventType {\n /// The library-user may write an informational string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Info(String),\n\n /// Emitted when SMTP connection is established and login was successful.\n SmtpConnected(String),\n\n /// Emitted when IMAP connection is established and login was successful.\n ImapConnected(String),\n\n /// Emitted when a message was successfully sent to the SMTP server.\n SmtpMessageSent(String),\n\n /// Emitted when an IMAP message has been marked as deleted\n ImapMessageDeleted(String),\n\n /// Emitted when an IMAP message has been moved\n ImapMessageMoved(String),\n\n /// Emitted before going into IDLE on the Inbox folder.\n ImapInboxIdle,\n\n /// Emitted when an new file in the $BLOBDIR was created\n NewBlobFile(String),\n\n /// Emitted when an file in the $BLOBDIR was deleted\n DeletedBlobFile(String),\n\n /// The library-user should write a warning string to the log.\n ///\n /// This event should *not* be reported to the end-user using a popup or something like\n /// that.\n Warning(String),\n\n /// The library-user should report an error to the end-user.\n ///\n /// As most things are asynchronous, things may go wrong at any time and the user\n /// should not be disturbed by a dialog or so. Instead, use a bubble or so.\n ///\n /// However, for ongoing processes (eg. configure())\n /// or for functions that are expected to fail (eg. dc_continue_key_transfer())\n /// it might be better to delay showing these events until the function has really\n /// failed (returned false). It should be sufficient to report only the *last* error\n /// in a messasge box then.\n Error(String),\n\n /// An action cannot be performed because the user is not in the group.\n /// Reported eg. after a call to\n /// dc_set_chat_name(), dc_set_chat_profile_image(),\n /// dc_add_contact_to_chat(), dc_remove_contact_from_chat(),\n /// dc_send_text_msg() or another sending function.\n ErrorSelfNotInGroup(String),\n\n /// Messages or chats changed. One or more messages or chats changed for various\n /// reasons in the database:\n /// - Messages sent, received or removed\n /// - Chats created, deleted or archived\n /// - A draft has been set\n ///\n MsgsChanged {\n /// Set if only a single chat is affected by the changes, otherwise 0.\n chat_id: ChatId,\n\n /// Set if only a single message is affected by the changes, otherwise 0.\n msg_id: MsgId,\n },\n\n /// Reactions for the message changed.\n ReactionsChanged {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message for which reactions were changed.\n msg_id: MsgId,\n\n /// ID of the contact whose reaction set is changed.\n contact_id: ContactId,\n },\n\n /// There is a fresh message. Typically, the user will show an notification\n /// when receiving this message.\n ///\n /// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event.\n IncomingMsg {\n /// ID of the chat where the message is assigned.\n chat_id: ChatId,\n\n /// ID of the message.\n msg_id: MsgId,\n },\n\n /// Downloading a bunch of messages just finished.\n IncomingMsgBunch,\n\n /// Messages were seen or noticed.\n /// chat id is always set.\n MsgsNoticed(ChatId),\n\n /// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to\n /// DC_STATE_OUT_DELIVERED, see dc_msg_get_state().\n MsgDelivered {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was successfully sent.\n msg_id: MsgId,\n },\n\n /// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_FAILED, see dc_msg_get_state().\n MsgFailed {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that could not be sent.\n msg_id: MsgId,\n },\n\n /// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to\n /// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state().\n MsgRead {\n /// ID of the chat which the message belongs to.\n chat_id: ChatId,\n\n /// ID of the message that was read.\n msg_id: MsgId,\n },\n\n /// A single message was deleted.\n ///\n /// This event means that the message will no longer appear in the messagelist.\n /// UI should remove the message from the messagelist\n /// in response to this event if the message is currently displayed.\n ///\n /// The message may have been explicitly deleted by the user or expired.\n /// Internally the message may have been removed from the database,\n /// moved to the trash chat or hidden.\n ///\n /// This event does not indicate the message\n /// deletion from the server.\n MsgDeleted {\n /// ID of the chat where the message was prior to deletion.\n /// Never 0 or trash chat.\n chat_id: ChatId,\n\n /// ID of the deleted message. Never 0.\n msg_id: MsgId,\n },\n\n /// Chat changed. The name or the image of a chat group was changed or members were added or removed.\n /// Or the verify state of a chat has changed.\n /// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat()\n /// and dc_remove_contact_from_chat().\n ///\n /// This event does not include ephemeral timer modification, which\n /// is a separate event.\n ChatModified(ChatId),\n\n /// Chat ephemeral timer changed.\n ChatEphemeralTimerModified {\n /// Chat ID.\n chat_id: ChatId,\n\n /// New ephemeral timer value.\n timer: EphemeralTimer,\n },\n\n /// Contact(s) created, renamed, blocked, deleted or changed their \"recently seen\" status.\n ///\n /// @param data1 (int) If set, this is the contact_id of an added contact that should be selected.\n ContactsChanged(Option),\n\n /// Location of one or more contact has changed.\n ///\n /// @param data1 (u32) contact_id of the contact for which the location has changed.\n /// If the locations of several contacts have been changed,\n /// eg. after calling dc_delete_all_locations(), this parameter is set to `None`.\n LocationChanged(Option),\n\n /// Inform about the configuration progress started by configure().\n ConfigureProgress {\n /// Progress.\n ///\n /// 0=error, 1-999=progress in permille, 1000=success and done\n progress: usize,\n\n /// Progress comment or error, something to display to the user.\n comment: Option,\n },\n\n /// Inform about the import/export progress started by imex().\n ///\n /// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done\n /// @param data2 0\n ImexProgress(usize),\n\n /// A file has been exported. A file has been written by imex().\n /// This event may be sent multiple times by a single call to imex().\n ///\n /// A typical purpose for a handler of this event may be to make the file public to some system\n /// services.\n ///\n /// @param data2 0\n ImexFileWritten(PathBuf),\n\n /// Progress information of a secure-join handshake from the view of the inviter\n /// (Alice, the person who shows the QR code).\n ///\n /// These events are typically sent after a joiner has scanned the QR code\n /// generated by dc_get_securejoin_qr().\n SecurejoinInviterProgress {\n /// ID of the contact that wants to join.\n contact_id: ContactId,\n\n /// Progress as:\n /// 300=vg-/vc-request received, typically shown as \"bob@addr joins\".\n /// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as \"bob@addr verified\".\n /// 800=contact added to chat, shown as \"bob@addr securely joined GROUP\". Only for the verified-group-protocol.\n /// 1000=Protocol finished for this contact.\n progress: usize,\n },\n\n /// Progress information of a secure-join handshake from the view of the joiner\n /// (Bob, the person who scans the QR code).\n /// The events are typically sent while dc_join_securejoin(), which\n /// may take some time, is executed.\n SecurejoinJoinerProgress {\n /// ID of the inviting contact.\n contact_id: ContactId,\n\n /// Progress as:\n /// 400=vg-/vc-request-with-auth sent, typically shown as \"alice@addr verified, introducing myself.\"\n /// (Bob has verified alice and waits until Alice does the same for him)\n /// 1000=vg-member-added/vc-contact-confirm received\n progress: usize,\n },\n\n /// The connectivity to the server changed.\n /// This means that you should refresh the connectivity view\n /// and possibly the connectivtiy HTML; see dc_get_connectivity() and\n /// dc_get_connectivity_html() for details.\n ConnectivityChanged,\n\n /// The user's avatar changed.\n /// Deprecated by `ConfigSynced`.\n SelfavatarChanged,\n\n /// A multi-device synced config value changed. Maybe the app needs to refresh smth. For\n /// uniformity this is emitted on the source device too. The value isn't here, otherwise it\n /// would be logged which might not be good for privacy.\n ConfigSynced {\n /// Configuration key.\n key: Config,\n },\n\n /// Webxdc status update received.\n WebxdcStatusUpdate {\n /// Message ID.\n msg_id: MsgId,\n\n /// Status update ID.\n status_update_serial: StatusUpdateSerial,\n },\n\n /// Data received over an ephemeral peer channel.\n WebxdcRealtimeData {\n /// Message ID.\n msg_id: MsgId,\n\n /// Realtime data.\n data: Vec,\n },\n\n /// Inform that a message containing a webxdc instance has been deleted.\n WebxdcInstanceDeleted {\n /// ID of the deleted message.\n msg_id: MsgId,\n },\n\n /// Tells that the Background fetch was completed (or timed out).\n /// This event acts as a marker, when you reach this event you can be sure\n /// that all events emitted during the background fetch were processed.\n ///\n /// This event is only emitted by the account manager\n AccountsBackgroundFetchDone,\n /// Inform that set of chats or the order of the chats in the chatlist has changed.\n ///\n /// Sometimes this is emitted together with `UIChatlistItemChanged`.\n ChatlistChanged,\n\n /// Inform that a single chat list item changed and needs to be rerendered.\n /// 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.\n ChatlistItemChanged {\n /// ID of the changed chat\n chat_id: Option,\n },\n\n /// Event for using in tests, e.g. as a fence between normally generated events.\n #[cfg(test)]\n Test,\n\n /// Inform than some events have been skipped due to event channel overflow.\n EventChannelOverflow {\n /// Number of events skipped.\n n: u64,\n },\n}", "rust_imports": "use std::any::Any;\nuse std::ffi::OsStr;\nuse std::path::{Path, PathBuf};\nuse ::pgp::types::KeyTrait;\nuse anyhow::{bail, ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse futures::StreamExt;\nuse futures_lite::FutureExt;\nuse rand::{thread_rng, Rng};\nuse tokio::fs::{self, File};\nuse tokio_tar::Archive;\nuse crate::blob::{BlobDirContents, BlobObject};\nuse crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};\nuse crate::config::Config;\nuse crate::contact::ContactId;\nuse crate::context::Context;\nuse crate::e2ee;\nuse crate::events::EventType;\nuse crate::key::{\n self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,\n};\nuse crate::log::LogExt;\nuse crate::message::{Message, MsgId, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::param::Param;\nuse crate::pgp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::tools::{\n create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,\n};\nuse transfer::{get_backup, BackupProvider};\nuse std::time::Duration;\nuse ::pgp::armor::BlockType;\nuse tokio::task;\nuse super::*;\nuse crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::StockMessage;\nuse crate::test_utils::{alice_keypair, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__imex__.rs__function__1.txt"} {"c_path": "projects/deltachat-core/c/dc_securejoin.c", "c_func": "char* dc_get_securejoin_qr(dc_context_t* context, uint32_t group_chat_id)\n{\n\t/* =========================================================\n\t ==== Alice - the inviter side ====\n\t ==== Step 1 in \"Setup verified contact\" protocol ====\n\t ========================================================= */\n\n\tchar* qr = NULL;\n\tchar* self_addr = NULL;\n\tchar* self_addr_urlencoded = NULL;\n\tchar* self_name = NULL;\n\tchar* self_name_urlencoded = NULL;\n\tchar* fingerprint = NULL;\n\tchar* invitenumber = NULL;\n\tchar* auth = NULL;\n\tdc_chat_t* chat = NULL;\n\tchar* group_name = NULL;\n\tchar* group_name_urlencoded= NULL;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\tgoto cleanup;\n\t}\n\n\tdc_ensure_secret_key_exists(context);\n\n\t\t// invitenumber will be used to allow starting the handshake, auth will be used to verify the fingerprint\n\t\tinvitenumber = dc_token_lookup(context, DC_TOKEN_INVITENUMBER, group_chat_id);\n\t\tif (invitenumber==NULL) {\n\t\t\tinvitenumber = dc_create_id();\n\t\t\tdc_token_save(context, DC_TOKEN_INVITENUMBER, group_chat_id, invitenumber);\n\t\t}\n\n\t\tauth = dc_token_lookup(context, DC_TOKEN_AUTH, group_chat_id);\n\t\tif (auth==NULL) {\n\t\t\tauth = dc_create_id();\n\t\t\tdc_token_save(context, DC_TOKEN_AUTH, group_chat_id, auth);\n\t\t}\n\n\t\tif ((self_addr = dc_sqlite3_get_config(context->sql, \"configured_addr\", NULL))==NULL) {\n\t\t\tdc_log_error(context, 0, \"Not configured, cannot generate QR code.\");\n\t\t\tgoto cleanup;\n\t\t}\n\n\t\tself_name = dc_sqlite3_get_config(context->sql, \"displayname\", \"\");\n\n\tif ((fingerprint=get_self_fingerprint(context))==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tself_addr_urlencoded = dc_urlencode(self_addr);\n\tself_name_urlencoded = dc_urlencode(self_name);\n\n\tif (group_chat_id)\n\t{\n\t\t// parameters used: a=g=x=i=s=\n\t\tchat = dc_get_chat(context, group_chat_id);\n\t\tif (chat==NULL) {\n\t\t\tdc_log_error(context, 0, \"Cannot get QR-code for chat-id %i\", group_chat_id);\n\t\t\tgoto cleanup;\n\t\t}\n\t\tgroup_name = dc_chat_get_name(chat);\n\t\tgroup_name_urlencoded = dc_urlencode(group_name);\n\t\tqr = dc_mprintf(DC_OPENPGP4FPR_SCHEME \"%s#a=%s&g=%s&x=%s&i=%s&s=%s\", fingerprint, self_addr_urlencoded, group_name_urlencoded, chat->grpid, invitenumber, auth);\n\t}\n\telse\n\t{\n\t\t// parameters used: a=n=i=s=\n\t\tqr = dc_mprintf(DC_OPENPGP4FPR_SCHEME \"%s#a=%s&n=%s&i=%s&s=%s\", fingerprint, self_addr_urlencoded, self_name_urlencoded, invitenumber, auth);\n\t}\n\n\tdc_log_info(context, 0, \"Generated QR code: %s\", qr);\n\ncleanup:\n\tfree(self_addr_urlencoded);\n\tfree(self_addr);\n\tfree(self_name);\n\tfree(self_name_urlencoded);\n\tfree(fingerprint);\n\tfree(invitenumber);\n\tfree(auth);\n\tdc_chat_unref(chat);\n\tfree(group_name);\n\tfree(group_name_urlencoded);\n\treturn qr? qr : dc_strdup(NULL);\n}", "rust_path": "projects/deltachat-core/rust/securejoin.rs", "rust_func": "pub async fn get_securejoin_qr(context: &Context, group: Option) -> Result {\n /*=======================================================\n ==== Alice - the inviter side ====\n ==== Step 1 in \"Setup verified contact\" protocol ====\n =======================================================*/\n\n ensure_secret_key_exists(context).await.ok();\n\n // invitenumber will be used to allow starting the handshake,\n // auth will be used to verify the fingerprint\n let sync_token = token::lookup(context, Namespace::InviteNumber, group)\n .await?\n .is_none();\n let invitenumber = token::lookup_or_new(context, Namespace::InviteNumber, group).await?;\n let auth = token::lookup_or_new(context, Namespace::Auth, group).await?;\n let self_addr = context.get_primary_self_addr().await?;\n let self_name = context\n .get_config(Config::Displayname)\n .await?\n .unwrap_or_default();\n\n let fingerprint: Fingerprint = match get_self_fingerprint(context).await {\n Some(fp) => fp,\n None => {\n bail!(\"No fingerprint, cannot generate QR code.\");\n }\n };\n\n let self_addr_urlencoded =\n utf8_percent_encode(&self_addr, NON_ALPHANUMERIC_WITHOUT_DOT).to_string();\n let self_name_urlencoded =\n utf8_percent_encode(&self_name, NON_ALPHANUMERIC_WITHOUT_DOT).to_string();\n\n let qr = if let Some(group) = group {\n // parameters used: a=g=x=i=s=\n let chat = Chat::load_from_db(context, group).await?;\n if chat.grpid.is_empty() {\n bail!(\n \"can't generate securejoin QR code for ad-hoc group {}\",\n group\n );\n }\n let group_name = chat.get_name();\n let group_name_urlencoded = utf8_percent_encode(group_name, NON_ALPHANUMERIC).to_string();\n if sync_token {\n context.sync_qr_code_tokens(Some(chat.id)).await?;\n }\n format!(\n \"OPENPGP4FPR:{}#a={}&g={}&x={}&i={}&s={}\",\n fingerprint.hex(),\n self_addr_urlencoded,\n &group_name_urlencoded,\n &chat.grpid,\n &invitenumber,\n &auth,\n )\n } else {\n // parameters used: a=n=i=s=\n if sync_token {\n context.sync_qr_code_tokens(None).await?;\n }\n format!(\n \"OPENPGP4FPR:{}#a={}&n={}&i={}&s={}\",\n fingerprint.hex(),\n self_addr_urlencoded,\n self_name_urlencoded,\n &invitenumber,\n &auth,\n )\n };\n\n info!(context, \"Generated QR code.\");\n Ok(qr)\n}", "rust_context": "pub async fn ensure_secret_key_exists(context: &Context) -> Result<()> {\n load_self_public_key(context).await?;\n Ok(())\n}\n\npub async fn lookup(\n context: &Context,\n namespace: Namespace,\n chat: Option,\n) -> Result> {\n let token = match chat {\n Some(chat_id) => {\n context\n .sql\n .query_get_value(\n \"SELECT token FROM tokens WHERE namespc=? AND foreign_id=? ORDER BY timestamp DESC LIMIT 1;\",\n (namespace, chat_id),\n )\n .await?\n }\n // foreign_id is declared as `INTEGER DEFAULT 0` in the schema.\n None => {\n context\n .sql\n .query_get_value(\n \"SELECT token FROM tokens WHERE namespc=? AND foreign_id=0 ORDER BY timestamp DESC LIMIT 1;\",\n (namespace,),\n )\n .await?\n }\n };\n Ok(token)\n}\n\npub async fn lookup_or_new(\n context: &Context,\n namespace: Namespace,\n foreign_id: Option,\n) -> Result {\n if let Some(token) = lookup(context, namespace, foreign_id).await? {\n return Ok(token);\n }\n\n let token = create_id();\n save(context, namespace, foreign_id, &token).await?;\n Ok(token)\n}\n\npub async fn get_config(&self, key: Config) -> Result> {\n let env_key = format!(\"DELTACHAT_{}\", key.as_ref().to_uppercase());\n if let Ok(value) = env::var(env_key) {\n return Ok(Some(value));\n }\n\n let value = match key {\n Config::Selfavatar => {\n let rel_path = self.sql.get_raw_config(key.as_ref()).await?;\n rel_path.map(|p| {\n get_abs_path(self, Path::new(&p))\n .to_string_lossy()\n .into_owned()\n })\n }\n Config::SysVersion => Some((*DC_VERSION_STR).clone()),\n Config::SysMsgsizeMaxRecommended => Some(format!(\"{RECOMMENDED_FILE_SIZE}\")),\n Config::SysConfigKeys => Some(get_config_keys_string()),\n _ => self.sql.get_raw_config(key.as_ref()).await?,\n };\n\n if value.is_some() {\n return Ok(value);\n }\n\n // Default values\n match key {\n Config::ConfiguredInboxFolder => Ok(Some(\"INBOX\".to_owned())),\n _ => Ok(key.get_str(\"default\").map(|s| s.to_string())),\n }\n }\n\npub fn is_empty(&self) -> bool {\n self.inner.is_empty()\n }\n\npub(crate) async fn sync_qr_code_tokens(&self, chat_id: Option) -> Result<()> {\n if !self.get_config_bool(Config::SyncMsgs).await? {\n return Ok(());\n }\n\n if let (Some(invitenumber), Some(auth)) = (\n token::lookup(self, Namespace::InviteNumber, chat_id).await?,\n token::lookup(self, Namespace::Auth, chat_id).await?,\n ) {\n let grpid = if let Some(chat_id) = chat_id {\n let chat = Chat::load_from_db(self, chat_id).await?;\n if !chat.is_promoted() {\n info!(\n self,\n \"group '{}' not yet promoted, do not sync tokens yet.\", chat.grpid\n );\n return Ok(());\n }\n Some(chat.grpid)\n } else {\n None\n };\n self.add_sync_item(SyncData::AddQrToken(QrTokenData {\n invitenumber,\n auth,\n grpid,\n }))\n .await?;\n }\n Ok(())\n }\n\npub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result {\n let mut chat = context\n .sql\n .query_row(\n \"SELECT c.type, c.name, c.grpid, c.param, c.archived,\n c.blocked, c.locations_send_until, c.muted_until, c.protected\n FROM chats c\n WHERE c.id=?;\",\n (chat_id,),\n |row| {\n let c = Chat {\n id: chat_id,\n typ: row.get(0)?,\n name: row.get::<_, String>(1)?,\n grpid: row.get::<_, String>(2)?,\n param: row.get::<_, String>(3)?.parse().unwrap_or_default(),\n visibility: row.get(4)?,\n blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),\n is_sending_locations: row.get(6)?,\n mute_duration: row.get(7)?,\n protected: row.get(8)?,\n };\n Ok(c)\n },\n )\n .await\n .context(format!(\"Failed loading chat {chat_id} from database\"))?;\n\n if chat.id.is_archived_link() {\n chat.name = stock_str::archived_chats(context).await;\n } else {\n if chat.typ == Chattype::Single && chat.name.is_empty() {\n // chat.name is set to contact.display_name on changes,\n // however, if things went wrong somehow, we do this here explicitly.\n let mut chat_name = \"Err [Name not found]\".to_owned();\n match get_chat_contacts(context, chat.id).await {\n Ok(contacts) => {\n if let Some(contact_id) = contacts.first() {\n if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {\n contact.get_display_name().clone_into(&mut chat_name);\n }\n }\n }\n Err(err) => {\n error!(\n context,\n \"Failed to load contacts for {}: {:#}.\", chat.id, err\n );\n }\n }\n chat.name = chat_name;\n }\n if chat.param.exists(Param::Selftalk) {\n chat.name = stock_str::saved_messages(context).await;\n } else if chat.param.exists(Param::Devicetalk) {\n chat.name = stock_str::device_messages(context).await;\n }\n }\n\n Ok(chat)\n }\n \npub async fn get_primary_self_addr(&self) -> Result {\n self.get_config(Config::ConfiguredAddr)\n .await?\n .context(\"No self addr configured\")\n }\n\npub fn get_name(&self) -> &str {\n &self.name\n }\n\nasync fn get_self_fingerprint(context: &Context) -> Option {\n match load_self_public_key(context).await {\n Ok(key) => Some(key.fingerprint()),\n Err(_) => {\n warn!(context, \"get_self_fingerprint(): failed to load key\");\n None\n }\n }\n}\n\npub enum Namespace {\n #[default]\n Unknown = 0,\n Auth = 110,\n InviteNumber = 100,\n}\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct Fingerprint(Vec);\n\npub enum Config {\n /// Email address, used in the `From:` field.\n Addr,\n\n /// IMAP server hostname.\n MailServer,\n\n /// IMAP server username.\n MailUser,\n\n /// IMAP server password.\n MailPw,\n\n /// IMAP server port.\n MailPort,\n\n /// IMAP server security (e.g. TLS, STARTTLS).\n MailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ImapCertificateChecks,\n\n /// SMTP server hostname.\n SendServer,\n\n /// SMTP server username.\n SendUser,\n\n /// SMTP server password.\n SendPw,\n\n /// SMTP server port.\n SendPort,\n\n /// SMTP server security (e.g. TLS, STARTTLS).\n SendSecurity,\n\n /// How to check SMTP server TLS certificates.\n SmtpCertificateChecks,\n\n /// Whether to use OAuth 2.\n ///\n /// Historically contained other bitflags, which are now deprecated.\n /// Should not be extended in the future, create new config keys instead.\n ServerFlags,\n\n /// True if SOCKS5 is enabled.\n ///\n /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.\n Socks5Enabled,\n\n /// SOCKS5 proxy server hostname or address.\n Socks5Host,\n\n /// SOCKS5 proxy server port.\n Socks5Port,\n\n /// SOCKS5 proxy server username.\n Socks5User,\n\n /// SOCKS5 proxy server password.\n Socks5Password,\n\n /// Own name to use in the `From:` field when sending messages.\n Displayname,\n\n /// Own status to display, sent in message footer.\n Selfstatus,\n\n /// Own avatar filename.\n Selfavatar,\n\n /// Send BCC copy to self.\n ///\n /// Should be enabled for multidevice setups.\n #[strum(props(default = \"1\"))]\n BccSelf,\n\n /// True if encryption is preferred according to Autocrypt standard.\n #[strum(props(default = \"1\"))]\n E2eeEnabled,\n\n /// True if Message Delivery Notifications (read receipts) should\n /// be sent and requested.\n #[strum(props(default = \"1\"))]\n MdnsEnabled,\n\n /// True if \"Sent\" folder should be watched for changes.\n #[strum(props(default = \"0\"))]\n SentboxWatch,\n\n /// True if chat messages should be moved to a separate folder.\n #[strum(props(default = \"1\"))]\n MvboxMove,\n\n /// Watch for new messages in the \"Mvbox\" (aka DeltaChat folder) only.\n ///\n /// This will not entirely disable other folders, e.g. the spam folder will also still\n /// be watched for new messages.\n #[strum(props(default = \"0\"))]\n OnlyFetchMvbox,\n\n /// Whether to show classic emails or only chat messages.\n #[strum(props(default = \"2\"))] // also change ShowEmails.default() on changes\n ShowEmails,\n\n /// Quality of the media files to send.\n #[strum(props(default = \"0\"))] // also change MediaQuality.default() on changes\n MediaQuality,\n\n /// If set to \"1\", on the first time `start_io()` is called after configuring,\n /// the newest existing messages are fetched.\n /// Existing recipients are added to the contact database regardless of this setting.\n #[strum(props(default = \"0\"))]\n FetchExistingMsgs,\n\n /// If set to \"1\", then existing messages are considered to be already fetched.\n /// This flag is reset after successful configuration.\n #[strum(props(default = \"1\"))]\n FetchedExistingMsgs,\n\n /// Type of the OpenPGP key to generate.\n #[strum(props(default = \"0\"))]\n KeyGenType,\n\n /// Timer in seconds after which the message is deleted from the\n /// server.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n ///\n /// Value 1 is treated as \"delete at once\": messages are deleted\n /// immediately, without moving to DeltaChat folder.\n #[strum(props(default = \"0\"))]\n DeleteServerAfter,\n\n /// Timer in seconds after which the message is deleted from the\n /// device.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n #[strum(props(default = \"0\"))]\n DeleteDeviceAfter,\n\n /// Move messages to the Trash folder instead of marking them \"\\Deleted\". Overrides\n /// `ProviderOptions::delete_to_trash`.\n DeleteToTrash,\n\n /// Save raw MIME messages with headers in the database if true.\n SaveMimeHeaders,\n\n /// The primary email address. Also see `SecondaryAddrs`.\n ConfiguredAddr,\n\n /// Configured IMAP server hostname.\n ConfiguredMailServer,\n\n /// Configured IMAP server username.\n ConfiguredMailUser,\n\n /// Configured IMAP server password.\n ConfiguredMailPw,\n\n /// Configured IMAP server port.\n ConfiguredMailPort,\n\n /// Configured IMAP server security (e.g. TLS, STARTTLS).\n ConfiguredMailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ConfiguredImapCertificateChecks,\n\n /// Configured SMTP server hostname.\n ConfiguredSendServer,\n\n /// Configured SMTP server username.\n ConfiguredSendUser,\n\n /// Configured SMTP server password.\n ConfiguredSendPw,\n\n /// Configured SMTP server port.\n ConfiguredSendPort,\n\n /// How to check SMTP server TLS certificates.\n ConfiguredSmtpCertificateChecks,\n\n /// Whether OAuth 2 is used with configured provider.\n ConfiguredServerFlags,\n\n /// Configured SMTP server security (e.g. TLS, STARTTLS).\n ConfiguredSendSecurity,\n\n /// Configured folder for incoming messages.\n ConfiguredInboxFolder,\n\n /// Configured folder for chat messages.\n ConfiguredMvboxFolder,\n\n /// Configured \"Sent\" folder.\n ConfiguredSentboxFolder,\n\n /// Configured \"Trash\" folder.\n ConfiguredTrashFolder,\n\n /// Unix timestamp of the last successful configuration.\n ConfiguredTimestamp,\n\n /// ID of the configured provider from the provider database.\n ConfiguredProvider,\n\n /// True if account is configured.\n Configured,\n\n /// True if account is a chatmail account.\n IsChatmail,\n\n /// All secondary self addresses separated by spaces\n /// (`addr1@example.org addr2@example.org addr3@example.org`)\n SecondaryAddrs,\n\n /// Read-only core version string.\n #[strum(serialize = \"sys.version\")]\n SysVersion,\n\n /// Maximal recommended attachment size in bytes.\n #[strum(serialize = \"sys.msgsize_max_recommended\")]\n SysMsgsizeMaxRecommended,\n\n /// Space separated list of all config keys available.\n #[strum(serialize = \"sys.config_keys\")]\n SysConfigKeys,\n\n /// True if it is a bot account.\n Bot,\n\n /// True when to skip initial start messages in groups.\n #[strum(props(default = \"0\"))]\n SkipStartMessages,\n\n /// Whether we send a warning if the password is wrong (set to false when we send a warning\n /// because we do not want to send a second warning)\n #[strum(props(default = \"0\"))]\n NotifyAboutWrongPw,\n\n /// If a warning about exceeding quota was shown recently,\n /// this is the percentage of quota at the time the warning was given.\n /// Unset, when quota falls below minimal warning threshold again.\n QuotaExceeding,\n\n /// address to webrtc instance to use for videochats\n WebrtcInstance,\n\n /// Timestamp of the last time housekeeping was run\n LastHousekeeping,\n\n /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.\n LastCantDecryptOutgoingMsgs,\n\n /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.\n #[strum(props(default = \"60\"))]\n ScanAllFoldersDebounceSecs,\n\n /// Whether to avoid using IMAP IDLE even if the server supports it.\n ///\n /// This is a developer option for testing \"fake idle\".\n #[strum(props(default = \"0\"))]\n DisableIdle,\n\n /// Defines the max. size (in bytes) of messages downloaded automatically.\n /// 0 = no limit.\n #[strum(props(default = \"0\"))]\n DownloadLimit,\n\n /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.\n #[strum(props(default = \"1\"))]\n SyncMsgs,\n\n /// Space-separated list of all the authserv-ids which we believe\n /// may be the one of our email server.\n ///\n /// See `crate::authres::update_authservid_candidates`.\n AuthservIdCandidates,\n\n /// Make all outgoing messages with Autocrypt header \"multipart/signed\".\n SignUnencrypted,\n\n /// Let the core save all events to the database.\n /// This value is used internally to remember the MsgId of the logging xdc\n #[strum(props(default = \"0\"))]\n DebugLogging,\n\n /// Last message processed by the bot.\n LastMsgId,\n\n /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by\n /// default.\n ///\n /// This is not supposed to be changed by UIs and only used for testing.\n #[strum(props(default = \"172800\"))]\n GossipPeriod,\n\n /// Feature flag for verified 1:1 chats; the UI should set it\n /// to 1 if it supports verified 1:1 chats.\n /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,\n /// and when the key changes, an info message is posted into the chat.\n /// 0=Nothing else happens when the key changes.\n /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true\n /// until `chat_id.accept()` is called.\n #[strum(props(default = \"0\"))]\n VerifiedOneOnOneChats,\n\n /// Row ID of the key in the `keypairs` table\n /// used for signatures, encryption to self and included in `Autocrypt` header.\n KeyId,\n\n /// This key is sent to the self_reporting bot so that the bot can recognize the user\n /// without storing the email address\n SelfReportingId,\n\n /// MsgId of webxdc map integration.\n WebxdcIntegration,\n\n /// Iroh secret key.\n IrohSecretKey,\n}", "rust_imports": "use anyhow::{bail, Context as _, Error, Result};\nuse percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};\nuse crate::aheader::EncryptPreference;\nuse crate::chat::{self, Chat, ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::Blocked;\nuse crate::contact::{Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::e2ee::ensure_secret_key_exists;\nuse crate::events::EventType;\nuse crate::headerdef::HeaderDef;\nuse crate::key::{load_self_public_key, DcKey, Fingerprint};\nuse crate::message::{Message, Viewtype};\nuse crate::mimeparser::{MimeMessage, SystemMessage};\nuse crate::param::Param;\nuse crate::peerstate::Peerstate;\nuse crate::qr::check_qr;\nuse crate::securejoin::bob::JoinerProgress;\nuse crate::stock_str;\nuse crate::sync::Sync::*;\nuse crate::token;\nuse crate::tools::time;\nuse bobstate::BobState;\nuse qrinvite::QrInvite;\nuse crate::token::Namespace;\nuse deltachat_contact_tools::{ContactAddress, EmailAddress};\nuse super::*;\nuse crate::chat::{remove_contact_from_chat, CantSendReason};\nuse crate::chatlist::Chatlist;\nuse crate::constants::{self, Chattype};\nuse crate::imex::{imex, ImexMode};\nuse crate::receive_imf::receive_imf;\nuse crate::stock_str::{self, chat_protection_enabled};\nuse crate::test_utils::get_chat_msg;\nuse crate::test_utils::{TestContext, TestContextManager};\nuse crate::tools::SystemTime;\nuse std::collections::HashSet;\nuse std::time::Duration;", "rustrepotrans_file": "projects__deltachat-core__rust__securejoin__.rs__function__2.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "char* dc_addr_normalize(const char* addr)\n{\n\tchar* addr_normalized = dc_strdup(addr);\n\tdc_trim(addr_normalized);\n\tif (strncmp(addr_normalized, \"mailto:\", 7)==0) {\n\t\tchar* old = addr_normalized;\n\t\taddr_normalized = dc_strdup(&old[7]);\n\t\tfree(old);\n\t\tdc_trim(addr_normalized);\n\t}\n\treturn addr_normalized;\n}", "rust_path": "projects/deltachat-core/rust/oauth2.rs", "rust_func": "fn normalize_addr(addr: &str) -> &str {\n let normalized = addr.trim();\n normalized.trim_start_matches(\"mailto:\")\n}", "rust_context": "", "rust_imports": "use std::collections::HashMap;\nuse anyhow::Result;\nuse percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};\nuse serde::Deserialize;\nuse crate::config::Config;\nuse crate::context::Context;\nuse crate::provider;\nuse crate::provider::Oauth2Authorizer;\nuse crate::socks::Socks5Config;\nuse crate::tools::time;\nuse super::*;\nuse crate::test_utils::TestContext;", "rustrepotrans_file": "projects__deltachat-core__rust__oauth2__.rs__function__8.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "int dc_addr_equals_self(dc_context_t* context, const char* addr)\n{\n\tint ret = 0;\n\tchar* normalized_addr = NULL;\n\tchar* self_addr = NULL;\n\n\tif (context==NULL || addr==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\tnormalized_addr = dc_addr_normalize(addr);\n\n\tif (NULL==(self_addr=dc_sqlite3_get_config(context->sql, \"configured_addr\", NULL))) {\n\t\tgoto cleanup;\n\t}\n\n\tret = strcasecmp(normalized_addr, self_addr)==0? 1 : 0;\n\ncleanup:\n\tfree(self_addr);\n\tfree(normalized_addr);\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/config.rs", "rust_func": "pub(crate) async fn is_self_addr(&self, addr: &str) -> Result {\n Ok(self\n .get_config(Config::ConfiguredAddr)\n .await?\n .iter()\n .any(|a| addr_cmp(addr, a))\n || self\n .get_secondary_self_addrs()\n .await?\n .iter()\n .any(|a| addr_cmp(addr, a)))\n }", "rust_context": "pub(crate) async fn get_secondary_self_addrs(&self) -> Result> {\n let secondary_addrs = self\n .get_config(Config::SecondaryAddrs)\n .await?\n .unwrap_or_default();\n Ok(secondary_addrs\n .split_ascii_whitespace()\n .map(|s| s.to_string())\n .collect())\n }\n\npub(crate) fn iter(&self) -> BlobDirIter<'_> {\n BlobDirIter::new(self.context, self.inner.iter())\n }\n\npub async fn get_config(&self, key: Config) -> Result> {\n let env_key = format!(\"DELTACHAT_{}\", key.as_ref().to_uppercase());\n if let Ok(value) = env::var(env_key) {\n return Ok(Some(value));\n }\n\n let value = match key {\n Config::Selfavatar => {\n let rel_path = self.sql.get_raw_config(key.as_ref()).await?;\n rel_path.map(|p| {\n get_abs_path(self, Path::new(&p))\n .to_string_lossy()\n .into_owned()\n })\n }\n Config::SysVersion => Some((*DC_VERSION_STR).clone()),\n Config::SysMsgsizeMaxRecommended => Some(format!(\"{RECOMMENDED_FILE_SIZE}\")),\n Config::SysConfigKeys => Some(get_config_keys_string()),\n _ => self.sql.get_raw_config(key.as_ref()).await?,\n };\n\n if value.is_some() {\n return Ok(value);\n }\n\n // Default values\n match key {\n Config::ConfiguredInboxFolder => Ok(Some(\"INBOX\".to_owned())),\n _ => Ok(key.get_str(\"default\").map(|s| s.to_string())),\n }\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub enum Config {\n /// Email address, used in the `From:` field.\n Addr,\n\n /// IMAP server hostname.\n MailServer,\n\n /// IMAP server username.\n MailUser,\n\n /// IMAP server password.\n MailPw,\n\n /// IMAP server port.\n MailPort,\n\n /// IMAP server security (e.g. TLS, STARTTLS).\n MailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ImapCertificateChecks,\n\n /// SMTP server hostname.\n SendServer,\n\n /// SMTP server username.\n SendUser,\n\n /// SMTP server password.\n SendPw,\n\n /// SMTP server port.\n SendPort,\n\n /// SMTP server security (e.g. TLS, STARTTLS).\n SendSecurity,\n\n /// How to check SMTP server TLS certificates.\n SmtpCertificateChecks,\n\n /// Whether to use OAuth 2.\n ///\n /// Historically contained other bitflags, which are now deprecated.\n /// Should not be extended in the future, create new config keys instead.\n ServerFlags,\n\n /// True if SOCKS5 is enabled.\n ///\n /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.\n Socks5Enabled,\n\n /// SOCKS5 proxy server hostname or address.\n Socks5Host,\n\n /// SOCKS5 proxy server port.\n Socks5Port,\n\n /// SOCKS5 proxy server username.\n Socks5User,\n\n /// SOCKS5 proxy server password.\n Socks5Password,\n\n /// Own name to use in the `From:` field when sending messages.\n Displayname,\n\n /// Own status to display, sent in message footer.\n Selfstatus,\n\n /// Own avatar filename.\n Selfavatar,\n\n /// Send BCC copy to self.\n ///\n /// Should be enabled for multidevice setups.\n #[strum(props(default = \"1\"))]\n BccSelf,\n\n /// True if encryption is preferred according to Autocrypt standard.\n #[strum(props(default = \"1\"))]\n E2eeEnabled,\n\n /// True if Message Delivery Notifications (read receipts) should\n /// be sent and requested.\n #[strum(props(default = \"1\"))]\n MdnsEnabled,\n\n /// True if \"Sent\" folder should be watched for changes.\n #[strum(props(default = \"0\"))]\n SentboxWatch,\n\n /// True if chat messages should be moved to a separate folder.\n #[strum(props(default = \"1\"))]\n MvboxMove,\n\n /// Watch for new messages in the \"Mvbox\" (aka DeltaChat folder) only.\n ///\n /// This will not entirely disable other folders, e.g. the spam folder will also still\n /// be watched for new messages.\n #[strum(props(default = \"0\"))]\n OnlyFetchMvbox,\n\n /// Whether to show classic emails or only chat messages.\n #[strum(props(default = \"2\"))] // also change ShowEmails.default() on changes\n ShowEmails,\n\n /// Quality of the media files to send.\n #[strum(props(default = \"0\"))] // also change MediaQuality.default() on changes\n MediaQuality,\n\n /// If set to \"1\", on the first time `start_io()` is called after configuring,\n /// the newest existing messages are fetched.\n /// Existing recipients are added to the contact database regardless of this setting.\n #[strum(props(default = \"0\"))]\n FetchExistingMsgs,\n\n /// If set to \"1\", then existing messages are considered to be already fetched.\n /// This flag is reset after successful configuration.\n #[strum(props(default = \"1\"))]\n FetchedExistingMsgs,\n\n /// Type of the OpenPGP key to generate.\n #[strum(props(default = \"0\"))]\n KeyGenType,\n\n /// Timer in seconds after which the message is deleted from the\n /// server.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n ///\n /// Value 1 is treated as \"delete at once\": messages are deleted\n /// immediately, without moving to DeltaChat folder.\n #[strum(props(default = \"0\"))]\n DeleteServerAfter,\n\n /// Timer in seconds after which the message is deleted from the\n /// device.\n ///\n /// Equals to 0 by default, which means the message is never\n /// deleted.\n #[strum(props(default = \"0\"))]\n DeleteDeviceAfter,\n\n /// Move messages to the Trash folder instead of marking them \"\\Deleted\". Overrides\n /// `ProviderOptions::delete_to_trash`.\n DeleteToTrash,\n\n /// Save raw MIME messages with headers in the database if true.\n SaveMimeHeaders,\n\n /// The primary email address. Also see `SecondaryAddrs`.\n ConfiguredAddr,\n\n /// Configured IMAP server hostname.\n ConfiguredMailServer,\n\n /// Configured IMAP server username.\n ConfiguredMailUser,\n\n /// Configured IMAP server password.\n ConfiguredMailPw,\n\n /// Configured IMAP server port.\n ConfiguredMailPort,\n\n /// Configured IMAP server security (e.g. TLS, STARTTLS).\n ConfiguredMailSecurity,\n\n /// How to check IMAP server TLS certificates.\n ConfiguredImapCertificateChecks,\n\n /// Configured SMTP server hostname.\n ConfiguredSendServer,\n\n /// Configured SMTP server username.\n ConfiguredSendUser,\n\n /// Configured SMTP server password.\n ConfiguredSendPw,\n\n /// Configured SMTP server port.\n ConfiguredSendPort,\n\n /// How to check SMTP server TLS certificates.\n ConfiguredSmtpCertificateChecks,\n\n /// Whether OAuth 2 is used with configured provider.\n ConfiguredServerFlags,\n\n /// Configured SMTP server security (e.g. TLS, STARTTLS).\n ConfiguredSendSecurity,\n\n /// Configured folder for incoming messages.\n ConfiguredInboxFolder,\n\n /// Configured folder for chat messages.\n ConfiguredMvboxFolder,\n\n /// Configured \"Sent\" folder.\n ConfiguredSentboxFolder,\n\n /// Configured \"Trash\" folder.\n ConfiguredTrashFolder,\n\n /// Unix timestamp of the last successful configuration.\n ConfiguredTimestamp,\n\n /// ID of the configured provider from the provider database.\n ConfiguredProvider,\n\n /// True if account is configured.\n Configured,\n\n /// True if account is a chatmail account.\n IsChatmail,\n\n /// All secondary self addresses separated by spaces\n /// (`addr1@example.org addr2@example.org addr3@example.org`)\n SecondaryAddrs,\n\n /// Read-only core version string.\n #[strum(serialize = \"sys.version\")]\n SysVersion,\n\n /// Maximal recommended attachment size in bytes.\n #[strum(serialize = \"sys.msgsize_max_recommended\")]\n SysMsgsizeMaxRecommended,\n\n /// Space separated list of all config keys available.\n #[strum(serialize = \"sys.config_keys\")]\n SysConfigKeys,\n\n /// True if it is a bot account.\n Bot,\n\n /// True when to skip initial start messages in groups.\n #[strum(props(default = \"0\"))]\n SkipStartMessages,\n\n /// Whether we send a warning if the password is wrong (set to false when we send a warning\n /// because we do not want to send a second warning)\n #[strum(props(default = \"0\"))]\n NotifyAboutWrongPw,\n\n /// If a warning about exceeding quota was shown recently,\n /// this is the percentage of quota at the time the warning was given.\n /// Unset, when quota falls below minimal warning threshold again.\n QuotaExceeding,\n\n /// address to webrtc instance to use for videochats\n WebrtcInstance,\n\n /// Timestamp of the last time housekeeping was run\n LastHousekeeping,\n\n /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.\n LastCantDecryptOutgoingMsgs,\n\n /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.\n #[strum(props(default = \"60\"))]\n ScanAllFoldersDebounceSecs,\n\n /// Whether to avoid using IMAP IDLE even if the server supports it.\n ///\n /// This is a developer option for testing \"fake idle\".\n #[strum(props(default = \"0\"))]\n DisableIdle,\n\n /// Defines the max. size (in bytes) of messages downloaded automatically.\n /// 0 = no limit.\n #[strum(props(default = \"0\"))]\n DownloadLimit,\n\n /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.\n #[strum(props(default = \"1\"))]\n SyncMsgs,\n\n /// Space-separated list of all the authserv-ids which we believe\n /// may be the one of our email server.\n ///\n /// See `crate::authres::update_authservid_candidates`.\n AuthservIdCandidates,\n\n /// Make all outgoing messages with Autocrypt header \"multipart/signed\".\n SignUnencrypted,\n\n /// Let the core save all events to the database.\n /// This value is used internally to remember the MsgId of the logging xdc\n #[strum(props(default = \"0\"))]\n DebugLogging,\n\n /// Last message processed by the bot.\n LastMsgId,\n\n /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by\n /// default.\n ///\n /// This is not supposed to be changed by UIs and only used for testing.\n #[strum(props(default = \"172800\"))]\n GossipPeriod,\n\n /// Feature flag for verified 1:1 chats; the UI should set it\n /// to 1 if it supports verified 1:1 chats.\n /// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,\n /// and when the key changes, an info message is posted into the chat.\n /// 0=Nothing else happens when the key changes.\n /// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true\n /// until `chat_id.accept()` is called.\n #[strum(props(default = \"0\"))]\n VerifiedOneOnOneChats,\n\n /// Row ID of the key in the `keypairs` table\n /// used for signatures, encryption to self and included in `Autocrypt` header.\n KeyId,\n\n /// This key is sent to the self_reporting bot so that the bot can recognize the user\n /// without storing the email address\n SelfReportingId,\n\n /// MsgId of webxdc map integration.\n WebxdcIntegration,\n\n /// Iroh secret key.\n IrohSecretKey,\n}", "rust_imports": "use std::env;\nuse std::path::Path;\nuse std::str::FromStr;\nuse anyhow::{ensure, Context as _, Result};\nuse base64::Engine as _;\nuse deltachat_contact_tools::addr_cmp;\nuse serde::{Deserialize, Serialize};\nuse strum::{EnumProperty, IntoEnumIterator};\nuse strum_macros::{AsRefStr, Display, EnumIter, EnumString};\nuse tokio::fs;\nuse crate::blob::BlobObject;\nuse crate::constants::{self, DC_VERSION_STR};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::log::LogExt;\nuse crate::mimefactory::RECOMMENDED_FILE_SIZE;\nuse crate::provider::{get_provider_by_id, Provider};\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{get_abs_path, improve_single_line_input};\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::test_utils::{sync, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__config__.rs__function__27.txt"} {"c_path": "projects/deltachat-core/c/dc_pgp.c", "c_func": "int dc_pgp_create_keypair(dc_context_t* context, const char* addr, dc_key_t* ret_public_key, dc_key_t* ret_private_key)\n{\n\tint success = 0;\n\tpgp_key_t seckey;\n\tpgp_key_t pubkey;\n\tpgp_key_t subkey;\n\tuint8_t subkeyid[PGP_KEY_ID_SIZE];\n\tuint8_t* user_id = NULL;\n\tpgp_memory_t* pubmem = pgp_memory_new();\n\tpgp_memory_t* secmem = pgp_memory_new();\n\tpgp_output_t* pubout = pgp_output_new();\n\tpgp_output_t* secout = pgp_output_new();\n\n\tmemset(&seckey, 0, sizeof(pgp_key_t));\n\tmemset(&pubkey, 0, sizeof(pgp_key_t));\n\tmemset(&subkey, 0, sizeof(pgp_key_t));\n\n\tif (context==NULL || addr==NULL || ret_public_key==NULL || ret_private_key==NULL\n\t || pubmem==NULL || secmem==NULL || pubout==NULL || secout==NULL) {\n\t\tgoto cleanup;\n\t}\n\n\t/* Generate User ID.\n\tBy convention, this is the e-mail-address in angle brackets.\n\n\tAs the user-id is only decorative in Autocrypt and not needed for Delta Chat,\n\tso we _could_ just use sth. that looks like an e-mail-address.\n\tThis would protect the user's privacy if someone else uploads the keys to keyservers.\n\n\tHowever, as eg. Enigmail displayes the user-id in \"Good signature from ,\n\tfor now, we decided to leave the address in the user-id */\n\t#if 0\n\t\tuser_id = (uint8_t*)dc_mprintf(\"<%08X@%08X.org>\", (int)random(), (int)random());\n\t#else\n\t\tuser_id = (uint8_t*)dc_mprintf(\"<%s>\", addr);\n\t#endif\n\n\n\t/* generate two keypairs */\n\tif (!pgp_rsa_generate_keypair(&seckey, DC_KEYGEN_BITS, DC_KEYGEN_E, NULL, NULL, NULL, 0)\n\t || !pgp_rsa_generate_keypair(&subkey, DC_KEYGEN_BITS, DC_KEYGEN_E, NULL, NULL, NULL, 0)) {\n\t\tgoto cleanup;\n\t}\n\n\n\t/* Create public key, bind public subkey to public key */\n\n\tpubkey.type = PGP_PTAG_CT_PUBLIC_KEY;\n\tpgp_pubkey_dup(&pubkey.key.pubkey, &seckey.key.pubkey);\n\tmemcpy(pubkey.pubkeyid, seckey.pubkeyid, PGP_KEY_ID_SIZE);\n\tpgp_fingerprint(&pubkey.pubkeyfpr, &seckey.key.pubkey, 0);\n\tadd_selfsigned_userid(&seckey, &pubkey, (const uint8_t*)user_id, 0/*never expire*/);\n\n\tEXPAND_ARRAY((&pubkey), subkey);\n\t{\n\t\tpgp_subkey_t* p = &pubkey.subkeys[pubkey.subkeyc++];\n\t\tpgp_pubkey_dup(&p->key.pubkey, &subkey.key.pubkey);\n\t\tpgp_keyid(subkeyid, PGP_KEY_ID_SIZE, &pubkey.key.pubkey, PGP_HASH_SHA1);\n\t\tmemcpy(p->id, subkeyid, PGP_KEY_ID_SIZE);\n\t}\n\n\tEXPAND_ARRAY((&pubkey), subkeysig);\n\tadd_subkey_binding_signature(&pubkey.subkeysigs[pubkey.subkeysigc++], &pubkey, &subkey, &seckey);\n\n\n\t/* Create secret key, bind secret subkey to secret key */\n\n\tEXPAND_ARRAY((&seckey), subkey);\n\t{\n\t\tpgp_subkey_t* p = &seckey.subkeys[seckey.subkeyc++];\n\t\tpgp_seckey_dup(&p->key.seckey, &subkey.key.seckey);\n\t\tpgp_keyid(subkeyid, PGP_KEY_ID_SIZE, &seckey.key.pubkey, PGP_HASH_SHA1);\n\t\tmemcpy(p->id, subkeyid, PGP_KEY_ID_SIZE);\n\t}\n\n\tEXPAND_ARRAY((&seckey), subkeysig);\n\tadd_subkey_binding_signature(&seckey.subkeysigs[seckey.subkeysigc++], &seckey, &subkey, &seckey);\n\n\n\t/* Done with key generation, write binary keys to memory */\n\n\tpgp_writer_set_memory(pubout, pubmem);\n\tif (!pgp_write_xfer_key(pubout, &pubkey, 0/*armored*/)\n\t || pubmem->buf==NULL || pubmem->length <= 0) {\n\t\tgoto cleanup;\n\t}\n\n\tpgp_writer_set_memory(secout, secmem);\n\tif (!pgp_write_xfer_key(secout, &seckey, 0/*armored*/)\n\t || secmem->buf==NULL || secmem->length <= 0) {\n\t\tgoto cleanup;\n\t}\n\n\tdc_key_set_from_binary(ret_public_key, pubmem->buf, pubmem->length, DC_KEY_PUBLIC);\n\tdc_key_set_from_binary(ret_private_key, secmem->buf, secmem->length, DC_KEY_PRIVATE);\n\n\tsuccess = 1;\n\ncleanup:\n\tif (pubout) { pgp_output_delete(pubout); }\n\tif (secout) { pgp_output_delete(secout); }\n\tif (pubmem) { pgp_memory_free(pubmem); }\n\tif (secmem) { pgp_memory_free(secmem); }\n\tpgp_key_free(&seckey); /* not: pgp_keydata_free() which will also free the pointer itself (we created it on the stack) */\n\tpgp_key_free(&pubkey);\n\tpgp_key_free(&subkey);\n\tfree(user_id);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/pgp.rs", "rust_func": "pub(crate) fn create_keypair(addr: EmailAddress, keygen_type: KeyGenType) -> Result {\n let (signing_key_type, encryption_key_type) = match keygen_type {\n KeyGenType::Rsa2048 => (PgpKeyType::Rsa(2048), PgpKeyType::Rsa(2048)),\n KeyGenType::Rsa4096 => (PgpKeyType::Rsa(4096), PgpKeyType::Rsa(4096)),\n KeyGenType::Ed25519 | KeyGenType::Default => (PgpKeyType::EdDSA, PgpKeyType::ECDH),\n };\n\n let user_id = format!(\"<{addr}>\");\n let key_params = SecretKeyParamsBuilder::default()\n .key_type(signing_key_type)\n .can_certify(true)\n .can_sign(true)\n .primary_user_id(user_id)\n .passphrase(None)\n .preferred_symmetric_algorithms(smallvec![\n SymmetricKeyAlgorithm::AES256,\n SymmetricKeyAlgorithm::AES192,\n SymmetricKeyAlgorithm::AES128,\n ])\n .preferred_hash_algorithms(smallvec![\n HashAlgorithm::SHA2_256,\n HashAlgorithm::SHA2_384,\n HashAlgorithm::SHA2_512,\n HashAlgorithm::SHA2_224,\n HashAlgorithm::SHA1,\n ])\n .preferred_compression_algorithms(smallvec![\n CompressionAlgorithm::ZLIB,\n CompressionAlgorithm::ZIP,\n ])\n .subkey(\n SubkeyParamsBuilder::default()\n .key_type(encryption_key_type)\n .can_encrypt(true)\n .passphrase(None)\n .build()\n .context(\"failed to build subkey parameters\")?,\n )\n .build()\n .context(\"failed to build key parameters\")?;\n\n let secret_key = key_params\n .generate()\n .context(\"failed to generate the key\")?\n .sign(|| \"\".into())\n .context(\"failed to sign secret key\")?;\n secret_key\n .verify()\n .context(\"invalid secret key generated\")?;\n\n let public_key = secret_key\n .public_key()\n .sign(&secret_key, || \"\".into())\n .context(\"failed to sign public key\")?;\n public_key\n .verify()\n .context(\"invalid public key generated\")?;\n\n Ok(KeyPair {\n addr,\n public: public_key,\n secret: secret_key,\n })\n}", "rust_context": "pub struct KeyPair {\n /// Email address.\n pub addr: EmailAddress,\n\n /// Public key.\n pub public: SignedPublicKey,\n\n /// Secret key.\n pub secret: SignedSecretKey,\n}\n\npub enum KeyGenType {\n #[default]\n Default = 0,\n\n /// 2048-bit RSA.\n Rsa2048 = 1,\n\n /// [Ed25519](https://ed25519.cr.yp.to/) signature and X25519 encryption.\n Ed25519 = 2,\n\n /// 4096-bit RSA.\n Rsa4096 = 3,\n}", "rust_imports": "use std::collections::{BTreeMap, HashSet};\nuse std::io;\nuse std::io::Cursor;\nuse anyhow::{bail, Context as _, Result};\nuse deltachat_contact_tools::EmailAddress;\nuse pgp::armor::BlockType;\nuse pgp::composed::{\n Deserializable, KeyType as PgpKeyType, Message, SecretKeyParamsBuilder, SignedPublicKey,\n SignedPublicSubKey, SignedSecretKey, StandaloneSignature, SubkeyParamsBuilder,\n};\nuse pgp::crypto::hash::HashAlgorithm;\nuse pgp::crypto::sym::SymmetricKeyAlgorithm;\nuse pgp::types::{\n CompressionAlgorithm, KeyTrait, Mpi, PublicKeyTrait, SecretKeyTrait, StringToKey,\n};\nuse rand::{thread_rng, CryptoRng, Rng};\nuse tokio::runtime::Handle;\nuse crate::constants::KeyGenType;\nuse crate::key::{DcKey, Fingerprint};\nuse std::io::Read;\nuse once_cell::sync::Lazy;\nuse tokio::sync::OnceCell;\nuse super::*;\nuse crate::test_utils::{alice_keypair, bob_keypair};", "rustrepotrans_file": "projects__deltachat-core__rust__pgp__.rs__function__8.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "* The result must be dc_array_unref()'d\n *\n * The list is already sorted and starts with the oldest message.\n * Clients should not try to re-sort the list as this would be an expensive action\n * and would result in inconsistencies between clients.\n *\n * @memberof dc_context_t\n * @param context The context object as returned from dc_context_new().\n * @param chat_id The chat ID to get all messages with media from.\n * @param msg_type Specify a message type to query here, one of the DC_MSG_* constats.\n * @param msg_type2 Alternative message type to search for. 0 to skip.\n * @param msg_type3 Alternative message type to search for. 0 to skip.\n * @return An array with messages from the given chat ID that have the wanted message types.\n */\ndc_array_t* dc_get_chat_media(dc_context_t* context, uint32_t chat_id,\n int msg_type, int msg_type2, int msg_type3)\n{\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\treturn NULL;\n\t}\n\n\tdc_array_t* ret = dc_array_new(context, 100);\n\n\tsqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql,\n\t\t\"SELECT id FROM msgs WHERE chat_id=? AND chat_id != ? AND (type=? OR type=? OR type=?) ORDER BY timestamp, id;\");\n\tsqlite3_bind_int(stmt, 1, chat_id);\n sqlite3_bind_int(stmt, 2, DC_CHAT_ID_TRASH);\n\tsqlite3_bind_int(stmt, 3, msg_type);\n\tsqlite3_bind_int(stmt, 4, msg_type2>0? msg_type2 : msg_type);\n\tsqlite3_bind_int(stmt, 5, msg_type3>0? msg_type3 : msg_type);\n\twhile (sqlite3_step(stmt)==SQLITE_ROW) {\n\t\tdc_array_add_id(ret, sqlite3_column_int(stmt, 0));\n\t}\n\tsqlite3_finalize(stmt);\n\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn get_chat_media(\n context: &Context,\n chat_id: Option,\n msg_type: Viewtype,\n msg_type2: Viewtype,\n msg_type3: Viewtype,\n) -> Result> {\n // TODO This query could/should be converted to `AND type IN (?, ?, ?)`.\n let list = context\n .sql\n .query_map(\n \"SELECT id\n FROM msgs\n WHERE (1=? OR chat_id=?)\n AND chat_id != ?\n AND (type=? OR type=? OR type=?)\n AND hidden=0\n ORDER BY timestamp, id;\",\n (\n chat_id.is_none(),\n chat_id.unwrap_or_else(|| ChatId::new(0)),\n DC_CHAT_ID_TRASH,\n msg_type,\n if msg_type2 != Viewtype::Unknown {\n msg_type2\n } else {\n msg_type\n },\n if msg_type3 != Viewtype::Unknown {\n msg_type3\n } else {\n msg_type\n },\n ),\n |row| row.get::<_, MsgId>(0),\n |ids| Ok(ids.flatten().collect()),\n )\n .await?;\n Ok(list)\n}", "rust_context": "pub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct InnerContext {\n /// Blob directory path\n pub(crate) blobdir: PathBuf,\n pub(crate) sql: Sql,\n pub(crate) smeared_timestamp: SmearedTimestamp,\n /// The global \"ongoing\" process state.\n ///\n /// This is a global mutex-like state for operations which should be modal in the\n /// clients.\n running_state: RwLock,\n /// Mutex to avoid generating the key for the user more than once.\n pub(crate) generating_key_mutex: Mutex<()>,\n /// Mutex to enforce only a single running oauth2 is running.\n pub(crate) oauth2_mutex: Mutex<()>,\n /// Mutex to prevent a race condition when a \"your pw is wrong\" warning is sent, resulting in multiple messages being sent.\n pub(crate) wrong_pw_warning_mutex: Mutex<()>,\n pub(crate) translated_stockstrings: StockStrings,\n pub(crate) events: Events,\n\n pub(crate) scheduler: SchedulerState,\n pub(crate) ratelimit: RwLock,\n\n /// Recently loaded quota information, if any.\n /// Set to `None` if quota was never tried to load.\n pub(crate) quota: RwLock>,\n\n /// IMAP UID resync request.\n pub(crate) resync_request: AtomicBool,\n\n /// Notify about new messages.\n ///\n /// This causes [`Context::wait_next_msgs`] to wake up.\n pub(crate) new_msgs_notify: Notify,\n\n /// Server ID response if ID capability is supported\n /// and the server returned non-NIL on the inbox connection.\n /// \n pub(crate) server_id: RwLock>>,\n\n /// IMAP METADATA.\n pub(crate) metadata: RwLock>,\n\n pub(crate) last_full_folder_scan: Mutex>,\n\n /// ID for this `Context` in the current process.\n ///\n /// This allows for multiple `Context`s open in a single process where each context can\n /// be identified by this ID.\n pub(crate) id: u32,\n\n creation_time: tools::Time,\n\n /// The text of the last error logged and emitted as an event.\n /// If the ui wants to display an error after a failure,\n /// `last_error` should be used to avoid races with the event thread.\n pub(crate) last_error: std::sync::RwLock,\n\n /// If debug logging is enabled, this contains all necessary information\n ///\n /// Standard RwLock instead of [`tokio::sync::RwLock`] is used\n /// because the lock is used from synchronous [`Context::emit_event`].\n pub(crate) debug_logging: std::sync::RwLock>,\n\n /// Push subscriber to store device token\n /// and register for heartbeat notifications.\n pub(crate) push_subscriber: PushSubscriber,\n\n /// True if account has subscribed to push notifications via IMAP.\n pub(crate) push_subscribed: AtomicBool,\n\n /// Iroh for realtime peer channels.\n pub(crate) iroh: OnceCell,\n}\n\npub async fn query_map(\n &self,\n sql: &str,\n params: impl rusqlite::Params + Send,\n f: F,\n mut g: G,\n ) -> Result\n where\n F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result,\n G: Send + FnMut(rusqlite::MappedRows) -> Result,\n H: Send + 'static,\n {\n self.call(move |conn| {\n let mut stmt = conn.prepare(sql)?;\n let res = stmt.query_map(params, f)?;\n g(res)\n })\n .await\n }\n\npub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}\n\npub struct MsgId(u32);\n\npub struct ChatId(u32);\n\nimpl ChatId {\n /// Create a new [ChatId].\n pub const fn new(id: u32) -> ChatId {\n ChatId(id)\n }\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__116.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "uint32_t dc_msg_get_from_id(const dc_msg_t* msg)\n{\n\tif (msg==NULL || msg->magic!=DC_MSG_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn msg->from_id;\n}", "rust_path": "projects/deltachat-core/rust/message.rs", "rust_func": "pub fn get_from_id(&self) -> ContactId {\n self.from_id\n }", "rust_context": "pub struct ContactId(u32);\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}", "rust_imports": "use std::collections::BTreeSet;\nuse std::path::{Path, PathBuf};\nuse anyhow::{ensure, format_err, Context as _, Result};\nuse deltachat_contact_tools::{parse_vcard, VcardContact};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse tokio::{fs, io};\nuse crate::blob::BlobObject;\nuse crate::chat::{Chat, ChatId, ChatIdBlocked};\nuse crate::chatlist_events;\nuse crate::config::Config;\nuse crate::constants::{\n Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,\n};\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::debug_logging::set_debug_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};\nuse crate::events::EventType;\nuse crate::imap::markseen_on_imap_table;\nuse crate::location::delete_poi_location;\nuse crate::mimeparser::{parse_message_id, SystemMessage};\nuse crate::param::{Param, Params};\nuse crate::pgp::split_armored_data;\nuse crate::reaction::get_msg_reactions;\nuse crate::sql;\nuse crate::summary::Summary;\nuse crate::tools::{\n buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,\n timestamp_to_str, truncate,\n};\nuse MessageState::*;\nuse MessageState::*;\nuse num_traits::FromPrimitive;\nuse super::*;\nuse crate::chat::{\n self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::config::Config;\nuse crate::reaction::send_reaction;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils as test;\nuse crate::test_utils::{TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__message__.rs__function__32.txt"} {"c_path": "projects/deltachat-core/c/dc_contact.c", "c_func": "uint32_t dc_contact_get_id(const dc_contact_t* contact)\n{\n\tif (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) {\n\t\treturn 0;\n\t}\n\treturn contact->id;\n}", "rust_path": "projects/deltachat-core/rust/contact.rs", "rust_func": "pub fn get_id(&self) -> ContactId {\n self.id\n }", "rust_context": "pub struct ContactId(u32);\n\npub struct Contact {\n /// The contact ID.\n pub id: ContactId,\n\n /// Contact name. It is recommended to use `Contact::get_name`,\n /// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.\n /// May be empty, initially set to `authname`.\n name: String,\n\n /// Name authorized by the contact himself. Only this name may be spread to others,\n /// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,\n /// to access this field.\n authname: String,\n\n /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.\n addr: String,\n\n /// Blocked state. Use contact_is_blocked to access this field.\n pub blocked: bool,\n\n /// Time when the contact was seen last time, Unix time in seconds.\n last_seen: i64,\n\n /// The origin/source of the contact.\n pub origin: Origin,\n\n /// Parameters as Param::ProfileImage\n pub param: Params,\n\n /// Last seen message signature for this contact, to be displayed in the profile.\n status: String,\n\n /// If the contact is a bot.\n is_bot: bool,\n}", "rust_imports": "use std::cmp::{min, Reverse};\nuse std::collections::BinaryHeap;\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::time::UNIX_EPOCH;\nuse anyhow::{bail, ensure, Context as _, Result};\nuse async_channel::{self as channel, Receiver, Sender};\nuse base64::Engine as _;\nuse deltachat_contact_tools::may_be_valid_addr;\nuse deltachat_contact_tools::{\n self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,\n ContactAddress, VcardContact,\n};\nuse deltachat_derive::{FromSql, ToSql};\nuse rusqlite::OptionalExtension;\nuse serde::{Deserialize, Serialize};\nuse tokio::task;\nuse tokio::time::{timeout, Duration};\nuse crate::aheader::{Aheader, EncryptPreference};\nuse crate::blob::BlobObject;\nuse crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};\nuse crate::context::Context;\nuse crate::events::EventType;\nuse crate::key::{load_self_public_key, DcKey, SignedPublicKey};\nuse crate::log::LogExt;\nuse crate::login_param::LoginParam;\nuse crate::message::MessageState;\nuse crate::mimeparser::AvatarAction;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::sql::{self, params_iter};\nuse crate::sync::{self, Sync::*};\nuse crate::tools::{\n duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,\n};\nuse crate::{chat, chatlist_events, stock_str};\nuse deltachat_contact_tools::{may_be_valid_addr, normalize_name};\nuse super::*;\nuse crate::chat::{get_chat_contacts, send_text_msg, Chat};\nuse crate::chatlist::Chatlist;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{self, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__contact__.rs__function__36.txt"} {"c_path": "projects/deltachat-core/c/dc_chat.c", "c_func": "uint32_t dc_get_chat_id_by_contact_id(dc_context_t* context, uint32_t contact_id)\n{\n\tuint32_t chat_id = 0;\n\tint chat_id_blocked = 0;\n\n\tif (context==NULL || context->magic!=DC_CONTEXT_MAGIC) {\n\t\treturn 0;\n\t}\n\n\tdc_lookup_real_nchat_by_contact_id(context, contact_id, &chat_id, &chat_id_blocked);\n\n\treturn chat_id_blocked? 0 : chat_id; /* from outside view, chats only existing in the deaddrop do not exist */\n}", "rust_path": "projects/deltachat-core/rust/chat.rs", "rust_func": "pub async fn lookup_by_contact(\n context: &Context,\n contact_id: ContactId,\n ) -> Result> {\n let Some(chat_id_blocked) = ChatIdBlocked::lookup_by_contact(context, contact_id).await?\n else {\n return Ok(None);\n };\n\n let chat_id = match chat_id_blocked.blocked {\n Blocked::Not | Blocked::Request => Some(chat_id_blocked.id),\n Blocked::Yes => None,\n };\n Ok(chat_id)\n }", "rust_context": "pub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct ChatId(u32);\n\npub(crate) struct ChatIdBlocked {\n /// Chat ID.\n pub id: ChatId,\n\n /// Whether the chat is blocked, unblocked or a contact request.\n pub blocked: Blocked,\n}\n\nimpl ChatIdBlocked {\n pub async fn lookup_by_contact(\n context: &Context,\n contact_id: ContactId,\n ) -> Result> {\n ensure!(context.sql.is_open().await, \"Database not available\");\n ensure!(\n contact_id != ContactId::UNDEFINED,\n \"Invalid contact id requested\"\n );\n\n context\n .sql\n .query_row_optional(\n \"SELECT c.id, c.blocked\n FROM chats c\n INNER JOIN chats_contacts j\n ON c.id=j.chat_id\n WHERE c.type=100 -- 100 = Chattype::Single\n AND c.id>9 -- 9 = DC_CHAT_ID_LAST_SPECIAL\n AND j.contact_id=?;\",\n (contact_id,),\n |row| {\n let id: ChatId = row.get(0)?;\n let blocked: Blocked = row.get(1)?;\n Ok(ChatIdBlocked { id, blocked })\n },\n )\n .await\n .map_err(Into::into)\n }\n}\n\npub struct ContactId(u32);\n\npub enum Blocked {\n #[default]\n Not = 0,\n Yes = 1,\n Request = 2,\n}", "rust_imports": "use std::cmp;\nuse std::collections::{HashMap, HashSet};\nuse std::fmt;\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse std::time::Duration;\nuse anyhow::{anyhow, bail, ensure, Context as _, Result};\nuse deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};\nuse deltachat_derive::{FromSql, ToSql};\nuse serde::{Deserialize, Serialize};\nuse strum_macros::EnumIter;\nuse tokio::task;\nuse crate::aheader::EncryptPreference;\nuse crate::blob::BlobObject;\nuse crate::chatlist::Chatlist;\nuse crate::chatlist_events;\nuse crate::color::str_to_color;\nuse crate::config::Config;\nuse crate::constants::{\n self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,\n DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,\n};\nuse crate::contact::{self, Contact, ContactId, Origin};\nuse crate::context::Context;\nuse crate::debug_logging::maybe_set_logging_xdc;\nuse crate::download::DownloadState;\nuse crate::ephemeral::Timer as EphemeralTimer;\nuse crate::events::EventType;\nuse crate::html::new_html_mimepart;\nuse crate::location;\nuse crate::log::LogExt;\nuse crate::message::{self, Message, MessageState, MsgId, Viewtype};\nuse crate::mimefactory::MimeFactory;\nuse crate::mimeparser::SystemMessage;\nuse crate::param::{Param, Params};\nuse crate::peerstate::Peerstate;\nuse crate::receive_imf::ReceivedMsg;\nuse crate::securejoin::BobState;\nuse crate::smtp::send_msg_to_smtp;\nuse crate::sql;\nuse crate::stock_str;\nuse crate::sync::{self, Sync::*, SyncData};\nuse crate::tools::{\n buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,\n create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,\n smeared_time, time, IsNoneOrEmpty, SystemTime,\n};\nuse crate::webxdc::WEBXDC_SUFFIX;\nuse CantSendReason::*;\nuse super::*;\nuse crate::chatlist::get_archived_cnt;\nuse crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};\nuse crate::message::delete_msgs;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{sync, TestContext, TestContextManager};\nuse strum::IntoEnumIterator;\nuse tokio::fs;", "rustrepotrans_file": "projects__deltachat-core__rust__chat__.rs__function__8.txt"} {"c_path": "projects/deltachat-core/c/dc_mimefactory.c", "c_func": "int dc_mimefactory_render(dc_mimefactory_t* factory)\n{\n\tstruct mailimf_fields* imf_fields = NULL;\n\tstruct mailmime* message = NULL;\n\tchar* message_text = NULL;\n\tchar* message_text2 = NULL;\n\tchar* subject_str = NULL;\n\tint afwd_email = 0;\n\tint col = 0;\n\tint success = 0;\n\tint parts = 0;\n\tint e2ee_guaranteed = 0;\n\tint min_verified = DC_NOT_VERIFIED;\n\tint force_plaintext = 0; // 1=add Autocrypt-header (needed eg. for handshaking), 2=no Autocrypte-header (used for MDN)\n\tint do_gossip = 0;\n\tchar* grpimage = NULL;\n\tdc_e2ee_helper_t e2ee_helper;\n\tmemset(&e2ee_helper, 0, sizeof(dc_e2ee_helper_t));\n\n\tif (factory==NULL || factory->loaded==DC_MF_NOTHING_LOADED || factory->out/*call empty() before*/) {\n\t\tset_error(factory, \"Invalid use of mimefactory-object.\");\n\t\tgoto cleanup;\n\t}\n\n\t/* create basic mail\n\t *************************************************************************/\n\n\t{\n\t\tstruct mailimf_mailbox_list* from = mailimf_mailbox_list_new_empty();\n\t\tmailimf_mailbox_list_add(from, mailimf_mailbox_new(factory->from_displayname? dc_encode_header_words(factory->from_displayname) : NULL, dc_strdup(factory->from_addr)));\n\n\t\tstruct mailimf_address_list* to = NULL;\n\t\tif (factory->recipients_names && factory->recipients_addr && clist_count(factory->recipients_addr)>0) {\n\t\t\tclistiter *iter1, *iter2;\n\t\t\tto = mailimf_address_list_new_empty();\n\t\t\tfor (iter1=clist_begin(factory->recipients_names),iter2=clist_begin(factory->recipients_addr); iter1!=NULL&&iter2!=NULL; iter1=clist_next(iter1),iter2=clist_next(iter2)) {\n\t\t\t\tconst char* name = clist_content(iter1);\n\t\t\t\tconst char* addr = clist_content(iter2);\n\t\t\t\tmailimf_address_list_add(to, mailimf_address_new(MAILIMF_ADDRESS_MAILBOX, mailimf_mailbox_new(name? dc_encode_header_words(name) : NULL, dc_strdup(addr)), NULL));\n\t\t\t}\n\t\t}\n\n\t\tclist* references_list = NULL;\n\t\tif (factory->references && factory->references[0]) {\n\t\t\treferences_list = dc_str_to_clist(factory->references, \" \");\n\t\t}\n\n\t\tclist* in_reply_to_list = NULL;\n\t\tif (factory->in_reply_to && factory->in_reply_to[0]) {\n\t\t\tin_reply_to_list = dc_str_to_clist(factory->in_reply_to, \" \");\n\t\t}\n\n\t\timf_fields = mailimf_fields_new_with_data_all(mailimf_get_date(factory->timestamp), from,\n\t\t\tNULL /* sender */, NULL /* reply-to */,\n\t\t\tto, NULL /* cc */, NULL /* bcc */, dc_strdup(factory->rfc724_mid), in_reply_to_list,\n\t\t\treferences_list /* references */,\n\t\t\tNULL /* subject set later */);\n\n\t\t/* Add a X-Mailer header. This is only informational for debugging and may be removed in the release.\n\t\tWe do not rely on this header as it may be removed by MTAs. */\n\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"X-Mailer\"),\n\t\t\tdc_mprintf(\"Delta Chat Core %s%s%s\",\n\t\t\tDC_VERSION_STR,\n\t\t\tfactory->context->os_name? \"/\" : \"\",\n\t\t\tfactory->context->os_name? factory->context->os_name : \"\")));\n\n\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Version\"), strdup(\"1.0\"))); /* mark message as being sent by a messenger */\n\n\t\tif (factory->req_mdn) {\n\t\t\t/* we use \"Chat-Disposition-Notification-To\" as replies to \"Disposition-Notification-To\" are weird in many cases, are just freetext and/or do not follow any standard. */\n\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Disposition-Notification-To\"), strdup(factory->from_addr)));\n\t\t}\n\n\t\tmessage = mailmime_new_message_data(NULL);\n\t\tmailmime_set_imf_fields(message, imf_fields);\n\t}\n\n\tif (factory->loaded==DC_MF_MSG_LOADED)\n\t{\n\t\t/* Render a normal message\n\t\t *********************************************************************/\n\n\t\tdc_chat_t* chat = factory->chat;\n\t\tdc_msg_t* msg = factory->msg;\n\n\t\tstruct mailmime* meta_part = NULL;\n\t\tchar* placeholdertext = NULL;\n\n\t\tif (chat->type==DC_CHAT_TYPE_VERIFIED_GROUP) {\n\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Verified\"), strdup(\"1\")));\n\t\t\tforce_plaintext = 0;\n\t\t\te2ee_guaranteed = 1;\n\t\t\tmin_verified = DC_BIDIRECT_VERIFIED;\n\t\t}\n\t\telse {\n\t\t\tif ((force_plaintext = dc_param_get_int(factory->msg->param, DC_PARAM_FORCE_PLAINTEXT, 0))==0) {\n\t\t\t\te2ee_guaranteed = dc_param_get_int(factory->msg->param, DC_PARAM_GUARANTEE_E2EE, 0);\n\t\t\t}\n\t\t}\n\n\t\t// beside key- and member-changes, force re-gossip every 48 hours\n\t\t#define AUTO_REGOSSIP (2*24*60*60)\n\t\tif (chat->gossiped_timestamp==0\n\t\t || chat->gossiped_timestamp+AUTO_REGOSSIP < time(NULL) ) {\n\t\t\tdo_gossip = 1;\n\t\t}\n\n\t\t/* build header etc. */\n\t\tint command = dc_param_get_int(msg->param, DC_PARAM_CMD, 0);\n\t\tif (DC_CHAT_TYPE_IS_MULTI(chat->type))\n\t\t{\n\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Group-ID\"), dc_strdup(chat->grpid)));\n\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Group-Name\"), dc_encode_header_words(chat->name)));\n\n\n\t\t\tif (command==DC_CMD_MEMBER_REMOVED_FROM_GROUP)\n\t\t\t{\n\t\t\t\tchar* email_to_remove = dc_param_get(msg->param, DC_PARAM_CMD_ARG, NULL);\n\t\t\t\tif (email_to_remove) {\n\t\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Group-Member-Removed\"), email_to_remove));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (command==DC_CMD_MEMBER_ADDED_TO_GROUP)\n\t\t\t{\n\t\t\t\tdo_gossip = 1;\n\n\t\t\t\tchar* email_to_add = dc_param_get(msg->param, DC_PARAM_CMD_ARG, NULL);\n\t\t\t\tif (email_to_add) {\n\t\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Group-Member-Added\"), email_to_add));\n\t\t\t\t\tgrpimage = dc_param_get(chat->param, DC_PARAM_PROFILE_IMAGE, NULL);\n\t\t\t\t}\n\n\t\t\t\tif (dc_param_get_int(msg->param, DC_PARAM_CMD_ARG2, 0)&DC_FROM_HANDSHAKE) {\n\t\t\t\t\tdc_log_info(msg->context, 0, \"sending secure-join message '%s' >>>>>>>>>>>>>>>>>>>>>>>>>\", \"vg-member-added\");\n\t\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Secure-Join\"), strdup(\"vg-member-added\")));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (command==DC_CMD_GROUPNAME_CHANGED)\n\t\t\t{\n\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Group-Name-Changed\"), dc_param_get(msg->param, DC_PARAM_CMD_ARG, \"\")));\n\t\t\t}\n\t\t\telse if (command==DC_CMD_GROUPIMAGE_CHANGED)\n\t\t\t{\n\t\t\t\tgrpimage = dc_param_get(msg->param, DC_PARAM_CMD_ARG, NULL);\n\t\t\t\tif (grpimage==NULL) {\n\t\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Group-Image\"), dc_strdup(\"0\")));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (command==DC_CMD_LOCATION_STREAMING_ENABLED) {\n\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(\n\t\t\t\tstrdup(\"Chat-Content\"),\n\t\t\t\tstrdup(\"location-streaming-enabled\")));\n\t\t}\n\n\t\tif (command==DC_CMD_AUTOCRYPT_SETUP_MESSAGE) {\n\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Autocrypt-Setup-Message\"), strdup(\"v1\")));\n\t\t\tplaceholdertext = dc_stock_str(factory->context, DC_STR_AC_SETUP_MSG_BODY);\n\t\t}\n\n\t\tif (command==DC_CMD_SECUREJOIN_MESSAGE) {\n\t\t\tchar* step = dc_param_get(msg->param, DC_PARAM_CMD_ARG, NULL);\n\t\t\tif (step) {\n\t\t\t\tdc_log_info(msg->context, 0, \"sending secure-join message '%s' >>>>>>>>>>>>>>>>>>>>>>>>>\", step);\n\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Secure-Join\"), step/*mailimf takes ownership of string*/));\n\n\t\t\t\tchar* param2 = dc_param_get(msg->param, DC_PARAM_CMD_ARG2, NULL);\n\t\t\t\tif (param2) {\n\t\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(\n\t\t\t\t\t\t(strcmp(step, \"vg-request-with-auth\")==0 || strcmp(step, \"vc-request-with-auth\")==0)?\n\t\t\t\t\t\t\tstrdup(\"Secure-Join-Auth\") : strdup(\"Secure-Join-Invitenumber\"),\n\t\t\t\t\t\tparam2/*mailimf takes ownership of string*/));\n\t\t\t\t}\n\n\t\t\t\tchar* fingerprint = dc_param_get(msg->param, DC_PARAM_CMD_ARG3, NULL);\n\t\t\t\tif (fingerprint) {\n\t\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(\n\t\t\t\t\t\tstrdup(\"Secure-Join-Fingerprint\"),\n\t\t\t\t\t\tfingerprint/*mailimf takes ownership of string*/));\n\t\t\t\t}\n\n\t\t\t\tchar* grpid = dc_param_get(msg->param, DC_PARAM_CMD_ARG4, NULL);\n\t\t\t\tif (grpid) {\n\t\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(\n\t\t\t\t\t\tstrdup(\"Secure-Join-Group\"),\n\t\t\t\t\t\tgrpid/*mailimf takes ownership of string*/));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (grpimage)\n\t\t{\n\t\t\tdc_msg_t* meta = dc_msg_new_untyped(factory->context);\n\t\t\tmeta->type = DC_MSG_IMAGE;\n\t\t\tdc_param_set(meta->param, DC_PARAM_FILE, grpimage);\n\t\t\tchar* filename_as_sent = NULL;\n\t\t\tif ((meta_part=build_body_file(meta, \"group-image\", &filename_as_sent))!=NULL) {\n\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Group-Image\"), filename_as_sent/*takes ownership*/));\n\t\t\t}\n\t\t\tdc_msg_unref(meta);\n\t\t}\n\n\t\tif (msg->type==DC_MSG_VOICE || msg->type==DC_MSG_AUDIO || msg->type==DC_MSG_VIDEO)\n\t\t{\n\t\t\tif (msg->type==DC_MSG_VOICE) {\n\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Voice-Message\"), strdup(\"1\")));\n\t\t\t}\n\n\t\t\tint duration_ms = dc_param_get_int(msg->param, DC_PARAM_DURATION, 0);\n\t\t\tif (duration_ms > 0) {\n\t\t\t\tmailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup(\"Chat-Duration\"), dc_mprintf(\"%i\", (int)duration_ms)));\n\t\t\t}\n\t\t}\n\n\t\t/* add text part - we even add empty text and force a MIME-multipart-message as:\n\t\t- some Apps have problems with Non-text in the main part (eg. \"Mail\" from stock Android)\n\t\t- we can add \"forward hints\" this way\n\t\t- it looks better */\n\t\tafwd_email = dc_param_exists(msg->param, DC_PARAM_FORWARDED);\n\t\tchar* fwdhint = NULL;\n\t\tif (afwd_email) {\n\t\t\tfwdhint = dc_strdup(\"----- Forwarded message -----\" LINEEND \"From: Delta Chat\" LINEEND LINEEND); /* do not chage this! expected this way in the simplifier to detect forwarding! */\n\t\t}\n\n\t\tconst char* final_text = NULL;\n\t\tif (placeholdertext) {\n\t\t\tfinal_text = placeholdertext;\n\t\t}\n\t\telse if (msg->text && msg->text[0]) {\n\t\t\tfinal_text = msg->text;\n\t\t}\n\n\t\tchar* footer = factory->selfstatus;\n\t\tmessage_text = dc_mprintf(\"%s%s%s%s%s\",\n\t\t\tfwdhint? fwdhint : \"\",\n\t\t\tfinal_text? final_text : \"\",\n\t\t\t(final_text&&footer&&footer[0])? (LINEEND LINEEND) : \"\",\n\t\t\t(footer&&footer[0])? (\"-- \" LINEEND) : \"\",\n\t\t\t(footer&&footer[0])? footer : \"\");\n\t\tstruct mailmime* text_part = build_body_text(message_text);\n\t\tmailmime_smart_add_part(message, text_part);\n\t\tparts++;\n\n\t\tfree(fwdhint);\n\t\tfree(placeholdertext);\n\n\t\t/* add attachment part */\n\t\tif (DC_MSG_NEEDS_ATTACHMENT(msg->type)) {\n\t\t\tif (!is_file_size_okay(msg)) {\n\t\t\t\tchar* error = dc_mprintf(\"Message exceeds the recommended %i MB.\", DC_MSGSIZE_MAX_RECOMMENDED/1000/1000);\n\t\t\t\tset_error(factory, error);\n\t\t\t\tfree(error);\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\n\t\t\tstruct mailmime* file_part = build_body_file(msg, NULL, NULL);\n\t\t\tif (file_part) {\n\t\t\t\tmailmime_smart_add_part(message, file_part);\n\t\t\t\tparts++;\n\t\t\t}\n\t\t}\n\n\t\tif (parts==0) {\n\t\t\tset_error(factory, \"Empty message.\");\n\t\t\tgoto cleanup;\n\t\t}\n\n\t\tif (meta_part) {\n\t\t\tmailmime_smart_add_part(message, meta_part); /* meta parts are only added if there are other parts */\n\t\t\tparts++;\n\t\t}\n\n\t\tif (dc_param_exists(msg->param, DC_PARAM_SET_LATITUDE)) {\n\t\t\tdouble latitude = dc_param_get_float(msg->param, DC_PARAM_SET_LATITUDE, 0.0);\n\t\t\tdouble longitude = dc_param_get_float(msg->param, DC_PARAM_SET_LONGITUDE, 0.0);\n\t\t\tchar* kml_file = dc_get_message_kml(msg->context, msg->timestamp_sort, latitude, longitude);\n\t\t\tif (kml_file) {\n\t\t\t\tstruct mailmime_content* content_type = mailmime_content_new_with_str(\"application/vnd.google-earth.kml+xml\");\n\t\t\t\tstruct mailmime_fields* mime_fields = mailmime_fields_new_filename(MAILMIME_DISPOSITION_TYPE_ATTACHMENT,\n\t\t\t\t\tdc_strdup(\"message.kml\"), MAILMIME_MECHANISM_8BIT);\n\t\t\t\tstruct mailmime* kml_mime_part = mailmime_new_empty(content_type, mime_fields);\n\t\t\t\tmailmime_set_body_text(kml_mime_part, kml_file, strlen(kml_file));\n\n\t\t\t\tmailmime_smart_add_part(message, kml_mime_part);\n\t\t\t\tparts++;\n\t\t\t}\n\t\t}\n\n\t\tif (dc_is_sending_locations_to_chat(msg->context, msg->chat_id)) {\n\t\t\tuint32_t last_added_location_id = 0;\n\t\t\tchar* kml_file = dc_get_location_kml(msg->context, msg->chat_id,\n\t\t\t\t&last_added_location_id);\n\t\t\tif (kml_file) {\n\t\t\t\tstruct mailmime_content* content_type = mailmime_content_new_with_str(\"application/vnd.google-earth.kml+xml\");\n\t\t\t\tstruct mailmime_fields* mime_fields = mailmime_fields_new_filename(MAILMIME_DISPOSITION_TYPE_ATTACHMENT,\n\t\t\t\t\tdc_strdup(\"location.kml\"), MAILMIME_MECHANISM_8BIT);\n\t\t\t\tstruct mailmime* kml_mime_part = mailmime_new_empty(content_type, mime_fields);\n\t\t\t\tmailmime_set_body_text(kml_mime_part, kml_file, strlen(kml_file));\n\n\t\t\t\tmailmime_smart_add_part(message, kml_mime_part);\n\t\t\t\tparts++;\n\n\t\t\t\tif (!dc_param_exists(msg->param, DC_PARAM_SET_LATITUDE)) { // otherwise, the independent location is already filed\n\t\t\t\t\tfactory->out_last_added_location_id = last_added_location_id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if (factory->loaded==DC_MF_MDN_LOADED)\n\t{\n\t\t/* Render a MDN\n\t\t *********************************************************************/\n\n\t\tstruct mailmime* multipart = mailmime_multiple_new(\"multipart/report\"); /* RFC 6522, this also requires the `report-type` parameter which is equal to the MIME subtype of the second body part of the multipart/report */\n\t\tstruct mailmime_content* content = multipart->mm_content_type;\n\t\tclist_append(content->ct_parameters, mailmime_param_new_with_data(\"report-type\", \"disposition-notification\")); /* RFC */\n\t\tmailmime_add_part(message, multipart);\n\n\t\t/* first body part: always human-readable, always REQUIRED by RFC 6522 */\n\t\tchar *p1 = NULL, *p2 = NULL;\n\t\tif (dc_param_get_int(factory->msg->param, DC_PARAM_GUARANTEE_E2EE, 0)) {\n\t\t\tp1 = dc_stock_str(factory->context, DC_STR_ENCRYPTEDMSG); /* we SHOULD NOT spread encrypted subjects, date etc. in potentially unencrypted MDNs */\n\t\t}\n\t\telse {\n\t\t\tp1 = dc_msg_get_summarytext(factory->msg, DC_APPROX_SUBJECT_CHARS);\n\t\t}\n\t\tp2 = dc_stock_str_repl_string(factory->context, DC_STR_READRCPT_MAILBODY, p1);\n\t\tmessage_text = dc_mprintf(\"%s\" LINEEND, p2);\n\t\tfree(p2);\n\t\tfree(p1);\n\n\t\tstruct mailmime* human_mime_part = build_body_text(message_text);\n\t\tmailmime_add_part(multipart, human_mime_part);\n\n\n\t\t/* second body part: machine-readable, always REQUIRED by RFC 6522 */\n\t\tmessage_text2 = dc_mprintf(\n\t\t\t\"Reporting-UA: Delta Chat %s\" LINEEND\n\t\t\t\"Original-Recipient: rfc822;%s\" LINEEND\n\t\t\t\"Final-Recipient: rfc822;%s\" LINEEND\n\t\t\t\"Original-Message-ID: <%s>\" LINEEND\n\t\t\t\"Disposition: manual-action/MDN-sent-automatically; displayed\" LINEEND, /* manual-action: the user has configured the MUA to send MDNs (automatic-action implies the receipts cannot be disabled) */\n\t\t\tDC_VERSION_STR,\n\t\t\tfactory->from_addr,\n\t\t\tfactory->from_addr,\n\t\t\tfactory->msg->rfc724_mid);\n\n\t\tstruct mailmime_content* content_type = mailmime_content_new_with_str(\"message/disposition-notification\");\n\t\tstruct mailmime_fields* mime_fields = mailmime_fields_new_encoding(MAILMIME_MECHANISM_8BIT);\n\t\tstruct mailmime* mach_mime_part = mailmime_new_empty(content_type, mime_fields);\n\t\tmailmime_set_body_text(mach_mime_part, message_text2, strlen(message_text2));\n\n\t\tmailmime_add_part(multipart, mach_mime_part);\n\n\t\t/* currently, we do not send MDNs encrypted:\n\t\t- in a multi-device-setup that is not set up properly, MDNs would disturb the communication as they\n\t\t are send automatically which may lead to spreading outdated Autocrypt headers.\n\t\t- they do not carry any information but the Message-ID\n\t\t- this save some KB\n\t\t- in older versions, we did not encrypt messages to ourself when they to to SMTP - however, if these messages\n\t\t are forwarded for any reasons (eg. gmail always forwards to IMAP), we have no chance to decrypt them;\n\t\t this issue is fixed with 0.9.4 */\n\t\tforce_plaintext = DC_FP_NO_AUTOCRYPT_HEADER;\n\t}\n\telse\n\t{\n\t\tset_error(factory, \"No message loaded.\");\n\t\tgoto cleanup;\n\t}\n\n\n\t/* Encrypt the message\n\t *************************************************************************/\n\n\tif (factory->loaded==DC_MF_MDN_LOADED) {\n\t\tchar* e = dc_stock_str(factory->context, DC_STR_READRCPT); subject_str = dc_mprintf(DC_CHAT_PREFIX \" %s\", e); free(e);\n\t}\n\telse {\n\t\tsubject_str = get_subject(factory->chat, factory->msg, afwd_email);\n\t}\n\n\tstruct mailimf_subject* subject = mailimf_subject_new(dc_encode_header_words(subject_str));\n\tmailimf_fields_add(imf_fields, mailimf_field_new(MAILIMF_FIELD_SUBJECT, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, subject, NULL, NULL, NULL));\n\n\tif (force_plaintext!=DC_FP_NO_AUTOCRYPT_HEADER) {\n\t\tdc_e2ee_encrypt(factory->context, factory->recipients_addr,\n\t\t\tforce_plaintext, e2ee_guaranteed, min_verified,\n\t\t\tdo_gossip, message, &e2ee_helper);\n\n\t}\n\n\tif (e2ee_helper.encryption_successfull) {\n\t\tfactory->out_encrypted = 1;\n\t\tif (do_gossip) {\n\t\t\tfactory->out_gossiped = 1;\n\t\t}\n\t}\n\n\t/* create the full mail and return */\n\tfactory->out = mmap_string_new(\"\");\n\tmailmime_write_mem(factory->out, &col, message);\n\n\t//{char* t4=dc_null_terminate(ret->str,ret->len); printf(\"MESSAGE:\\n%s\\n\",t4);free(t4);}\n\n\tsuccess = 1;\n\ncleanup:\n\tif (message) {\n\t\tmailmime_free(message);\n\t}\n\tdc_e2ee_thanks(&e2ee_helper); // frees data referenced by \"mailmime\" but not freed by mailmime_free()\n\tfree(message_text); // mailmime_set_body_text() does not take ownership of \"text\"\n\tfree(message_text2); // - \" --\n\tfree(subject_str);\n\tfree(grpimage);\n\treturn success;\n}", "rust_path": "projects/deltachat-core/rust/mimefactory.rs", "rust_func": "pub async fn render(mut self, context: &Context) -> Result {\n let mut headers: MessageHeaders = Default::default();\n\n let from = Address::new_mailbox_with_name(\n self.from_displayname.to_string(),\n self.from_addr.clone(),\n );\n\n let undisclosed_recipients = match &self.loaded {\n Loaded::Message { chat } => chat.typ == Chattype::Broadcast,\n Loaded::Mdn { .. } => false,\n };\n\n let mut to = Vec::new();\n if undisclosed_recipients {\n to.push(Address::new_group(\n \"hidden-recipients\".to_string(),\n Vec::new(),\n ));\n } else {\n let email_to_remove =\n if self.msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {\n self.msg.param.get(Param::Arg)\n } else {\n None\n };\n\n for (name, addr) in &self.recipients {\n if let Some(email_to_remove) = email_to_remove {\n if email_to_remove == addr {\n continue;\n }\n }\n\n if name.is_empty() {\n to.push(Address::new_mailbox(addr.clone()));\n } else {\n to.push(Address::new_mailbox_with_name(\n name.to_string(),\n addr.clone(),\n ));\n }\n }\n\n if to.is_empty() {\n to.push(from.clone());\n }\n }\n\n // Start with Internet Message Format headers in the order of the standard example\n // .\n let from_header = Header::new_with_value(\"From\".into(), vec![from]).unwrap();\n headers.unprotected.push(from_header.clone());\n headers.protected.push(from_header);\n\n if let Some(sender_displayname) = &self.sender_displayname {\n let sender =\n Address::new_mailbox_with_name(sender_displayname.clone(), self.from_addr.clone());\n headers\n .unprotected\n .push(Header::new_with_value(\"Sender\".into(), vec![sender]).unwrap());\n }\n headers\n .unprotected\n .push(Header::new_with_value(\"To\".into(), to).unwrap());\n\n let subject_str = self.subject_str(context).await?;\n let encoded_subject = if subject_str\n .chars()\n .all(|c| c.is_ascii_alphanumeric() || c == ' ')\n // We do not use needs_encoding() here because needs_encoding() returns true if the string contains a space\n // but we do not want to encode all subjects just because they contain a space.\n {\n subject_str.clone()\n } else {\n encode_words(&subject_str)\n };\n headers\n .protected\n .push(Header::new(\"Subject\".into(), encoded_subject));\n\n let date = chrono::DateTime::::from_timestamp(self.timestamp, 0)\n .unwrap()\n .to_rfc2822();\n headers.unprotected.push(Header::new(\"Date\".into(), date));\n\n let rfc724_mid = match self.loaded {\n Loaded::Message { .. } => self.msg.rfc724_mid.clone(),\n Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),\n };\n let rfc724_mid_headervalue = render_rfc724_mid(&rfc724_mid);\n let rfc724_mid_header = Header::new(\"Message-ID\".into(), rfc724_mid_headervalue);\n headers.unprotected.push(rfc724_mid_header.clone());\n headers.hidden.push(rfc724_mid_header);\n\n // Reply headers as in .\n if !self.in_reply_to.is_empty() {\n headers\n .unprotected\n .push(Header::new(\"In-Reply-To\".into(), self.in_reply_to.clone()));\n }\n if !self.references.is_empty() {\n headers\n .unprotected\n .push(Header::new(\"References\".into(), self.references.clone()));\n }\n\n // Automatic Response headers \n if let Loaded::Mdn { .. } = self.loaded {\n headers.unprotected.push(Header::new(\n \"Auto-Submitted\".to_string(),\n \"auto-replied\".to_string(),\n ));\n } else if context.get_config_bool(Config::Bot).await? {\n headers.unprotected.push(Header::new(\n \"Auto-Submitted\".to_string(),\n \"auto-generated\".to_string(),\n ));\n }\n\n if let Loaded::Message { chat } = &self.loaded {\n if chat.typ == Chattype::Broadcast {\n let encoded_chat_name = encode_words(&chat.name);\n headers.protected.push(Header::new(\n \"List-ID\".into(),\n format!(\"{encoded_chat_name} <{}>\", chat.grpid),\n ));\n }\n }\n\n // Non-standard headers.\n headers\n .unprotected\n .push(Header::new(\"Chat-Version\".to_string(), \"1.0\".to_string()));\n\n if self.req_mdn {\n // we use \"Chat-Disposition-Notification-To\"\n // because replies to \"Disposition-Notification-To\" are weird in many cases\n // eg. are just freetext and/or do not follow any standard.\n headers.protected.push(Header::new(\n \"Chat-Disposition-Notification-To\".into(),\n self.from_addr.clone(),\n ));\n }\n\n let verified = self.verified();\n let grpimage = self.grpimage();\n let force_plaintext = self.should_force_plaintext();\n let skip_autocrypt = self.should_skip_autocrypt();\n let e2ee_guaranteed = self.is_e2ee_guaranteed();\n let encrypt_helper = EncryptHelper::new(context).await?;\n\n if !skip_autocrypt {\n // unless determined otherwise we add the Autocrypt header\n let aheader = encrypt_helper.get_aheader().to_string();\n headers\n .unprotected\n .push(Header::new(\"Autocrypt\".into(), aheader));\n }\n\n let ephemeral_timer = self.msg.chat_id.get_ephemeral_timer(context).await?;\n if let EphemeralTimer::Enabled { duration } = ephemeral_timer {\n headers.protected.push(Header::new(\n \"Ephemeral-Timer\".to_string(),\n duration.to_string(),\n ));\n }\n\n // MIME header .\n // Content-Type\n headers\n .unprotected\n .push(Header::new(\"MIME-Version\".into(), \"1.0\".into()));\n\n let mut is_gossiped = false;\n\n let peerstates = self.peerstates_for_recipients(context).await?;\n let should_encrypt =\n encrypt_helper.should_encrypt(context, e2ee_guaranteed, &peerstates)?;\n let is_encrypted = should_encrypt && !force_plaintext;\n\n let (main_part, parts) = match self.loaded {\n Loaded::Message { .. } => {\n self.render_message(context, &mut headers, &grpimage, is_encrypted)\n .await?\n }\n Loaded::Mdn { .. } => (self.render_mdn(context).await?, Vec::new()),\n };\n\n let message = if parts.is_empty() {\n // Single part, render as regular message.\n main_part\n } else {\n // Multiple parts, render as multipart.\n let part_holder = if self.msg.param.get_cmd() == SystemMessage::MultiDeviceSync {\n PartBuilder::new().header((\n \"Content-Type\".to_string(),\n \"multipart/report; report-type=multi-device-sync\".to_string(),\n ))\n } else if self.msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {\n PartBuilder::new().header((\n \"Content-Type\".to_string(),\n \"multipart/report; report-type=status-update\".to_string(),\n ))\n } else {\n PartBuilder::new().message_type(MimeMultipartType::Mixed)\n };\n\n parts\n .into_iter()\n .fold(part_holder.child(main_part.build()), |message, part| {\n message.child(part.build())\n })\n };\n\n let get_content_type_directives_header = || {\n (\n \"Content-Type-Deltachat-Directives\".to_string(),\n \"protected-headers=\\\"v1\\\"\".to_string(),\n )\n };\n let outer_message = if is_encrypted {\n // Store protected headers in the inner message.\n let message = headers\n .protected\n .into_iter()\n .fold(message, |message, header| message.header(header));\n\n // Add hidden headers to encrypted payload.\n let mut message = headers\n .hidden\n .into_iter()\n .fold(message, |message, header| message.header(header));\n\n // Add gossip headers in chats with multiple recipients\n let multiple_recipients =\n peerstates.len() > 1 || context.get_config_bool(Config::BccSelf).await?;\n if self.should_do_gossip(context, multiple_recipients).await? {\n for peerstate in peerstates.iter().filter_map(|(state, _)| state.as_ref()) {\n if let Some(header) = peerstate.render_gossip_header(verified) {\n message = message.header(Header::new(\"Autocrypt-Gossip\".into(), header));\n is_gossiped = true;\n }\n }\n }\n\n // Set the appropriate Content-Type for the inner message.\n let mut existing_ct = message\n .get_header(\"Content-Type\".to_string())\n .and_then(|h| h.get_value::().ok())\n .unwrap_or_else(|| \"text/plain; charset=utf-8;\".to_string());\n\n if !existing_ct.ends_with(';') {\n existing_ct += \";\";\n }\n let message = message.header(get_content_type_directives_header());\n\n // Set the appropriate Content-Type for the outer message\n let outer_message = PartBuilder::new().header((\n \"Content-Type\".to_string(),\n \"multipart/encrypted; protocol=\\\"application/pgp-encrypted\\\"\".to_string(),\n ));\n\n if std::env::var(crate::DCC_MIME_DEBUG).is_ok() {\n info!(\n context,\n \"mimefactory: unencrypted message mime-body:\\n{}\",\n message.clone().build().as_string(),\n );\n }\n\n // Disable compression for SecureJoin to ensure\n // there are no compression side channels\n // leaking information about the tokens.\n let compress = self.msg.param.get_cmd() != SystemMessage::SecurejoinMessage;\n let encrypted = encrypt_helper\n .encrypt(context, verified, message, peerstates, compress)\n .await?;\n\n outer_message\n .child(\n // Autocrypt part 1\n PartBuilder::new()\n .content_type(&\"application/pgp-encrypted\".parse::().unwrap())\n .header((\"Content-Description\", \"PGP/MIME version identification\"))\n .body(\"Version: 1\\r\\n\")\n .build(),\n )\n .child(\n // Autocrypt part 2\n PartBuilder::new()\n .content_type(\n &\"application/octet-stream; name=\\\"encrypted.asc\\\"\"\n .parse::()\n .unwrap(),\n )\n .header((\"Content-Description\", \"OpenPGP encrypted message\"))\n .header((\"Content-Disposition\", \"inline; filename=\\\"encrypted.asc\\\";\"))\n .body(encrypted)\n .build(),\n )\n .header((\"Subject\".to_string(), \"...\".to_string()))\n } else if matches!(self.loaded, Loaded::Mdn { .. }) {\n // Never add outer multipart/mixed wrapper to MDN\n // as multipart/report Content-Type is used to recognize MDNs\n // by Delta Chat receiver and Chatmail servers\n // allowing them to be unencrypted and not contain Autocrypt header\n // without resetting Autocrypt encryption or triggering Chatmail filter\n // that normally only allows encrypted mails.\n\n // Hidden headers are dropped.\n\n // Store protected headers in the outer message.\n let message = headers\n .protected\n .iter()\n .fold(message, |message, header| message.header(header.clone()));\n\n let protected: HashSet
= HashSet::from_iter(headers.protected.into_iter());\n for h in headers.unprotected.split_off(0) {\n if !protected.contains(&h) {\n headers.unprotected.push(h);\n }\n }\n\n message\n } else {\n // Store hidden headers in the inner unencrypted message.\n let message = headers\n .hidden\n .into_iter()\n .fold(message, |message, header| message.header(header));\n let message = PartBuilder::new()\n .message_type(MimeMultipartType::Mixed)\n .child(message.build());\n\n // Store protected headers in the outer message.\n let message = headers\n .protected\n .iter()\n .fold(message, |message, header| message.header(header.clone()));\n\n if skip_autocrypt || !context.get_config_bool(Config::SignUnencrypted).await? {\n let protected: HashSet
= HashSet::from_iter(headers.protected.into_iter());\n for h in headers.unprotected.split_off(0) {\n if !protected.contains(&h) {\n headers.unprotected.push(h);\n }\n }\n message\n } else {\n let message = message.header(get_content_type_directives_header());\n let (payload, signature) = encrypt_helper.sign(context, message).await?;\n PartBuilder::new()\n .header((\n \"Content-Type\",\n \"multipart/signed; protocol=\\\"application/pgp-signature\\\"\",\n ))\n .child(payload)\n .child(\n PartBuilder::new()\n .content_type(\n &\"application/pgp-signature; name=\\\"signature.asc\\\"\"\n .parse::()\n .unwrap(),\n )\n .header((\"Content-Description\", \"OpenPGP digital signature\"))\n .header((\"Content-Disposition\", \"attachment; filename=\\\"signature\\\";\"))\n .body(signature)\n .build(),\n )\n }\n };\n\n // Store the unprotected headers on the outer message.\n let outer_message = headers\n .unprotected\n .into_iter()\n .fold(outer_message, |message, header| message.header(header));\n\n if std::env::var(crate::DCC_MIME_DEBUG).is_ok() {\n info!(\n context,\n \"mimefactory: outgoing message mime-body:\\n{}\",\n outer_message.clone().build().as_string(),\n );\n }\n\n let MimeFactory {\n last_added_location_id,\n ..\n } = self;\n\n Ok(RenderedEmail {\n message: outer_message.build().as_string(),\n // envelope: Envelope::new,\n is_encrypted,\n is_gossiped,\n last_added_location_id,\n sync_ids_to_delete: self.sync_ids_to_delete,\n rfc724_mid,\n subject: subject_str,\n })\n }", "rust_context": "pub fn is_empty(&self) -> bool {\n self.ids.is_empty()\n }\n\nasync fn render_mdn(&mut self, context: &Context) -> Result {\n // RFC 6522, this also requires the `report-type` parameter which is equal\n // to the MIME subtype of the second body part of the multipart/report\n //\n // currently, we do not send MDNs encrypted:\n // - in a multi-device-setup that is not set up properly, MDNs would disturb the communication as they\n // are send automatically which may lead to spreading outdated Autocrypt headers.\n // - they do not carry any information but the Message-ID\n // - this save some KB\n // - in older versions, we did not encrypt messages to ourself when they to to SMTP - however, if these messages\n // are forwarded for any reasons (eg. gmail always forwards to IMAP), we have no chance to decrypt them;\n // this issue is fixed with 0.9.4\n\n let additional_msg_ids = match &self.loaded {\n Loaded::Message { .. } => bail!(\"Attempt to render a message as MDN\"),\n Loaded::Mdn {\n additional_msg_ids, ..\n } => additional_msg_ids,\n };\n\n let mut message = PartBuilder::new().header((\n \"Content-Type\".to_string(),\n \"multipart/report; report-type=disposition-notification\".to_string(),\n ));\n\n // first body part: always human-readable, always REQUIRED by RFC 6522\n let p1 = if 0\n != self\n .msg\n .param\n .get_int(Param::GuaranteeE2ee)\n .unwrap_or_default()\n {\n stock_str::encrypted_msg(context).await\n } else {\n self.msg\n .get_summary(context, None)\n .await?\n .truncated_text(32)\n .to_string()\n };\n let p2 = stock_str::read_rcpt_mail_body(context, &p1).await;\n let message_text = format!(\"{}\\r\\n\", format_flowed(&p2));\n let text_part = PartBuilder::new().header((\n \"Content-Type\".to_string(),\n \"text/plain; charset=utf-8; format=flowed; delsp=no\".to_string(),\n ));\n let text_part = self.add_message_text(text_part, message_text);\n message = message.child(text_part.build());\n\n // second body part: machine-readable, always REQUIRED by RFC 6522\n let message_text2 = format!(\n \"Original-Recipient: rfc822;{}\\r\\n\\\n Final-Recipient: rfc822;{}\\r\\n\\\n Original-Message-ID: <{}>\\r\\n\\\n Disposition: manual-action/MDN-sent-automatically; displayed\\r\\n\",\n self.from_addr, self.from_addr, self.msg.rfc724_mid\n );\n\n let extension_fields = if additional_msg_ids.is_empty() {\n \"\".to_string()\n } else {\n \"Additional-Message-IDs: \".to_string()\n + &additional_msg_ids\n .iter()\n .map(|mid| render_rfc724_mid(mid))\n .collect::>()\n .join(\" \")\n + \"\\r\\n\"\n };\n\n message = message.child(\n PartBuilder::new()\n .content_type(&\"message/disposition-notification\".parse().unwrap())\n .body(message_text2 + &extension_fields)\n .build(),\n );\n\n Ok(message)\n }\n\npub(crate) fn create_outgoing_rfc724_mid() -> String {\n format!(\"Mr.{}.{}@localhost\", create_id(), create_id())\n}\n\nfn encode_words(word: &str) -> String {\n encoded_words::encode(word, None, encoded_words::EncodingFlag::Shortest, None)\n}\n\nfn render_rfc724_mid(rfc724_mid: &str) -> String {\n let rfc724_mid = rfc724_mid.trim().to_string();\n\n if rfc724_mid.chars().next().unwrap_or_default() == '<' {\n rfc724_mid\n } else {\n format!(\"<{rfc724_mid}>\")\n }\n}\n\npub enum Chattype {\n /// 1:1 chat.\n Single = 100,\n\n /// Group chat.\n Group = 120,\n\n /// Mailing list.\n Mailinglist = 140,\n\n /// Broadcast list.\n Broadcast = 160,\n}\n\npub enum Loaded {\n Message { chat: Chat },\n Mdn { additional_msg_ids: Vec },\n}\n\npub enum SystemMessage {\n /// Unknown type of system message.\n #[default]\n Unknown = 0,\n\n /// Group name changed.\n GroupNameChanged = 2,\n\n /// Group avatar changed.\n GroupImageChanged = 3,\n\n /// Member was added to the group.\n MemberAddedToGroup = 4,\n\n /// Member was removed from the group.\n MemberRemovedFromGroup = 5,\n\n /// Autocrypt Setup Message.\n AutocryptSetupMessage = 6,\n\n /// Secure-join message.\n SecurejoinMessage = 7,\n\n /// Location streaming is enabled.\n LocationStreamingEnabled = 8,\n\n /// Location-only message.\n LocationOnly = 9,\n\n /// Chat ephemeral message timer is changed.\n EphemeralTimerChanged = 10,\n\n /// \"Messages are guaranteed to be end-to-end encrypted from now on.\"\n ChatProtectionEnabled = 11,\n\n /// \"%1$s sent a message from another device.\"\n ChatProtectionDisabled = 12,\n\n /// Message can't be sent because of `Invalid unencrypted mail to <>`\n /// which is sent by chatmail servers.\n InvalidUnencryptedMail = 13,\n\n /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it\n /// to complete.\n SecurejoinWait = 14,\n\n /// 1:1 chats info message telling that SecureJoin is still running, but the user may already\n /// send messages.\n SecurejoinWaitTimeout = 15,\n\n /// Self-sent-message that contains only json used for multi-device-sync;\n /// if possible, we attach that to other messages as for locations.\n MultiDeviceSync = 20,\n\n /// Sync message that contains a json payload\n /// sent to the other webxdc instances\n /// These messages are not shown in the chat.\n WebxdcStatusUpdate = 30,\n\n /// Webxdc info added with `info` set in `send_webxdc_status_update()`.\n WebxdcInfoMessage = 32,\n\n /// This message contains a users iroh node address.\n IrohNodeAddr = 40,\n}\n\npub enum Param {\n /// For messages\n File = b'f',\n\n /// For messages: original filename (as shown in chat)\n Filename = b'v',\n\n /// For messages: This name should be shown instead of contact.get_display_name()\n /// (used if this is a mailinglist\n /// or explicitly set using set_override_sender_name(), eg. by bots)\n OverrideSenderDisplayname = b'O',\n\n /// For Messages\n Width = b'w',\n\n /// For Messages\n Height = b'h',\n\n /// For Messages\n Duration = b'd',\n\n /// For Messages\n MimeType = b'm',\n\n /// For Messages: HTML to be written to the database and to be send.\n /// `SendHtml` param is not used for received messages.\n /// Use `MsgId::get_html()` to get HTML of received messages.\n SendHtml = b'T',\n\n /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send\n GuaranteeE2ee = b'c',\n\n /// For Messages: quoted message is encrypted.\n ///\n /// If this message is sent unencrypted, quote text should be replaced.\n ProtectQuote = b'0',\n\n /// For Messages: decrypted with validation errors or without mutual set, if neither\n /// 'c' nor 'e' are preset, the messages is only transport encrypted.\n ErroneousE2ee = b'e',\n\n /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.\n ForcePlaintext = b'u',\n\n /// For Messages: do not include Autocrypt header.\n SkipAutocrypt = b'o',\n\n /// For Messages\n WantsMdn = b'r',\n\n /// For Messages: the message is a reaction.\n Reaction = b'x',\n\n /// For Chats: the timestamp of the last reaction.\n LastReactionTimestamp = b'y',\n\n /// For Chats: Message ID of the last reaction.\n LastReactionMsgId = b'Y',\n\n /// For Chats: Contact ID of the last reaction.\n LastReactionContactId = b'1',\n\n /// For Messages: a message with \"Auto-Submitted: auto-generated\" header (\"bot\").\n Bot = b'b',\n\n /// For Messages: unset or 0=not forwarded,\n /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id\n Forwarded = b'a',\n\n /// For Messages: quoted text.\n Quote = b'q',\n\n /// For Messages\n Cmd = b'S',\n\n /// For Messages\n Arg = b'E',\n\n /// For Messages\n Arg2 = b'F',\n\n /// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.\n Arg3 = b'G',\n\n /// Deprecated `Secure-Join-Group` header for messages.\n Arg4 = b'H',\n\n /// For Messages\n AttachGroupImage = b'A',\n\n /// For Messages\n WebrtcRoom = b'V',\n\n /// For Messages: space-separated list of messaged IDs of forwarded copies.\n ///\n /// This is used when a [crate::message::Message] is in the\n /// [crate::message::MessageState::OutPending] state but is already forwarded.\n /// In this case the forwarded messages are written to the\n /// database and their message IDs are added to this parameter of\n /// the original message, which is also saved in the database.\n /// When the original message is then finally sent this parameter\n /// is used to also send all the forwarded messages.\n PrepForwards = b'P',\n\n /// For Messages\n SetLatitude = b'l',\n\n /// For Messages\n SetLongitude = b'n',\n\n /// For Groups\n ///\n /// An unpromoted group has not had any messages sent to it and thus only exists on the\n /// creator's device. Any changes made to an unpromoted group do not need to send\n /// system messages to the group members to update them of the changes. Once a message\n /// has been sent to a group it is promoted and group changes require sending system\n /// messages to all members.\n Unpromoted = b'U',\n\n /// For Groups and Contacts\n ProfileImage = b'i',\n\n /// For Chats\n /// Signals whether the chat is the `saved messages` chat\n Selftalk = b'K',\n\n /// For Chats: On sending a new message we set the subject to `Re: `.\n /// Usually we just use the subject of the parent message, but if the parent message\n /// is deleted, we use the LastSubject of the chat.\n LastSubject = b't',\n\n /// For Chats\n Devicetalk = b'D',\n\n /// For Chats: If this is a mailing list chat, contains the List-Post address.\n /// None if there simply is no `List-Post` header in the mailing list.\n /// Some(\"\") if the mailing list is using multiple different List-Post headers.\n ///\n /// The List-Post address is the email address where the user can write to in order to\n /// post something to the mailing list.\n ListPost = b'p',\n\n /// For Contacts: If this is the List-Post address of a mailing list, contains\n /// the List-Id of the mailing list (which is also used as the group id of the chat).\n ListId = b's',\n\n /// For Contacts: timestamp of status (aka signature or footer) update.\n StatusTimestamp = b'j',\n\n /// For Contacts and Chats: timestamp of avatar update.\n AvatarTimestamp = b'J',\n\n /// For Chats: timestamp of status/signature/footer update.\n EphemeralSettingsTimestamp = b'B',\n\n /// For Chats: timestamp of subject update.\n SubjectTimestamp = b'C',\n\n /// For Chats: timestamp of group name update.\n GroupNameTimestamp = b'g',\n\n /// For Chats: timestamp of member list update.\n MemberListTimestamp = b'k',\n\n /// For Webxdc Message Instances: Current document name\n WebxdcDocument = b'R',\n\n /// For Webxdc Message Instances: timestamp of document name update.\n WebxdcDocumentTimestamp = b'W',\n\n /// For Webxdc Message Instances: Current summary\n WebxdcSummary = b'N',\n\n /// For Webxdc Message Instances: timestamp of summary update.\n WebxdcSummaryTimestamp = b'Q',\n\n /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()\n WebxdcIntegration = b'3',\n\n /// For Webxdc Message Instances: Chat to integrate the Webxdc for.\n WebxdcIntegrateFor = b'2',\n\n /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.\n ForceSticker = b'X',\n // 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.\n}", "rust_imports": "use deltachat_contact_tools::ContactAddress;\nuse mailparse::{addrparse_header, MailHeaderMap};\nuse std::str;\nuse super::*;\nuse crate::chat::{\n add_contact_to_chat, create_group_chat, remove_contact_from_chat, send_text_msg, ChatId,\n ProtectionStatus,\n };\nuse crate::chatlist::Chatlist;\nuse crate::constants;\nuse crate::contact::Origin;\nuse crate::mimeparser::MimeMessage;\nuse crate::receive_imf::receive_imf;\nuse crate::test_utils::{get_chat_msg, TestContext, TestContextManager};", "rustrepotrans_file": "projects__deltachat-core__rust__mimefactory__.rs__function__13.txt"} {"c_path": "projects/deltachat-core/c/dc_msg.c", "c_func": "char* dc_msg_get_summarytext_by_raw(int type, const char* text, dc_param_t* param, int approx_characters, dc_context_t* context)\n{\n\t/* get a summary text, result must be free()'d, never returns NULL. */\n\tchar* ret = NULL;\n\tchar* prefix = NULL;\n\tchar* pathNfilename = NULL;\n\tchar* label = NULL;\n\tchar* value = NULL;\n\tint append_text = 1;\n\n\tswitch (type) {\n\t\tcase DC_MSG_IMAGE:\n\t\t\tprefix = dc_stock_str(context, DC_STR_IMAGE);\n\t\t\tbreak;\n\n\t\tcase DC_MSG_GIF:\n\t\t\tprefix = dc_stock_str(context, DC_STR_GIF);\n\t\t\tbreak;\n\n\t\tcase DC_MSG_VIDEO:\n\t\t\tprefix = dc_stock_str(context, DC_STR_VIDEO);\n\t\t\tbreak;\n\n\t\tcase DC_MSG_VOICE:\n\t\t\tprefix = dc_stock_str(context, DC_STR_VOICEMESSAGE);\n\t\t\tbreak;\n\n\t\tcase DC_MSG_AUDIO:\n\t\tcase DC_MSG_FILE:\n\t\t\tif (dc_param_get_int(param, DC_PARAM_CMD, 0)==DC_CMD_AUTOCRYPT_SETUP_MESSAGE) {\n\t\t\t\tprefix = dc_stock_str(context, DC_STR_AC_SETUP_MSG_SUBJECT);\n\t\t\t\tappend_text = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpathNfilename = dc_param_get(param, DC_PARAM_FILE, \"ErrFilename\");\n\t\t\t\tvalue = dc_get_filename(pathNfilename);\n\t\t\t\tlabel = dc_stock_str(context, type==DC_MSG_AUDIO? DC_STR_AUDIO : DC_STR_FILE);\n\t\t\t\tprefix = dc_mprintf(\"%s \" DC_NDASH \" %s\", label, value);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tif (dc_param_get_int(param, DC_PARAM_CMD, 0)==DC_CMD_LOCATION_ONLY) {\n\t\t\t\tprefix = dc_stock_str(context, DC_STR_LOCATION);\n\t\t\t\tappend_text = 0;\n\t\t\t}\n\t\t\tbreak;\n\t}\n\n\tif (append_text && prefix && text && text[0]) {\n\t\tret = dc_mprintf(\"%s \" DC_NDASH \" %s\", prefix, text);\n\t\tdc_truncate_n_unwrap_str(ret, approx_characters, 1/*unwrap*/);\n\t}\n\telse if (append_text && text && text[0]) {\n\t\tret = dc_strdup(text);\n\t\tdc_truncate_n_unwrap_str(ret, approx_characters, 1/*unwrap*/);\n\t}\n\telse {\n\t\tret = prefix;\n\t\tprefix = NULL;\n\t}\n\n\t/* cleanup */\n\tfree(prefix);\n\tfree(pathNfilename);\n\tfree(label);\n\tfree(value);\n\tif (ret==NULL) {\n\t\tret = dc_strdup(NULL);\n\t}\n\treturn ret;\n}", "rust_path": "projects/deltachat-core/rust/summary.rs", "rust_func": "async fn get_summary_text_without_prefix(&self, context: &Context) -> String {\n let (emoji, type_name, type_file, append_text);\n match self.viewtype {\n Viewtype::Image => {\n emoji = Some(\"\ud83d\udcf7\");\n type_name = Some(stock_str::image(context).await);\n type_file = None;\n append_text = true;\n }\n Viewtype::Gif => {\n emoji = None;\n type_name = Some(stock_str::gif(context).await);\n type_file = None;\n append_text = true;\n }\n Viewtype::Sticker => {\n emoji = None;\n type_name = Some(stock_str::sticker(context).await);\n type_file = None;\n append_text = true;\n }\n Viewtype::Video => {\n emoji = Some(\"\ud83c\udfa5\");\n type_name = Some(stock_str::video(context).await);\n type_file = None;\n append_text = true;\n }\n Viewtype::Voice => {\n emoji = Some(\"\ud83c\udfa4\");\n type_name = Some(stock_str::voice_message(context).await);\n type_file = None;\n append_text = true;\n }\n Viewtype::Audio => {\n emoji = Some(\"\ud83c\udfb5\");\n type_name = Some(stock_str::audio(context).await);\n type_file = self.get_filename();\n append_text = true\n }\n Viewtype::File => {\n if self.param.get_cmd() == SystemMessage::AutocryptSetupMessage {\n emoji = None;\n type_name = Some(stock_str::ac_setup_msg_subject(context).await);\n type_file = None;\n append_text = false;\n } else {\n emoji = Some(\"\ud83d\udcce\");\n type_name = Some(stock_str::file(context).await);\n type_file = self.get_filename();\n append_text = true\n }\n }\n Viewtype::VideochatInvitation => {\n emoji = None;\n type_name = Some(stock_str::videochat_invitation(context).await);\n type_file = None;\n append_text = false;\n }\n Viewtype::Webxdc => {\n emoji = None;\n type_name = None;\n type_file = Some(\n self.get_webxdc_info(context)\n .await\n .map(|info| info.name)\n .unwrap_or_else(|_| \"ErrWebxdcName\".to_string()),\n );\n append_text = true;\n }\n Viewtype::Vcard => {\n emoji = Some(\"\ud83d\udc64\");\n type_name = Some(stock_str::contact(context).await);\n type_file = None;\n append_text = true;\n }\n Viewtype::Text | Viewtype::Unknown => {\n emoji = None;\n if self.param.get_cmd() == SystemMessage::LocationOnly {\n type_name = Some(stock_str::location(context).await);\n type_file = None;\n append_text = false;\n } else {\n type_name = None;\n type_file = None;\n append_text = true;\n }\n }\n };\n\n let text = self.text.clone();\n\n let summary = if let Some(type_file) = type_file {\n if append_text && !text.is_empty() {\n format!(\"{type_file} \u2013 {text}\")\n } else {\n type_file\n }\n } else if append_text && !text.is_empty() {\n if emoji.is_some() {\n text\n } else if let Some(type_name) = type_name {\n format!(\"{type_name} \u2013 {text}\")\n } else {\n text\n }\n } else if let Some(type_name) = type_name {\n type_name\n } else {\n \"\".to_string()\n };\n\n let summary = if let Some(emoji) = emoji {\n format!(\"{emoji} {summary}\")\n } else {\n summary\n };\n\n summary.split_whitespace().collect::>().join(\" \")\n }", "rust_context": "pub(crate) async fn voice_message(context: &Context) -> String {\n translated(context, StockMessage::VoiceMessage).await\n}\n\npub(crate) async fn image(context: &Context) -> String {\n translated(context, StockMessage::Image).await\n}\n\npub(crate) async fn video(context: &Context) -> String {\n translated(context, StockMessage::Video).await\n}\n\npub(crate) async fn audio(context: &Context) -> String {\n translated(context, StockMessage::Audio).await\n}\n\npub(crate) async fn file(context: &Context) -> String {\n translated(context, StockMessage::File).await\n}\n\npub(crate) async fn gif(context: &Context) -> String {\n translated(context, StockMessage::Gif).await\n}\n\npub(crate) async fn sticker(context: &Context) -> String {\n translated(context, StockMessage::Sticker).await\n}\n\npub(crate) async fn location(context: &Context) -> String {\n translated(context, StockMessage::Location).await\n}\n\npub(crate) async fn ac_setup_msg_subject(context: &Context) -> String {\n translated(context, StockMessage::AcSetupMsgSubject).await\n}\n\npub(crate) async fn videochat_invitation(context: &Context) -> String {\n translated(context, StockMessage::VideochatInvitation).await\n}\n\npub(crate) async fn contact(context: &Context) -> String {\n translated(context, StockMessage::Contact).await\n}\n\npub fn is_empty(&self) -> bool {\n self.inner.is_empty()\n }\n\npub fn get_cmd(&self) -> SystemMessage {\n self.get_int(Param::Cmd)\n .and_then(SystemMessage::from_i32)\n .unwrap_or_default()\n }\n\npub fn get_filename(&self) -> Option {\n if let Some(name) = self.param.get(Param::Filename) {\n return Some(name.to_string());\n }\n self.param\n .get(Param::File)\n .and_then(|file| Path::new(file).file_name())\n .map(|name| name.to_string_lossy().to_string())\n }\n\npub struct Context {\n pub(crate) inner: Arc,\n}\n\npub struct Message {\n /// Message ID.\n pub(crate) id: MsgId,\n\n /// `From:` contact ID.\n pub(crate) from_id: ContactId,\n\n /// ID of the first contact in the `To:` header.\n pub(crate) to_id: ContactId,\n\n /// ID of the chat message belongs to.\n pub(crate) chat_id: ChatId,\n\n /// Type of the message.\n pub(crate) viewtype: Viewtype,\n\n /// State of the message.\n pub(crate) state: MessageState,\n pub(crate) download_state: DownloadState,\n\n /// Whether the message is hidden.\n pub(crate) hidden: bool,\n pub(crate) timestamp_sort: i64,\n pub(crate) timestamp_sent: i64,\n pub(crate) timestamp_rcvd: i64,\n pub(crate) ephemeral_timer: EphemeralTimer,\n pub(crate) ephemeral_timestamp: i64,\n pub(crate) text: String,\n\n /// Message subject.\n ///\n /// If empty, a default subject will be generated when sending.\n pub(crate) subject: String,\n\n /// `Message-ID` header value.\n pub(crate) rfc724_mid: String,\n\n /// `In-Reply-To` header value.\n pub(crate) in_reply_to: Option,\n pub(crate) is_dc_message: MessengerMessage,\n pub(crate) mime_modified: bool,\n pub(crate) chat_blocked: Blocked,\n pub(crate) location_id: u32,\n pub(crate) error: Option,\n pub(crate) param: Params,\n}\n\npub enum Viewtype {\n /// Unknown message type.\n #[default]\n Unknown = 0,\n\n /// Text message.\n /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().\n Text = 10,\n\n /// Image message.\n /// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to\n /// `Gif` when sending the message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension\n /// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().\n Image = 20,\n\n /// Animated GIF message.\n /// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().\n Gif = 21,\n\n /// Message containing a sticker, similar to image.\n /// If possible, the ui should display the image without borders in a transparent way.\n /// A click on a sticker will offer to install the sticker set in some future.\n Sticker = 23,\n\n /// Message containing an Audio file.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration().\n Audio = 40,\n\n /// A voice message that was directly recorded by the user.\n /// For all other audio messages, the type #DC_MSG_AUDIO should be used.\n /// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()\n /// and retrieved via dc_msg_get_file(), dc_msg_get_duration()\n Voice = 41,\n\n /// Video messages.\n /// File, width, height and durarion\n /// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()\n /// and retrieved via\n /// dc_msg_get_file(), dc_msg_get_width(),\n /// dc_msg_get_height(), dc_msg_get_duration().\n Video = 50,\n\n /// Message containing any file, eg. a PDF.\n /// The file is set via dc_msg_set_file()\n /// and retrieved via dc_msg_get_file().\n File = 60,\n\n /// Message is an invitation to a videochat.\n VideochatInvitation = 70,\n\n /// Message is an webxdc instance.\n Webxdc = 80,\n\n /// Message containing shared contacts represented as a vCard (virtual contact file)\n /// with email addresses and possibly other fields.\n /// Use `parse_vcard()` to retrieve them.\n Vcard = 90,\n}", "rust_imports": "use std::borrow::Cow;\nuse std::fmt;\nuse std::str;\nuse crate::chat::Chat;\nuse crate::constants::Chattype;\nuse crate::contact::{Contact, ContactId};\nuse crate::context::Context;\nuse crate::message::{Message, MessageState, Viewtype};\nuse crate::mimeparser::SystemMessage;\nuse crate::stock_str;\nuse crate::stock_str::msg_reacted;\nuse crate::tools::truncate;\nuse anyhow::Result;\nuse super::*;\nuse crate::param::Param;\nuse crate::test_utils as test;", "rustrepotrans_file": "projects__deltachat-core__rust__summary__.rs__function__6.txt"}