diff --git a/Cargo.lock b/Cargo.lock index df00a1903..a3688efe6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3306,6 +3306,7 @@ dependencies = [ "mio", "num_cpus", "once_cell", + "parking_lot", "pin-project-lite", "socket2", "tokio-macros", diff --git a/Cargo.toml b/Cargo.toml index 139735bc3..beffe3da5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -89,6 +89,7 @@ log = "0.4" pretty_env_logger = "0.4" proptest = { version = "1", default-features = false, features = ["std"] } tempfile = "3" +tokio = { version = "1", features = ["parking_lot", "rt-multi-thread", "macros"] } [workspace] members = [ diff --git a/benches/receive_emails.rs b/benches/receive_emails.rs index 4fde0c80c..e51509556 100644 --- a/benches/receive_emails.rs +++ b/benches/receive_emails.rs @@ -4,8 +4,8 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion}; use deltachat::{ config::Config, context::Context, - dc_receive_imf::dc_receive_imf, imex::{imex, ImexMode}, + receive_imf::receive_imf, Events, }; use tempfile::tempdir; @@ -30,7 +30,7 @@ Hello {i}", i = i, i_dec = i - 1, ); - dc_receive_imf(&context, black_box(imf_raw.as_bytes()), false) + receive_imf(&context, black_box(imf_raw.as_bytes()), false) .await .unwrap(); } diff --git a/deltachat-ffi/build.rs b/deltachat-ffi/build.rs index 701ed7d74..f771f4f98 100644 --- a/deltachat-ffi/build.rs +++ b/deltachat-ffi/build.rs @@ -1,4 +1,3 @@ -use std::io::Write; use std::path::PathBuf; use std::{env, fs}; @@ -28,8 +27,9 @@ fn main() { ); fs::create_dir_all(target_path.join("pkgconfig")).unwrap(); - fs::File::create(target_path.join("pkgconfig").join("deltachat.pc")) - .unwrap() - .write_all(pkg_config.as_bytes()) - .unwrap(); + fs::write( + target_path.join("pkgconfig").join("deltachat.pc"), + pkg_config.as_bytes(), + ) + .unwrap(); } diff --git a/deltachat-ffi/src/lib.rs b/deltachat-ffi/src/lib.rs index c429aeed3..7b16e6af9 100644 --- a/deltachat-ffi/src/lib.rs +++ b/deltachat-ffi/src/lib.rs @@ -395,7 +395,7 @@ pub unsafe extern "C" fn dc_get_oauth2_url( let redirect = to_string_lossy(redirect); block_on(async move { - match oauth2::dc_get_oauth2_url(ctx, &addr, &redirect) + match oauth2::get_oauth2_url(ctx, &addr, &redirect) .await .log_err(ctx, "dc_get_oauth2_url failed") { @@ -739,7 +739,7 @@ pub unsafe extern "C" fn dc_preconfigure_keypair( } let ctx = &*context; block_on(async move { - let addr = dc_tools::EmailAddress::new(&to_string_lossy(addr))?; + let addr = tools::EmailAddress::new(&to_string_lossy(addr))?; let public = key::SignedPublicKey::from_asc(&to_string_lossy(public_data))?.0; let secret = key::SignedSecretKey::from_asc(&to_string_lossy(secret_data))?.0; let keypair = key::KeyPair { @@ -2244,7 +2244,7 @@ pub unsafe extern "C" fn dc_get_securejoin_qr( Some(ChatId::new(chat_id)) }; - block_on(securejoin::dc_get_securejoin_qr(ctx, chat_id)) + block_on(securejoin::get_securejoin_qr(ctx, chat_id)) .unwrap_or_else(|_| "".to_string()) .strdup() } @@ -2282,7 +2282,7 @@ pub unsafe extern "C" fn dc_join_securejoin( let ctx = &*context; block_on(async move { - securejoin::dc_join_securejoin(ctx, &to_string_lossy(qr)) + securejoin::join_securejoin(ctx, &to_string_lossy(qr)) .await .map(|chatid| chatid.to_u32()) .log_err(ctx, "failed dc_join_securejoin() call") diff --git a/deltachat-ffi/src/string.rs b/deltachat-ffi/src/string.rs index 00d1518ee..65c091108 100644 --- a/deltachat-ffi/src/string.rs +++ b/deltachat-ffi/src/string.rs @@ -55,7 +55,7 @@ pub(crate) enum CStringError { /// # Example /// /// ``` -/// use deltachat::dc_tools::{dc_strdup, OsStrExt}; +/// use deltachat::tools::{dc_strdup, OsStrExt}; /// let path = std::path::Path::new("/some/path"); /// let path_c = path.to_c_string().unwrap(); /// unsafe { diff --git a/examples/repl/cmdline.rs b/examples/repl/cmdline.rs index 341e97f07..aaff0ba66 100644 --- a/examples/repl/cmdline.rs +++ b/examples/repl/cmdline.rs @@ -12,8 +12,6 @@ use deltachat::chatlist::*; use deltachat::constants::*; use deltachat::contact::*; use deltachat::context::*; -use deltachat::dc_receive_imf::*; -use deltachat::dc_tools::*; use deltachat::download::DownloadState; use deltachat::imex::*; use deltachat::location; @@ -21,7 +19,9 @@ use deltachat::log::LogExt; use deltachat::message::{self, Message, MessageState, MsgId, Viewtype}; use deltachat::peerstate::*; use deltachat::qr::*; +use deltachat::receive_imf::*; use deltachat::sql; +use deltachat::tools::*; use deltachat::{config, provider}; use tokio::fs; @@ -96,10 +96,10 @@ async fn reset_tables(context: &Context, bits: i32) { } async fn poke_eml_file(context: &Context, filename: impl AsRef) -> Result<()> { - let data = dc_read_file(context, filename).await?; + let data = read_file(context, filename).await?; - if let Err(err) = dc_receive_imf(context, &data, false).await { - println!("dc_receive_imf errored: {:?}", err); + if let Err(err) = receive_imf(context, &data, false).await { + println!("receive_imf errored: {:?}", err); } Ok(()) } @@ -128,7 +128,7 @@ async fn poke_spec(context: &Context, spec: Option<&str>) -> bool { } real_spec = rs.unwrap(); } - if let Some(suffix) = dc_get_filesuffix_lc(&real_spec) { + if let Some(suffix) = get_filesuffix_lc(&real_spec) { if suffix == "eml" && poke_eml_file(context, &real_spec).await.is_ok() { read_cnt += 1 } @@ -187,7 +187,7 @@ async fn log_msg(context: &Context, prefix: impl AsRef, msg: &Message) { DownloadState::Failure => " [⬇ Download failed]", }; - let temp2 = dc_timestamp_to_str(msg.get_timestamp()); + let temp2 = timestamp_to_str(msg.get_timestamp()); let msgtext = msg.get_text(); println!( "{}{}{}{}: {} (Contact#{}): {} {}{}{}{}{}{}{} [{}]", @@ -593,7 +593,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu _ => "", } }; - let timestr = dc_timestamp_to_str(summary.timestamp); + let timestr = timestamp_to_str(summary.timestamp); println!( "{}{}{} [{}]{}", summary @@ -806,7 +806,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu println!( "Loc#{}: {}: lat={} lng={} acc={} Chat#{} Contact#{} {} {}", location.location_id, - dc_timestamp_to_str(location.timestamp), + timestamp_to_str(location.timestamp), location.latitude, location.longitude, location.accuracy, @@ -1229,8 +1229,8 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu "fileinfo" => { ensure!(!arg1.is_empty(), "Argument missing."); - if let Ok(buf) = dc_read_file(&context, &arg1).await { - let (width, height) = dc_get_filemeta(&buf)?; + if let Ok(buf) = read_file(&context, &arg1).await { + let (width, height) = get_filemeta(&buf)?; println!("width={}, height={}", width, height); } else { bail!("Command failed."); diff --git a/examples/repl/main.rs b/examples/repl/main.rs index 4c0041894..1c35fe181 100644 --- a/examples/repl/main.rs +++ b/examples/repl/main.rs @@ -409,7 +409,7 @@ async fn handle_cmd( "oauth2" => { if let Some(addr) = ctx.get_config(config::Config::Addr).await? { let oauth2_url = - dc_get_oauth2_url(&ctx, &addr, "chat.delta:/com.b44t.messenger").await?; + get_oauth2_url(&ctx, &addr, "chat.delta:/com.b44t.messenger").await?; if oauth2_url.is_none() { println!("OAuth2 not available for {}.", &addr); } else { @@ -426,7 +426,7 @@ async fn handle_cmd( "getqr" | "getbadqr" => { ctx.start_io().await; let group = arg1.parse::().ok().map(ChatId::new); - let mut qr = dc_get_securejoin_qr(&ctx, group).await?; + let mut qr = get_securejoin_qr(&ctx, group).await?; if !qr.is_empty() { if arg0 == "getbadqr" && qr.len() > 40 { qr.replace_range(12..22, "0000000000") @@ -457,7 +457,7 @@ async fn handle_cmd( "joinqr" => { ctx.start_io().await; if !arg0.is_empty() { - dc_join_securejoin(&ctx, arg1).await?; + join_securejoin(&ctx, arg1).await?; } } "exit" | "quit" => return Ok(ExitResult::Exit), diff --git a/src/blob.rs b/src/blob.rs index 5d1cc5bd0..62717a619 100644 --- a/src/blob.rs +++ b/src/blob.rs @@ -724,19 +724,14 @@ mod tests { let t = TestContext::new().await; let avatar_src = t.dir.path().join("avatar.jpg"); let avatar_bytes = include_bytes!("../test-data/image/avatar1000x1000.jpg"); - File::create(&avatar_src) - .await - .unwrap() - .write_all(avatar_bytes) - .await - .unwrap(); + fs::write(&avatar_src, avatar_bytes).await.unwrap(); let avatar_blob = t.get_blobdir().join("avatar.jpg"); assert!(!avatar_blob.exists()); t.set_config(Config::Selfavatar, Some(avatar_src.to_str().unwrap())) .await .unwrap(); assert!(avatar_blob.exists()); - assert!(tokio::fs::metadata(&avatar_blob).await.unwrap().len() < avatar_bytes.len() as u64); + assert!(fs::metadata(&avatar_blob).await.unwrap().len() < avatar_bytes.len() as u64); let avatar_cfg = t.get_config(Config::Selfavatar).await.unwrap(); assert_eq!(avatar_cfg, avatar_blob.to_str().map(|s| s.to_string())); @@ -766,10 +761,7 @@ mod tests { async fn test_selfavatar_in_blobdir() { let t = TestContext::new().await; let avatar_src = t.get_blobdir().join("avatar.png"); - File::create(&avatar_src) - .await - .unwrap() - .write_all(test_utils::AVATAR_900x900_BYTES) + fs::write(&avatar_src, test_utils::AVATAR_900x900_BYTES) .await .unwrap(); @@ -792,12 +784,7 @@ mod tests { let t = TestContext::new().await; let avatar_src = t.dir.path().join("avatar.png"); let avatar_bytes = include_bytes!("../test-data/image/avatar64x64.png"); - File::create(&avatar_src) - .await - .unwrap() - .write_all(avatar_bytes) - .await - .unwrap(); + fs::write(&avatar_src, avatar_bytes).await.unwrap(); let avatar_blob = t.get_blobdir().join("avatar.png"); assert!(!avatar_blob.exists()); t.set_config(Config::Selfavatar, Some(avatar_src.to_str().unwrap())) @@ -805,7 +792,7 @@ mod tests { .unwrap(); assert!(avatar_blob.exists()); assert_eq!( - tokio::fs::metadata(&avatar_blob).await.unwrap().len(), + fs::metadata(&avatar_blob).await.unwrap().len(), avatar_bytes.len() as u64 ); let avatar_cfg = t.get_config(Config::Selfavatar).await.unwrap(); @@ -976,7 +963,7 @@ mod tests { let chat_id = create_group_chat(&t, ProtectionStatus::Unprotected, "abc").await?; let file = t.get_blobdir().join("anyfile.dat"); - File::create(&file).await?.write_all("bla".as_ref()).await?; + fs::write(&file, b"bla").await?; let mut msg = Message::new(Viewtype::File); msg.set_file(file.to_str().unwrap(), None); let prepared_id = chat::prepare_msg(&t, chat_id, &mut msg).await?; @@ -996,7 +983,7 @@ mod tests { assert_ne!(t.get_blobdir().to_str(), t.dir.path().to_str()); let file = t.dir.path().join("anyfile.dat"); - File::create(&file).await?.write_all("bla".as_ref()).await?; + fs::write(&file, b"bla").await?; let mut msg = Message::new(Viewtype::File); msg.set_file(file.to_str().unwrap(), None); assert!(chat::prepare_msg(&t, chat_id, &mut msg).await.is_err()); diff --git a/src/chat.rs b/src/chat.rs index 52d8d871a..9262d3c06 100644 --- a/src/chat.rs +++ b/src/chat.rs @@ -20,12 +20,6 @@ use crate::constants::{ }; use crate::contact::{Contact, ContactId, Origin, VerifiedStatus}; use crate::context::Context; -use crate::dc_receive_imf::ReceivedMsg; -use crate::dc_tools::{ - dc_create_id, dc_create_outgoing_rfc724_mid, dc_create_smeared_timestamp, - dc_create_smeared_timestamps, dc_get_abs_path, dc_gm2local_offset, improve_single_line_input, - time, IsNoneOrEmpty, -}; use crate::ephemeral::Timer as EphemeralTimer; use crate::events::EventType; use crate::html::new_html_mimepart; @@ -34,9 +28,14 @@ use crate::mimefactory::MimeFactory; use crate::mimeparser::SystemMessage; use crate::param::{Param, Params}; use crate::peerstate::{Peerstate, PeerstateVerifiedStatus}; +use crate::receive_imf::ReceivedMsg; use crate::scheduler::InterruptInfo; use crate::smtp::send_msg_to_smtp; use crate::stock_str; +use crate::tools::{ + create_id, create_outgoing_rfc724_mid, create_smeared_timestamp, create_smeared_timestamps, + get_abs_path, gm2local_offset, improve_single_line_input, time, IsNoneOrEmpty, +}; use crate::webxdc::WEBXDC_SUFFIX; use crate::{location, sql}; @@ -233,7 +232,7 @@ impl ChatId { grpname, grpid, create_blocked, - dc_create_smeared_timestamp(context).await, + create_smeared_timestamp(context).await, create_protected, param.unwrap_or_default(), ], @@ -435,7 +434,7 @@ impl ChatId { self, &msg_text, cmd, - dc_create_smeared_timestamp(context).await, + create_smeared_timestamp(context).await, None, None, None, @@ -1134,7 +1133,7 @@ impl Chat { pub async fn get_profile_image(&self, context: &Context) -> Result> { if let Some(image_rel) = self.param.get(Param::ProfileImage) { if !image_rel.is_empty() { - return Ok(Some(dc_get_abs_path(context, image_rel))); + return Ok(Some(get_abs_path(context, image_rel))); } } else if self.typ == Chattype::Single { let contacts = get_chat_contacts(context, self.id).await?; @@ -1145,7 +1144,7 @@ impl Chat { } } else if self.typ == Chattype::Broadcast { if let Ok(image_rel) = get_broadcast_icon(context).await { - return Ok(Some(dc_get_abs_path(context, image_rel))); + return Ok(Some(get_abs_path(context, image_rel))); } } Ok(None) @@ -1271,7 +1270,7 @@ impl Chat { Chattype::Group => Some(self.grpid.as_str()), _ => None, }; - dc_create_outgoing_rfc724_mid(grpid, &from) + create_outgoing_rfc724_mid(grpid, &from) }; if self.typ == Chattype::Single { @@ -1748,7 +1747,7 @@ impl ChatIdBlocked { _ => (), } - let created_timestamp = dc_create_smeared_timestamp(context).await; + let created_timestamp = create_smeared_timestamp(context).await; let chat_id = context .sql .transaction(move |transaction| { @@ -1901,7 +1900,7 @@ async fn prepare_msg_common( context, msg, update_msg_id, - dc_create_smeared_timestamp(context).await, + create_smeared_timestamp(context).await, ) .await?; msg.chat_id = chat_id; @@ -1995,7 +1994,7 @@ async fn prepare_send_msg( chat_id: ChatId, msg: &mut Message, ) -> Result> { - // dc_prepare_msg() leaves the message state to OutPreparing, we + // prepare_msg() leaves the message state to OutPreparing, we // only have to change the state to OutPending in this case. // Otherwise we still have to prepare the message, which will set // the state to OutPending. @@ -2179,7 +2178,7 @@ pub async fn send_videochat_invitation(context: &Context, chat_id: ChatId) -> Re bail!("webrtc_instance not set"); }; - let instance = Message::create_webrtc_instance(&instance, &dc_create_id()); + let instance = Message::create_webrtc_instance(&instance, &create_id()); let mut msg = Message::new(Viewtype::VideochatInvitation); msg.param.set(Param::WebrtcRoom, &instance); @@ -2242,7 +2241,7 @@ pub async fn get_chat_msgs( let mut ret = Vec::new(); let mut last_day = 0; - let cnv_to_local = dc_gm2local_offset(); + let cnv_to_local = gm2local_offset(); for (ts, curr_id) in sorted_rows { if (flags & DC_GCM_ADDDAYMARKER) != 0 { @@ -2538,7 +2537,7 @@ pub async fn create_group_chat( let chat_name = improve_single_line_input(chat_name); ensure!(!chat_name.is_empty(), "Invalid chat name"); - let grpid = dc_create_id(); + let grpid = create_id(); let row_id = context .sql @@ -2550,7 +2549,7 @@ pub async fn create_group_chat( Chattype::Group, chat_name, grpid, - dc_create_smeared_timestamp(context).await, + create_smeared_timestamp(context).await, ], ) .await?; @@ -2597,7 +2596,7 @@ async fn find_unused_broadcast_list_name(context: &Context) -> Result { /// Creates a new broadcast list. pub async fn create_broadcast_list(context: &Context) -> Result { let chat_name = find_unused_broadcast_list_name(context).await?; - let grpid = dc_create_id(); + let grpid = create_id(); let row_id = context .sql .insert( @@ -2608,7 +2607,7 @@ pub async fn create_broadcast_list(context: &Context) -> Result { Chattype::Broadcast, chat_name, grpid, - dc_create_smeared_timestamp(context).await, + create_smeared_timestamp(context).await, ], ) .await?; @@ -3049,7 +3048,7 @@ pub async fn forward_msgs(context: &Context, msg_ids: &[MsgId], chat_id: ChatId) chat_id.unarchive_if_not_muted(context).await?; if let Ok(mut chat) = Chat::load_from_db(context, chat_id).await { ensure!(chat.can_send(context).await?, "cannot send to {}", chat_id); - curr_timestamp = dc_create_smeared_timestamps(context, msg_ids.len()).await; + curr_timestamp = create_smeared_timestamps(context, msg_ids.len()).await; let ids = context .sql .query_map( @@ -3244,12 +3243,12 @@ pub async fn add_device_msg_with_importance( if let Some(msg) = msg { chat_id = ChatId::get_for_contact(context, ContactId::DEVICE).await?; - let rfc724_mid = dc_create_outgoing_rfc724_mid(None, "@device"); + let rfc724_mid = create_outgoing_rfc724_mid(None, "@device"); msg.try_calc_and_set_dimensions(context).await.ok(); prepare_msg_blob(context, msg).await?; chat_id.unarchive_if_not_muted(context).await?; - let timestamp_sent = dc_create_smeared_timestamp(context).await; + let timestamp_sent = create_smeared_timestamp(context).await; // makes sure, the added message is the last one, // even if the date is wrong (useful esp. when warning about bad dates) @@ -3382,7 +3381,7 @@ pub(crate) async fn add_info_msg_with_cmd( parent: Option<&Message>, from_id: Option, ) -> Result { - let rfc724_mid = dc_create_outgoing_rfc724_mid(None, "@device"); + let rfc724_mid = create_outgoing_rfc724_mid(None, "@device"); let ephemeral_timer = chat_id.get_ephemeral_timer(context).await?; let mut param = Params::new(); @@ -3459,13 +3458,11 @@ pub(crate) async fn update_msg_text_and_timestamp( mod tests { use super::*; - use crate::chatlist::{dc_get_archived_cnt, Chatlist}; + use crate::chatlist::{get_archived_cnt, Chatlist}; use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS}; use crate::contact::Contact; - use crate::dc_receive_imf::dc_receive_imf; + use crate::receive_imf::receive_imf; use crate::test_utils::TestContext; - use tokio::fs::File; - use tokio::io::AsyncWriteExt; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_chat_info() { @@ -4246,7 +4243,7 @@ mod tests { let t = TestContext::new_alice().await; async fn msg_from_bob(t: &TestContext, num: u32) -> Result<()> { - dc_receive_imf( + receive_imf( t, format!( "From: bob@example.net\n\ @@ -4269,17 +4266,17 @@ mod tests { let chat_id = t.get_last_msg().await.get_chat_id(); chat_id.accept(&t).await?; chat_id.set_visibility(&t, ChatVisibility::Archived).await?; - assert_eq!(dc_get_archived_cnt(&t).await?, 1); + assert_eq!(get_archived_cnt(&t).await?, 1); // not muted chat is unarchived on receiving a message msg_from_bob(&t, 2).await?; - assert_eq!(dc_get_archived_cnt(&t).await?, 0); + assert_eq!(get_archived_cnt(&t).await?, 0); // forever muted chat is not unarchived on receiving a message chat_id.set_visibility(&t, ChatVisibility::Archived).await?; set_muted(&t, chat_id, MuteDuration::Forever).await?; msg_from_bob(&t, 3).await?; - assert_eq!(dc_get_archived_cnt(&t).await?, 1); + assert_eq!(get_archived_cnt(&t).await?, 1); // otherwise muted chat is not unarchived on receiving a message set_muted( @@ -4293,7 +4290,7 @@ mod tests { ) .await?; msg_from_bob(&t, 4).await?; - assert_eq!(dc_get_archived_cnt(&t).await?, 1); + assert_eq!(get_archived_cnt(&t).await?, 1); // expired mute will unarchive the chat set_muted( @@ -4307,19 +4304,19 @@ mod tests { ) .await?; msg_from_bob(&t, 5).await?; - assert_eq!(dc_get_archived_cnt(&t).await?, 0); + assert_eq!(get_archived_cnt(&t).await?, 0); // no unarchiving on sending to muted chat or on adding info messages to muted chat chat_id.set_visibility(&t, ChatVisibility::Archived).await?; set_muted(&t, chat_id, MuteDuration::Forever).await?; send_text_msg(&t, chat_id, "out".to_string()).await?; add_info_msg(&t, chat_id, "info", time()).await?; - assert_eq!(dc_get_archived_cnt(&t).await?, 1); + assert_eq!(get_archived_cnt(&t).await?, 1); // finally, unarchive on sending to not muted chat set_muted(&t, chat_id, MuteDuration::NotMuted).await?; send_text_msg(&t, chat_id, "out2".to_string()).await?; - assert_eq!(dc_get_archived_cnt(&t).await?, 0); + assert_eq!(get_archived_cnt(&t).await?, 0); Ok(()) } @@ -4706,7 +4703,7 @@ mod tests { assert_eq!(msg.match_indices("Gr.").count(), 1); // Bob receives this message, he may detect group by `References:`- or `Chat-Group:`-header - dc_receive_imf(&bob, msg.as_bytes(), false).await.unwrap(); + receive_imf(&bob, msg.as_bytes(), false).await.unwrap(); let msg = bob.get_last_msg().await; let bob_chat = Chat::load_from_db(&bob, msg.chat_id).await?; @@ -4725,7 +4722,7 @@ mod tests { assert_eq!(msg.match_indices("Chat-").count(), 0); // Alice receives this message - she can still detect the group by the `References:`-header - dc_receive_imf(&alice, msg.as_bytes(), false).await.unwrap(); + receive_imf(&alice, msg.as_bytes(), false).await.unwrap(); let msg = alice.get_last_msg().await; assert_eq!(msg.chat_id, alice_chat_id); assert_eq!(msg.text, Some("ho!".to_string())); @@ -4738,7 +4735,7 @@ mod tests { let t = TestContext::new_alice().await; let chat = t.create_chat_with_contact("bob", "bob@example.org").await; - dc_receive_imf( + receive_imf( &t, b"From: bob@example.org\n\ To: alice@example.org\n\ @@ -4785,7 +4782,7 @@ mod tests { let chats = Chatlist::try_load(&t, 0, None, None).await?; assert_eq!(chats.len(), 0); - dc_receive_imf( + receive_imf( &t, b"From: bob@example.org\n\ To: alice@example.org\n\ @@ -4832,7 +4829,7 @@ mod tests { async fn test_contact_request_archive() -> Result<()> { let t = TestContext::new_alice().await; - dc_receive_imf( + receive_imf( &t, b"From: bob@example.org\n\ To: alice@example.org\n\ @@ -4849,7 +4846,7 @@ mod tests { assert_eq!(chats.len(), 1); let chat_id = chats.get_chat_id(0)?; assert!(Chat::load_from_db(&t, chat_id).await?.is_contact_request()); - assert_eq!(dc_get_archived_cnt(&t).await?, 0); + assert_eq!(get_archived_cnt(&t).await?, 0); // archive request without accepting or blocking chat_id.set_visibility(&t, ChatVisibility::Archived).await?; @@ -4858,7 +4855,7 @@ mod tests { assert_eq!(chats.len(), 1); let chat_id = chats.get_chat_id(0)?; assert!(chat_id.is_archived_link()); - assert_eq!(dc_get_archived_cnt(&t).await?, 1); + assert_eq!(get_archived_cnt(&t).await?, 1); let chats = Chatlist::try_load(&t, DC_GCL_ARCHIVED_ONLY, None, None).await?; assert_eq!(chats.len(), 1); @@ -4879,7 +4876,7 @@ mod tests { .unwrap(); // Alice receives a classic (non-chat) message from Bob. - dc_receive_imf( + receive_imf( &alice, b"From: bob@example.org\n\ To: alice@example.org\n\ @@ -4936,7 +4933,7 @@ mod tests { let bob_chat = bob.create_chat(&alice).await; let file = alice.get_blobdir().join(filename); - File::create(&file).await?.write_all(bytes).await?; + tokio::fs::write(&file, bytes).await?; let mut msg = Message::new(Viewtype::Sticker); msg.set_file(file.to_str().unwrap(), None); @@ -5001,7 +4998,7 @@ mod tests { let file_name = "sticker.jpg"; let bytes = include_bytes!("../test-data/image/avatar1000x1000.jpg"); let file = alice.get_blobdir().join(file_name); - File::create(&file).await?.write_all(bytes).await?; + tokio::fs::write(&file, bytes).await?; let mut msg = Message::new(Viewtype::Sticker); msg.set_file(file.to_str().unwrap(), None); diff --git a/src/chatlist.rs b/src/chatlist.rs index ed3e650bc..8482213f2 100644 --- a/src/chatlist.rs +++ b/src/chatlist.rs @@ -240,7 +240,7 @@ impl Chatlist { ids }; - if add_archived_link_item && dc_get_archived_cnt(context).await? > 0 { + if add_archived_link_item && get_archived_cnt(context).await? > 0 { if ids.is_empty() && flag_add_alldone_hint { ids.push((DC_CHAT_ID_ALLDONE_HINT, None)); } @@ -355,7 +355,7 @@ impl Chatlist { } /// Returns the number of archived chats -pub async fn dc_get_archived_cnt(context: &Context) -> Result { +pub async fn get_archived_cnt(context: &Context) -> Result { let count = context .sql .count( @@ -371,8 +371,8 @@ mod tests { use super::*; use crate::chat::{create_group_chat, get_chat_contacts, ProtectionStatus}; - use crate::dc_receive_imf::dc_receive_imf; use crate::message::Viewtype; + use crate::receive_imf::receive_imf; use crate::stock_str::StockMessage; use crate::test_utils::TestContext; @@ -493,7 +493,7 @@ mod tests { let t = TestContext::new_alice().await; // receive a one-to-one-message - dc_receive_imf( + receive_imf( &t, b"From: Bob Authname \n\ To: alice@example.org\n\ @@ -553,7 +553,7 @@ mod tests { let t = TestContext::new_alice().await; // receive a one-to-one-message without authname set - dc_receive_imf( + receive_imf( &t, b"From: bob@example.org\n\ To: alice@example.org\n\ diff --git a/src/config.rs b/src/config.rs index 231069b6a..4a38463e5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,10 +8,10 @@ use crate::blob::BlobObject; use crate::constants::DC_VERSION_STR; use crate::contact::addr_cmp; use crate::context::Context; -use crate::dc_tools::{dc_get_abs_path, improve_single_line_input, EmailAddress}; use crate::events::EventType; use crate::mimefactory::RECOMMENDED_FILE_SIZE; use crate::provider::{get_provider_by_id, Provider}; +use crate::tools::{get_abs_path, improve_single_line_input, EmailAddress}; /// The available configuration keys. #[derive( @@ -196,7 +196,7 @@ impl Context { let value = match key { Config::Selfavatar => { let rel_path = self.sql.get_raw_config(key).await?; - rel_path.map(|p| dc_get_abs_path(self, &p).to_string_lossy().into_owned()) + rel_path.map(|p| get_abs_path(self, &p).to_string_lossy().into_owned()) } Config::SysVersion => Some((&*DC_VERSION_STR).clone()), Config::SysMsgsizeMaxRecommended => Some(format!("{}", RECOMMENDED_FILE_SIZE)), @@ -437,7 +437,7 @@ mod tests { use std::string::ToString; use crate::constants; - use crate::dc_receive_imf::dc_receive_imf; + use crate::receive_imf::receive_imf; use crate::test_utils::TestContext; use crate::test_utils::TestContextManager; use num_traits::FromPrimitive; @@ -597,7 +597,7 @@ mod tests { // it's still assigned to the 1:1 chat with Bob and not to // a group (without secondary addresses, an ad-hoc group // would be created) - dc_receive_imf( + receive_imf( &alice, b"From: bob@example.net To: alice@example.org diff --git a/src/configure.rs b/src/configure.rs index a81122509..a44028521 100644 --- a/src/configure.rs +++ b/src/configure.rs @@ -13,16 +13,16 @@ use tokio::task; use crate::config::Config; use crate::context::Context; -use crate::dc_tools::{time, EmailAddress}; use crate::imap::Imap; use crate::job; use crate::login_param::{CertificateChecks, LoginParam, ServerLoginParam, Socks5Config}; use crate::message::{Message, Viewtype}; -use crate::oauth2::dc_get_oauth2_addr; +use crate::oauth2::get_oauth2_addr; use crate::provider::{Protocol, Socket, UsernamePattern}; use crate::scheduler::InterruptInfo; use crate::smtp::Smtp; use crate::stock_str; +use crate::tools::{time, EmailAddress}; use crate::{chat, e2ee, provider}; use auto_mozilla::moz_autoconfigure; @@ -154,9 +154,9 @@ async fn configure(ctx: &Context, param: &mut LoginParam) -> Result<()> { // IMAP and SMTP or not at all. if param.imap.oauth2 && !socks5_enabled { // the used oauth2 addr may differ, check this. - // if dc_get_oauth2_addr() is not available in the oauth2 implementation, just use the given one. + // if get_oauth2_addr() is not available in the oauth2 implementation, just use the given one. progress!(ctx, 10); - if let Some(oauth2_addr) = dc_get_oauth2_addr(ctx, ¶m.addr, ¶m.imap.password) + if let Some(oauth2_addr) = get_oauth2_addr(ctx, ¶m.addr, ¶m.imap.password) .await? .and_then(|e| e.parse().ok()) { diff --git a/src/contact.rs b/src/contact.rs index eaa0d803a..05a09a30d 100644 --- a/src/contact.rs +++ b/src/contact.rs @@ -16,7 +16,6 @@ use crate::color::str_to_color; use crate::config::Config; use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY}; use crate::context::Context; -use crate::dc_tools::{dc_get_abs_path, improve_single_line_input, EmailAddress}; use crate::events::EventType; use crate::key::{DcKey, SignedPublicKey}; use crate::login_param::LoginParam; @@ -25,6 +24,7 @@ use crate::mimeparser::AvatarAction; use crate::param::{Param, Params}; use crate::peerstate::{Peerstate, PeerstateVerifiedStatus}; use crate::sql::{self, params_iter}; +use crate::tools::{get_abs_path, improve_single_line_input, EmailAddress}; use crate::{chat, stock_str}; /// Contact ID, including reserved IDs. @@ -38,7 +38,7 @@ impl ContactId { pub const UNDEFINED: ContactId = ContactId::new(0); /// The owner of the account. /// - /// The email-address is set by `dc_set_config` using "addr". + /// The email-address is set by `set_config` using "addr". pub const SELF: ContactId = ContactId::new(1); pub const INFO: ContactId = ContactId::new(2); pub const DEVICE: ContactId = ContactId::new(5); @@ -142,7 +142,7 @@ pub struct Contact { /// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field. addr: String, - /// Blocked state. Use dc_contact_is_blocked to access this field. + /// Blocked state. Use contact_is_blocked to access this field. pub blocked: bool, /// Time when the contact was seen last time, Unix time in seconds. @@ -212,13 +212,13 @@ pub enum Origin { /// address is in our address book AddressBook = 0x80000, - /// set on Alice's side for contacts like Bob that have scanned the QR code offered by her. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling dc_contact_is_verified() ! + /// set on Alice's side for contacts like Bob that have scanned the QR code offered by her. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling contact_is_verified() ! SecurejoinInvited = 0x0100_0000, - /// set on Bob's side for contacts scanned and verified from a QR code. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling dc_contact_is_verified() ! + /// set on Bob's side for contacts scanned and verified from a QR code. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling contact_is_verified() ! SecurejoinJoined = 0x0200_0000, - /// contact added mannually by dc_create_contact(), this should be the largest origin as otherwise the user cannot modify the names + /// contact added mannually by create_contact(), this should be the largest origin as otherwise the user cannot modify the names ManuallyCreated = 0x0400_0000, } @@ -344,7 +344,7 @@ impl Contact { /// We assume, the contact name, if any, is entered by the user and is used "as is" therefore, /// normalize() is *not* called for the name. If the contact is blocked, it is unblocked. /// - /// To add a number of contacts, see `dc_add_address_book()` which is much faster for adding + /// To add a number of contacts, see `add_address_book()` which is much faster for adding /// a bunch of addresses. /// /// May result in a `#DC_EVENT_CONTACTS_CHANGED` event. @@ -384,10 +384,10 @@ impl Contact { /// Check if an e-mail address belongs to a known and unblocked contact. /// - /// Known and unblocked contacts will be returned by `dc_get_contacts()`. + /// Known and unblocked contacts will be returned by `get_contacts()`. /// /// To validate an e-mail address independently of the contact database - /// use `dc_may_be_valid_addr()`. + /// use `may_be_valid_addr()`. pub async fn lookup_id_by_addr( context: &Context, addr: &str, @@ -676,7 +676,7 @@ impl Contact { /// Returns known and unblocked contacts. /// - /// To get information about a single contact, see dc_get_contact(). + /// To get information about a single contact, see get_contact(). /// /// `listflags` is a combination of flags: /// - if the flag DC_GCL_ADD_SELF is set, SELF is added to the list unless filtered by other parameters @@ -970,11 +970,11 @@ impl Contact { bail!("Could not delete contact with ongoing chats"); } - /// Get a single contact object. For a list, see eg. dc_get_contacts(). + /// Get a single contact object. For a list, see eg. get_contacts(). /// /// For contact ContactId::SELF (1), the function returns sth. /// like "Me" in the selected language and the email address - /// defined by dc_set_config(). + /// defined by set_config(). pub async fn get_by_id(context: &Context, contact_id: ContactId) -> Result { let contact = Contact::load_from_db(context, contact_id).await?; @@ -1063,7 +1063,7 @@ impl Contact { /// Get the contact's profile image. /// This is the image set by each remote user on their own - /// using dc_set_config(context, "selfavatar", image). + /// using set_config(context, "selfavatar", image). pub async fn get_profile_image(&self, context: &Context) -> Result> { if self.id == ContactId::SELF { if let Some(p) = context.get_config(Config::Selfavatar).await? { @@ -1071,7 +1071,7 @@ impl Contact { } } else if let Some(image_rel) = self.param.get(Param::ProfileImage) { if !image_rel.is_empty() { - return Ok(Some(dc_get_abs_path(context, image_rel))); + return Ok(Some(get_abs_path(context, image_rel))); } } Ok(None) @@ -1438,15 +1438,12 @@ fn split_address_book(book: &str) -> Vec<(&str, &str)> { #[cfg(test)] mod tests { - use tokio::fs::File; - use tokio::io::AsyncWriteExt; - use super::*; use crate::chat::{get_chat_contacts, send_text_msg, Chat}; use crate::chatlist::Chatlist; - use crate::dc_receive_imf::dc_receive_imf; use crate::message::Message; + use crate::receive_imf::receive_imf; use crate::test_utils::{self, TestContext}; #[test] @@ -1690,7 +1687,7 @@ mod tests { let t = TestContext::new_alice().await; // first message creates contact and one-to-one-chat without name set - dc_receive_imf( + receive_imf( &t, b"From: f@example.org\n\ To: alice@example.org\n\ @@ -1719,7 +1716,7 @@ mod tests { assert_eq!(contacts.len(), 1); // second message inits the name - dc_receive_imf( + receive_imf( &t, b"From: Flobbyfoo \n\ To: alice@example.org\n\ @@ -1747,7 +1744,7 @@ mod tests { assert_eq!(contacts.len(), 1); // third message changes the name - dc_receive_imf( + receive_imf( &t, b"From: Foo Flobby \n\ To: alice@example.org\n\ @@ -2200,10 +2197,7 @@ CCCB 5AA9 F6E1 141C 9431 assert_eq!(alice1.get_config(Config::Selfavatar).await?, None); let avatar_src = alice1.get_blobdir().join("avatar.png"); - File::create(&avatar_src) - .await? - .write_all(test_utils::AVATAR_900x900_BYTES) - .await?; + tokio::fs::write(&avatar_src, test_utils::AVATAR_900x900_BYTES).await?; alice1 .set_config(Config::Selfavatar, Some(avatar_src.to_str().unwrap())) @@ -2266,7 +2260,7 @@ Chat-Version: 1.0 Date: Sun, 22 Mar 2020 22:37:55 +0000 Hi."#; - dc_receive_imf(&alice, mime, false).await?; + receive_imf(&alice, mime, false).await?; let msg = alice.get_last_msg().await; let timestamp = msg.get_timestamp(); diff --git a/src/context.rs b/src/context.rs index 55d2e6150..279633af2 100644 --- a/src/context.rs +++ b/src/context.rs @@ -15,7 +15,6 @@ use crate::chat::{get_chat_cnt, ChatId}; use crate::config::Config; use crate::constants::DC_VERSION_STR; use crate::contact::Contact; -use crate::dc_tools::{duration_to_str, time}; use crate::events::{Event, EventEmitter, EventType, Events}; use crate::key::{DcKey, SignedPublicKey}; use crate::login_param::LoginParam; @@ -24,6 +23,7 @@ use crate::quota::QuotaInfo; use crate::ratelimit::Ratelimit; use crate::scheduler::Scheduler; use crate::sql::Sql; +use crate::tools::{duration_to_str, time}; #[derive(Clone, Debug)] pub struct Context { @@ -669,10 +669,10 @@ mod tests { get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, ChatId, MuteDuration, }; use crate::contact::ContactId; - use crate::dc_receive_imf::dc_receive_imf; - use crate::dc_tools::dc_create_outgoing_rfc724_mid; use crate::message::{Message, Viewtype}; + use crate::receive_imf::receive_imf; use crate::test_utils::TestContext; + use crate::tools::create_outgoing_rfc724_mid; use anyhow::Context as _; use std::time::Duration; use strum::IntoEnumIterator; @@ -711,10 +711,10 @@ mod tests { \n\ hello\n", contact.get_addr(), - dc_create_outgoing_rfc724_mid(None, contact.get_addr()) + create_outgoing_rfc724_mid(None, contact.get_addr()) ); println!("{}", msg); - dc_receive_imf(t, msg.as_bytes(), false).await.unwrap(); + receive_imf(t, msg.as_bytes(), false).await.unwrap(); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/src/download.rs b/src/download.rs index 4682bd458..ea2b6fefc 100644 --- a/src/download.rs +++ b/src/download.rs @@ -7,12 +7,12 @@ use std::collections::BTreeMap; use crate::config::Config; use crate::context::Context; -use crate::dc_tools::time; use crate::imap::{Imap, ImapActionResult}; use crate::job::{self, Action, Job, Status}; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::{MimeMessage, Part}; use crate::param::Params; +use crate::tools::time; use crate::{job_try, stock_str, EventType}; use std::cmp::max; @@ -257,9 +257,9 @@ mod tests { use num_traits::FromPrimitive; use crate::chat::send_msg; - use crate::dc_receive_imf::dc_receive_imf_inner; use crate::ephemeral::Timer; use crate::message::Viewtype; + use crate::receive_imf::receive_imf_inner; use crate::test_utils::TestContext; use super::*; @@ -342,7 +342,7 @@ mod tests { Date: Sun, 22 Mar 2020 22:37:57 +0000\ Content-Type: text/plain"; - dc_receive_imf_inner( + receive_imf_inner( &t, "Mr.12345678901@example.com", header.as_bytes(), @@ -359,7 +359,7 @@ mod tests { .unwrap() .contains(&stock_str::partial_download_msg_body(&t, 100000).await)); - dc_receive_imf_inner( + receive_imf_inner( &t, "Mr.12345678901@example.com", format!("{}\n\n100k text...", header).as_bytes(), @@ -388,7 +388,7 @@ mod tests { .await?; // download message from bob partially, this must not change the ephemeral timer - dc_receive_imf_inner( + receive_imf_inner( &t, "first@example.org", b"From: Bob \n\ diff --git a/src/e2ee.rs b/src/e2ee.rs index 311f7d7b9..daa183fdb 100644 --- a/src/e2ee.rs +++ b/src/e2ee.rs @@ -411,10 +411,10 @@ pub async fn ensure_secret_key_exists(context: &Context) -> Result { #[cfg(test)] mod tests { use crate::chat; - use crate::dc_receive_imf::dc_receive_imf; use crate::message::{Message, Viewtype}; use crate::param::Param; use crate::peerstate::ToSave; + use crate::receive_imf::receive_imf; use crate::test_utils::{bob_keypair, TestContext}; use super::*; @@ -646,7 +646,7 @@ Sent with my Delta Chat Messenger: https://delta.chat"; assert!(get_attachment_mime(&mail).is_some()); let bob = TestContext::new_bob().await; - dc_receive_imf(&bob, attachment_mime, false).await?; + receive_imf(&bob, attachment_mime, false).await?; let msg = bob.get_last_msg().await; assert_eq!(msg.text.as_deref(), Some("Hello from Thunderbird!")); diff --git a/src/ephemeral.rs b/src/ephemeral.rs index da585b4d3..ef90e7b3a 100644 --- a/src/ephemeral.rs +++ b/src/ephemeral.rs @@ -70,7 +70,6 @@ use crate::chat::{send_msg, ChatId}; use crate::constants::{DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH}; use crate::contact::ContactId; use crate::context::Context; -use crate::dc_tools::{duration_to_str, time}; use crate::download::MIN_DELETE_SERVER_AFTER; use crate::events::EventType; use crate::log::LogExt; @@ -78,6 +77,7 @@ use crate::message::{Message, MessageState, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::sql::{self, params_iter}; use crate::stock_str; +use crate::tools::{duration_to_str, time}; use std::cmp::max; #[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)] @@ -339,7 +339,7 @@ pub(crate) async fn delete_expired_messages(context: &Context, now: i64) -> Resu .sql .execute( // If you change which information is removed here, also change MsgId::trash() and - // which information dc_receive_imf::add_parts() still adds to the db if the chat_id is TRASH + // which information receive_imf::add_parts() still adds to the db if the chat_id is TRASH r#" UPDATE msgs SET @@ -572,13 +572,13 @@ pub(crate) async fn start_ephemeral_timers(context: &Context) -> Result<()> { mod tests { use super::*; use crate::config::Config; - use crate::dc_receive_imf::dc_receive_imf; - use crate::dc_tools::MAX_SECONDS_TO_LEND_FROM_FUTURE; use crate::download::DownloadState; + use crate::receive_imf::receive_imf; use crate::test_utils::TestContext; + use crate::tools::MAX_SECONDS_TO_LEND_FROM_FUTURE; use crate::{ chat::{self, Chat, ChatItem}, - dc_tools::IsNoneOrEmpty, + tools::IsNoneOrEmpty, }; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -1101,7 +1101,7 @@ mod tests { let alice = TestContext::new_alice().await; // Message with Message-ID and no timer is received. - dc_receive_imf( + receive_imf( &alice, b"From: Bob \n\ To: Alice \n\ @@ -1120,7 +1120,7 @@ mod tests { assert_eq!(chat_id.get_ephemeral_timer(&alice).await?, Timer::Disabled); // Message with Message-ID is received. - dc_receive_imf( + receive_imf( &alice, b"From: Bob \n\ To: Alice \n\ @@ -1155,7 +1155,7 @@ mod tests { // // The message also contains a quote of the first message to test that only References: // header and not In-Reply-To: is consulted by the rollback protection. - dc_receive_imf( + receive_imf( &alice, b"From: Bob \n\ To: Alice \n\ diff --git a/src/html.rs b/src/html.rs index dbe2b3943..951da5d95 100644 --- a/src/html.rs +++ b/src/html.rs @@ -280,8 +280,8 @@ mod tests { use crate::chat::forward_msgs; use crate::config::Config; use crate::contact::ContactId; - use crate::dc_receive_imf::dc_receive_imf; use crate::message::{MessengerMessage, Viewtype}; + use crate::receive_imf::receive_imf; use crate::test_utils::TestContext; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -440,7 +440,7 @@ test some special html-characters as < > and & but also " and &#x .create_chat_with_contact("", "sender@testrun.org") .await; let raw = include_bytes!("../test-data/message/text_alt_plain_html.eml"); - dc_receive_imf(&alice, raw, false).await.unwrap(); + receive_imf(&alice, raw, false).await.unwrap(); let msg = alice.get_last_msg_in(chat.get_id()).await; assert_ne!(msg.get_from_id(), ContactId::SELF); assert_eq!(msg.is_dc_message, MessengerMessage::No); @@ -489,7 +489,7 @@ test some special html-characters as < > and & but also " and &#x .create_chat_with_contact("", "sender@testrun.org") .await; let raw = include_bytes!("../test-data/message/text_alt_plain_html.eml"); - dc_receive_imf(&alice, raw, false).await.unwrap(); + receive_imf(&alice, raw, false).await.unwrap(); let msg = alice.get_last_msg_in(chat.get_id()).await; // forward the message to saved-messages, @@ -551,7 +551,7 @@ test some special html-characters as < > and & but also " and &#x async fn test_cp1252_html() -> Result<()> { let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await?; - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/cp1252-html.eml"), false, diff --git a/src/imap.rs b/src/imap.rs index a7a60ea96..6dc003091 100644 --- a/src/imap.rs +++ b/src/imap.rs @@ -25,10 +25,6 @@ use crate::constants::{ }; use crate::contact::{normalize_name, Contact, ContactId, Modifier, Origin}; use crate::context::Context; -use crate::dc_receive_imf::{ - dc_receive_imf_inner, from_field_to_contact_id, get_prefetch_parent_message, ReceivedMsg, -}; -use crate::dc_tools::dc_create_id; use crate::events::EventType; use crate::headerdef::{HeaderDef, HeaderDefMap}; use crate::job; @@ -37,12 +33,16 @@ use crate::login_param::{ }; use crate::message::{self, Message, MessageState, MessengerMessage, MsgId, Viewtype}; use crate::mimeparser; -use crate::oauth2::dc_get_oauth2_access_token; +use crate::oauth2::get_oauth2_access_token; use crate::provider::Socket; +use crate::receive_imf::{ + from_field_to_contact_id, get_prefetch_parent_message, receive_imf_inner, ReceivedMsg, +}; use crate::scheduler::connectivity::ConnectivityStore; use crate::scheduler::InterruptInfo; use crate::sql; use crate::stock_str; +use crate::tools::create_id; mod client; mod idle; @@ -390,7 +390,7 @@ impl Imap { let login_res = if oauth2 { let addr: &str = config.addr.as_ref(); - let token = dc_get_oauth2_access_token(context, addr, imap_pw, true) + let token = get_oauth2_access_token(context, addr, imap_pw, true) .await? .context("IMAP could not get OAUTH token")?; let auth = OAuth2 { @@ -787,7 +787,7 @@ impl Imap { }; // Get the Message-ID or generate a fake one to identify the message in the database. - let message_id = prefetch_get_message_id(&headers).unwrap_or_else(dc_create_id); + let message_id = prefetch_get_message_id(&headers).unwrap_or_else(create_id); let target = match target_folder(context, folder, is_spam_folder, &headers).await? { Some(config) => match context.get_config(config).await? { @@ -875,8 +875,8 @@ impl Imap { received_msgs.extend(received_msgs_2); // determine which uid_next to use to update to - // dc_receive_imf() returns an `Err` value only on recoverable errors, otherwise it just logs an error. - // `largest_uid_processed` is the largest uid where dc_receive_imf() did NOT return an error. + // receive_imf() returns an `Err` value only on recoverable errors, otherwise it just logs an error. + // `largest_uid_processed` is the largest uid where receive_imf() did NOT return an error. // So: Update the uid_next to the largest uid that did NOT recoverably fail. Not perfect because if there was // another message afterwards that succeeded, we will not retry. The upside is that we will not retry an infinite amount of times. @@ -1431,7 +1431,7 @@ impl Imap { continue; } - // XXX put flags into a set and pass them to dc_receive_imf + // XXX put flags into a set and pass them to receive_imf let context = context.clone(); // safe, as we checked above that there is a body. @@ -1449,7 +1449,7 @@ impl Imap { ); "" }; - match dc_receive_imf_inner( + match receive_imf_inner( &context, rfc724_mid, body, @@ -1466,7 +1466,7 @@ impl Imap { last_uid = Some(server_uid) } Err(err) => { - warn!(context, "dc_receive_imf error: {:#}", err); + warn!(context, "receive_imf error: {:#}", err); } }; } @@ -1717,11 +1717,11 @@ async fn should_move_out_of_spam( // the SecureJoin header. So, we always move chat messages out of Spam. // Two possibilities to change this would be: // 1. Remove the `&& !context.is_spam_folder(folder).await?` check from - // `fetch_new_messages()`, and then let `dc_receive_imf()` check + // `fetch_new_messages()`, and then let `receive_imf()` check // if it's a spam message and should be hidden. // 2. Or add a flag to the ChatVersion header that this is a securejoin // request, and return `true` here only if the message has this flag. - // `dc_receive_imf()` can then check if the securejoin request is valid. + // `receive_imf()` can then check if the securejoin request is valid. return Ok(true); } diff --git a/src/imap/client.rs b/src/imap/client.rs index ed6faa64c..0e405a60d 100644 --- a/src/imap/client.rs +++ b/src/imap/client.rs @@ -11,7 +11,7 @@ use async_smtp::ServerAddress; use tokio::net::{self, TcpStream}; use super::session::Session; -use crate::login_param::{dc_build_tls, Socks5Config}; +use crate::login_param::{build_tls, Socks5Config}; use super::session::SessionStream; @@ -67,7 +67,7 @@ impl Client { strict_tls: bool, ) -> Result { let stream = TcpStream::connect(addr).await?; - let tls = dc_build_tls(strict_tls); + let tls = build_tls(strict_tls); let tls_stream: Box = Box::new(tls.connect(domain, stream).await?); let mut client = ImapClient::new(tls_stream); @@ -108,7 +108,7 @@ impl Client { .await?, ); - let tls = dc_build_tls(strict_tls); + let tls = build_tls(strict_tls); let tls_stream: Box = Box::new(tls.connect(target_addr.host.clone(), socks5_stream).await?); let mut client = ImapClient::new(tls_stream); @@ -151,7 +151,7 @@ impl Client { Ok(self) } else { let Client { mut inner, .. } = self; - let tls = dc_build_tls(strict_tls); + let tls = build_tls(strict_tls); inner.run_command_and_check_ok("STARTTLS", None).await?; let stream = inner.into_inner(); diff --git a/src/imex.rs b/src/imex.rs index ac2cd8303..e7ec2582f 100644 --- a/src/imex.rs +++ b/src/imex.rs @@ -17,10 +17,6 @@ use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId}; use crate::config::Config; use crate::contact::ContactId; use crate::context::Context; -use crate::dc_tools::{ - dc_create_folder, dc_delete_file, dc_get_filesuffix_lc, dc_open_file_std, dc_read_file, - dc_write_file, time, EmailAddress, -}; use crate::e2ee; use crate::events::EventType; use crate::key::{self, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey}; @@ -31,6 +27,10 @@ use crate::param::Param; use crate::pgp; use crate::sql; use crate::stock_str; +use crate::tools::{ + create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file, + EmailAddress, +}; // Name of the database file in the backup. const DBFILE_BACKUP_NAME: &str = "dc_database_backup.sqlite"; @@ -58,7 +58,7 @@ pub enum ImexMode { ExportBackup = 11, /// `path` is the file (not: directory) to import. The file is normally - /// created by DC_IMEX_EXPORT_BACKUP and detected by dc_imex_has_backup(). Importing a backup + /// created by DC_IMEX_EXPORT_BACKUP and detected by imex_has_backup(). Importing a backup /// is only possible as long as the context is not configured or used in another way. ImportBackup = 12, } @@ -290,7 +290,7 @@ pub async fn continue_key_transfer( ); if let Some(filename) = msg.get_file(context) { - let file = dc_open_file_std(context, filename)?; + let file = open_file_std(context, filename)?; let sc = normalize_setup_code(setup_code); let armored_key = decrypt_setup_file(&sc, file).await?; set_self_key(context, &armored_key, true, true).await?; @@ -393,7 +393,7 @@ async fn imex_inner( if e2ee::ensure_secret_key_exists(context).await.is_err() { bail!("Cannot create private key or private key not available."); } else { - dc_create_folder(context, &path).await?; + create_folder(context, &path).await?; } } @@ -499,7 +499,7 @@ async fn import_backup( fn get_next_backup_path(folder: &Path, backup_time: i64) -> Result<(PathBuf, PathBuf, PathBuf)> { let folder = PathBuf::from(folder); let stem = chrono::NaiveDateTime::from_timestamp(backup_time, 0) - // Don't change this file name format, in has_backup() we use string comparison to determine which backup is newer: + // Don't change this file name format, in `dc_imex_has_backup` we use string comparison to determine which backup is newer: .format("delta-chat-backup-%Y-%m-%d") .to_string(); @@ -577,7 +577,7 @@ struct DeleteOnDrop(PathBuf); impl Drop for DeleteOnDrop { fn drop(&mut self) { let file = self.0.clone(); - // Not using dc_delete_file() here because it would send a DeletedBlobFile event + // Not using `tools::delete_file` here because it would send a DeletedBlobFile event // Hack to avoid panic in nested runtime calls of tokio std::fs::remove_file(file).ok(); } @@ -650,7 +650,7 @@ async fn import_self_keys(context: &Context, dir: &Path) -> Result<()> { let entry_fn = entry.file_name(); let name_f = entry_fn.to_string_lossy(); let path_plus_name = dir.join(&entry_fn); - match dc_get_filesuffix_lc(&name_f) { + match get_filesuffix_lc(&name_f) { Some(suffix) => { if suffix != "asc" { continue; @@ -672,7 +672,7 @@ async fn import_self_keys(context: &Context, dir: &Path) -> Result<()> { path_plus_name.display() ); - match dc_read_file(context, &path_plus_name).await { + match read_file(context, &path_plus_name).await { Ok(buf) => { let armored = std::string::String::from_utf8_lossy(&buf); if let Err(err) = set_self_key(context, &armored, set_default, false).await { @@ -775,10 +775,10 @@ where key.key_id(), file_name.display() ); - dc_delete_file(context, &file_name).await; + delete_file(context, &file_name).await; let content = key.to_asc(None).into_bytes(); - let res = dc_write_file(context, &file_name, &content).await; + let res = write_file(context, &file_name, &content).await; if res.is_err() { error!(context, "Cannot write key to {}", file_name.display()); } else { diff --git a/src/job.rs b/src/job.rs index 14072d603..cb9db3043 100644 --- a/src/job.rs +++ b/src/job.rs @@ -9,10 +9,10 @@ use deltachat_derive::{FromSql, ToSql}; use rand::{thread_rng, Rng}; use crate::context::Context; -use crate::dc_tools::time; use crate::imap::Imap; use crate::param::Params; use crate::scheduler::InterruptInfo; +use crate::tools::time; // results in ~3 weeks for the last backoff timespan const JOB_RETRIES: u32 = 17; diff --git a/src/key.rs b/src/key.rs index 566d49a4f..7c385a313 100644 --- a/src/key.rs +++ b/src/key.rs @@ -16,7 +16,7 @@ use tokio::runtime::Handle; use crate::config::Config; use crate::constants::KeyGenType; use crate::context::Context; -use crate::dc_tools::{time, EmailAddress}; +use crate::tools::{time, EmailAddress}; // Re-export key types pub use crate::pgp::KeyPair; diff --git a/src/lib.rs b/src/lib.rs index 3f64ecdb7..4a76bbb0a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -98,8 +98,8 @@ pub mod plaintext; mod ratelimit; pub mod summary; -pub mod dc_receive_imf; -pub mod dc_tools; +pub mod receive_imf; +pub mod tools; pub mod accounts; diff --git a/src/location.rs b/src/location.rs index 3db46b807..10e6a77fd 100644 --- a/src/location.rs +++ b/src/location.rs @@ -11,11 +11,11 @@ use tokio::time::timeout; use crate::chat::{self, ChatId}; use crate::contact::ContactId; use crate::context::Context; -use crate::dc_tools::{duration_to_str, time}; use crate::events::EventType; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::stock_str; +use crate::tools::{duration_to_str, time}; /// Location record #[derive(Debug, Clone, Default)] @@ -728,7 +728,7 @@ mod tests { #![allow(clippy::indexing_slicing)] use super::*; - use crate::dc_receive_imf::dc_receive_imf; + use crate::receive_imf::receive_imf; use crate::test_utils::TestContext; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -795,7 +795,7 @@ mod tests { async fn receive_location_kml() -> Result<()> { let alice = TestContext::new_alice().await; - dc_receive_imf( + receive_imf( &alice, br#"Subject: Hello Message-ID: hello@example.net @@ -812,7 +812,7 @@ Text message."#, let received_msg = alice.get_last_msg().await; assert_eq!(received_msg.text.unwrap(), "Text message."); - dc_receive_imf( + receive_imf( &alice, br#"Subject: locations MIME-Version: 1.0 diff --git a/src/login_param.rs b/src/login_param.rs index 9fe58b6c1..153b7d199 100644 --- a/src/login_param.rs +++ b/src/login_param.rs @@ -393,7 +393,7 @@ static LETSENCRYPT_ROOT: Lazy = Lazy::new(|| { .unwrap() }); -pub fn dc_build_tls(strict_tls: bool) -> async_native_tls::TlsConnector { +pub fn build_tls(strict_tls: bool) -> async_native_tls::TlsConnector { let tls_builder = async_native_tls::TlsConnector::new().add_root_certificate(LETSENCRYPT_ROOT.clone()); @@ -462,8 +462,8 @@ mod tests { async fn test_build_tls() -> Result<()> { // we are using some additional root certificates. // make sure, they do not break construction of TlsConnector - let _ = dc_build_tls(true); - let _ = dc_build_tls(false); + let _ = build_tls(true); + let _ = build_tls(false); Ok(()) } } diff --git a/src/message.rs b/src/message.rs index 20077bc8c..5d9741a12 100644 --- a/src/message.rs +++ b/src/message.rs @@ -15,10 +15,6 @@ use crate::constants::{ }; use crate::contact::{Contact, ContactId, Origin}; use crate::context::Context; -use crate::dc_tools::{ - dc_create_smeared_timestamp, dc_get_filebytes, dc_get_filemeta, dc_gm2local_offset, - dc_read_file, dc_timestamp_to_str, dc_truncate, time, -}; use crate::download::DownloadState; use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer}; use crate::events::EventType; @@ -30,6 +26,10 @@ use crate::scheduler::InterruptInfo; use crate::sql; use crate::stock_str; use crate::summary::Summary; +use crate::tools::{ + create_smeared_timestamp, get_filebytes, get_filemeta, gm2local_offset, read_file, time, + timestamp_to_str, truncate, +}; /// Message ID, including reserved IDs. /// @@ -94,7 +94,7 @@ impl MsgId { .sql .execute( // If you change which information is removed here, also change delete_expired_messages() and - // which information dc_receive_imf::add_parts() still adds to the db if the chat_id is TRASH + // which information receive_imf::add_parts() still adds to the db if the chat_id is TRASH r#" UPDATE msgs SET @@ -232,10 +232,6 @@ impl Default for MessengerMessage { /// An object representing a single message in memory. /// The message object is not updated. /// If you want an update, you have to recreate the object. -/// -/// to check if a mail was sent, use dc_msg_is_sent() -/// approx. max. length returned by dc_msg_get_text() -/// approx. max. length returned by dc_get_msg_info() #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Message { pub(crate) id: MsgId, @@ -395,8 +391,8 @@ impl Message { self.param.set_int(Param::Width, 0); self.param.set_int(Param::Height, 0); - if let Ok(buf) = dc_read_file(context, path_and_filename).await { - if let Ok((width, height)) = dc_get_filemeta(&buf) { + if let Ok(buf) = read_file(context, path_and_filename).await { + if let Ok((width, height)) = get_filemeta(&buf) { self.param.set_int(Param::Width, width as i32); self.param.set_int(Param::Height, height as i32); } @@ -412,7 +408,7 @@ impl Message { } /// Check if a message has a location bound to it. - /// These messages are also returned by dc_get_locations() + /// These messages are also returned by get_locations() /// and the UI may decide to display a special icon beside such messages, /// /// @memberof Message @@ -427,7 +423,7 @@ impl Message { /// at a position different from the self-location. /// You should not call this function /// if you want to bind the current self-location to a message; - /// this is done by dc_set_location() and dc_send_locations_to_chat(). + /// this is done by set_location() and send_locations_to_chat(). /// /// Typically results in the event #DC_EVENT_LOCATION_CHANGED with /// contact_id set to ContactId::SELF. @@ -497,7 +493,7 @@ impl Message { pub async fn get_filebytes(&self, context: &Context) -> u64 { match self.param.get_path(Param::File, context) { - Ok(Some(path)) => dc_get_filebytes(context, &path).await, + Ok(Some(path)) => get_filebytes(context, &path).await, Ok(None) => 0, Err(_) => 0, } @@ -557,9 +553,9 @@ impl Message { Ok(Summary::new(context, self, chat, contact.as_ref()).await) } - // It's a little unfortunate that the UI has to first call dc_msg_get_override_sender_name() and then if it was NULL, call - // dc_contact_get_display_name() but this was the best solution: - // - We could load a Contact struct from the db here to call get_display_name() instead of returning None, but then we had a db + // It's a little unfortunate that the UI has to first call `dc_msg_get_override_sender_name` and then if it was `NULL`, call + // `dc_contact_get_display_name` but this was the best solution: + // - We could load a Contact struct from the db here to call `dc_get_display_name` instead of returning `None`, but then we had a db // call everytime (and this fn is called a lot while the user is scrolling through a group), so performance would be bad // - We could pass both a Contact struct and a Message struct in the FFI, but at least on Android we would need to handle raw // C-data in the Java code (i.e. a `long` storing a C pointer) @@ -572,14 +568,14 @@ impl Message { } // Exposing this function over the ffi instead of get_override_sender_name() would mean that at least Android Java code has - // to handle raw C-data (as it is done for dc_msg_get_summary()) + // to handle raw C-data (as it is done for msg_get_summary()) pub fn get_sender_name(&self, contact: &Contact) -> String { self.get_override_sender_name() .unwrap_or_else(|| contact.get_display_name().to_string()) } pub fn has_deviating_timestamp(&self) -> bool { - let cnv_to_local = dc_gm2local_offset(); + let cnv_to_local = gm2local_offset(); let sort_timestamp = self.get_sort_timestamp() as i64 + cnv_to_local; let send_timestamp = self.get_timestamp() as i64 + cnv_to_local; @@ -636,7 +632,7 @@ impl Message { } if let Some(filename) = self.get_file(context) { - if let Ok(ref buf) = dc_read_file(context, filename).await { + if let Ok(ref buf) = read_file(context, filename).await { if let Ok((typ, headers, _)) = split_armored_data(buf) { if typ == pgp::armor::BlockType::Message { return headers.get(crate::pgp::HEADER_SETUPCODE).cloned(); @@ -1004,9 +1000,9 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result { return Ok(ret); } let rawtxt = rawtxt.unwrap_or_default(); - let rawtxt = dc_truncate(rawtxt.trim(), DC_DESIRED_TEXT_LEN); + let rawtxt = truncate(rawtxt.trim(), DC_DESIRED_TEXT_LEN); - let fts = dc_timestamp_to_str(msg.get_timestamp()); + let fts = timestamp_to_str(msg.get_timestamp()); ret += &format!("Sent: {}", fts); let name = Contact::load_from_db(context, msg.from_id) @@ -1018,7 +1014,7 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result { ret += "\n"; if msg.from_id != ContactId::SELF { - let s = dc_timestamp_to_str(if 0 != msg.timestamp_rcvd { + let s = timestamp_to_str(if 0 != msg.timestamp_rcvd { msg.timestamp_rcvd } else { msg.timestamp_sort @@ -1032,10 +1028,7 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result { } if msg.ephemeral_timestamp != 0 { - ret += &format!( - "Expires: {}\n", - dc_timestamp_to_str(msg.ephemeral_timestamp) - ); + ret += &format!("Expires: {}\n", timestamp_to_str(msg.ephemeral_timestamp)); } if msg.from_id == ContactId::INFO || msg.to_id == ContactId::INFO { @@ -1058,7 +1051,7 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result { .await { for (contact_id, ts) in rows { - let fts = dc_timestamp_to_str(ts); + let fts = timestamp_to_str(ts); ret += &format!("Read: {}", fts); let name = Contact::load_from_db(context, contact_id) @@ -1094,7 +1087,7 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result { } if let Some(path) = msg.get_file(context) { - let bytes = dc_get_filebytes(context, &path).await; + let bytes = get_filebytes(context, &path).await; ret += &format!("\nFile: {}, {}, bytes\n", path.display(), bytes); } @@ -1208,7 +1201,7 @@ pub fn guess_msgtype_from_suffix(path: &Path) -> Option<(Viewtype, &str)> { /// Get the raw mime-headers of the given message. /// Raw headers are saved for incoming messages -/// only if `dc_set_config(context, "save_mime_headers", "1")` +/// only if `set_config(context, "save_mime_headers", "1")` /// was called before. /// /// Returns an empty vector if there are no headers saved for the given message, @@ -1606,7 +1599,7 @@ async fn ndn_maybe_add_info_msg( context, chat_id, &text, - dc_create_smeared_timestamp(context).await, + create_smeared_timestamp(context).await, ) .await?; context.emit_event(EventType::ChatModified(chat_id)); @@ -1636,7 +1629,7 @@ pub async fn get_unblocked_msg_cnt(context: &Context) -> usize { { Ok(res) => res, Err(err) => { - error!(context, "dc_get_unblocked_msg_cnt() failed. {}", err); + error!(context, "get_unblocked_msg_cnt() failed. {}", err); 0 } } @@ -1656,7 +1649,7 @@ pub async fn get_request_msg_cnt(context: &Context) -> usize { { Ok(res) => res, Err(err) => { - error!(context, "dc_get_request_msg_cnt() failed. {}", err); + error!(context, "get_request_msg_cnt() failed. {}", err); 0 } } @@ -1753,8 +1746,7 @@ pub enum Viewtype { Unknown = 0, /// Text message. - /// The text of the message is set using dc_msg_set_text() - /// and retrieved with dc_msg_get_text(). + /// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text(). Text = 10, /// Image message. @@ -1835,7 +1827,7 @@ mod tests { use crate::chat::{marknoticed_chat, ChatItem}; use crate::chatlist::Chatlist; - use crate::dc_receive_imf::dc_receive_imf; + use crate::receive_imf::receive_imf; use crate::test_utils as test; use crate::test_utils::TestContext; @@ -2037,7 +2029,7 @@ mod tests { async fn test_get_chat_id() { // Alice receives a message that pops up as a contact request let alice = TestContext::new_alice().await; - dc_receive_imf( + receive_imf( &alice, b"From: Bob \n\ To: alice@example.org\n\ @@ -2239,7 +2231,7 @@ mod tests { let alice = TestContext::new_alice().await; // Alice receives a message from Bob the bot. - dc_receive_imf( + receive_imf( &alice, b"From: Bob \n\ To: alice@example.org\n\ @@ -2257,7 +2249,7 @@ mod tests { assert!(msg.is_bot()); // Alice receives a message from Bob who is not the bot anymore. - dc_receive_imf( + receive_imf( &alice, b"From: Bob \n\ To: alice@example.org\n\ diff --git a/src/mimefactory.rs b/src/mimefactory.rs index 221ab0fef..0479f2605 100644 --- a/src/mimefactory.rs +++ b/src/mimefactory.rs @@ -13,11 +13,6 @@ use crate::config::Config; use crate::constants::{Chattype, DC_FROM_HANDSHAKE}; use crate::contact::Contact; use crate::context::{get_version_str, Context}; -use crate::dc_tools::IsNoneOrEmpty; -use crate::dc_tools::{ - dc_create_outgoing_rfc724_mid, dc_create_smeared_timestamp, dc_get_filebytes, - remove_subject_prefix, time, -}; use crate::e2ee::EncryptHelper; use crate::ephemeral::Timer as EphemeralTimer; use crate::format_flowed::{format_flowed, format_flowed_quote}; @@ -29,6 +24,11 @@ use crate::param::Param; use crate::peerstate::{Peerstate, PeerstateVerifiedStatus}; use crate::simplify::escape_message_footer_marks; use crate::stock_str; +use crate::tools::IsNoneOrEmpty; +use crate::tools::{ + create_outgoing_rfc724_mid, create_smeared_timestamp, get_filebytes, remove_subject_prefix, + time, +}; // attachments of 25 mb brutto should work on the majority of providers // (brutto examples: web.de=50, 1&1=40, t-online.de=32, gmail=25, posteo=50, yahoo=25, all-inkl=100). @@ -243,7 +243,7 @@ impl<'a> MimeFactory<'a> { .get_config(Config::Selfstatus) .await? .unwrap_or_default(); - let timestamp = dc_create_smeared_timestamp(context).await; + let timestamp = create_smeared_timestamp(context).await; let res = MimeFactory::<'a> { from_addr, @@ -533,7 +533,7 @@ impl<'a> MimeFactory<'a> { let rfc724_mid = match self.loaded { Loaded::Message { .. } => self.msg.rfc724_mid.clone(), - Loaded::Mdn { .. } => dc_create_outgoing_rfc724_mid(None, &self.from_addr), + Loaded::Mdn { .. } => create_outgoing_rfc724_mid(None, &self.from_addr), }; let rfc724_mid_headervalue = render_rfc724_mid(&rfc724_mid); @@ -1401,7 +1401,7 @@ fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool async fn is_file_size_okay(context: &Context, msg: &Message) -> Result { match msg.param.get_path(Param::File, context)? { Some(path) => { - let bytes = dc_get_filebytes(context, &path).await; + let bytes = get_filebytes(context, &path).await; Ok(bytes <= UPPER_LIMIT_FILE_SIZE) } None => Ok(false), @@ -1452,8 +1452,6 @@ fn maybe_encode_words(words: &str) -> String { #[cfg(test)] mod tests { use mailparse::{addrparse_header, MailHeaderMap}; - use tokio::fs::File; - use tokio::io::AsyncWriteExt; use crate::chat::ChatId; use crate::chat::{ @@ -1462,8 +1460,8 @@ mod tests { }; use crate::chatlist::Chatlist; use crate::contact::Origin; - use crate::dc_receive_imf::dc_receive_imf; use crate::mimeparser::MimeMessage; + use crate::receive_imf::receive_imf; use crate::test_utils::{get_chat_msg, TestContext}; use super::*; @@ -1660,7 +1658,7 @@ mod tests { async fn test_subject_mdn() { // 5. Receive an mdn (read receipt) and make sure the mdn's subject is not used let t = TestContext::new_alice().await; - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: alice@example.org\n\ @@ -1748,7 +1746,7 @@ mod tests { let subject = send_msg_get_subject(&t, group_id, None).await?; assert_eq!(subject, "Re: groupname"); - dc_receive_imf( + receive_imf( &t, format!( "Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ @@ -1863,7 +1861,7 @@ mod tests { } if message_arrives_inbetween { - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: Bob \n\ @@ -1897,7 +1895,7 @@ mod tests { .await .unwrap(); - dc_receive_imf(context, imf_raw, false).await.unwrap(); + receive_imf(context, imf_raw, false).await.unwrap(); let chats = Chatlist::try_load(context, 0, None, None).await.unwrap(); @@ -2016,7 +2014,7 @@ mod tests { let file = t.dir.path().join("avatar.png"); let bytes = include_bytes!("../test-data/image/avatar64x64.png"); - File::create(&file).await?.write_all(bytes).await?; + tokio::fs::write(&file, bytes).await?; t.set_config(Config::Selfavatar, Some(file.to_str().unwrap())) .await?; diff --git a/src/mimeparser.rs b/src/mimeparser.rs index 6761a939a..e61c64891 100644 --- a/src/mimeparser.rs +++ b/src/mimeparser.rs @@ -15,7 +15,6 @@ use crate::blob::BlobObject; use crate::constants::{DC_DESIRED_TEXT_LEN, DC_ELLIPSIS}; use crate::contact::{addr_normalize, ContactId}; use crate::context::Context; -use crate::dc_tools::{dc_get_filemeta, dc_truncate, parse_receive_headers}; use crate::dehtml::dehtml; use crate::e2ee; use crate::events::EventType; @@ -29,6 +28,7 @@ use crate::peerstate::Peerstate; use crate::simplify::{simplify, SimplifiedText}; use crate::stock_str; use crate::sync::SyncItems; +use crate::tools::{get_filemeta, parse_receive_headers, truncate}; /// A parsed MIME message. /// @@ -979,7 +979,7 @@ impl MimeMessage { > DC_DESIRED_TEXT_LEN + DC_ELLIPSIS.len() { self.is_mime_modified = true; - dc_truncate(&*simplified_txt, DC_DESIRED_TEXT_LEN).to_string() + truncate(&*simplified_txt, DC_DESIRED_TEXT_LEN).to_string() } else { simplified_txt }; @@ -1090,7 +1090,7 @@ impl MimeMessage { /* create and register Mime part referencing the new Blob object */ let mut part = Part::default(); if mime_type.type_() == mime::IMAGE { - if let Ok((width, height)) = dc_get_filemeta(decoded_data) { + if let Ok((width, height)) = get_filemeta(decoded_data) { part.param.set_int(Param::Width, width as i32); part.param.set_int(Param::Height, height as i32); } @@ -1337,7 +1337,7 @@ impl MimeMessage { /// Some providers like GMX and Yahoo do not send standard NDNs (Non Delivery notifications). /// If you improve heuristics here you might also have to change prefetch_should_download() in imap/mod.rs. - /// Also you should add a test in dc_receive_imf.rs (there already are lots of test_parse_ndn_* tests). + /// Also you should add a test in receive_imf.rs (there already are lots of test_parse_ndn_* tests). #[allow(clippy::indexing_slicing)] async fn heuristically_parse_ndn(&mut self, context: &Context) { let maybe_ndn = if let Some(from) = self.get_header(HeaderDef::From_) { @@ -1733,8 +1733,8 @@ mod tests { chatlist::Chatlist, config::Config, constants::Blocked, - dc_receive_imf::dc_receive_imf, message::{Message, MessageState, MessengerMessage}, + receive_imf::receive_imf, test_utils::TestContext, }; use mailparse::ParsedMail; @@ -1807,7 +1807,7 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn test_dc_mimeparser_crash() { + async fn test_mimeparser_crash() { let context = TestContext::new().await; let raw = include_bytes!("../test-data/message/issue_523.txt"); let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..]) @@ -2907,7 +2907,7 @@ On 2020-10-25, Bob wrote: async fn test_add_subj_to_multimedia_msg() { let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf( + receive_imf( &t.ctx, include_bytes!("../test-data/message/subj_with_multimedia_msg.eml"), false, @@ -3058,7 +3058,7 @@ Subject: ... Some quote. "###; - dc_receive_imf(&t, raw, false).await?; + receive_imf(&t, raw, false).await?; // Delta Chat generates In-Reply-To with a starting tab when Message-ID is too long. let raw = br###"In-Reply-To: @@ -3075,7 +3075,7 @@ Subject: ... Some reply "###; - dc_receive_imf(&t, raw, false).await?; + receive_imf(&t, raw, false).await?; let msg = t.get_last_msg().await; assert_eq!(msg.get_text().unwrap(), "Some reply"); @@ -3103,13 +3103,13 @@ Message. "###; // Bob receives message. - dc_receive_imf(&bob, raw, false).await?; + receive_imf(&bob, raw, false).await?; let msg = bob.get_last_msg().await; // Message is incoming. assert!(msg.param.get_bool(Param::WantsMdn).unwrap()); // Alice receives copy-to-self. - dc_receive_imf(&alice, raw, false).await?; + receive_imf(&alice, raw, false).await?; let msg = alice.get_last_msg().await; // Message is outgoing, don't send read receipt to self. assert!(msg.param.get_bool(Param::WantsMdn).is_none()); @@ -3122,7 +3122,7 @@ Message. let alice = TestContext::new_alice().await; // Alice receives BCC-self copy of a message sent to Bob. - dc_receive_imf( + receive_imf( &alice, "Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: alice@example.org\n\ @@ -3143,7 +3143,7 @@ Message. // Due to a bug in the old version running on the other device, Alice receives a read // receipt from self. - dc_receive_imf( + receive_imf( &alice, "Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: alice@example.org\n\ @@ -3194,7 +3194,7 @@ Message. let original = include_bytes!("../test-data/message/ms_exchange_report_original_message.eml"); - dc_receive_imf(&t, original, false).await?; + receive_imf(&t, original, false).await?; let original_msg_id = t.get_last_msg().await.id; // 1. Test mimeparser directly @@ -3209,7 +3209,7 @@ Message. assert!(mimeparser.mdn_reports[0].additional_message_ids.is_empty()); // 2. Test that marking the original msg as read works - dc_receive_imf(&t, mdn, false).await?; + receive_imf(&t, mdn, false).await?; assert_eq!( original_msg_id.get_state(&t).await?, diff --git a/src/oauth2.rs b/src/oauth2.rs index 8eb91bb01..1d0296716 100644 --- a/src/oauth2.rs +++ b/src/oauth2.rs @@ -8,9 +8,9 @@ use serde::Deserialize; use crate::config::Config; use crate::context::Context; -use crate::dc_tools::time; use crate::provider; use crate::provider::Oauth2Authorizer; +use crate::tools::time; const OAUTH2_GMAIL: Oauth2 = Oauth2 { // see @@ -53,7 +53,7 @@ struct Response { scope: Option, } -pub async fn dc_get_oauth2_url( +pub async fn get_oauth2_url( context: &Context, addr: &str, redirect_uri: &str, @@ -73,7 +73,7 @@ pub async fn dc_get_oauth2_url( } } -pub async fn dc_get_oauth2_access_token( +pub async fn get_oauth2_access_token( context: &Context, addr: &str, code: &str, @@ -224,11 +224,7 @@ pub async fn dc_get_oauth2_access_token( } } -pub async fn dc_get_oauth2_addr( - context: &Context, - addr: &str, - code: &str, -) -> Result> { +pub async fn get_oauth2_addr(context: &Context, addr: &str, code: &str) -> Result> { let socks5_enabled = context.get_config_bool(Config::Socks5Enabled).await?; let oauth2 = match Oauth2::from_address(context, addr, socks5_enabled).await { Some(o) => o, @@ -238,13 +234,11 @@ pub async fn dc_get_oauth2_addr( return Ok(None); } - if let Some(access_token) = dc_get_oauth2_access_token(context, addr, code, false).await? { + if let Some(access_token) = get_oauth2_access_token(context, addr, code, false).await? { let addr_out = oauth2.get_addr(context, &access_token).await; if addr_out.is_none() { // regenerate - if let Some(access_token) = - dc_get_oauth2_access_token(context, addr, code, true).await? - { + if let Some(access_token) = get_oauth2_access_token(context, addr, code, true).await? { Ok(oauth2.get_addr(context, &access_token).await) } else { Ok(None) @@ -404,33 +398,31 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn test_dc_get_oauth2_addr() { + async fn test_get_oauth2_addr() { let ctx = TestContext::new().await; let addr = "dignifiedquire@gmail.com"; let code = "fail"; - let res = dc_get_oauth2_addr(&ctx.ctx, addr, code).await.unwrap(); + let res = get_oauth2_addr(&ctx.ctx, addr, code).await.unwrap(); // this should fail as it is an invalid password assert_eq!(res, None); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn test_dc_get_oauth2_url() { + async fn test_get_oauth2_url() { let ctx = TestContext::new().await; let addr = "dignifiedquire@gmail.com"; let redirect_uri = "chat.delta:/com.b44t.messenger"; - let res = dc_get_oauth2_url(&ctx.ctx, addr, redirect_uri) - .await - .unwrap(); + let res = get_oauth2_url(&ctx.ctx, addr, redirect_uri).await.unwrap(); assert_eq!(res, Some("https://accounts.google.com/o/oauth2/auth?client_id=959970109878%2D4mvtgf6feshskf7695nfln6002mom908%2Eapps%2Egoogleusercontent%2Ecom&redirect_uri=chat%2Edelta%3A%2Fcom%2Eb44t%2Emessenger&response_type=code&scope=https%3A%2F%2Fmail.google.com%2F%20email&access_type=offline".into())); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn test_dc_get_oauth2_token() { + async fn test_get_oauth2_token() { let ctx = TestContext::new().await; let addr = "dignifiedquire@gmail.com"; let code = "fail"; - let res = dc_get_oauth2_access_token(&ctx.ctx, addr, code, false) + let res = get_oauth2_access_token(&ctx.ctx, addr, code, false) .await .unwrap(); // this should fail as it is an invalid password diff --git a/src/pgp.rs b/src/pgp.rs index ba90ea7da..e9b9e7c84 100644 --- a/src/pgp.rs +++ b/src/pgp.rs @@ -18,9 +18,9 @@ use rand::{thread_rng, CryptoRng, Rng}; use tokio::runtime::Handle; use crate::constants::KeyGenType; -use crate::dc_tools::EmailAddress; use crate::key::{DcKey, Fingerprint}; use crate::keyring::Keyring; +use crate::tools::EmailAddress; pub const HEADER_AUTOCRYPT: &str = "autocrypt-prefer-encrypt"; pub const HEADER_SETUPCODE: &str = "passphrase-begin"; @@ -386,6 +386,7 @@ mod tests { use super::*; use crate::test_utils::{alice_keypair, bob_keypair}; use once_cell::sync::Lazy; + use tokio::sync::OnceCell; #[test] fn test_split_armored_data_1() { @@ -456,37 +457,50 @@ mod tests { /// Initialised [TestKeys] for tests. static KEYS: Lazy = Lazy::new(TestKeys::new); + static CTEXT_SIGNED: OnceCell = OnceCell::const_new(); + static CTEXT_UNSIGNED: OnceCell = OnceCell::const_new(); + /// A cyphertext encrypted to Alice & Bob, signed by Alice. - static CTEXT_SIGNED: Lazy = Lazy::new(|| { - let mut keyring = Keyring::new(); - keyring.add(KEYS.alice_public.clone()); - keyring.add(KEYS.bob_public.clone()); - futures_lite::future::block_on(pk_encrypt( - CLEARTEXT, - keyring, - Some(KEYS.alice_secret.clone()), - )) - .unwrap() - }); + async fn ctext_signed() -> &'static String { + CTEXT_SIGNED + .get_or_init(|| async { + let mut keyring = Keyring::new(); + keyring.add(KEYS.alice_public.clone()); + keyring.add(KEYS.bob_public.clone()); - /// A cyphertext encrypted to Alice & Bob, not signed. - static CTEXT_UNSIGNED: Lazy = Lazy::new(|| { - let mut keyring = Keyring::new(); - keyring.add(KEYS.alice_public.clone()); - keyring.add(KEYS.bob_public.clone()); - futures_lite::future::block_on(pk_encrypt(CLEARTEXT, keyring, None)).unwrap() - }); - - #[test] - fn test_encrypt_signed() { - assert!(!CTEXT_SIGNED.is_empty()); - assert!(CTEXT_SIGNED.starts_with("-----BEGIN PGP MESSAGE-----")); + pk_encrypt(CLEARTEXT, keyring, Some(KEYS.alice_secret.clone())) + .await + .unwrap() + }) + .await } - #[test] - fn test_encrypt_unsigned() { - assert!(!CTEXT_UNSIGNED.is_empty()); - assert!(CTEXT_UNSIGNED.starts_with("-----BEGIN PGP MESSAGE-----")); + /// A cyphertext encrypted to Alice & Bob, not signed. + async fn ctext_unsigned() -> &'static String { + CTEXT_UNSIGNED + .get_or_init(|| async { + let mut keyring = Keyring::new(); + keyring.add(KEYS.alice_public.clone()); + keyring.add(KEYS.bob_public.clone()); + pk_encrypt(CLEARTEXT, keyring, None).await.unwrap() + }) + .await + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_encrypt_signed() { + assert!(!ctext_signed().await.is_empty()); + assert!(ctext_signed() + .await + .starts_with("-----BEGIN PGP MESSAGE-----")); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_encrypt_unsigned() { + assert!(!ctext_unsigned().await.is_empty()); + assert!(ctext_unsigned() + .await + .starts_with("-----BEGIN PGP MESSAGE-----")); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -497,7 +511,7 @@ mod tests { let mut sig_check_keyring: Keyring = Keyring::new(); sig_check_keyring.add(KEYS.alice_public.clone()); let (plain, valid_signatures) = pk_decrypt( - CTEXT_SIGNED.as_bytes().to_vec(), + ctext_signed().await.as_bytes().to_vec(), decrypt_keyring, &sig_check_keyring, ) @@ -512,7 +526,7 @@ mod tests { let mut sig_check_keyring = Keyring::new(); sig_check_keyring.add(KEYS.alice_public.clone()); let (plain, valid_signatures) = pk_decrypt( - CTEXT_SIGNED.as_bytes().to_vec(), + ctext_signed().await.as_bytes().to_vec(), decrypt_keyring, &sig_check_keyring, ) @@ -527,10 +541,13 @@ mod tests { let mut keyring = Keyring::new(); keyring.add(KEYS.alice_secret.clone()); let empty_keyring = Keyring::new(); - let (plain, valid_signatures) = - pk_decrypt(CTEXT_SIGNED.as_bytes().to_vec(), keyring, &empty_keyring) - .await - .unwrap(); + let (plain, valid_signatures) = pk_decrypt( + ctext_signed().await.as_bytes().to_vec(), + keyring, + &empty_keyring, + ) + .await + .unwrap(); assert_eq!(plain, CLEARTEXT); assert_eq!(valid_signatures.len(), 0); } @@ -543,7 +560,7 @@ mod tests { let mut sig_check_keyring = Keyring::new(); sig_check_keyring.add(KEYS.bob_public.clone()); let (plain, valid_signatures) = pk_decrypt( - CTEXT_SIGNED.as_bytes().to_vec(), + ctext_signed().await.as_bytes().to_vec(), decrypt_keyring, &sig_check_keyring, ) @@ -559,7 +576,7 @@ mod tests { decrypt_keyring.add(KEYS.bob_secret.clone()); let sig_check_keyring = Keyring::new(); let (plain, valid_signatures) = pk_decrypt( - CTEXT_UNSIGNED.as_bytes().to_vec(), + ctext_unsigned().await.as_bytes().to_vec(), decrypt_keyring, &sig_check_keyring, ) diff --git a/src/provider.rs b/src/provider.rs index 01ad90f88..506223bde 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -192,8 +192,8 @@ mod tests { #![allow(clippy::indexing_slicing)] use super::*; - use crate::dc_tools::time; use crate::test_utils::TestContext; + use crate::tools::time; use chrono::NaiveDate; #[test] diff --git a/src/qr.rs b/src/qr.rs index 20edeb3b8..157f66c00 100644 --- a/src/qr.rs +++ b/src/qr.rs @@ -11,11 +11,11 @@ use crate::config::Config; use crate::constants::Blocked; use crate::contact::{addr_normalize, may_be_valid_addr, Contact, ContactId, Origin}; use crate::context::Context; -use crate::dc_tools::time; use crate::key::Fingerprint; use crate::message::Message; use crate::peerstate::Peerstate; use crate::token; +use crate::tools::time; const OPENPGP4FPR_SCHEME: &str = "OPENPGP4FPR:"; // yes: uppercase const DCACCOUNT_SCHEME: &str = "DCACCOUNT:"; @@ -561,7 +561,7 @@ mod tests { use crate::chat::{create_group_chat, ProtectionStatus}; use crate::key::DcKey; use crate::peerstate::ToSave; - use crate::securejoin::dc_get_securejoin_qr; + use crate::securejoin::get_securejoin_qr; use crate::test_utils::{alice_keypair, TestContext}; use anyhow::Result; @@ -889,7 +889,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_withdraw_verifycontact() -> Result<()> { let alice = TestContext::new_alice().await; - let qr = dc_get_securejoin_qr(&alice, None).await?; + let qr = get_securejoin_qr(&alice, None).await?; // scanning own verify-contact code offers withdrawing assert!(matches!( @@ -924,7 +924,7 @@ mod tests { async fn test_withdraw_verifygroup() -> Result<()> { let alice = TestContext::new_alice().await; let chat_id = create_group_chat(&alice, ProtectionStatus::Unprotected, "foo").await?; - let qr = dc_get_securejoin_qr(&alice, Some(chat_id)).await?; + let qr = get_securejoin_qr(&alice, Some(chat_id)).await?; // scanning own verify-group code offers withdrawing if let Qr::WithdrawVerifyGroup { grpname, .. } = check_qr(&alice, &qr).await? { diff --git a/src/qr_code_generator.rs b/src/qr_code_generator.rs index a4d90ed4e..b3b4aef11 100644 --- a/src/qr_code_generator.rs +++ b/src/qr_code_generator.rs @@ -32,7 +32,7 @@ async fn generate_join_group_qr_code(context: &Context, chat_id: ChatId) -> Resu inner_generate_secure_join_qr_code( &stock_str::secure_join_group_qr_description(context, &chat).await, - &securejoin::dc_get_securejoin_qr(context, Some(chat_id)).await?, + &securejoin::get_securejoin_qr(context, Some(chat_id)).await?, &color_int_to_hex_string(chat.get_color(context).await?), avatar, chat.get_name().chars().next().unwrap_or('#'), @@ -57,7 +57,7 @@ async fn generate_verification_qr(context: &Context) -> Result { inner_generate_secure_join_qr_code( &stock_str::setup_contact_qr_description(context, &displayname, contact.get_addr()).await, - &securejoin::dc_get_securejoin_qr(context, None).await?, + &securejoin::get_securejoin_qr(context, None).await?, &color_int_to_hex_string(contact.get_color()), avatar, displayname.chars().next().unwrap_or('#'), diff --git a/src/quota.rs b/src/quota.rs index 2dc552537..7c74e63a0 100644 --- a/src/quota.rs +++ b/src/quota.rs @@ -7,12 +7,12 @@ use std::collections::BTreeMap; use crate::chat::add_device_msg_with_importance; use crate::config::Config; use crate::context::Context; -use crate::dc_tools::time; use crate::imap::scan_folders::get_watched_folders; use crate::imap::Imap; use crate::job::{Action, Status}; use crate::message::{Message, Viewtype}; use crate::param::Params; +use crate::tools::time; use crate::{job, stock_str, EventType}; /// warn about a nearly full mailbox after this usage percentage is reached. diff --git a/src/dc_receive_imf.rs b/src/receive_imf.rs similarity index 97% rename from src/dc_receive_imf.rs rename to src/receive_imf.rs index c0a37ee05..ec2e951c1 100644 --- a/src/dc_receive_imf.rs +++ b/src/receive_imf.rs @@ -18,7 +18,6 @@ use crate::contact::{ may_be_valid_addr, normalize_name, Contact, ContactId, Origin, VerifiedStatus, }; use crate::context::Context; -use crate::dc_tools::{dc_create_id, dc_extract_grpid_from_rfc724_mid, dc_smeared_time}; use crate::download::DownloadState; use crate::ephemeral::{stock_ephemeral_timer_changed, Timer as EphemeralTimer}; use crate::events::EventType; @@ -37,6 +36,7 @@ use crate::peerstate::{Peerstate, PeerstateKeyType, PeerstateVerifiedStatus}; use crate::securejoin::{self, handle_securejoin_handshake, observe_securejoin_on_other_device}; use crate::sql; use crate::stock_str; +use crate::tools::{create_id, extract_grpid_from_rfc724_mid, smeared_time}; /// This is the struct that is returned after receiving one email (aka MIME message). /// @@ -59,7 +59,7 @@ pub struct ReceivedMsg { /// /// This method returns errors on a failure to parse the mail or extract Message-ID. It's only used /// for tests and REPL tool, not actual message reception pipeline. -pub async fn dc_receive_imf( +pub async fn receive_imf( context: &Context, imf_raw: &[u8], seen: bool, @@ -69,8 +69,8 @@ pub async fn dc_receive_imf( .headers .get_header_value(HeaderDef::MessageId) .and_then(|msgid| parse_message_id(&msgid).ok()) - .unwrap_or_else(dc_create_id); - dc_receive_imf_inner(context, &rfc724_mid, imf_raw, seen, None, false).await + .unwrap_or_else(create_id); + receive_imf_inner(context, &rfc724_mid, imf_raw, seen, None, false).await } /// Receive a message and add it to the database. @@ -87,7 +87,7 @@ pub async fn dc_receive_imf( /// /// If `is_partial_download` is set, it contains the full message size in bytes. /// Do not confuse that with `replace_partial_download` that will be set when the full message is loaded later. -pub(crate) async fn dc_receive_imf_inner( +pub(crate) async fn receive_imf_inner( context: &Context, rfc724_mid: &str, imf_raw: &[u8], @@ -98,14 +98,14 @@ pub(crate) async fn dc_receive_imf_inner( info!(context, "Receiving message, seen={}...", seen); if std::env::var(crate::DCC_MIME_DEBUG).unwrap_or_default() == "2" { - info!(context, "dc_receive_imf: incoming message mime-body:"); + info!(context, "receive_imf: incoming message mime-body:"); println!("{}", String::from_utf8_lossy(imf_raw)); } let mut mime_parser = match MimeMessage::from_bytes_with_partial(context, imf_raw, is_partial_download).await { Err(err) => { - warn!(context, "dc_receive_imf: can't parse MIME: {}", err); + warn!(context, "receive_imf: can't parse MIME: {}", err); return Ok(None); } Ok(mime_parser) => mime_parser, @@ -113,7 +113,7 @@ pub(crate) async fn dc_receive_imf_inner( // we can not add even an empty record if we have no info whatsoever if !mime_parser.has_headers() { - warn!(context, "dc_receive_imf: no headers found"); + warn!(context, "receive_imf: no headers found"); return Ok(None); } @@ -158,7 +158,7 @@ pub(crate) async fn dc_receive_imf_inner( let incoming = from_id != ContactId::SELF; - let to_ids = dc_add_or_lookup_contacts_by_address_list( + let to_ids = add_or_lookup_contacts_by_address_list( context, &mime_parser.recipients, if !incoming { @@ -172,7 +172,7 @@ pub(crate) async fn dc_receive_imf_inner( ) .await?; - let rcvd_timestamp = dc_smeared_time(context).await; + let rcvd_timestamp = smeared_time(context).await; let sent_timestamp = mime_parser .get_header(HeaderDef::Date) .and_then(|value| mailparse::dateparse(value).ok()) @@ -346,13 +346,13 @@ pub(crate) async fn dc_receive_imf_inner( /// /// Also returns whether it is blocked or not and its origin. /// -/// * `prevent_rename`: passed through to `dc_add_or_lookup_contacts_by_address_list()` +/// * `prevent_rename`: passed through to `add_or_lookup_contacts_by_address_list()` pub async fn from_field_to_contact_id( context: &Context, from_address_list: &[SingleInfo], prevent_rename: bool, ) -> Result<(ContactId, bool, Origin)> { - let from_ids = dc_add_or_lookup_contacts_by_address_list( + let from_ids = add_or_lookup_contacts_by_address_list( context, from_address_list, Origin::IncomingUnknownFrom, @@ -1271,7 +1271,7 @@ async fn calc_sort_timestamp( } } - Ok(min(sort_timestamp, dc_smeared_time(context).await)) + Ok(min(sort_timestamp, smeared_time(context).await)) } async fn lookup_chat_by_reply( @@ -1885,7 +1885,7 @@ fn extract_grpid(mime_parser: &MimeMessage, headerdef: HeaderDef) -> Option<&str .split(',') .map(str::trim) .filter(|part| !part.is_empty()); - parts.filter_map(dc_extract_grpid_from_rfc724_mid).next() + parts.filter_map(extract_grpid_from_rfc724_mid).next() } /// Creates ad-hoc group and returns chat ID on success. @@ -2162,7 +2162,7 @@ pub(crate) async fn get_prefetch_parent_message( /// mailing lists: In some mailing lists, many users write from the same address but with different /// display names. We don't want the display name to change everytime the user gets a new email from /// a mailing list. -async fn dc_add_or_lookup_contacts_by_address_list( +async fn add_or_lookup_contacts_by_address_list( context: &Context, address_list: &[SingleInfo], origin: Origin, @@ -2205,9 +2205,7 @@ async fn add_or_lookup_contact_by_addr( #[cfg(test)] mod tests { - - use tokio::fs::{self, File}; - use tokio::io::AsyncWriteExt; + use tokio::fs; use super::*; @@ -2294,17 +2292,15 @@ mod tests { let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap(); assert_eq!(chats.len(), 0); - dc_receive_imf(&t, MSGRMSG, false).await.unwrap(); + receive_imf(&t, MSGRMSG, false).await.unwrap(); let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap(); assert_eq!(chats.len(), 1); - dc_receive_imf(&t, ONETOONE_NOREPLY_MAIL, false) - .await - .unwrap(); + receive_imf(&t, ONETOONE_NOREPLY_MAIL, false).await.unwrap(); let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap(); assert_eq!(chats.len(), 1); - dc_receive_imf(&t, GRP_MAIL, false).await.unwrap(); + receive_imf(&t, GRP_MAIL, false).await.unwrap(); let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap(); assert_eq!(chats.len(), 1); } @@ -2313,7 +2309,7 @@ mod tests { async fn test_adhoc_group_show_accepted_contact_unknown() { let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("1")).await.unwrap(); - dc_receive_imf(&t, GRP_MAIL, false).await.unwrap(); + receive_imf(&t, GRP_MAIL, false).await.unwrap(); // adhoc-group with unknown contacts with show_emails=accepted is ignored for unknown contacts let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap(); @@ -2325,7 +2321,7 @@ mod tests { let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("1")).await.unwrap(); Contact::create(&t, "Bob", "bob@example.com").await.unwrap(); - dc_receive_imf(&t, GRP_MAIL, false).await.unwrap(); + receive_imf(&t, GRP_MAIL, false).await.unwrap(); // adhoc-group with known contacts with show_emails=accepted is still ignored for known contacts // (and existent chat is required) @@ -2339,7 +2335,7 @@ mod tests { t.set_config(Config::ShowEmails, Some("1")).await.unwrap(); // accept Bob by accepting a delta-message from Bob - dc_receive_imf(&t, MSGRMSG, false).await.unwrap(); + receive_imf(&t, MSGRMSG, false).await.unwrap(); let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap(); assert_eq!(chats.len(), 1); let chat_id = chats.get_chat_id(0).unwrap(); @@ -2354,14 +2350,12 @@ mod tests { assert_eq!(chat::get_chat_msgs(&t, chat_id, 0).await.unwrap().len(), 1); // receive a non-delta-message from Bob, shows up because of the show_emails setting - dc_receive_imf(&t, ONETOONE_NOREPLY_MAIL, false) - .await - .unwrap(); + receive_imf(&t, ONETOONE_NOREPLY_MAIL, false).await.unwrap(); assert_eq!(chat::get_chat_msgs(&t, chat_id, 0).await.unwrap().len(), 2); // let Bob create an adhoc-group by a non-delta-message, shows up because of the show_emails setting - dc_receive_imf(&t, GRP_MAIL, false).await.unwrap(); + receive_imf(&t, GRP_MAIL, false).await.unwrap(); let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap(); assert_eq!(chats.len(), 2); let chat_id = chats.get_chat_id(0).unwrap(); @@ -2375,7 +2369,7 @@ mod tests { async fn test_adhoc_group_show_all() { let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf(&t, GRP_MAIL, false).await.unwrap(); + receive_imf(&t, GRP_MAIL, false).await.unwrap(); // adhoc-group with unknown contacts with show_emails=all will show up in a single chat let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap(); @@ -2423,7 +2417,7 @@ mod tests { ); // send a message to group with bob - dc_receive_imf( + receive_imf( &t, format!( "Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ @@ -2452,7 +2446,7 @@ mod tests { assert!(group.get_visibility() == ChatVisibility::Normal); // bob sends a read receipt to the group - dc_receive_imf( + receive_imf( &t, format!( "Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ @@ -2516,7 +2510,7 @@ mod tests { let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap(); assert!(chats.get_msg_id(0).is_err()); - dc_receive_imf( + receive_imf( context, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ To: bob@example.com\n\ @@ -2543,7 +2537,7 @@ mod tests { .await .unwrap(); let chat_id = ChatId::create_for_contact(&t, contact_id).await.unwrap(); - dc_receive_imf( + receive_imf( &t, b"From: =?UTF-8?B?0JjQvNGPLCDQpNCw0LzQuNC70LjRjw==?= \n\ To: alice@example.org\n\ @@ -2582,7 +2576,7 @@ mod tests { .unwrap() .0; - dc_receive_imf( + receive_imf( &t, b"From: Foobar \n\ To: =?UTF-8?B?0JjQvNGPLCDQpNCw0LzQuNC70LjRjw==?= alice@example.org\n\ @@ -2624,7 +2618,7 @@ mod tests { .unwrap() .0; - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: Foobar \n\ @@ -2741,7 +2735,7 @@ mod tests { let t = TestContext::new().await; t.configure_addr(self_addr).await; - dc_receive_imf( + receive_imf( &t, format!( "Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ @@ -2776,7 +2770,7 @@ mod tests { .await .unwrap()); - dc_receive_imf(&t, raw_ndn, false).await.unwrap(); + receive_imf(&t, raw_ndn, false).await.unwrap(); let msg = Message::load_from_db(&t, msg_id).await.unwrap(); assert_eq!(msg.state, MessageState::OutFailed); @@ -2789,7 +2783,7 @@ mod tests { let t = TestContext::new().await; t.configure_addr("alice@gmail.com").await; - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: alice@gmail.com\n\ @@ -2811,7 +2805,7 @@ mod tests { let msg_id = chats.get_msg_id(0)?.unwrap(); let raw = include_bytes!("../test-data/message/gmail_ndn_group.eml"); - dc_receive_imf(&t, raw, false).await?; + receive_imf(&t, raw, false).await?; let msg = Message::load_from_db(&t, msg_id).await?; @@ -2838,7 +2832,7 @@ mod tests { .set_config(Config::ShowEmails, Some("2")) .await .unwrap(); - dc_receive_imf(context, imf_raw, false).await.unwrap(); + receive_imf(context, imf_raw, false).await.unwrap(); let chats = Chatlist::try_load(context, 0, None, None).await.unwrap(); let msg_id = chats.get_msg_id(0).unwrap().unwrap(); Message::load_from_db(context, msg_id).await.unwrap() @@ -2882,7 +2876,7 @@ mod tests { let t = TestContext::new_alice().await; t.ctx.set_config(Config::ShowEmails, Some("2")).await?; - dc_receive_imf(&t.ctx, GH_MAILINGLIST, false).await?; + receive_imf(&t.ctx, GH_MAILINGLIST, false).await?; let chats = Chatlist::try_load(&t.ctx, 0, None, None).await?; assert_eq!(chats.len(), 1); @@ -2896,7 +2890,7 @@ mod tests { assert_eq!(chat.name, "deltachat/deltachat-core-rust"); assert_eq!(chat::get_chat_contacts(&t.ctx, chat_id).await?.len(), 1); - dc_receive_imf(&t.ctx, GH_MAILINGLIST2.as_bytes(), false).await?; + receive_imf(&t.ctx, GH_MAILINGLIST2.as_bytes(), false).await?; let chat = chat::Chat::load_from_db(&t.ctx, chat_id).await?; assert!(!chat.can_send(&t.ctx).await?); @@ -2951,7 +2945,7 @@ mod tests { .set_config(Config::ShowEmails, Some("2")) .await .unwrap(); - dc_receive_imf(&t.ctx, DC_MAILINGLIST, false).await.unwrap(); + receive_imf(&t.ctx, DC_MAILINGLIST, false).await.unwrap(); let chats = Chatlist::try_load(&t.ctx, 0, None, None).await.unwrap(); let chat_id = chats.get_chat_id(0).unwrap(); chat_id.accept(&t).await.unwrap(); @@ -2982,7 +2976,7 @@ mod tests { Hello mailinglist!\r\n" )); - dc_receive_imf(&t.ctx, DC_MAILINGLIST2, false).await?; + receive_imf(&t.ctx, DC_MAILINGLIST2, false).await?; let chat = chat::Chat::load_from_db(&t.ctx, chat_id).await?; assert!(chat.can_send(&t.ctx).await?); @@ -2994,7 +2988,7 @@ Hello mailinglist!\r\n" async fn test_other_device_writes_to_mailinglist() -> Result<()> { let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await?; - dc_receive_imf(&t, DC_MAILINGLIST, false).await.unwrap(); + receive_imf(&t, DC_MAILINGLIST, false).await.unwrap(); let first_msg = t.get_last_msg().await; let first_chat = Chat::load_from_db(&t, first_msg.chat_id).await?; assert_eq!( @@ -3018,7 +3012,7 @@ Hello mailinglist!\r\n" (first_chat.id, false, Blocked::Request) ); - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: Alice \n\ @@ -3048,7 +3042,7 @@ Hello mailinglist!\r\n" .await .unwrap(); - dc_receive_imf(&t.ctx, DC_MAILINGLIST, false).await.unwrap(); + receive_imf(&t.ctx, DC_MAILINGLIST, false).await.unwrap(); let chats = Chatlist::try_load(&t.ctx, 0, None, None).await.unwrap(); assert_eq!(chats.len(), 1); let chat_id = chats.get_chat_id(0).unwrap(); @@ -3061,9 +3055,7 @@ Hello mailinglist!\r\n" let chats = Chatlist::try_load(&t.ctx, 0, None, None).await.unwrap(); assert_eq!(chats.len(), 0); // Test that the message disappeared - dc_receive_imf(&t.ctx, DC_MAILINGLIST2, false) - .await - .unwrap(); + receive_imf(&t.ctx, DC_MAILINGLIST2, false).await.unwrap(); // Test that the mailing list stays disappeared let chats = Chatlist::try_load(&t.ctx, 0, None, None).await.unwrap(); @@ -3079,7 +3071,7 @@ Hello mailinglist!\r\n" let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf(&t, DC_MAILINGLIST, false).await.unwrap(); + receive_imf(&t, DC_MAILINGLIST, false).await.unwrap(); let blocked = Contact::get_all_blocked(&t).await.unwrap(); assert_eq!(blocked.len(), 0); @@ -3099,9 +3091,7 @@ Hello mailinglist!\r\n" let blocked = Contact::get_all_blocked(&t).await.unwrap(); assert_eq!(blocked.len(), 0); - dc_receive_imf(&t.ctx, DC_MAILINGLIST2, false) - .await - .unwrap(); + receive_imf(&t.ctx, DC_MAILINGLIST2, false).await.unwrap(); let msg = t.get_last_msg().await; let msgs = chat::get_chat_msgs(&t, msg.chat_id, 0).await.unwrap(); assert_eq!(msgs.len(), 2); @@ -3115,7 +3105,7 @@ Hello mailinglist!\r\n" .await .unwrap(); - dc_receive_imf(&t.ctx, DC_MAILINGLIST, false).await.unwrap(); + receive_imf(&t.ctx, DC_MAILINGLIST, false).await.unwrap(); let msg = t.get_last_msg().await; let chat_id = msg.get_chat_id(); @@ -3128,9 +3118,7 @@ Hello mailinglist!\r\n" let msgs = chat::get_chat_msgs(&t.ctx, chat_id, 0).await.unwrap(); assert_eq!(msgs.len(), 1); // ...and contains 1 message - dc_receive_imf(&t.ctx, DC_MAILINGLIST2, false) - .await - .unwrap(); + receive_imf(&t.ctx, DC_MAILINGLIST2, false).await.unwrap(); let chats = Chatlist::try_load(&t.ctx, 0, None, None).await.unwrap(); assert_eq!(chats.len(), 1); // Test that the new mailing list message got into the same chat @@ -3148,7 +3136,7 @@ Hello mailinglist!\r\n" .await .unwrap(); - dc_receive_imf(&t.ctx, DC_MAILINGLIST, false).await.unwrap(); + receive_imf(&t.ctx, DC_MAILINGLIST, false).await.unwrap(); let msg = t.get_last_msg().await; let chat_id = msg.get_chat_id(); @@ -3158,9 +3146,7 @@ Hello mailinglist!\r\n" assert_eq!(chats.len(), 1); // Test that the message is shown assert!(!chat_id.is_special()); - dc_receive_imf(&t.ctx, DC_MAILINGLIST2, false) - .await - .unwrap(); + receive_imf(&t.ctx, DC_MAILINGLIST2, false).await.unwrap(); let msgs = chat::get_chat_msgs(&t.ctx, chat_id, 0).await.unwrap(); assert_eq!(msgs.len(), 2); @@ -3172,7 +3158,7 @@ Hello mailinglist!\r\n" async fn test_mailing_list_multiple_names_in_subject() -> Result<()> { let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await?; - dc_receive_imf( + receive_imf( &t, b"From: Foo Bar \n\ To: deltachat/deltachat-core-rust \n\ @@ -3199,7 +3185,7 @@ Hello mailinglist!\r\n" t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); // test mailing lists not having a `ListId:`-header - dc_receive_imf( + receive_imf( &t, b"From: Foo Bar \n\ To: deltachat/deltachat-core-rust \n\ @@ -3224,7 +3210,7 @@ Hello mailinglist!\r\n" // receive another message with no sender name but the same address, // make sure this lands in the same chat - dc_receive_imf( + receive_imf( &t, b"From: Nu Bar \n\ To: deltachat/deltachat-core-rust \n\ @@ -3247,7 +3233,7 @@ Hello mailinglist!\r\n" let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf( + receive_imf( &t, b"To: alice \n\ Subject: =?utf-8?Q?How=20early=20megacities=20emerged=20from=20Cambodia=E2=80=99s=20jungles?=\n\ @@ -3277,7 +3263,7 @@ Hello mailinglist!\r\n" let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/mailinglist_dhl.eml"), false, @@ -3302,7 +3288,7 @@ Hello mailinglist!\r\n" let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/mailinglist_dpd.eml"), false, @@ -3327,7 +3313,7 @@ Hello mailinglist!\r\n" let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await?; - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/mailinglist_xt_local_microsoft.eml"), false, @@ -3338,7 +3324,7 @@ Hello mailinglist!\r\n" assert_eq!(chat.grpid, "96540.xt.local"); assert_eq!(chat.name, "Microsoft Store"); - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/mailinglist_xt_local_spiegel.eml"), false, @@ -3357,7 +3343,7 @@ Hello mailinglist!\r\n" let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await?; - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/mailinglist_xing.eml"), false, @@ -3378,7 +3364,7 @@ Hello mailinglist!\r\n" let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await?; - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/mailinglist_ttline.eml"), false, @@ -3404,7 +3390,7 @@ Hello mailinglist!\r\n" // if the user-edited text contains html. // this footer should not become a text-message in delta chat // (otherwise every second mail might be the same footer) - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/mailinglist_with_mimepart_footer.eml"), false, @@ -3430,7 +3416,7 @@ Hello mailinglist!\r\n" let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/mailinglist_with_mimepart_footer_signed.eml"), false, @@ -3455,7 +3441,7 @@ Hello mailinglist!\r\n" let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf(&t, GH_MAILINGLIST, false).await.unwrap(); + receive_imf(&t, GH_MAILINGLIST, false).await.unwrap(); let chat_id = t.get_last_msg().await.chat_id; chat_id.accept(&t).await.unwrap(); @@ -3463,7 +3449,7 @@ Hello mailinglist!\r\n" assert!(chat.can_send(&t).await.unwrap()); let imf_raw = format!("In-Reply-To: 3333@example.org\n{}", GH_MAILINGLIST2); - dc_receive_imf(&t, imf_raw.as_bytes(), false).await.unwrap(); + receive_imf(&t, imf_raw.as_bytes(), false).await.unwrap(); assert_eq!( t.get_last_msg().await.in_reply_to.unwrap(), @@ -3511,7 +3497,7 @@ Hello mailinglist!\r\n" .set_config(Config::ShowEmails, Some("2")) .await .unwrap(); - dc_receive_imf( + receive_imf( &t, format!( "Subject: Re: [deltachat/deltachat-core-rust] DC is the best repo on GitHub! @@ -3583,7 +3569,7 @@ YEAAAAAA!. let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/many_images_amazon_via_apple_mail.eml"), false, @@ -3605,7 +3591,7 @@ YEAAAAAA!. t.configure_addr("bob@example.com").await; // Receive message from Alice about group "foo". - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: alice@example.org\n\ @@ -3624,7 +3610,7 @@ YEAAAAAA!. .unwrap(); // Receive reply from Charlie without group ID but with In-Reply-To header. - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: charlie@example.net\n\ @@ -3670,7 +3656,7 @@ YEAAAAAA!. t.configure_addr("bob@example.com").await; // Receive message from Alice about group "foo". - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: alice@example.org\n\ @@ -3690,7 +3676,7 @@ YEAAAAAA!. // Receive a classic MUA reply from Alice. // It is assigned to the group chat. - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: alice@example.org\n\ @@ -3714,7 +3700,7 @@ YEAAAAAA!. // Receive a Delta Chat reply from Alice. // It is assigned to group chat, because it has a group ID. - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: alice@example.org\n\ @@ -3742,7 +3728,7 @@ YEAAAAAA!. // It is assigned to 1:1 chat, because it has no group ID, // which means it was created using "reply privately" feature. // Normally it contains a quote, but it should not matter. - dc_receive_imf( + receive_imf( &t, b"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ From: alice@example.org\n\ @@ -3865,7 +3851,7 @@ YEAAAAAA!. .set_config(Config::ShowEmails, Some("2")) .await .unwrap(); - dc_receive_imf(&alice, claire_request.as_bytes(), false) + receive_imf(&alice, claire_request.as_bytes(), false) .await .unwrap(); @@ -3888,7 +3874,7 @@ YEAAAAAA!. .set_config(Config::ShowEmails, Some("2")) .await .unwrap(); - dc_receive_imf(&claire, claire_request.as_bytes(), false) + receive_imf(&claire, claire_request.as_bytes(), false) .await .unwrap(); @@ -3918,7 +3904,7 @@ YEAAAAAA!. // Check that Alice gets the message in the same chat. let request = alice.get_last_msg().await; - dc_receive_imf(&alice, reply, false).await.unwrap(); + receive_imf(&alice, reply, false).await.unwrap(); let answer = alice.get_last_msg().await; assert_eq!(answer.get_subject(), "Re: i have a question"); assert!(answer.get_text().unwrap().contains("the version is 1.0")); @@ -3941,7 +3927,7 @@ YEAAAAAA!. // Check that Claire also gets the message in the same chat. let request = claire.get_last_msg().await; - dc_receive_imf(&claire, reply, false).await.unwrap(); + receive_imf(&claire, reply, false).await.unwrap(); let answer = claire.get_last_msg().await; assert_eq!(answer.get_subject(), "Re: i have a question"); assert!(answer.get_text().unwrap().contains("the version is 1.0")); @@ -4001,7 +3987,7 @@ YEAAAAAA!. let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); println!("\n========= Receive a message =========="); - dc_receive_imf( + receive_imf( &t, b"From: Nu Bar \n\ To: alice@example.org, bob@example.org\n\ @@ -4026,7 +4012,7 @@ YEAAAAAA!. assert_eq!(msgs.len(), 0); println!("\n========= Receive a message that is a reply to the deleted message =========="); - dc_receive_imf( + receive_imf( &t, b"From: Nu Bar \n\ To: alice@example.org, bob@example.org\n\ @@ -4051,7 +4037,7 @@ YEAAAAAA!. // be shown in the self-chat. let t = TestContext::new_alice().await; - dc_receive_imf( + receive_imf( &t, b"Bcc: alice@example.org Received: from [127.0.0.1] @@ -4082,7 +4068,7 @@ Message content", .unwrap(); // Alice downloads outgoing classic email. - dc_receive_imf( + receive_imf( &alice, b"Received: from [127.0.0.1] Subject: Subj @@ -4139,18 +4125,18 @@ Message content -- Second signature"; - dc_receive_imf(&alice, first_message, false).await?; + receive_imf(&alice, first_message, false).await?; let contact = Contact::load_from_db(&alice, bob_contact_id).await?; assert_eq!(contact.get_status(), "First signature"); assert_eq!(contact.get_display_name(), "Bob1"); - dc_receive_imf(&alice, second_message, false).await?; + receive_imf(&alice, second_message, false).await?; let contact = Contact::load_from_db(&alice, bob_contact_id).await?; assert_eq!(contact.get_status(), "Second signature"); assert_eq!(contact.get_display_name(), "Bob2"); // Duplicate message, should be ignored - dc_receive_imf(&alice, first_message, false).await?; + receive_imf(&alice, first_message, false).await?; // No change because last message is duplicate of the first. let contact = Contact::load_from_db(&alice, bob_contact_id).await?; @@ -4171,7 +4157,7 @@ Second signature"; assert_eq!(bob.get_status(), ""); assert_eq!(Chatlist::try_load(&t, 0, None, None).await?.len(), 0); - dc_receive_imf( + receive_imf( &t, b"From: Bob To: Alice @@ -4189,7 +4175,7 @@ Original signature", let bob = Contact::load_from_db(&t, bob_id).await?; assert_eq!(bob.get_status(), "Original signature"); - dc_receive_imf( + receive_imf( &t, b"From: Bob Sender: ml@example.net @@ -4211,7 +4197,7 @@ Tap here to unsubscribe ...", let bob = Contact::load_from_db(&t, bob_id).await?; assert_eq!(bob.get_status(), "Original signature"); - dc_receive_imf( + receive_imf( &t, b"From: Bob To: Alice @@ -4239,7 +4225,7 @@ Original signature updated", let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf( + receive_imf( &t, format!( r#"Received: from mout.gmx.net (mout.gmx.net [212.227.17.22]) @@ -4281,7 +4267,7 @@ Message-ID: " assert_eq!(group_chat.typ, Chattype::Group); assert_eq!(group_chat.name, "single reply-to"); - dc_receive_imf( + receive_imf( &t, format!( r#"Subject: Re: single reply-to @@ -4325,7 +4311,7 @@ Private reply"#, let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf( + receive_imf( &t, format!( r#"Received: from mout.gmx.net (mout.gmx.net [212.227.17.22]) @@ -4371,7 +4357,7 @@ Message-ID: " assert_eq!(group_chat.typ, Chattype::Group); assert_eq!(group_chat.name, "single reply-to"); - dc_receive_imf( + receive_imf( &t, format!( r#"Subject: =?utf-8?q?Re=3A_single_reply-to?= @@ -4419,7 +4405,7 @@ Sent with my Delta Chat Messenger: https://delta.chat let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf( + receive_imf( &t, format!( r#"Received: from mout.gmx.net (mout.gmx.net [212.227.17.22]) @@ -4461,7 +4447,7 @@ Message-ID: " assert_eq!(group_chat.name, "single reply-to"); // =============== Receive another outgoing message and check that it is put into the same chat =============== - dc_receive_imf( + receive_imf( &t, format!( r#"Received: from mout.gmx.net (mout.gmx.net [212.227.17.22]) @@ -4492,7 +4478,7 @@ Outgoing reply to all"#, assert_eq!(reply.chat_id, group_msg.chat_id); // =============== Receive an incoming message and check that it is put into the same chat =============== - dc_receive_imf( + receive_imf( &t, br#"Received: from mout.gmx.net (mout.gmx.net [212.227.17.22]) Subject: In subj @@ -4545,15 +4531,15 @@ Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no Second thread."#; // Alice receives two classic emails from Claire. - dc_receive_imf(&alice, first_thread_mime, false).await?; + receive_imf(&alice, first_thread_mime, false).await?; let alice_first_msg = alice.get_last_msg().await; - dc_receive_imf(&alice, second_thread_mime, false).await?; + receive_imf(&alice, second_thread_mime, false).await?; let alice_second_msg = alice.get_last_msg().await; // Bob receives the same two emails. - dc_receive_imf(&bob, first_thread_mime, false).await?; + receive_imf(&bob, first_thread_mime, false).await?; let bob_first_msg = bob.get_last_msg().await; - dc_receive_imf(&bob, second_thread_mime, false).await?; + receive_imf(&bob, second_thread_mime, false).await?; let bob_second_msg = bob.get_last_msg().await; // Messages go to separate chats both for Alice and Bob. @@ -4626,7 +4612,7 @@ Second thread."#; let mdn_body = rendered_mdn.message; // Alice receives the read receipt. - dc_receive_imf(&alice, mdn_body.as_bytes(), false).await?; + receive_imf(&alice, mdn_body.as_bytes(), false).await?; // Chat should not pop up in the chatlist. let chats = Chatlist::try_load(&alice, 0, None, None).await?; @@ -4640,7 +4626,7 @@ Second thread."#; let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await?; - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/gmx-forward.eml"), false, @@ -4659,7 +4645,7 @@ Second thread."#; async fn test_incoming_contact_request() -> Result<()> { let t = TestContext::new_alice().await; - dc_receive_imf(&t, MSGRMSG, false).await?; + receive_imf(&t, MSGRMSG, false).await?; let msg = t.get_last_msg().await; let chat = chat::Chat::load_from_db(&t, msg.chat_id).await?; assert!(chat.is_contact_request()); @@ -4692,7 +4678,7 @@ From: Bob Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no First."#; - dc_receive_imf(&t, mime, false).await?; + receive_imf(&t, mime, false).await?; let first = t.get_last_msg().await; let mime = br#"Subject: Second Message-ID: second@example.net @@ -4701,7 +4687,7 @@ From: Bob Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no First."#; - dc_receive_imf(&t, mime, false).await?; + receive_imf(&t, mime, false).await?; let second = t.get_last_msg().await; let mime = br#"Subject: Third Message-ID: third@example.net @@ -4710,7 +4696,7 @@ From: Bob Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no First."#; - dc_receive_imf(&t, mime, false).await?; + receive_imf(&t, mime, false).await?; let third = t.get_last_msg().await; let mime = br#"Subject: Message with references. @@ -4761,7 +4747,7 @@ Message with references."#; // Alice sends a message to Bob using Thunderbird. let raw = include_bytes!("../test-data/message/rfc1847_encapsulation.eml"); - dc_receive_imf(&bob, raw, false).await?; + receive_imf(&bob, raw, false).await?; let msg = bob.get_last_msg().await; assert!(msg.get_showpadlock()); @@ -4775,8 +4761,8 @@ Message with references."#; let mime = include_bytes!("../test-data/message/invalid_email_to.eml"); - // dc_receive_imf should not fail on this mail with invalid To: field - dc_receive_imf(&alice, mime, false).await?; + // receive_imf should not fail on this mail with invalid To: field + receive_imf(&alice, mime, false).await?; Ok(()) } @@ -4787,7 +4773,7 @@ Message with references."#; t.set_config(Config::ShowEmails, Some("2")).await?; // Alice creates a 2-person-group with Bob - dc_receive_imf( + receive_imf( &t, br#"Subject: =?utf-8?q?Januar_13-19?= Chat-Group-ID: qetqsutor7a @@ -4811,7 +4797,7 @@ Hi, I created a group"#, assert_eq!(msg_out.in_reply_to, None); // Bob replies from a different address - dc_receive_imf( + receive_imf( &t, b"Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable @@ -4863,10 +4849,7 @@ Reply from different address ] { let attachment = alice.blobdir.join(filename_sent); let content = format!("File content of {}", filename_sent); - File::create(&attachment) - .await? - .write_all(content.as_bytes()) - .await?; + tokio::fs::write(&attachment, content.as_bytes()).await?; let mut msg_alice = Message::new(Viewtype::File); msg_alice.set_file(attachment.to_str().unwrap(), None); diff --git a/src/scheduler.rs b/src/scheduler.rs index 46b98ba71..aeaf2d32e 100644 --- a/src/scheduler.rs +++ b/src/scheduler.rs @@ -6,8 +6,6 @@ use tokio::task; use crate::config::Config; use crate::context::Context; -use crate::dc_tools::time; -use crate::dc_tools::{duration_to_str, maybe_add_time_based_warnings}; use crate::ephemeral::{self, delete_expired_imap_messages}; use crate::imap::Imap; use crate::job; @@ -15,6 +13,8 @@ use crate::location; use crate::log::LogExt; use crate::smtp::{send_smtp_messages, Smtp}; use crate::sql; +use crate::tools::time; +use crate::tools::{duration_to_str, maybe_add_time_based_warnings}; use self::connectivity::ConnectivityStore; diff --git a/src/scheduler/connectivity.rs b/src/scheduler/connectivity.rs index 8564046a5..4fe16c90b 100644 --- a/src/scheduler/connectivity.rs +++ b/src/scheduler/connectivity.rs @@ -3,13 +3,13 @@ use std::{ops::Deref, sync::Arc}; use tokio::sync::{Mutex, RwLockReadGuard}; -use crate::dc_tools::time; use crate::events::EventType; use crate::imap::scan_folders::get_watched_folder_configs; use crate::quota::{ QUOTA_ERROR_THRESHOLD_PERCENTAGE, QUOTA_MAX_AGE_SECONDS, QUOTA_WARN_THRESHOLD_PERCENTAGE, }; -use crate::{config::Config, dc_tools, scheduler::Scheduler, stock_str}; +use crate::tools::time; +use crate::{config::Config, scheduler::Scheduler, stock_str, tools}; use crate::{context::Context, log::LogExt}; use anyhow::{anyhow, Result}; use humansize::{file_size_opts, FileSize}; @@ -449,7 +449,7 @@ impl Context { // [======67%===== ] // ============================================================================================= - let domain = dc_tools::EmailAddress::new(&self.get_primary_self_addr().await?)?.domain; + let domain = tools::EmailAddress::new(&self.get_primary_self_addr().await?)?.domain; ret += &format!( "

{}

    ", stock_str::storage_on_domain(self, domain).await diff --git a/src/securejoin.rs b/src/securejoin.rs index f6a6cbdcb..2f573659f 100644 --- a/src/securejoin.rs +++ b/src/securejoin.rs @@ -11,7 +11,6 @@ use crate::config::Config; use crate::constants::Blocked; use crate::contact::{Contact, ContactId, Origin, VerifiedStatus}; use crate::context::Context; -use crate::dc_tools::time; use crate::e2ee::ensure_secret_key_exists; use crate::events::EventType; use crate::headerdef::HeaderDef; @@ -23,6 +22,7 @@ use crate::peerstate::{Peerstate, PeerstateKeyType, PeerstateVerifiedStatus, ToS use crate::qr::check_qr; use crate::stock_str; use crate::token; +use crate::tools::time; mod bob; mod bobstate; @@ -51,7 +51,7 @@ macro_rules! inviter_progress { /// /// With `group` set to `None` this generates a setup-contact QR code, with `group` set to a /// [`ChatId`] generates a join-group QR code for the given chat. -pub async fn dc_get_securejoin_qr(context: &Context, group: Option) -> Result { +pub async fn get_securejoin_qr(context: &Context, group: Option) -> Result { /*======================================================= ==== Alice - the inviter side ==== ==== Step 1 in "Setup verified contact" protocol ==== @@ -143,7 +143,7 @@ async fn get_self_fingerprint(context: &Context) -> Option { /// for more details. /// /// The function returns immediately and the handshake will run in background. -pub async fn dc_join_securejoin(context: &Context, qr: &str) -> Result { +pub async fn join_securejoin(context: &Context, qr: &str) -> Result { securejoin(context, qr).await.map_err(|err| { warn!(context, "Fatal joiner error: {:#}", err); // The user just scanned this QR code so has context on what failed. @@ -238,10 +238,10 @@ async fn fingerprint_equals_sender( /// What to do with a Secure-Join handshake message after it was handled. /// -/// This status is returned to [`dc_receive_imf`] which will use it to decide what to do +/// This status is returned to [`receive_imf`] which will use it to decide what to do /// next with this incoming setup-contact/secure-join handshake message. /// -/// [`dc_receive_imf`]: crate::dc_receive_imf::dc_receive_imf +/// [`receive_imf`]: crate::receive_imf::receive_imf pub(crate) enum HandshakeMessage { /// The message has been fully handled and should be removed/delete. /// @@ -692,8 +692,8 @@ mod tests { use crate::chat::ProtectionStatus; use crate::chatlist::Chatlist; use crate::constants::{Chattype, DC_GCM_ADDDAYMARKER}; - use crate::dc_receive_imf::dc_receive_imf; use crate::peerstate::Peerstate; + use crate::receive_imf::receive_imf; use crate::test_utils::{TestContext, TestContextManager}; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -714,10 +714,10 @@ mod tests { ); // Step 1: Generate QR-code, ChatId(0) indicates setup-contact - let qr = dc_get_securejoin_qr(&alice.ctx, None).await.unwrap(); + let qr = get_securejoin_qr(&alice.ctx, None).await.unwrap(); // Step 2: Bob scans QR-code, sends vc-request - dc_join_securejoin(&bob.ctx, &qr).await.unwrap(); + join_securejoin(&bob.ctx, &qr).await.unwrap(); assert_eq!( Chatlist::try_load(&bob, 0, None, None).await.unwrap().len(), 1 @@ -906,7 +906,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_setup_contact_bad_qr() { let bob = TestContext::new_bob().await; - let ret = dc_join_securejoin(&bob.ctx, "not a qr code").await; + let ret = join_securejoin(&bob.ctx, "not a qr code").await; assert!(ret.is_err()); } @@ -936,10 +936,10 @@ mod tests { peerstate.save_to_db(&bob.ctx.sql, true).await?; // Step 1: Generate QR-code, ChatId(0) indicates setup-contact - let qr = dc_get_securejoin_qr(&alice.ctx, None).await?; + let qr = get_securejoin_qr(&alice.ctx, None).await?; // Step 2+4: Bob scans QR-code, sends vc-request-with-auth, skipping vc-request - dc_join_securejoin(&bob.ctx, &qr).await.unwrap(); + join_securejoin(&bob.ctx, &qr).await.unwrap(); // Check Bob emitted the JoinerProgress event. let event = bob @@ -1043,7 +1043,7 @@ mod tests { // do a scan that is not working as claire is never responding let qr_stale = "OPENPGP4FPR:1234567890123456789012345678901234567890#a=claire%40foo.de&n=&i=12345678901&s=23456789012"; - let claire_id = dc_join_securejoin(&bob, qr_stale).await?; + let claire_id = join_securejoin(&bob, qr_stale).await?; let chat = Chat::load_from_db(&bob, claire_id).await?; assert!(!claire_id.is_special()); assert_eq!(chat.typ, Chattype::Single); @@ -1051,8 +1051,8 @@ mod tests { // subsequent scans shall abort existing ones or run concurrently - // but they must not fail as otherwise the whole qr scanning becomes unusable until restart. - let qr = dc_get_securejoin_qr(&alice, None).await?; - let alice_id = dc_join_securejoin(&bob, &qr).await?; + let qr = get_securejoin_qr(&alice, None).await?; + let alice_id = join_securejoin(&bob, &qr).await?; let chat = Chat::load_from_db(&bob, alice_id).await?; assert!(!alice_id.is_special()); assert_eq!(chat.typ, Chattype::Single); @@ -1080,12 +1080,12 @@ mod tests { chat::create_group_chat(&alice.ctx, ProtectionStatus::Protected, "the chat").await?; // Step 1: Generate QR-code, secure-join implied by chatid - let qr = dc_get_securejoin_qr(&alice.ctx, Some(alice_chatid)) + let qr = get_securejoin_qr(&alice.ctx, Some(alice_chatid)) .await .unwrap(); // Step 2: Bob scans QR-code, sends vg-request - let bob_chatid = dc_join_securejoin(&bob.ctx, &qr).await?; + let bob_chatid = join_securejoin(&bob.ctx, &qr).await?; assert_eq!(Chatlist::try_load(&bob, 0, None, None).await?.len(), 1); let sent = bob.pop_sent_msg().await; @@ -1303,11 +1303,11 @@ Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no First thread."#; - dc_receive_imf(&alice, mime, false).await?; + receive_imf(&alice, mime, false).await?; let msg = alice.get_last_msg().await; let chat_id = msg.chat_id; - assert!(dc_get_securejoin_qr(&alice, Some(chat_id)).await.is_err()); + assert!(get_securejoin_qr(&alice, Some(chat_id)).await.is_err()); Ok(()) } } diff --git a/src/securejoin/bob.rs b/src/securejoin/bob.rs index e99c7c196..a0f048b83 100644 --- a/src/securejoin/bob.rs +++ b/src/securejoin/bob.rs @@ -9,9 +9,9 @@ use crate::chat::{is_contact_in_chat, ChatId, ProtectionStatus}; use crate::constants::{Blocked, Chattype}; use crate::contact::Contact; use crate::context::Context; -use crate::dc_tools::time; use crate::events::EventType; use crate::mimeparser::MimeMessage; +use crate::tools::time; use crate::{chat, stock_str}; use super::bobstate::{BobHandshakeStage, BobState}; @@ -33,7 +33,7 @@ use super::HandshakeMessage; pub(super) async fn start_protocol(context: &Context, invite: QrInvite) -> Result { // A 1:1 chat is needed to send messages to Alice. When joining a group this chat is // hidden, if a user starts sending messages in it it will be unhidden in - // dc_receive_imf. + // receive_imf. let hidden = match invite { QrInvite::Contact { .. } => Blocked::Not, QrInvite::Group { .. } => Blocked::Yes, diff --git a/src/smtp.rs b/src/smtp.rs index 830e3ecf8..3a4fe5f1c 100644 --- a/src/smtp.rs +++ b/src/smtp.rs @@ -14,12 +14,12 @@ use crate::config::Config; use crate::contact::{Contact, ContactId}; use crate::events::EventType; use crate::login_param::{ - dc_build_tls, CertificateChecks, LoginParam, ServerLoginParam, Socks5Config, + build_tls, CertificateChecks, LoginParam, ServerLoginParam, Socks5Config, }; use crate::message::Message; use crate::message::{self, MsgId}; use crate::mimefactory::MimeFactory; -use crate::oauth2::dc_get_oauth2_access_token; +use crate::oauth2::get_oauth2_access_token; use crate::provider::Socket; use crate::sql; use crate::{context::Context, scheduler::connectivity::ConnectivityStore}; @@ -140,13 +140,13 @@ impl Smtp { CertificateChecks::AcceptInvalidCertificates | CertificateChecks::AcceptInvalidCertificates2 => false, }; - let tls_config = dc_build_tls(strict_tls); + let tls_config = build_tls(strict_tls); let tls_parameters = ClientTlsParameters::new(domain.to_string(), tls_config); let (creds, mechanism) = if lp.oauth2 { // oauth2 let send_pw = &lp.password; - let access_token = dc_get_oauth2_access_token(context, addr, send_pw, false).await?; + let access_token = get_oauth2_access_token(context, addr, send_pw, false).await?; if access_token.is_none() { bail!("SMTP OAuth 2 error {}", addr); } @@ -434,7 +434,7 @@ pub(crate) async fn send_msg_to_smtp( .collect::>(); // If there is a msg-id and it does not exist in the db, cancel sending. this happens if - // dc_delete_msgs() was called before the generated mime was sent out. + // delete_msgs() was called before the generated mime was sent out. if !message::exists(context, msg_id) .await .with_context(|| format!("failed to check message {} existence", msg_id))? diff --git a/src/sql.rs b/src/sql.rs index 2ac4b7cf9..0a56ada1f 100644 --- a/src/sql.rs +++ b/src/sql.rs @@ -15,13 +15,13 @@ use crate::chat::{add_device_msg, update_device_icon, update_saved_messages_icon use crate::config::Config; use crate::constants::DC_CHAT_ID_TRASH; use crate::context::Context; -use crate::dc_tools::{dc_delete_file, time}; use crate::ephemeral::start_ephemeral_timers; use crate::log::LogExt; use crate::message::{Message, Viewtype}; use crate::param::{Param, Params}; use crate::peerstate::{deduplicate_peerstates, Peerstate}; use crate::stock_str; +use crate::tools::{delete_file, time}; #[macro_export] macro_rules! paramsv { @@ -788,7 +788,7 @@ pub async fn remove_unused_files(context: &Context) -> Result<()> { entry.file_name() ); let path = entry.path(); - dc_delete_file(context, path).await; + delete_file(context, path).await; } } Err(err) => { @@ -879,8 +879,6 @@ pub fn repeat_vars(count: usize) -> String { #[cfg(test)] mod tests { use async_channel as channel; - use tokio::fs::File; - use tokio::io::AsyncWriteExt; use crate::config::Config; use crate::{test_utils::TestContext, EventType}; @@ -950,12 +948,7 @@ mod tests { let avatar_src = t.dir.path().join("avatar.png"); let avatar_bytes = include_bytes!("../test-data/image/avatar64x64.png"); - File::create(&avatar_src) - .await - .unwrap() - .write_all(avatar_bytes) - .await - .unwrap(); + tokio::fs::write(&avatar_src, avatar_bytes).await.unwrap(); t.set_config(Config::Selfavatar, Some(avatar_src.to_str().unwrap())) .await .unwrap(); diff --git a/src/sql/migrations.rs b/src/sql/migrations.rs index e2e5dc354..2d4f43fd7 100644 --- a/src/sql/migrations.rs +++ b/src/sql/migrations.rs @@ -5,10 +5,10 @@ use anyhow::{Context as _, Result}; use crate::config::Config; use crate::constants::ShowEmails; use crate::context::Context; -use crate::dc_tools::EmailAddress; use crate::imap; use crate::provider::get_provider_by_domain; use crate::sql::Sql; +use crate::tools::EmailAddress; const DBVERSION: i32 = 68; const VERSION_CFG: &str = "dbversion"; diff --git a/src/stock_str.rs b/src/stock_str.rs index fdd56a41a..ff5d071c4 100644 --- a/src/stock_str.rs +++ b/src/stock_str.rs @@ -12,9 +12,9 @@ use crate::chat::{self, Chat, ChatId, ProtectionStatus}; use crate::config::Config; use crate::contact::{Contact, ContactId, Origin}; use crate::context::Context; -use crate::dc_tools::dc_timestamp_to_str; use crate::message::{Message, Viewtype}; use crate::param::Param; +use crate::tools::timestamp_to_str; use humansize::{file_size_opts, FileSize}; /// Stock strings @@ -988,7 +988,7 @@ pub(crate) async fn partial_download_msg_body(context: &Context, org_bytes: u32) pub(crate) async fn download_availability(context: &Context, timestamp: i64) -> String { translated(context, StockMessage::DownloadAvailability) .await - .replace1(dc_timestamp_to_str(timestamp)) + .replace1(timestamp_to_str(timestamp)) } /// Stock string: `Incoming Messages`. diff --git a/src/summary.rs b/src/summary.rs index ccef5a849..5f6a0537a 100644 --- a/src/summary.rs +++ b/src/summary.rs @@ -4,11 +4,11 @@ use crate::chat::Chat; use crate::constants::Chattype; use crate::contact::{Contact, ContactId}; use crate::context::Context; -use crate::dc_tools::dc_truncate; use crate::message::{Message, MessageState, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::stock_str; +use crate::tools::truncate; use std::borrow::Cow; use std::fmt; @@ -97,7 +97,7 @@ impl Summary { /// Returns the [`Summary::text`] attribute truncated to an approximate length. pub fn truncated_text(&self, approx_chars: usize) -> Cow { - dc_truncate(&self.text, approx_chars) + truncate(&self.text, approx_chars) } } diff --git a/src/sync.rs b/src/sync.rs index 28fb12299..326ed53bd 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -5,12 +5,12 @@ use crate::config::Config; use crate::constants::Blocked; use crate::contact::ContactId; use crate::context::Context; -use crate::dc_tools::time; use crate::message::{Message, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::sync::SyncData::{AddQrToken, DeleteQrToken}; use crate::token::Namespace; +use crate::tools::time; use crate::{chat, stock_str, token}; use anyhow::Result; use lettre_email::mime::{self}; diff --git a/src/test_utils.rs b/src/test_utils.rs index 038e6885b..423cd0845 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -25,12 +25,12 @@ use crate::constants::Chattype; use crate::constants::{DC_GCM_ADDDAYMARKER, DC_MSG_ID_DAYMARKER}; use crate::contact::{Contact, ContactId, Modifier, Origin}; use crate::context::Context; -use crate::dc_receive_imf::dc_receive_imf; -use crate::dc_tools::EmailAddress; use crate::events::{Event, EventType, Events}; use crate::key::{self, DcKey, KeyPair, KeyPairUse}; use crate::message::{update_msg_state, Message, MessageState, MsgId, Viewtype}; use crate::mimeparser::MimeMessage; +use crate::receive_imf::receive_imf; +use crate::tools::EmailAddress; #[allow(non_upper_case_globals)] pub const AVATAR_900x900_BYTES: &[u8] = include_bytes!("../test-data/image/avatar900x900.png"); @@ -426,13 +426,13 @@ impl TestContext { .unwrap() } - /// Receive a message using the `dc_receive_imf()` pipeline. Panics if it's not shown + /// Receive a message using the `receive_imf()` pipeline. Panics if it's not shown /// in the chat as exactly one message. pub async fn recv_msg(&self, msg: &SentMessage) -> Message { let received = self .recv_msg_opt(msg) .await - .expect("dc_receive_imf() seems not to have added a new message to the db"); + .expect("receive_imf() seems not to have added a new message to the db"); assert_eq!( received.msg_ids.len(), @@ -455,13 +455,10 @@ impl TestContext { msg } - /// Receive a message using the `dc_receive_imf()` pipeline. This is similar + /// Receive a message using the `receive_imf()` pipeline. This is similar /// to `recv_msg()`, but doesn't assume that the message is shown in the chat. - pub async fn recv_msg_opt( - &self, - msg: &SentMessage, - ) -> Option { - dc_receive_imf(self, msg.payload().as_bytes(), false) + pub async fn recv_msg_opt(&self, msg: &SentMessage) -> Option { + receive_imf(self, msg.payload().as_bytes(), false) .await .unwrap() } diff --git a/src/token.rs b/src/token.rs index e4f9a4ff8..048bc9f90 100644 --- a/src/token.rs +++ b/src/token.rs @@ -9,7 +9,7 @@ use deltachat_derive::{FromSql, ToSql}; use crate::chat::ChatId; use crate::context::Context; -use crate::dc_tools::{dc_create_id, time}; +use crate::tools::{create_id, time}; /// Token namespace #[derive( @@ -103,7 +103,7 @@ pub async fn lookup_or_new( return token; } - let token = dc_create_id(); + let token = create_id(); save(context, namespace, foreign_id, &token).await.ok(); token } diff --git a/src/dc_tools.rs b/src/tools.rs similarity index 85% rename from src/dc_tools.rs rename to src/tools.rs index 49287d48c..5b953f9bb 100644 --- a/src/dc_tools.rs +++ b/src/tools.rs @@ -30,7 +30,7 @@ use crate::stock_str; /// Shortens a string to a specified length and adds "[...]" to the /// end of the shortened string. #[allow(clippy::indexing_slicing)] -pub(crate) fn dc_truncate(buf: &str, approx_chars: usize) -> Cow { +pub(crate) fn truncate(buf: &str, approx_chars: usize) -> Cow { let count = buf.chars().count(); if count > approx_chars + DC_ELLIPSIS.len() { let end_pos = buf @@ -53,7 +53,7 @@ pub(crate) fn dc_truncate(buf: &str, approx_chars: usize) -> Cow { * date/time tools ******************************************************************************/ -pub fn dc_timestamp_to_str(wanted: i64) -> String { +pub fn timestamp_to_str(wanted: i64) -> String { let ts = Local.timestamp(wanted, 0); ts.format("%Y.%m.%d %H:%M:%S").to_string() } @@ -66,7 +66,7 @@ pub fn duration_to_str(duration: Duration) -> String { format!("{}h {}m {}s", h, m, s) } -pub(crate) fn dc_gm2local_offset() -> i64 { +pub(crate) fn gm2local_offset() -> i64 { /* returns the offset that must be _added_ to an UTC/GMT-time to create the localtime. the function may return negative values. */ let lt = Local::now(); @@ -90,7 +90,7 @@ pub(crate) const MAX_SECONDS_TO_LEND_FROM_FUTURE: i64 = 5; /// Returns the current smeared timestamp, /// /// The returned timestamp MUST NOT be sent out. -pub(crate) async fn dc_smeared_time(context: &Context) -> i64 { +pub(crate) async fn smeared_time(context: &Context) -> i64 { let mut now = time(); let ts = *context.last_smeared_timestamp.read().await; if ts >= now { @@ -101,7 +101,7 @@ pub(crate) async fn dc_smeared_time(context: &Context) -> i64 { } /// Returns a timestamp that is guaranteed to be unique. -pub(crate) async fn dc_create_smeared_timestamp(context: &Context) -> i64 { +pub(crate) async fn create_smeared_timestamp(context: &Context) -> i64 { let now = time(); let mut ret = now; @@ -120,7 +120,7 @@ pub(crate) async fn dc_create_smeared_timestamp(context: &Context) -> i64 { // creates `count` timestamps that are guaranteed to be unique. // the frist created timestamps is returned directly, // get the other timestamps just by adding 1..count-1 -pub(crate) async fn dc_create_smeared_timestamps(context: &Context, count: usize) -> i64 { +pub(crate) async fn create_smeared_timestamps(context: &Context, count: usize) -> i64 { let now = time(); let count = count as i64; let mut start = now + min(count, MAX_SECONDS_TO_LEND_FROM_FUTURE) - count; @@ -204,7 +204,7 @@ async fn maybe_warn_on_outdated(context: &Context, now: i64, approx_compile_time /// - for OUTGOING messages this ID is written to the header as `Chat-Group-ID:` and is added to the message ID as Gr..@ /// - for INCOMING messages, the ID is taken from the Chat-Group-ID-header or from the Message-ID in the In-Reply-To: or References:-Header /// - the group-id should be a string with the characters [a-zA-Z0-9\-_] -pub(crate) fn dc_create_id() -> String { +pub(crate) fn create_id() -> String { // ThreadRng implements CryptoRng trait and is supposed to be cryptographically secure. let mut rng = thread_rng(); @@ -223,14 +223,14 @@ pub(crate) fn dc_create_id() -> String { /// - this function is called for all outgoing messages. /// - the message ID should be globally unique /// - do not add a counter or any private data as this leaks information unncessarily -pub(crate) fn dc_create_outgoing_rfc724_mid(grpid: Option<&str>, from_addr: &str) -> String { +pub(crate) fn create_outgoing_rfc724_mid(grpid: Option<&str>, from_addr: &str) -> String { let hostname = from_addr .find('@') .and_then(|k| from_addr.get(k..)) .unwrap_or("@nohost"); match grpid { - Some(grpid) => format!("Gr.{}.{}{}", grpid, dc_create_id(), hostname), - None => format!("Mr.{}.{}{}", dc_create_id(), dc_create_id(), hostname), + Some(grpid) => format!("Gr.{}.{}{}", grpid, create_id(), hostname), + None => format!("Mr.{}.{}{}", create_id(), create_id(), hostname), } } @@ -240,7 +240,7 @@ pub(crate) fn dc_create_outgoing_rfc724_mid(grpid: Option<&str>, from_addr: &str /// /// * `mid` - A string that holds the message id. Leading/Trailing <> /// characters are automatically stripped. -pub(crate) fn dc_extract_grpid_from_rfc724_mid(mid: &str) -> Option<&str> { +pub(crate) fn extract_grpid_from_rfc724_mid(mid: &str) -> Option<&str> { let mid = mid.trim_start_matches('<').trim_end_matches('>'); if mid.len() < 9 || !mid.starts_with("Gr.") { @@ -260,14 +260,14 @@ pub(crate) fn dc_extract_grpid_from_rfc724_mid(mid: &str) -> Option<&str> { } // the returned suffix is lower-case -pub fn dc_get_filesuffix_lc(path_filename: impl AsRef) -> Option { +pub fn get_filesuffix_lc(path_filename: impl AsRef) -> Option { Path::new(path_filename.as_ref()) .extension() .map(|p| p.to_string_lossy().to_lowercase()) } /// Returns the `(width, height)` of the given image buffer. -pub fn dc_get_filemeta(buf: &[u8]) -> Result<(u32, u32), Error> { +pub fn get_filemeta(buf: &[u8]) -> Result<(u32, u32), Error> { let image = image::io::Reader::new(Cursor::new(buf)).with_guessed_format()?; let dimensions = image.into_dimensions()?; Ok(dimensions) @@ -277,7 +277,7 @@ pub fn dc_get_filemeta(buf: &[u8]) -> Result<(u32, u32), Error> { /// /// If `path` starts with "$BLOBDIR", replaces it with the blobdir path. /// Otherwise, returns path as is. -pub(crate) fn dc_get_abs_path(context: &Context, path: impl AsRef) -> PathBuf { +pub(crate) fn get_abs_path(context: &Context, path: impl AsRef) -> PathBuf { let p: &Path = path.as_ref(); if let Ok(p) = p.strip_prefix("$BLOBDIR") { context.get_blobdir().join(p) @@ -286,16 +286,16 @@ pub(crate) fn dc_get_abs_path(context: &Context, path: impl AsRef) -> Path } } -pub(crate) async fn dc_get_filebytes(context: &Context, path: impl AsRef) -> u64 { - let path_abs = dc_get_abs_path(context, &path); +pub(crate) async fn get_filebytes(context: &Context, path: impl AsRef) -> u64 { + let path_abs = get_abs_path(context, &path); match fs::metadata(&path_abs).await { Ok(meta) => meta.len() as u64, Err(_err) => 0, } } -pub(crate) async fn dc_delete_file(context: &Context, path: impl AsRef) -> bool { - let path_abs = dc_get_abs_path(context, &path); +pub(crate) async fn delete_file(context: &Context, path: impl AsRef) -> bool { + let path_abs = get_abs_path(context, &path); if !path_abs.exists() { return false; } @@ -321,14 +321,14 @@ pub(crate) async fn dc_delete_file(context: &Context, path: impl AsRef) -> } } -pub async fn dc_delete_files_in_dir(context: &Context, path: impl AsRef) { +pub async fn delete_files_in_dir(context: &Context, path: impl AsRef) { match tokio::fs::read_dir(path).await { Ok(read_dir) => { let mut read_dir = tokio_stream::wrappers::ReadDirStream::new(read_dir); while let Some(entry) = read_dir.next().await { match entry { Ok(file) => { - dc_delete_file(context, file.file_name()).await; + delete_file(context, file.file_name()).await; } Err(e) => warn!(context, "Could not read file to delete: {}", e), } @@ -339,11 +339,11 @@ pub async fn dc_delete_files_in_dir(context: &Context, path: impl AsRef) { } } -pub(crate) async fn dc_create_folder( +pub(crate) async fn create_folder( context: &Context, path: impl AsRef, ) -> Result<(), io::Error> { - let path_abs = dc_get_abs_path(context, &path); + let path_abs = get_abs_path(context, &path); if !path_abs.exists() { match fs::create_dir_all(path_abs).await { Ok(_) => Ok(()), @@ -363,12 +363,12 @@ pub(crate) async fn dc_create_folder( } /// Write a the given content to provied file path. -pub(crate) async fn dc_write_file( +pub(crate) async fn write_file( context: &Context, path: impl AsRef, buf: &[u8], ) -> Result<(), io::Error> { - let path_abs = dc_get_abs_path(context, &path); + let path_abs = get_abs_path(context, &path); fs::write(&path_abs, buf).await.map_err(|err| { warn!( context, @@ -381,8 +381,8 @@ pub(crate) async fn dc_write_file( }) } -pub async fn dc_read_file>(context: &Context, path: P) -> Result, Error> { - let path_abs = dc_get_abs_path(context, &path); +pub async fn read_file>(context: &Context, path: P) -> Result, Error> { + let path_abs = get_abs_path(context, &path); match fs::read(&path_abs).await { Ok(bytes) => Ok(bytes), @@ -398,8 +398,8 @@ pub async fn dc_read_file>(context: &Context, path: P) -> Result< } } -pub async fn dc_open_file>(context: &Context, path: P) -> Result { - let path_abs = dc_get_abs_path(context, &path); +pub async fn open_file>(context: &Context, path: P) -> Result { + let path_abs = get_abs_path(context, &path); match fs::File::open(&path_abs).await { Ok(bytes) => Ok(bytes), @@ -415,12 +415,12 @@ pub async fn dc_open_file>(context: &Context, path: P) -> Result< } } -pub fn dc_open_file_std>( +pub fn open_file_std>( context: &Context, path: P, ) -> Result { let p: PathBuf = path.as_ref().into(); - let path_abs = dc_get_abs_path(context, p); + let path_abs = get_abs_path(context, p); match std::fs::File::open(&path_abs) { Ok(bytes) => Ok(bytes), @@ -450,7 +450,7 @@ pub(crate) fn time() -> i64 { /// # Example /// /// ``` -/// use deltachat::dc_tools::EmailAddress; +/// use deltachat::tools::EmailAddress; /// let email = match EmailAddress::new("someone@example.com") { /// Ok(addr) => addr, /// Err(e) => panic!("Error parsing address, error was {}", e), @@ -619,8 +619,7 @@ mod tests { use super::*; use crate::{ - config::Config, dc_receive_imf::dc_receive_imf, message::get_msg_info, - test_utils::TestContext, + config::Config, message::get_msg_info, receive_imf::receive_imf, test_utils::TestContext, }; #[test] @@ -689,7 +688,7 @@ Hop: From: hq5.example.org; By: hq5.example.org; Date: Mon, 27 Dec 2021 11:21:22 async fn check_parse_receive_headers_integration(raw: &[u8], expected: &str) { let t = TestContext::new_alice().await; t.set_config(Config::ShowEmails, Some("2")).await.unwrap(); - dc_receive_imf(&t, raw, false).await.unwrap(); + receive_imf(&t, raw, false).await.unwrap(); let msg = t.get_last_msg().await; let msg_info = get_msg_info(&t, msg.id).await.unwrap(); @@ -706,108 +705,108 @@ Hop: From: hq5.example.org; By: hq5.example.org; Date: Mon, 27 Dec 2021 11:21:22 } #[test] - fn test_dc_truncate_1() { + fn test_truncate_1() { let s = "this is a little test string"; - assert_eq!(dc_truncate(s, 16), "this is a [...]"); + assert_eq!(truncate(s, 16), "this is a [...]"); } #[test] - fn test_dc_truncate_2() { - assert_eq!(dc_truncate("1234", 2), "1234"); + fn test_truncate_2() { + assert_eq!(truncate("1234", 2), "1234"); } #[test] - fn test_dc_truncate_3() { - assert_eq!(dc_truncate("1234567", 1), "1[...]"); + fn test_truncate_3() { + assert_eq!(truncate("1234567", 1), "1[...]"); } #[test] - fn test_dc_truncate_4() { - assert_eq!(dc_truncate("123456", 4), "123456"); + fn test_truncate_4() { + assert_eq!(truncate("123456", 4), "123456"); } #[test] - fn test_dc_truncate_edge() { - assert_eq!(dc_truncate("", 4), ""); + fn test_truncate_edge() { + assert_eq!(truncate("", 4), ""); - assert_eq!(dc_truncate("\n hello \n world", 4), "\n [...]"); + assert_eq!(truncate("\n hello \n world", 4), "\n [...]"); - assert_eq!(dc_truncate("𐠈0Aᝮa𫝀®!ꫛa¡0A𐢧00𐹠®A 丽ⷐએ", 1), "𐠈[...]"); - assert_eq!(dc_truncate("𐠈0Aᝮa𫝀®!ꫛa¡0A𐢧00𐹠®A 丽ⷐએ", 0), "[...]"); + assert_eq!(truncate("𐠈0Aᝮa𫝀®!ꫛa¡0A𐢧00𐹠®A 丽ⷐએ", 1), "𐠈[...]"); + assert_eq!(truncate("𐠈0Aᝮa𫝀®!ꫛa¡0A𐢧00𐹠®A 丽ⷐએ", 0), "[...]"); // 9 characters, so no truncation - assert_eq!(dc_truncate("𑒀ὐ¢🜀\u{1e01b}A a🟠", 6), "𑒀ὐ¢🜀\u{1e01b}A a🟠",); + assert_eq!(truncate("𑒀ὐ¢🜀\u{1e01b}A a🟠", 6), "𑒀ὐ¢🜀\u{1e01b}A a🟠",); // 12 characters, truncation assert_eq!( - dc_truncate("𑒀ὐ¢🜀\u{1e01b}A a🟠bcd", 6), + truncate("𑒀ὐ¢🜀\u{1e01b}A a🟠bcd", 6), "𑒀ὐ¢🜀\u{1e01b}A[...]", ); } #[test] - fn test_dc_create_id() { - let buf = dc_create_id(); + fn test_create_id() { + let buf = create_id(); assert_eq!(buf.len(), 11); } #[test] - fn test_dc_create_id_invalid_chars() { + fn test_create_id_invalid_chars() { for _ in 1..1000 { - let buf = dc_create_id(); + let buf = create_id(); assert!(!buf.contains('/')); // `/` must not be used to be URL-safe assert!(!buf.contains('.')); // `.` is used as a delimiter when extracting grpid from Message-ID } } #[test] - fn test_dc_extract_grpid_from_rfc724_mid() { + fn test_extract_grpid_from_rfc724_mid() { // Should return None if we pass invalid mid let mid = "foobar"; - let grpid = dc_extract_grpid_from_rfc724_mid(mid); + let grpid = extract_grpid_from_rfc724_mid(mid); assert_eq!(grpid, None); // Should return None if grpid has a length which is not 11 or 16 let mid = "Gr.12345678.morerandom@domain.de"; - let grpid = dc_extract_grpid_from_rfc724_mid(mid); + let grpid = extract_grpid_from_rfc724_mid(mid); assert_eq!(grpid, None); // Should return extracted grpid for grpid with length of 11 let mid = "Gr.12345678901.morerandom@domain.de"; - let grpid = dc_extract_grpid_from_rfc724_mid(mid); + let grpid = extract_grpid_from_rfc724_mid(mid); assert_eq!(grpid, Some("12345678901")); // Should return extracted grpid for grpid with length of 11 let mid = "Gr.1234567890123456.morerandom@domain.de"; - let grpid = dc_extract_grpid_from_rfc724_mid(mid); + let grpid = extract_grpid_from_rfc724_mid(mid); assert_eq!(grpid, Some("1234567890123456")); // Should return extracted grpid for grpid with length of 11 let mid = ""; - let grpid = dc_extract_grpid_from_rfc724_mid(mid); + let grpid = extract_grpid_from_rfc724_mid(mid); assert_eq!(grpid, Some("12345678901")); // Should return extracted grpid for grpid with length of 11 let mid = ""; - let grpid = dc_extract_grpid_from_rfc724_mid(mid); + let grpid = extract_grpid_from_rfc724_mid(mid); assert_eq!(grpid, Some("1234567890123456")); } #[test] - fn test_dc_create_outgoing_rfc724_mid() { + fn test_create_outgoing_rfc724_mid() { // create a normal message-id - let mid = dc_create_outgoing_rfc724_mid(None, "foo@bar.de"); + let mid = create_outgoing_rfc724_mid(None, "foo@bar.de"); assert!(mid.starts_with("Mr.")); assert!(mid.ends_with("bar.de")); - assert!(dc_extract_grpid_from_rfc724_mid(mid.as_str()).is_none()); + assert!(extract_grpid_from_rfc724_mid(mid.as_str()).is_none()); // create a message-id containing a group-id - let grpid = dc_create_id(); - let mid = dc_create_outgoing_rfc724_mid(Some(&grpid), "foo@bar.de"); + let grpid = create_id(); + let mid = create_outgoing_rfc724_mid(Some(&grpid), "foo@bar.de"); assert!(mid.starts_with("Gr.")); assert!(mid.ends_with("bar.de")); assert_eq!( - dc_extract_grpid_from_rfc724_mid(mid.as_str()), + extract_grpid_from_rfc724_mid(mid.as_str()), Some(grpid.as_str()) ); } @@ -853,11 +852,11 @@ Hop: From: hq5.example.org; By: hq5.example.org; Date: Mon, 27 Dec 2021 11:21:22 proptest! { #[test] - fn test_dc_truncate( + fn test_truncate( buf: String, approx_chars in 0..100usize ) { - let res = dc_truncate(&buf, approx_chars); + let res = truncate(&buf, approx_chars); let el_len = 5; let l = res.chars().count(); assert!( @@ -877,7 +876,7 @@ Hop: From: hq5.example.org; By: hq5.example.org; Date: Mon, 27 Dec 2021 11:21:22 async fn test_file_handling() { let t = TestContext::new().await; let context = &t; - macro_rules! dc_file_exist { + macro_rules! file_exist { ($ctx:expr, $fname:expr) => { $ctx.get_blobdir() .join(Path::new($fname).file_name().unwrap()) @@ -885,13 +884,13 @@ Hop: From: hq5.example.org; By: hq5.example.org; Date: Mon, 27 Dec 2021 11:21:22 }; } - assert!(!dc_delete_file(context, "$BLOBDIR/lkqwjelqkwlje").await); - assert!(dc_write_file(context, "$BLOBDIR/foobar", b"content") + assert!(!delete_file(context, "$BLOBDIR/lkqwjelqkwlje").await); + assert!(write_file(context, "$BLOBDIR/foobar", b"content") .await .is_ok()); - assert!(dc_file_exist!(context, "$BLOBDIR/foobar")); - assert!(!dc_file_exist!(context, "$BLOBDIR/foobarx")); - assert_eq!(dc_get_filebytes(context, "$BLOBDIR/foobar").await, 7); + assert!(file_exist!(context, "$BLOBDIR/foobar")); + assert!(!file_exist!(context, "$BLOBDIR/foobarx")); + assert_eq!(get_filebytes(context, "$BLOBDIR/foobar").await, 7); let abs_path = context .get_blobdir() @@ -899,31 +898,31 @@ Hop: From: hq5.example.org; By: hq5.example.org; Date: Mon, 27 Dec 2021 11:21:22 .to_string_lossy() .to_string(); - assert!(dc_file_exist!(context, &abs_path)); + assert!(file_exist!(context, &abs_path)); - assert!(dc_delete_file(context, "$BLOBDIR/foobar").await); - assert!(dc_create_folder(context, "$BLOBDIR/foobar-folder") + assert!(delete_file(context, "$BLOBDIR/foobar").await); + assert!(create_folder(context, "$BLOBDIR/foobar-folder") .await .is_ok()); - assert!(dc_file_exist!(context, "$BLOBDIR/foobar-folder")); - assert!(!dc_delete_file(context, "$BLOBDIR/foobar-folder").await); + assert!(file_exist!(context, "$BLOBDIR/foobar-folder")); + assert!(!delete_file(context, "$BLOBDIR/foobar-folder").await); let fn0 = "$BLOBDIR/data.data"; - assert!(dc_write_file(context, &fn0, b"content").await.is_ok()); + assert!(write_file(context, &fn0, b"content").await.is_ok()); - assert!(dc_delete_file(context, &fn0).await); - assert!(!dc_file_exist!(context, &fn0)); + assert!(delete_file(context, &fn0).await); + assert!(!file_exist!(context, &fn0)); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_create_smeared_timestamp() { let t = TestContext::new().await; assert_ne!( - dc_create_smeared_timestamp(&t).await, - dc_create_smeared_timestamp(&t).await + create_smeared_timestamp(&t).await, + create_smeared_timestamp(&t).await ); assert!( - dc_create_smeared_timestamp(&t).await + create_smeared_timestamp(&t).await >= SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() @@ -935,13 +934,13 @@ Hop: From: hq5.example.org; By: hq5.example.org; Date: Mon, 27 Dec 2021 11:21:22 async fn test_create_smeared_timestamps() { let t = TestContext::new().await; let count = MAX_SECONDS_TO_LEND_FROM_FUTURE - 1; - let start = dc_create_smeared_timestamps(&t, count as usize).await; - let next = dc_smeared_time(&t).await; + let start = create_smeared_timestamps(&t, count as usize).await; + let next = smeared_time(&t).await; assert!((start + count - 1) < next); let count = MAX_SECONDS_TO_LEND_FROM_FUTURE + 30; - let start = dc_create_smeared_timestamps(&t, count as usize).await; - let next = dc_smeared_time(&t).await; + let start = create_smeared_timestamps(&t, count as usize).await; + let next = smeared_time(&t).await; assert!((start + count - 1) < next); } @@ -980,17 +979,17 @@ Hop: From: hq5.example.org; By: hq5.example.org; Date: Mon, 27 Dec 2021 11:21:22 #[test] fn test_get_filemeta() { - let (w, h) = dc_get_filemeta(test_utils::AVATAR_900x900_BYTES).unwrap(); + let (w, h) = get_filemeta(test_utils::AVATAR_900x900_BYTES).unwrap(); assert_eq!(w, 900); assert_eq!(h, 900); let data = include_bytes!("../test-data/image/avatar1000x1000.jpg"); - let (w, h) = dc_get_filemeta(data).unwrap(); + let (w, h) = get_filemeta(data).unwrap(); assert_eq!(w, 1000); assert_eq!(h, 1000); let data = include_bytes!("../test-data/image/image100x50.gif"); - let (w, h) = dc_get_filemeta(data).unwrap(); + let (w, h) = get_filemeta(data).unwrap(); assert_eq!(w, 100); assert_eq!(h, 50); } diff --git a/src/update_helper.rs b/src/update_helper.rs index 7de265587..bfe46d500 100644 --- a/src/update_helper.rs +++ b/src/update_helper.rs @@ -59,9 +59,9 @@ impl Params { #[cfg(test)] mod tests { use super::*; - use crate::dc_receive_imf::dc_receive_imf; - use crate::dc_tools::time; + use crate::receive_imf::receive_imf; use crate::test_utils::TestContext; + use crate::tools::time; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_params_update_timestamp() -> Result<()> { @@ -89,7 +89,7 @@ mod tests { async fn test_out_of_order_subject() -> Result<()> { let t = TestContext::new_alice().await; - dc_receive_imf( + receive_imf( &t, b"From: Bob Authname \n\ To: alice@example.org\n\ @@ -102,7 +102,7 @@ mod tests { false, ) .await?; - dc_receive_imf( + receive_imf( &t, b"From: Bob Authname \n\ To: alice@example.org\n\ @@ -130,7 +130,7 @@ mod tests { async fn test_out_of_order_group_name() -> Result<()> { let t = TestContext::new_alice().await; - dc_receive_imf( + receive_imf( &t, b"From: Bob Authname \n\ To: alice@example.org\n\ @@ -148,7 +148,7 @@ mod tests { let chat = Chat::load_from_db(&t, msg.chat_id).await?; assert_eq!(chat.name, "initial name"); - dc_receive_imf( + receive_imf( &t, b"From: Bob Authname \n\ To: alice@example.org\n\ @@ -163,7 +163,7 @@ mod tests { false, ) .await?; - dc_receive_imf( + receive_imf( &t, b"From: Bob Authname \n\ To: alice@example.org\n\ diff --git a/src/webxdc.rs b/src/webxdc.rs index 8085b5b1f..8c20bb46a 100644 --- a/src/webxdc.rs +++ b/src/webxdc.rs @@ -14,13 +14,12 @@ use tokio::io::AsyncReadExt; use crate::chat::Chat; use crate::contact::ContactId; use crate::context::Context; -use crate::dc_tools::dc_create_smeared_timestamp; -use crate::dc_tools::dc_get_abs_path; use crate::message::{Message, MessageState, MsgId, Viewtype}; use crate::mimeparser::SystemMessage; use crate::param::Param; use crate::param::Params; use crate::scheduler::InterruptInfo; +use crate::tools::{create_smeared_timestamp, get_abs_path}; use crate::{chat, EventType}; /// The current API version. @@ -367,7 +366,7 @@ impl Context { .create_status_update_record( &mut instance, update_str, - dc_create_smeared_timestamp(self).await, + create_smeared_timestamp(self).await, send_now, ContactId::SELF, ) @@ -618,7 +617,7 @@ impl Message { let path = self .get_file(context) .ok_or_else(|| format_err!("No webxdc instance file."))?; - let path_abs = dc_get_abs_path(context, &path); + let path_abs = get_abs_path(context, &path); let archive = async_zip::read::fs::ZipFileReader::new(path_abs).await?; Ok(archive) } @@ -724,9 +723,6 @@ impl Message { #[cfg(test)] mod tests { - use tokio::fs::File; - use tokio::io::AsyncWriteExt; - use crate::chat::{ add_contact_to_chat, create_group_chat, forward_msgs, resend_msgs, send_msg, send_text_msg, ChatId, ProtectionStatus, @@ -734,7 +730,7 @@ mod tests { use crate::chatlist::Chatlist; use crate::config::Config; use crate::contact::Contact; - use crate::dc_receive_imf::dc_receive_imf; + use crate::receive_imf::receive_imf; use crate::test_utils::TestContext; use super::*; @@ -792,7 +788,7 @@ mod tests { async fn create_webxdc_instance(t: &TestContext, name: &str, bytes: &[u8]) -> Result { let file = t.get_blobdir().join(name); - File::create(&file).await?.write_all(bytes).await?; + tokio::fs::write(&file, bytes).await?; let mut instance = Message::new(Viewtype::File); instance.set_file(file.to_str().unwrap(), None); Ok(instance) @@ -823,10 +819,7 @@ mod tests { // sending using bad extension is not working, even when setting Viewtype to webxdc let file = t.get_blobdir().join("index.html"); - File::create(&file) - .await? - .write_all("ola!".as_ref()) - .await?; + tokio::fs::write(&file, b"ola!").await?; let mut instance = Message::new(Viewtype::Webxdc); instance.set_file(file.to_str().unwrap(), None); assert!(send_msg(&t, chat_id, &mut instance).await.is_err()); @@ -853,12 +846,11 @@ mod tests { // sending invalid .xdc as Viewtype::Webxdc should fail already on sending let file = t.get_blobdir().join("invalid2.xdc"); - File::create(&file) - .await? - .write_all(include_bytes!( - "../test-data/webxdc/invalid-no-zip-but-7z.xdc" - )) - .await?; + tokio::fs::write( + &file, + include_bytes!("../test-data/webxdc/invalid-no-zip-but-7z.xdc"), + ) + .await?; let mut instance = Message::new(Viewtype::Webxdc); instance.set_file(file.to_str().unwrap(), None); assert!(send_msg(&t, chat_id, &mut instance).await.is_err()); @@ -957,7 +949,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_receive_webxdc_instance() -> Result<()> { let t = TestContext::new_alice().await; - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/webxdc_good_extension.eml"), false, @@ -967,7 +959,7 @@ mod tests { assert_eq!(instance.viewtype, Viewtype::Webxdc); assert_eq!(instance.get_filename(), Some("minimal.xdc".to_string())); - dc_receive_imf( + receive_imf( &t, include_bytes!("../test-data/message/webxdc_bad_extension.eml"), false,