Merge remote-tracking branch 'upstream/master'

This commit is contained in:
adbenitez
2021-06-26 21:12:23 -04:00
9 changed files with 202 additions and 121 deletions
+20 -8
View File
@@ -2318,11 +2318,14 @@ pub unsafe extern "C" fn dc_chatlist_get_msg_id(
return 0;
}
let ffi_list = &*chatlist;
ffi_list
.list
.get_msg_id(index as usize)
.map(|msg_id| msg_id.to_u32())
.unwrap_or(0)
let ctx = &*ffi_list.context;
match ffi_list.list.get_msg_id(index as usize) {
Ok(msg_id) => msg_id.map_or(0, |msg_id| msg_id.to_u32()),
Err(err) => {
warn!(ctx, "get_msg_id failed: {}", err);
0
}
}
}
#[no_mangle]
@@ -2348,7 +2351,9 @@ pub unsafe extern "C" fn dc_chatlist_get_summary(
let lot = ffi_list
.list
.get_summary(&ctx, index as usize, maybe_chat)
.await;
.await
.log_err(ctx, "get_summary failed")
.unwrap_or_default();
Box::into_raw(Box::new(lot))
})
}
@@ -2364,9 +2369,16 @@ pub unsafe extern "C" fn dc_chatlist_get_summary2(
return ptr::null_mut();
}
let ctx = &*context;
let msg_id = if msg_id == 0 {
None
} else {
Some(MsgId::new(msg_id))
};
block_on(async move {
let lot =
Chatlist::get_summary2(&ctx, ChatId::new(chat_id), MsgId::new(msg_id), None).await;
let lot = Chatlist::get_summary2(&ctx, ChatId::new(chat_id), msg_id, None)
.await
.log_err(ctx, "get_summary2 failed")
.unwrap_or_default();
Box::into_raw(Box::new(lot))
})
}
+1 -1
View File
@@ -551,7 +551,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
},
if chat.is_protected() { "🛡️" } else { "" },
);
let lot = chatlist.get_summary(&context, i, Some(&chat)).await;
let lot = chatlist.get_summary(&context, i, Some(&chat)).await?;
let statestr = if chat.visibility == ChatVisibility::Archived {
" [Archived]"
} else {
+1 -1
View File
@@ -86,7 +86,7 @@ async fn main() {
let chats = Chatlist::try_load(&ctx, 0, None, None).await.unwrap();
for i in 0..chats.len() {
let msg = Message::load_from_db(&ctx, chats.get_msg_id(i).unwrap())
let msg = Message::load_from_db(&ctx, chats.get_msg_id(i).unwrap().unwrap())
.await
.unwrap();
log::info!("[{}] msg: {:?}", i, msg);
+8 -2
View File
@@ -1535,6 +1535,7 @@ impl ChatIdBlocked {
_ => (),
}
let created_timestamp = dc_create_smeared_timestamp(context).await;
let chat_id = context
.sql
.transaction(move |transaction| {
@@ -1547,7 +1548,7 @@ impl ChatIdBlocked {
chat_name,
params.to_string(),
create_blocked as u8,
time(),
created_timestamp,
],
)?;
let chat_id = ChatId::new(
@@ -2214,7 +2215,12 @@ pub async fn create_group_chat(
"INSERT INTO chats
(type, name, grpid, param, created_timestamp)
VALUES(?, ?, ?, \'U=1\', ?);",
paramsv![Chattype::Group, chat_name, grpid, time(),],
paramsv![
Chattype::Group,
chat_name,
grpid,
dc_create_smeared_timestamp(context).await,
],
)
.await?;
+40 -39
View File
@@ -42,7 +42,7 @@ use crate::stock_str;
#[derive(Debug)]
pub struct Chatlist {
/// Stores pairs of `chat_id, message_id`
ids: Vec<(ChatId, MsgId)>,
ids: Vec<(ChatId, Option<MsgId>)>,
}
impl Chatlist {
@@ -111,7 +111,7 @@ impl Chatlist {
let process_row = |row: &rusqlite::Row| {
let chat_id: ChatId = row.get(0)?;
let msg_id: MsgId = row.get(1).unwrap_or_default();
let msg_id: Option<MsgId> = row.get(1)?;
Ok((chat_id, msg_id))
};
@@ -261,7 +261,7 @@ impl Chatlist {
get_last_deaddrop_fresh_msg(context).await?
{
if !flag_for_forwarding {
ids.insert(0, (DC_CHAT_ID_DEADDROP, last_deaddrop_fresh_msg_id));
ids.insert(0, (DC_CHAT_ID_DEADDROP, Some(last_deaddrop_fresh_msg_id)));
}
}
add_archived_link_item = true;
@@ -271,9 +271,9 @@ impl Chatlist {
if add_archived_link_item && dc_get_archived_cnt(context).await? > 0 {
if ids.is_empty() && flag_add_alldone_hint {
ids.push((DC_CHAT_ID_ALLDONE_HINT, MsgId::new(0)));
ids.push((DC_CHAT_ID_ALLDONE_HINT, None));
}
ids.push((DC_CHAT_ID_ARCHIVED_LINK, MsgId::new(0)));
ids.push((DC_CHAT_ID_ARCHIVED_LINK, None));
}
Ok(Chatlist { ids })
@@ -302,7 +302,7 @@ impl Chatlist {
/// Get a single message ID of a chatlist.
///
/// To get the message object from the message ID, use dc_get_msg().
pub fn get_msg_id(&self, index: usize) -> Result<MsgId> {
pub fn get_msg_id(&self, index: usize) -> Result<Option<MsgId>> {
match self.ids.get(index) {
Some((_chat_id, msg_id)) => Ok(*msg_id),
None => bail!("Chatlist index out of range"),
@@ -323,18 +323,19 @@ impl Chatlist {
/// - dc_lot_t::timestamp: the timestamp of the message. 0 if not applicable.
/// - dc_lot_t::state: The state of the message as one of the DC_STATE_* constants (see #dc_msg_get_state()).
// 0 if not applicable.
pub async fn get_summary(&self, context: &Context, index: usize, chat: Option<&Chat>) -> Lot {
pub async fn get_summary(
&self,
context: &Context,
index: usize,
chat: Option<&Chat>,
) -> Result<Lot> {
// The summary is created by the chat, not by the last message.
// This is because we may want to display drafts here or stuff as
// "is typing".
// Also, sth. as "No messages" would not work if the summary comes from a message.
let (chat_id, lastmsg_id) = match self.ids.get(index) {
Some(ids) => ids,
None => {
let mut ret = Lot::new();
ret.text2 = Some("ErrBadChatlistIndex".to_string());
return Lot::new();
}
None => bail!("Chatlist index out of range"),
};
Chatlist::get_summary2(context, *chat_id, *lastmsg_id, chat).await
@@ -343,50 +344,50 @@ impl Chatlist {
pub async fn get_summary2(
context: &Context,
chat_id: ChatId,
lastmsg_id: MsgId,
lastmsg_id: Option<MsgId>,
chat: Option<&Chat>,
) -> Lot {
) -> Result<Lot> {
let mut ret = Lot::new();
let chat_loaded: Chat;
let chat = if let Some(chat) = chat {
chat
} else if let Ok(chat) = Chat::load_from_db(context, chat_id).await {
} else {
let chat = Chat::load_from_db(context, chat_id).await?;
chat_loaded = chat;
&chat_loaded
} else {
return ret;
};
let (lastmsg, lastcontact) =
if let Ok(lastmsg) = Message::load_from_db(context, lastmsg_id).await {
if lastmsg.from_id == DC_CONTACT_ID_SELF {
(Some(lastmsg), None)
} else {
match chat.typ {
Chattype::Group | Chattype::Mailinglist => {
let lastcontact =
Contact::load_from_db(context, lastmsg.from_id).await.ok();
(Some(lastmsg), lastcontact)
}
Chattype::Single | Chattype::Undefined => (Some(lastmsg), None),
}
}
let (lastmsg, lastcontact) = if let Some(lastmsg_id) = lastmsg_id {
let lastmsg = Message::load_from_db(context, lastmsg_id).await?;
if lastmsg.from_id == DC_CONTACT_ID_SELF {
(Some(lastmsg), None)
} else {
(None, None)
};
match chat.typ {
Chattype::Group | Chattype::Mailinglist => {
let lastcontact =
Contact::load_from_db(context, lastmsg.from_id).await.ok();
(Some(lastmsg), lastcontact)
}
Chattype::Single | Chattype::Undefined => (Some(lastmsg), None),
}
}
} else {
(None, None)
};
if chat.id.is_archived_link() {
ret.text2 = None;
} else if lastmsg.is_none() || lastmsg.as_ref().unwrap().from_id == DC_CONTACT_ID_UNDEFINED
} else if let Some(mut lastmsg) =
lastmsg.filter(|msg| msg.from_id != DC_CONTACT_ID_UNDEFINED)
{
ret.text2 = Some(stock_str::no_messages(context).await);
} else {
ret.fill(&mut lastmsg.unwrap(), chat, lastcontact.as_ref(), context)
ret.fill(&mut lastmsg, chat, lastcontact.as_ref(), context)
.await;
} else {
ret.text2 = Some(stock_str::no_messages(context).await);
}
ret
Ok(ret)
}
pub fn get_index_for_id(&self, id: ChatId) -> Option<usize> {
@@ -684,7 +685,7 @@ mod tests {
chat_id1.set_draft(&t, Some(&mut msg)).await.unwrap();
let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
let summary = chats.get_summary(&t, 0, None).await;
let summary = chats.get_summary(&t, 0, None).await.unwrap();
assert_eq!(summary.get_text2().unwrap(), "foo: bar test"); // the linebreak should be removed from summary
}
}
+129 -67
View File
@@ -90,6 +90,35 @@ pub(crate) async fn dc_receive_imf_inner(
return Ok(());
}
let mut sent_timestamp = if let Some(value) = mime_parser
.get(HeaderDef::Date)
.and_then(|value| mailparse::dateparse(value).ok())
{
value
} else {
dc_create_smeared_timestamp(context).await
};
let rfc724_mid = mime_parser.get_rfc724_mid().unwrap_or_else(||
// missing Message-IDs may come if the mail was set from this account with another
// client that relies in the SMTP server to generate one.
// true eg. for the Webmailer used in all-inkl-KAS
dc_create_incoming_rfc724_mid(&mime_parser));
// check, if the mail is already in our database - if so, just update the folder/uid
// (if the mail was moved around) and finish. (we may get a mail twice eg. if it is
// moved between folders. make sure, this check is done eg. before securejoin-processing) */
if let Some((old_server_folder, old_server_uid, _)) =
message::rfc724_mid_exists(context, &rfc724_mid).await?
{
if old_server_folder != server_folder || old_server_uid != server_uid {
message::update_server_uid(context, &rfc724_mid, server_folder, server_uid).await;
}
warn!(context, "Message already in DB");
return Ok(());
}
// the function returns the number of created messages in the database
let mut chat_id = ChatId::new(0);
let mut hidden = false;
@@ -97,7 +126,6 @@ pub(crate) async fn dc_receive_imf_inner(
let mut needs_delete_job = false;
let mut insert_msg_id = MsgId::new_unset();
let mut sent_timestamp = 0;
let mut created_db_entries = Vec::new();
let mut create_event_to_send = Some(CreateEvent::MsgsChanged);
@@ -116,11 +144,6 @@ pub(crate) async fn dc_receive_imf_inner(
}
};
if let Some(value) = mime_parser.get(HeaderDef::Date) {
// is not yet checked against bad times! we do this later if we have the database information.
sent_timestamp = mailparse::dateparse(value).unwrap_or_default();
}
let prevent_rename =
mime_parser.is_mailinglist_message() || mime_parser.get(HeaderDef::Sender).is_some();
@@ -156,16 +179,6 @@ pub(crate) async fn dc_receive_imf_inner(
);
// Add parts
let rfc724_mid = match mime_parser.get_rfc724_mid() {
Some(x) => x,
None => {
// missing Message-IDs may come if the mail was set from this account with another
// client that relies in the SMTP server to generate one.
// true eg. for the Webmailer used in all-inkl-KAS
dc_create_incoming_rfc724_mid(sent_timestamp, from_id, &to_ids)
}
};
if mime_parser.parts.last().is_some() {
if let Err(err) = add_parts(
context,
@@ -385,20 +398,6 @@ async fn add_parts(
let mut mime_references = String::new();
let mut incoming_origin = incoming_origin;
// check, if the mail is already in our database - if so, just update the folder/uid
// (if the mail was moved around) and finish. (we may get a mail twice eg. if it is
// moved between folders. make sure, this check is done eg. before securejoin-processing) */
if let Some((old_server_folder, old_server_uid, _)) =
message::rfc724_mid_exists(context, rfc724_mid).await?
{
if old_server_folder != server_folder || old_server_uid != server_uid {
message::update_server_uid(context, rfc724_mid, server_folder, server_uid).await;
}
warn!(context, "Message already in DB");
return Ok(());
}
let parent = get_parent_message(context, mime_parser).await?;
let mut is_dc_message = if mime_parser.has_chat_version() {
@@ -1801,7 +1800,7 @@ async fn create_multiuser_record(
grpname.as_ref(),
grpid.as_ref(),
create_blocked,
time(),
dc_create_smeared_timestamp(context).await,
create_protected,
if chattype == Chattype::Group || chattype == Chattype::Mailinglist {
-1
@@ -2108,18 +2107,25 @@ async fn add_or_lookup_contact_by_addr(
Ok(row_id)
}
fn dc_create_incoming_rfc724_mid(
message_timestamp: i64,
contact_id_from: u32,
contact_ids_to: &ContactIds,
) -> String {
/* create a deterministic rfc724_mid from input such that
repeatedly calling it with the same input results in the same Message-id */
let largest_id_to = contact_ids_to.iter().max().copied().unwrap_or_default();
/// Creates fake Message-ID to identify the message in the database for
/// messages which does not have one.
///
/// Concatenates Date:, From: and To: fields, then hashes them.
fn dc_create_incoming_rfc724_mid(mime: &MimeMessage) -> String {
format!(
"{}-{}-{}@stub",
message_timestamp, contact_id_from, largest_id_to
"{}@stub",
hex_hash(&format!(
"{}-{}-{}",
mime.get(HeaderDef::Date)
.map(|s| s.to_string())
.unwrap_or_default(),
mime.get(HeaderDef::From_)
.map(|s| s.to_string())
.unwrap_or_default(),
mime.get(HeaderDef::To)
.map(|s| s.to_string())
.unwrap_or_default()
))
)
}
@@ -2182,23 +2188,20 @@ mod tests {
assert_eq!(extract_grpid(&mimeparser, HeaderDef::References), grpid);
}
#[test]
fn test_dc_create_incoming_rfc724_mid() {
let mut members = ContactIds::new();
#[async_std::test]
async fn test_dc_create_incoming_rfc724_mid() {
let context = TestContext::new().await;
let raw = b"From: Alice <alice@example.com>\n\
To: Bob <bob@example.org>\n\
Subject: Some subject\n\
hello\n";
let mimeparser = MimeMessage::from_bytes(&context.ctx, &raw[..])
.await
.unwrap();
assert_eq!(
dc_create_incoming_rfc724_mid(123, 45, &members),
"123-45-0@stub"
);
members.insert(7);
members.insert(3);
assert_eq!(
dc_create_incoming_rfc724_mid(123, 45, &members),
"123-45-7@stub"
);
members.insert(9);
assert_eq!(
dc_create_incoming_rfc724_mid(123, 45, &members),
"123-45-9@stub"
dc_create_incoming_rfc724_mid(&mimeparser),
"08d11318608d5191@stub"
);
}
@@ -2300,7 +2303,7 @@ mod tests {
let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
assert_eq!(chats.len(), 1);
assert!(chats.get_chat_id(0).is_deaddrop());
let chat_id = chat::create_by_msg_id(&t, chats.get_msg_id(0).unwrap())
let chat_id = chat::create_by_msg_id(&t, chats.get_msg_id(0).unwrap().unwrap())
.await
.unwrap();
assert!(!chat_id.is_special());
@@ -2335,7 +2338,7 @@ mod tests {
.unwrap();
let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
assert_eq!(chats.len(), 2);
let chat_id = chat::create_by_msg_id(&t, chats.get_msg_id(0).unwrap())
let chat_id = chat::create_by_msg_id(&t, chats.get_msg_id(0).unwrap().unwrap())
.await
.unwrap();
let chat = chat::Chat::load_from_db(&t, chat_id).await.unwrap();
@@ -2356,7 +2359,7 @@ mod tests {
let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
assert_eq!(chats.len(), 1);
assert!(chats.get_chat_id(0).is_deaddrop());
let chat_id = chat::create_by_msg_id(&t, chats.get_msg_id(0).unwrap())
let chat_id = chat::create_by_msg_id(&t, chats.get_msg_id(0).unwrap().unwrap())
.await
.unwrap();
let chat = chat::Chat::load_from_db(&t, chat_id).await.unwrap();
@@ -2605,7 +2608,7 @@ mod tests {
assert_eq!(contact.get_display_name(), "h2");
let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
let msg = Message::load_from_db(&t, chats.get_msg_id(0).unwrap())
let msg = Message::load_from_db(&t, chats.get_msg_id(0).unwrap().unwrap())
.await
.unwrap();
assert_eq!(msg.is_dc_message, MessengerMessage::Yes);
@@ -2756,7 +2759,7 @@ mod tests {
.unwrap();
let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
let msg_id = chats.get_msg_id(0).unwrap();
let msg_id = chats.get_msg_id(0).unwrap().unwrap();
// Check that the ndn would be downloaded:
let headers = mailparse::parse_mail(raw_ndn).unwrap().headers;
@@ -2806,7 +2809,7 @@ mod tests {
.unwrap();
let chats = Chatlist::try_load(&t, 0, None, None).await.unwrap();
let msg_id = chats.get_msg_id(0).unwrap();
let msg_id = chats.get_msg_id(0).unwrap().unwrap();
let raw = include_bytes!("../test-data/message/gmail_ndn_group.eml");
dc_receive_imf(&t, raw, "INBOX", 1, false).await.unwrap();
@@ -2839,7 +2842,7 @@ mod tests {
.await
.unwrap();
let chats = Chatlist::try_load(context, 0, None, None).await.unwrap();
let msg_id = chats.get_msg_id(0).unwrap();
let msg_id = chats.get_msg_id(0).unwrap().unwrap();
Message::load_from_db(context, msg_id).await.unwrap()
}
@@ -2889,7 +2892,7 @@ mod tests {
let chats = Chatlist::try_load(&t.ctx, 0, None, None).await.unwrap();
assert_eq!(chats.len(), 1);
let chat_id = chat::create_by_msg_id(&t.ctx, chats.get_msg_id(0).unwrap())
let chat_id = chat::create_by_msg_id(&t.ctx, chats.get_msg_id(0).unwrap().unwrap())
.await
.unwrap();
let chat = chat::Chat::load_from_db(&t.ctx, chat_id).await.unwrap();
@@ -2960,7 +2963,7 @@ mod tests {
.await
.unwrap();
let chats = Chatlist::try_load(&t.ctx, 0, None, None).await.unwrap();
let chat_id = chat::create_by_msg_id(&t.ctx, chats.get_msg_id(0).unwrap())
let chat_id = chat::create_by_msg_id(&t.ctx, chats.get_msg_id(0).unwrap().unwrap())
.await
.unwrap();
let chat = Chat::load_from_db(&t.ctx, chat_id).await.unwrap();
@@ -4071,4 +4074,63 @@ Message content",
assert_ne!(msg.chat_id, DC_CHAT_ID_DEADDROP);
assert_eq!(msg.get_text().unwrap(), "Subj – Message content");
}
#[async_std::test]
async fn test_duplicate_message() -> Result<()> {
// Test that duplicate messages are ignored based on the Message-ID
let alice = TestContext::new_alice().await;
let bob_contact_id = Contact::add_or_lookup(
&alice,
"Bob",
"bob@example.org",
Origin::IncomingUnknownFrom,
)
.await?
.0;
let first_message = b"Received: from [127.0.0.1]
Subject: First message
Message-ID: <first@example.org>
To: Alice <alice@example.com>
From: Bob1 <bob@example.org>
Chat-Version: 1.0
Message content
--
First signature";
let second_message = b"Received: from [127.0.0.1]
Subject: Second message
Message-ID: <second@example.org>
To: Alice <alice@example.com>
From: Bob2 <bob@example.org>
Chat-Version: 1.0
Message content
--
Second signature";
dc_receive_imf(&alice, first_message, "Inbox", 1, 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, "Inbox", 2, 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, "Inbox", 3, false).await?;
// No change because last message is duplicate of the first.
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");
Ok(())
}
}
+1 -1
View File
@@ -1800,7 +1800,7 @@ mod tests {
let chats = Chatlist::try_load(context, 0, None, None).await.unwrap();
let chat_id = chat::create_by_msg_id(context, chats.get_msg_id(0).unwrap())
let chat_id = chat::create_by_msg_id(context, chats.get_msg_id(0).unwrap().unwrap())
.await
.unwrap();
+1 -1
View File
@@ -2834,7 +2834,7 @@ On 2020-10-25, Bob wrote:
.unwrap();
let chats = Chatlist::try_load(&t.ctx, 0, None, None).await.unwrap();
let msg_id = chats.get_msg_id(0).unwrap();
let msg_id = chats.get_msg_id(0).unwrap().unwrap();
let msg = Message::load_from_db(&t.ctx, msg_id).await.unwrap();
assert_eq!(
+1 -1
View File
@@ -331,7 +331,7 @@ impl TestContext {
// The chatlist describes what you see when you open DC, a list of chats and in each of them
// the first words of the last message. To get the last message overall, we look at the chat at the top of the
// list, which has the index 0.
let msg_id = chats.get_msg_id(0).unwrap();
let msg_id = chats.get_msg_id(0).unwrap().unwrap();
Message::load_from_db(&self.ctx, msg_id)
.await
.expect("failed to load msg")