deltachat/param.rs
1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::PathBuf;
4use std::str;
5
6use anyhow::ensure;
7use anyhow::{Error, Result, bail};
8use num_traits::FromPrimitive;
9use serde::{Deserialize, Serialize};
10
11use crate::blob::BlobObject;
12use crate::context::Context;
13use crate::mimeparser::SystemMessage;
14
15/// Available param keys.
16#[derive(
17 PartialEq, Eq, Debug, Clone, Copy, Hash, PartialOrd, Ord, FromPrimitive, Serialize, Deserialize,
18)]
19#[repr(u8)]
20pub enum Param {
21 /// For messages
22 File = b'f',
23
24 /// For messages: original filename (as shown in chat)
25 Filename = b'v',
26
27 /// For messages: This name should be shown instead of contact.get_display_name()
28 /// (used if this is a mailinglist
29 /// or explicitly set using set_override_sender_name(), eg. by bots)
30 OverrideSenderDisplayname = b'O',
31
32 /// For Messages
33 Width = b'w',
34
35 /// For Messages
36 Height = b'h',
37
38 /// For Messages
39 Duration = b'd',
40
41 /// For Messages
42 MimeType = b'm',
43
44 /// For Messages: HTML to be written to the database and to be send.
45 /// `SendHtml` param is not used for received messages.
46 /// Use `MsgId::get_html()` to get HTML of received messages.
47 SendHtml = b'T',
48
49 /// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send
50 GuaranteeE2ee = b'c',
51
52 /// For Messages: quoted message is encrypted.
53 ///
54 /// If this message is sent unencrypted, quote text should be replaced.
55 ProtectQuote = b'0',
56
57 /// For Messages: decrypted with validation errors or without mutual set, if neither
58 /// 'c' nor 'e' are preset, the messages is only transport encrypted.
59 ///
60 /// Deprecated on 2024-12-25.
61 ErroneousE2ee = b'e',
62
63 /// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.
64 ForcePlaintext = b'u',
65
66 /// For Messages: do not include Autocrypt header.
67 SkipAutocrypt = b'o',
68
69 /// For Messages
70 WantsMdn = b'r',
71
72 /// For Messages: the message is a reaction.
73 Reaction = b'x',
74
75 /// For Chats: the timestamp of the last reaction.
76 LastReactionTimestamp = b'y',
77
78 /// For Chats: Message ID of the last reaction.
79 LastReactionMsgId = b'Y',
80
81 /// For Chats: Contact ID of the last reaction.
82 LastReactionContactId = b'1',
83
84 /// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot").
85 Bot = b'b',
86
87 /// For Messages: unset or 0=not forwarded,
88 /// 1=forwarded from unknown msg_id, >9 forwarded from msg_id
89 Forwarded = b'a',
90
91 /// For Messages: quoted text.
92 Quote = b'q',
93
94 /// For Messages: the 1st part of summary text (i.e. before the dash if any).
95 Summary1 = b'4',
96
97 /// For Messages
98 Cmd = b'S',
99
100 /// For Messages
101 ///
102 /// For "MemberAddedToGroup" and "MemberRemovedFromGroup",
103 /// this is the email address added to / removed from the group.
104 ///
105 /// For securejoin messages other than `vg-member-added`, this is the step,
106 /// which is put into the `Secure-Join` header.
107 Arg = b'E',
108
109 /// For Messages
110 ///
111 /// For `BobHandshakeMsg::Request`, this is the `Secure-Join-Invitenumber` header.
112 ///
113 /// For `BobHandshakeMsg::RequestWithAuth`, this is the `Secure-Join-Auth` header.
114 ///
115 /// For [`SystemMessage::MultiDeviceSync`], this contains the ids that are synced.
116 ///
117 /// For [`SystemMessage::MemberAddedToGroup`],
118 /// this is '1' if it was added because of a securejoin-handshake, and '0' otherwise.
119 ///
120 /// For call messages, this is the accept timestamp.
121 Arg2 = b'F',
122
123 /// For Messages
124 ///
125 /// For `BobHandshakeMsg::RequestWithAuth`,
126 /// this contains the `Secure-Join-Fingerprint` header.
127 ///
128 /// For [`SystemMessage::MemberAddedToGroup`] that add to a broadcast channel,
129 /// this contains the broadcast channel's shared secret.
130 Arg3 = b'G',
131
132 /// For Messages
133 ///
134 /// Deprecated `Secure-Join-Group` header for `BobHandshakeMsg::RequestWithAuth` messages.
135 ///
136 /// For "MemberAddedToGroup" and "MemberRemovedFromGroup",
137 /// this is the fingerprint added to / removed from the group.
138 ///
139 /// For call messages, this is the end timsetamp.
140 Arg4 = b'H',
141
142 /// For Messages
143 AttachGroupImage = b'A',
144
145 /// For Messages
146 WebrtcRoom = b'V',
147
148 /// For Messages
149 WebrtcAccepted = b'7',
150
151 /// For Messages: space-separated list of messaged IDs of forwarded copies.
152 ///
153 /// This is used when a [crate::message::Message] is in the
154 /// [crate::message::MessageState::OutPending] state but is already forwarded.
155 /// In this case the forwarded messages are written to the
156 /// database and their message IDs are added to this parameter of
157 /// the original message, which is also saved in the database.
158 /// When the original message is then finally sent this parameter
159 /// is used to also send all the forwarded messages.
160 PrepForwards = b'P',
161
162 /// For Messages
163 SetLatitude = b'l',
164
165 /// For Messages
166 SetLongitude = b'n',
167
168 /// For Groups
169 ///
170 /// An unpromoted group has not had any messages sent to it and thus only exists on the
171 /// creator's device. Any changes made to an unpromoted group do not need to send
172 /// system messages to the group members to update them of the changes. Once a message
173 /// has been sent to a group it is promoted and group changes require sending system
174 /// messages to all members.
175 Unpromoted = b'U',
176
177 /// For Groups and Contacts
178 ProfileImage = b'i',
179
180 /// For Chats
181 /// Signals whether the chat is the `saved messages` chat
182 Selftalk = b'K',
183
184 /// For Chats: On sending a new message we set the subject to `Re: <last subject>`.
185 /// Usually we just use the subject of the parent message, but if the parent message
186 /// is deleted, we use the LastSubject of the chat.
187 LastSubject = b't',
188
189 /// For Chats
190 Devicetalk = b'D',
191
192 /// For Chats: If this is a mailing list chat, contains the List-Post address.
193 /// None if there simply is no `List-Post` header in the mailing list.
194 /// Some("") if the mailing list is using multiple different List-Post headers.
195 ///
196 /// The List-Post address is the email address where the user can write to in order to
197 /// post something to the mailing list.
198 ListPost = b'p',
199
200 /// For Contacts: If this is the List-Post address of a mailing list, contains
201 /// the List-Id of the mailing list (which is also used as the group id of the chat).
202 ListId = b's',
203
204 /// For Contacts: timestamp of status (aka signature or footer) update.
205 StatusTimestamp = b'j',
206
207 /// For Contacts and Chats: timestamp of avatar update.
208 AvatarTimestamp = b'J',
209
210 /// For Chats: timestamp of status/signature/footer update.
211 EphemeralSettingsTimestamp = b'B',
212
213 /// For Chats: timestamp of subject update.
214 SubjectTimestamp = b'C',
215
216 /// For Chats: timestamp of group name update.
217 GroupNameTimestamp = b'g',
218
219 /// For Chats: timestamp of member list update.
220 MemberListTimestamp = b'k',
221
222 /// For Webxdc Message Instances: Current document name
223 WebxdcDocument = b'R',
224
225 /// For Webxdc Message Instances: timestamp of document name update.
226 WebxdcDocumentTimestamp = b'W',
227
228 /// For Webxdc Message Instances: Current summary
229 WebxdcSummary = b'N',
230
231 /// For Webxdc Message Instances: timestamp of summary update.
232 WebxdcSummaryTimestamp = b'Q',
233
234 /// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()
235 WebxdcIntegration = b'3',
236
237 /// For Webxdc Message Instances: Chat to integrate the Webxdc for.
238 WebxdcIntegrateFor = b'2',
239
240 /// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.
241 ForceSticker = b'X',
242
243 /// For messages: Message is a deletion request. The value is a list of rfc724_mid of the messages to delete.
244 DeleteRequestFor = b'M',
245
246 /// For messages: Message is a text edit message. the value of this parameter is the rfc724_mid of the original message.
247 TextEditFor = b'I',
248
249 /// For messages: Message text was edited.
250 IsEdited = b'L',
251
252 /// For info messages: Contact ID in added or removed to a group.
253 ContactAddedRemoved = b'5',
254
255 /// For (pre-)Message: ViewType of the Post-Message,
256 /// because pre message is always `Viewtype::Text`.
257 PostMessageViewtype = b'8',
258
259 /// For (pre-)Message: File byte size of Post-Message attachment
260 PostMessageFileBytes = b'9',
261}
262
263/// An object for handling key=value parameter lists.
264///
265/// The structure is serialized by calling `to_string()` on it.
266///
267/// Only for library-internal use.
268#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
269pub struct Params {
270 inner: BTreeMap<Param, String>,
271}
272
273impl fmt::Display for Params {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 for (i, (key, value)) in self.inner.iter().enumerate() {
276 if i > 0 {
277 writeln!(f)?;
278 }
279 write!(
280 f,
281 "{}={}",
282 *key as u8 as char,
283 value.split('\n').collect::<Vec<&str>>().join("\n\n")
284 )?;
285 }
286 Ok(())
287 }
288}
289
290impl str::FromStr for Params {
291 type Err = Error;
292
293 /// Parse a raw string to Param.
294 ///
295 /// Silently ignore unknown keys:
296 /// they may come from a downgrade (when a shortly new version adds a key)
297 /// or from an upgrade (when a key is dropped but was used in the past)
298 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
299 let mut inner = BTreeMap::new();
300 let mut lines = s.split('\n').peekable();
301
302 while let Some(line) = lines.next() {
303 if let [key, value] = line.splitn(2, '=').collect::<Vec<_>>()[..] {
304 let key = key.to_string();
305 let mut value = value.to_string();
306 while let Some(s) = lines.peek() {
307 if !s.is_empty() {
308 break;
309 }
310 lines.next();
311 value.push('\n');
312 value += lines.next().unwrap_or_default();
313 }
314
315 if let Some(key) = key.as_bytes().first().and_then(|key| Param::from_u8(*key)) {
316 inner.insert(key, value);
317 }
318 } else {
319 bail!("Not a key-value pair: {line:?}");
320 }
321 }
322
323 Ok(Params { inner })
324 }
325}
326
327impl Params {
328 /// Create new empty params.
329 pub fn new() -> Self {
330 Default::default()
331 }
332
333 /// Get the value of the given key, return `None` if no value is set.
334 pub fn get(&self, key: Param) -> Option<&str> {
335 self.inner.get(&key).map(|s| s.as_str())
336 }
337
338 /// Check if the given key is set.
339 pub fn exists(&self, key: Param) -> bool {
340 self.inner.contains_key(&key)
341 }
342
343 /// Set the given key to the passed in value.
344 pub fn set(&mut self, key: Param, value: impl ToString) -> &mut Self {
345 if key == Param::File {
346 debug_assert!(value.to_string().starts_with("$BLOBDIR/"));
347 }
348 self.inner.insert(key, value.to_string());
349 self
350 }
351
352 /// Removes the given key, if it exists.
353 pub fn remove(&mut self, key: Param) -> &mut Self {
354 self.inner.remove(&key);
355 self
356 }
357
358 /// Sets the given key from an optional value.
359 /// Removes the key if the value is `None`.
360 pub fn set_optional(&mut self, key: Param, value: Option<impl ToString>) -> &mut Self {
361 if let Some(value) = value {
362 self.set(key, value)
363 } else {
364 self.remove(key)
365 }
366 }
367
368 /// Check if there are any values in this.
369 pub fn is_empty(&self) -> bool {
370 self.inner.is_empty()
371 }
372
373 /// Returns how many key-value pairs are set.
374 pub fn len(&self) -> usize {
375 self.inner.len()
376 }
377
378 /// Get the given parameter and parse as `i32`.
379 pub fn get_int(&self, key: Param) -> Option<i32> {
380 self.get(key).and_then(|s| s.parse().ok())
381 }
382
383 /// Get the given parameter and parse as `i64`.
384 pub fn get_i64(&self, key: Param) -> Option<i64> {
385 self.get(key).and_then(|s| s.parse().ok())
386 }
387
388 /// Get the given parameter and parse as `bool`.
389 pub fn get_bool(&self, key: Param) -> Option<bool> {
390 self.get_int(key).map(|v| v != 0)
391 }
392
393 /// Get the parameter behind `Param::Cmd` interpreted as `SystemMessage`.
394 pub fn get_cmd(&self) -> SystemMessage {
395 self.get_int(Param::Cmd)
396 .and_then(SystemMessage::from_i32)
397 .unwrap_or_default()
398 }
399
400 /// Set the parameter behind `Param::Cmd`.
401 pub fn set_cmd(&mut self, value: SystemMessage) {
402 self.set_int(Param::Cmd, value as i32);
403 }
404
405 /// Get the given parameter and parse as `f64`.
406 pub fn get_float(&self, key: Param) -> Option<f64> {
407 self.get(key).and_then(|s| s.parse().ok())
408 }
409
410 /// Returns a [BlobObject] for the [Param::File] parameter.
411 pub fn get_file_blob<'a>(&self, context: &'a Context) -> Result<Option<BlobObject<'a>>> {
412 let Some(val) = self.get(Param::File) else {
413 return Ok(None);
414 };
415 ensure!(val.starts_with("$BLOBDIR/"));
416 let blob = BlobObject::from_name(context, val)?;
417 Ok(Some(blob))
418 }
419
420 /// Returns a [PathBuf] for the [Param::File] parameter.
421 pub fn get_file_path(&self, context: &Context) -> Result<Option<PathBuf>> {
422 let blob = self.get_file_blob(context)?;
423 Ok(blob.map(|p| p.to_abs_path()))
424 }
425
426 /// Set the given parameter to the passed in `i32`.
427 pub fn set_int(&mut self, key: Param, value: i32) -> &mut Self {
428 self.set(key, format!("{value}"));
429 self
430 }
431
432 /// Set the given parameter to the passed in `i64`.
433 pub fn set_i64(&mut self, key: Param, value: i64) -> &mut Self {
434 self.set(key, value.to_string());
435 self
436 }
437
438 /// Set the given parameter to the passed in `f64` .
439 pub fn set_float(&mut self, key: Param, value: f64) -> &mut Self {
440 self.set(key, format!("{value}"));
441 self
442 }
443
444 pub fn steal(&mut self, src: &mut Self, key: Param) -> &mut Self {
445 let val = src.inner.remove(&key);
446 if let Some(val) = val {
447 self.inner.insert(key, val);
448 }
449 self
450 }
451
452 /// Merge in parameters from other Params struct,
453 /// overwriting the keys that are in both
454 /// with the values from the new Params struct.
455 pub fn merge_in_params(&mut self, new_params: Self) -> &mut Self {
456 let mut new_params = new_params;
457 self.inner.append(&mut new_params.inner);
458 self
459 }
460}
461
462#[cfg(test)]
463mod tests {
464 use std::str::FromStr;
465
466 use super::*;
467
468 #[test]
469 fn test_dc_param() {
470 let mut p1: Params = "a=1\nw=2\nc=3".parse().unwrap();
471
472 assert_eq!(p1.get_int(Param::Forwarded), Some(1));
473 assert_eq!(p1.get_int(Param::Width), Some(2));
474 assert_eq!(p1.get_int(Param::Height), None);
475 assert!(!p1.exists(Param::Height));
476
477 p1.set_int(Param::Duration, 4);
478
479 assert_eq!(p1.get_int(Param::Duration), Some(4));
480
481 let mut p1 = Params::new();
482
483 p1.set(Param::Forwarded, "foo")
484 .set_int(Param::Width, 2)
485 .remove(Param::GuaranteeE2ee)
486 .set_int(Param::Duration, 4);
487
488 assert_eq!(p1.to_string(), "a=foo\nd=4\nw=2");
489
490 p1.remove(Param::Width);
491
492 assert_eq!(p1.to_string(), "a=foo\nd=4",);
493 assert_eq!(p1.len(), 2);
494
495 p1.remove(Param::Forwarded);
496 p1.remove(Param::Duration);
497
498 assert_eq!(p1.to_string(), "",);
499
500 assert!(p1.is_empty());
501 assert_eq!(p1.len(), 0)
502 }
503
504 #[test]
505 fn test_roundtrip() {
506 let mut params = Params::new();
507 params.set(Param::Height, "foo\nbar=baz\nquux");
508 params.set(Param::Width, "\n\n\na=\n=");
509 params.set(Param::WebrtcRoom, "foo\r\nbar\r\n\r\nbaz\r\n");
510 assert_eq!(params.to_string().parse::<Params>().unwrap(), params);
511 }
512
513 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
514 async fn test_params_unknown_key() -> Result<()> {
515 // 'Z' is used as a key that is known to be unused; these keys should be ignored silently by definition.
516 let p = Params::from_str("w=12\nZ=13\nh=14")?;
517 assert_eq!(p.len(), 2);
518 assert_eq!(p.get(Param::Width), Some("12"));
519 assert_eq!(p.get(Param::Height), Some("14"));
520 Ok(())
521 }
522
523 #[test]
524 fn test_merge() -> Result<()> {
525 let mut p = Params::from_str("w=12\na=5\nh=14")?;
526 let p2 = Params::from_str("L=1\nh=17")?;
527 assert_eq!(p.len(), 3);
528 p.merge_in_params(p2);
529 assert_eq!(p.len(), 4);
530 assert_eq!(p.get(Param::Width), Some("12"));
531 assert_eq!(p.get(Param::Height), Some("17"));
532 assert_eq!(p.get(Param::Forwarded), Some("5"));
533 assert_eq!(p.get(Param::IsEdited), Some("1"));
534 Ok(())
535 }
536}