Skip to content

Commit c32d436

Browse files
committed
feat: Display vCard contact name in the message summary
1 parent 4049d34 commit c32d436

File tree

8 files changed

+122
-55
lines changed

8 files changed

+122
-55
lines changed

deltachat-ffi/deltachat.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7366,7 +7366,7 @@ void dc_event_unref(dc_event_t* event);
73667366
/// Used as info message.
73677367
#define DC_STR_SECUREJOIN_WAIT_TIMEOUT 191
73687368

7369-
/// "Contact"
7369+
/// "Contact". Deprecated, currently unused.
73707370
#define DC_STR_CONTACT 200
73717371

73727372
/**

src/chat.rs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ use crate::tools::{
4949
create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,
5050
smeared_time, time, IsNoneOrEmpty, SystemTime,
5151
};
52-
use crate::webxdc::WEBXDC_SUFFIX;
5352

5453
/// An chat item, such as a message or a marker.
5554
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
@@ -894,8 +893,20 @@ impl ChatId {
894893
.await?
895894
.context("no file stored in params")?;
896895
msg.param.set(Param::File, blob.as_name());
897-
if blob.suffix() == Some(WEBXDC_SUFFIX) {
898-
msg.viewtype = Viewtype::Webxdc;
896+
if msg.viewtype == Viewtype::File {
897+
if let Some((better_type, _)) =
898+
message::guess_msgtype_from_suffix(&blob.to_abs_path())
899+
// We do not do an automatic conversion to other viewtypes here so that
900+
// users can send images as "files" to preserve the original quality
901+
// (usually we compress images). The remaining conversions are done by
902+
// `prepare_msg_blob()` later.
903+
.filter(|&(vt, _)| vt == Viewtype::Webxdc || vt == Viewtype::Vcard)
904+
{
905+
msg.viewtype = better_type;
906+
}
907+
}
908+
if msg.viewtype == Viewtype::Vcard {
909+
msg.try_set_vcard(context, &blob.to_abs_path()).await?;
899910
}
900911
}
901912
}
@@ -2649,6 +2660,10 @@ async fn prepare_msg_blob(context: &Context, msg: &mut Message) -> Result<()> {
26492660
.await?;
26502661
}
26512662

2663+
if msg.viewtype == Viewtype::Vcard {
2664+
msg.try_set_vcard(context, &blob.to_abs_path()).await?;
2665+
}
2666+
26522667
let mut maybe_sticker = msg.viewtype == Viewtype::Sticker;
26532668
if !send_as_is
26542669
&& (msg.viewtype == Viewtype::Image

src/message.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use std::collections::BTreeSet;
44
use std::path::{Path, PathBuf};
5+
use std::str;
56

67
use anyhow::{ensure, format_err, Context as _, Result};
78
use deltachat_contact_tools::{parse_vcard, VcardContact};
@@ -1093,6 +1094,18 @@ impl Message {
10931094
.await
10941095
}
10951096

1097+
/// Updates message state from the vCard attachment.
1098+
pub(crate) async fn try_set_vcard(&mut self, context: &Context, path: &Path) -> Result<()> {
1099+
let vcard = fs::read(path).await.context("Could not read {path}")?;
1100+
if let Some(summary) = get_vcard_summary(&vcard) {
1101+
self.param.set(Param::Summary1, summary);
1102+
} else {
1103+
warn!(context, "try_set_vcard: Not a valid DeltaChat vCard.");
1104+
self.viewtype = Viewtype::File;
1105+
}
1106+
Ok(())
1107+
}
1108+
10961109
/// Set different sender name for a message.
10971110
/// This overrides the name set by the `set_config()`-option `displayname`.
10981111
pub fn set_override_sender_name(&mut self, name: Option<String>) {
@@ -1947,6 +1960,19 @@ pub(crate) async fn get_by_rfc724_mids(
19471960
Ok(latest)
19481961
}
19491962

1963+
/// Returns the 1st part of summary text (i.e. before the dash if any) for a valid DeltaChat vCard.
1964+
pub(crate) fn get_vcard_summary(vcard: &[u8]) -> Option<String> {
1965+
let vcard = str::from_utf8(vcard).ok()?;
1966+
let contacts = deltachat_contact_tools::parse_vcard(vcard);
1967+
let [c] = &contacts[..] else {
1968+
return None;
1969+
};
1970+
if !deltachat_contact_tools::may_be_valid_addr(&c.addr) {
1971+
return None;
1972+
}
1973+
Some(c.display_name().to_string())
1974+
}
1975+
19501976
/// How a message is primarily displayed.
19511977
#[derive(
19521978
Debug,

src/mimeparser.rs

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ use crate::events::EventType;
2828
use crate::headerdef::{HeaderDef, HeaderDefMap};
2929
use crate::key::{self, load_self_secret_keyring, DcKey, Fingerprint, SignedPublicKey};
3030
use crate::message::{
31-
self, set_msg_failed, update_msg_state, Message, MessageState, MsgId, Viewtype,
31+
self, get_vcard_summary, set_msg_failed, update_msg_state, Message, MessageState, MsgId,
32+
Viewtype,
3233
};
3334
use crate::param::{Param, Params};
3435
use crate::peerstate::Peerstate;
@@ -1234,6 +1235,7 @@ impl MimeMessage {
12341235
return Ok(());
12351236
}
12361237
}
1238+
let mut part = Part::default();
12371239
let msg_type = if context
12381240
.is_webxdc_file(filename, decoded_data)
12391241
.await
@@ -1277,6 +1279,13 @@ impl MimeMessage {
12771279
.unwrap_or_default();
12781280
self.webxdc_status_update = Some(serialized);
12791281
return Ok(());
1282+
} else if msg_type == Viewtype::Vcard {
1283+
if let Some(summary) = get_vcard_summary(decoded_data) {
1284+
part.param.set(Param::Summary1, summary);
1285+
msg_type
1286+
} else {
1287+
Viewtype::File
1288+
}
12801289
} else {
12811290
msg_type
12821291
};
@@ -1296,8 +1305,6 @@ impl MimeMessage {
12961305
};
12971306
info!(context, "added blobfile: {:?}", blob.as_name());
12981307

1299-
/* create and register Mime part referencing the new Blob object */
1300-
let mut part = Part::default();
13011308
if mime_type.type_() == mime::IMAGE {
13021309
if let Ok((width, height)) = get_filemeta(decoded_data) {
13031310
part.param.set_int(Param::Width, width as i32);
@@ -1929,7 +1936,10 @@ pub struct Part {
19291936
pub(crate) is_reaction: bool,
19301937
}
19311938

1932-
/// return mimetype and viewtype for a parsed mail
1939+
/// Returns the mimetype and viewtype for a parsed mail.
1940+
///
1941+
/// This only looks at the metadata, not at the content;
1942+
/// the viewtype may later be corrected in `do_add_single_file_part()`.
19331943
fn get_mime_type(
19341944
mail: &mailparse::ParsedMail<'_>,
19351945
filename: &Option<String>,
@@ -1938,7 +1948,7 @@ fn get_mime_type(
19381948

19391949
let viewtype = match mimetype.type_() {
19401950
mime::TEXT => match mimetype.subtype() {
1941-
mime::VCARD if is_valid_deltachat_vcard(mail) => Viewtype::Vcard,
1951+
mime::VCARD => Viewtype::Vcard,
19421952
mime::PLAIN | mime::HTML if !is_attachment_disposition(mail) => Viewtype::Text,
19431953
_ => Viewtype::File,
19441954
},
@@ -1989,17 +1999,6 @@ fn is_attachment_disposition(mail: &mailparse::ParsedMail<'_>) -> bool {
19891999
.any(|(key, _value)| key.starts_with("filename"))
19902000
}
19912001

1992-
fn is_valid_deltachat_vcard(mail: &mailparse::ParsedMail) -> bool {
1993-
let Ok(body) = &mail.get_body() else {
1994-
return false;
1995-
};
1996-
let contacts = deltachat_contact_tools::parse_vcard(body);
1997-
if let [c] = &contacts[..] {
1998-
return deltachat_contact_tools::may_be_valid_addr(&c.addr);
1999-
}
2000-
false
2001-
}
2002-
20032002
/// Tries to get attachment filename.
20042003
///
20052004
/// If filename is explicitly specified in Content-Disposition, it is

src/param.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,9 @@ pub enum Param {
8888
/// For Messages: quoted text.
8989
Quote = b'q',
9090

91+
/// For Messages: the 1st part of summary text (i.e. before the dash if any).
92+
Summary1 = b'4',
93+
9194
/// For Messages
9295
Cmd = b'S',
9396

src/receive_imf/tests.rs

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4705,10 +4705,15 @@ async fn test_receive_vcard() -> Result<()> {
47054705
let alice = tcm.alice().await;
47064706
let bob = tcm.bob().await;
47074707

4708-
for vcard_contains_address in [true, false] {
4709-
let mut msg = Message::new(Viewtype::Vcard);
4708+
async fn test(
4709+
alice: &TestContext,
4710+
bob: &TestContext,
4711+
vcard_contains_address: bool,
4712+
viewtype: Viewtype,
4713+
) -> Result<()> {
4714+
let mut msg = Message::new(viewtype);
47104715
msg.set_file_from_bytes(
4711-
&alice,
4716+
alice,
47124717
"claire.vcf",
47134718
format!(
47144719
"BEGIN:VCARD\n\
@@ -4728,19 +4733,24 @@ async fn test_receive_vcard() -> Result<()> {
47284733
.await
47294734
.unwrap();
47304735

4731-
let alice_bob_chat = alice.create_chat(&bob).await;
4736+
let alice_bob_chat = alice.create_chat(bob).await;
47324737
let sent = alice.send_msg(alice_bob_chat.id, &mut msg).await;
47334738
let rcvd = bob.recv_msg(&sent).await;
4739+
let sent = Message::load_from_db(alice, sent.sender_msg_id).await?;
47344740

47354741
if vcard_contains_address {
4742+
assert_eq!(sent.viewtype, Viewtype::Vcard);
4743+
assert_eq!(sent.get_summary_text(alice).await, "👤 Claire");
47364744
assert_eq!(rcvd.viewtype, Viewtype::Vcard);
4745+
assert_eq!(rcvd.get_summary_text(bob).await, "👤 Claire");
47374746
} else {
47384747
// VCards without an email address are not "deltachat contacts",
47394748
// so they are shown as files
4749+
assert_eq!(sent.viewtype, Viewtype::File);
47404750
assert_eq!(rcvd.viewtype, Viewtype::File);
47414751
}
47424752

4743-
let vcard = tokio::fs::read(rcvd.get_file(&bob).unwrap()).await?;
4753+
let vcard = tokio::fs::read(rcvd.get_file(bob).unwrap()).await?;
47444754
let vcard = std::str::from_utf8(&vcard)?;
47454755
let parsed = deltachat_contact_tools::parse_vcard(vcard);
47464756
assert_eq!(parsed.len(), 1);
@@ -4749,6 +4759,13 @@ async fn test_receive_vcard() -> Result<()> {
47494759
} else {
47504760
assert_eq!(&parsed[0].addr, "");
47514761
}
4762+
Ok(())
4763+
}
4764+
4765+
for vcard_contains_address in [true, false] {
4766+
for viewtype in [Viewtype::File, Viewtype::Vcard] {
4767+
test(&alice, &bob, vcard_contains_address, viewtype).await?;
4768+
}
47524769
}
47534770

47544771
Ok(())
@@ -4776,7 +4793,9 @@ async fn test_make_n_send_vcard() -> Result<()> {
47764793
let sent = Message::load_from_db(alice, sent.sender_msg_id).await?;
47774794

47784795
assert_eq!(sent.viewtype, Viewtype::Vcard);
4796+
assert_eq!(sent.get_summary_text(alice).await, "👤 Claire");
47794797
assert_eq!(rcvd.viewtype, Viewtype::Vcard);
4798+
assert_eq!(rcvd.get_summary_text(bob).await, "👤 Claire");
47804799

47814800
let vcard = tokio::fs::read(rcvd.get_file(bob).unwrap()).await?;
47824801
let vcard = std::str::from_utf8(&vcard)?;

src/stock_str.rs

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -443,9 +443,6 @@ pub enum StockMessage {
443443
fallback = "Could not yet establish guaranteed end-to-end encryption, but you may already send a message."
444444
))]
445445
SecurejoinWaitTimeout = 191,
446-
447-
#[strum(props(fallback = "Contact"))]
448-
Contact = 200,
449446
}
450447

451448
impl StockMessage {
@@ -1101,11 +1098,6 @@ pub(crate) async fn videochat_invite_msg_body(context: &Context, url: &str) -> S
11011098
.replace1(url)
11021099
}
11031100

1104-
/// Stock string: `Contact`.
1105-
pub(crate) async fn contact(context: &Context) -> String {
1106-
translated(context, StockMessage::Contact).await
1107-
}
1108-
11091101
/// Stock string: `Error:\n\n“%1$s”`.
11101102
pub(crate) async fn configuration_failed(context: &Context, details: &str) -> String {
11111103
translated(context, StockMessage::ConfigurationFailed)

src/summary.rs

Lines changed: 35 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use crate::contact::{Contact, ContactId};
1010
use crate::context::Context;
1111
use crate::message::{Message, MessageState, Viewtype};
1212
use crate::mimeparser::SystemMessage;
13+
use crate::param::Param;
1314
use crate::stock_str;
1415
use crate::stock_str::msg_reacted;
1516
use crate::tools::truncate;
@@ -149,7 +150,7 @@ impl Summary {
149150

150151
impl Message {
151152
/// Returns a summary text.
152-
async fn get_summary_text(&self, context: &Context) -> String {
153+
pub(crate) async fn get_summary_text(&self, context: &Context) -> String {
153154
let summary = self.get_summary_text_without_prefix(context).await;
154155

155156
if self.is_forwarded() {
@@ -231,8 +232,8 @@ impl Message {
231232
}
232233
Viewtype::Vcard => {
233234
emoji = Some("👤");
234-
type_name = Some(stock_str::contact(context).await);
235-
type_file = None;
235+
type_name = None;
236+
type_file = self.param.get(Param::Summary1).map(|s| s.to_string());
236237
append_text = true;
237238
}
238239
Viewtype::Text | Viewtype::Unknown => {
@@ -284,6 +285,7 @@ impl Message {
284285
#[cfg(test)]
285286
mod tests {
286287
use super::*;
288+
use crate::chat::ChatId;
287289
use crate::param::Param;
288290
use crate::test_utils as test;
289291

@@ -296,7 +298,9 @@ mod tests {
296298
async fn test_get_summary_text() {
297299
let d = test::TestContext::new().await;
298300
let ctx = &d.ctx;
299-
301+
let chat_id = ChatId::create_for_contact(ctx, ContactId::SELF)
302+
.await
303+
.unwrap();
300304
let some_text = " bla \t\n\tbla\n\t".to_string();
301305

302306
let mut msg = Message::new(Viewtype::Text);
@@ -367,25 +371,34 @@ mod tests {
367371
assert_summary_texts(&msg, ctx, "Video chat invitation").await; // text is not added for videochat invitations
368372

369373
let mut msg = Message::new(Viewtype::Vcard);
370-
msg.set_file("foo.vcf", None);
371-
assert_summary_texts(&msg, ctx, "👤 Contact").await;
374+
msg.set_file_from_bytes(ctx, "foo.vcf", b"", None)
375+
.await
376+
.unwrap();
377+
chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
378+
// If a vCard can't be parsed, the message becomes `Viewtype::File`.
379+
assert_eq!(msg.viewtype, Viewtype::File);
380+
assert_summary_texts(&msg, ctx, "📎 foo.vcf").await;
372381
msg.set_text(some_text.clone());
373-
assert_summary_texts(&msg, ctx, "👤 bla bla").await;
374-
375-
let mut msg = Message::new(Viewtype::Vcard);
376-
msg.set_file_from_bytes(
377-
ctx,
378-
"alice.vcf",
379-
b"BEGIN:VCARD\n\
380-
VERSION:4.0\n\
381-
FN:Alice Wonderland\n\
382-
EMAIL;TYPE=work:[email protected]\n\
383-
END:VCARD",
384-
None,
385-
)
386-
.await
387-
.unwrap();
388-
assert_summary_texts(&msg, ctx, "👤 Contact").await;
382+
assert_summary_texts(&msg, ctx, "📎 foo.vcf \u{2013} bla bla").await;
383+
384+
for vt in [Viewtype::Vcard, Viewtype::File] {
385+
let mut msg = Message::new(vt);
386+
msg.set_file_from_bytes(
387+
ctx,
388+
"alice.vcf",
389+
b"BEGIN:VCARD\n\
390+
VERSION:4.0\n\
391+
FN:Alice Wonderland\n\
392+
EMAIL;TYPE=work:[email protected]\n\
393+
END:VCARD",
394+
None,
395+
)
396+
.await
397+
.unwrap();
398+
chat_id.set_draft(ctx, Some(&mut msg)).await.unwrap();
399+
assert_eq!(msg.viewtype, Viewtype::Vcard);
400+
assert_summary_texts(&msg, ctx, "👤 Alice Wonderland").await;
401+
}
389402

390403
// Forwarded
391404
let mut msg = Message::new(Viewtype::Text);

0 commit comments

Comments
 (0)