1mod integration;
19mod maps_integration;
20
21use std::cmp::max;
22use std::collections::HashMap;
23use std::path::Path;
24
25use anyhow::{Context as _, Result, anyhow, bail, ensure, format_err};
26
27use async_zip::tokio::read::seek::ZipFileReader as SeekZipFileReader;
28use deltachat_contact_tools::sanitize_bidi_characters;
29use deltachat_derive::FromSql;
30use mail_builder::mime::MimePart;
31use rusqlite::OptionalExtension;
32use serde::{Deserialize, Serialize};
33use serde_json::Value;
34use sha2::{Digest, Sha256};
35use tokio::{fs::File, io::BufReader};
36
37use crate::chat::{self, Chat};
38use crate::constants::Chattype;
39use crate::contact::ContactId;
40use crate::context::Context;
41use crate::events::EventType;
42use crate::key::self_fingerprint;
43use crate::log::warn;
44use crate::message::{Message, MessageState, MsgId, Viewtype};
45use crate::mimefactory::RECOMMENDED_FILE_SIZE;
46use crate::mimeparser::SystemMessage;
47use crate::param::Param;
48use crate::param::Params;
49use crate::tools::{create_id, create_smeared_timestamp, get_abs_path};
50
51const WEBXDC_API_VERSION: u32 = 1;
56
57pub const WEBXDC_SUFFIX: &str = "xdc";
59const WEBXDC_DEFAULT_ICON: &str = "__webxdc__/default-icon.png";
60
61const BODY_DESCR: &str = "Webxdc Status Update";
63
64#[derive(Debug, Deserialize, Default)]
66#[non_exhaustive]
67pub struct WebxdcManifest {
68 pub name: Option<String>,
70
71 pub min_api: Option<u32>,
73
74 pub source_code_url: Option<String>,
76
77 pub request_integration: Option<String>,
79}
80
81#[derive(Debug, Serialize)]
83pub struct WebxdcInfo {
84 pub name: String,
87
88 pub icon: String,
90
91 pub document: String,
95
96 pub summary: String,
99
100 pub source_code_url: String,
102
103 pub request_integration: String,
105
106 pub internet_access: bool,
110
111 pub self_addr: String,
113
114 pub send_update_interval: usize,
117
118 pub send_update_max_size: usize,
121}
122
123#[derive(
125 Debug,
126 Copy,
127 Clone,
128 Default,
129 PartialEq,
130 Eq,
131 Hash,
132 PartialOrd,
133 Ord,
134 Serialize,
135 Deserialize,
136 FromSql,
137 FromPrimitive,
138)]
139pub struct StatusUpdateSerial(u32);
140
141impl StatusUpdateSerial {
142 pub fn new(id: u32) -> StatusUpdateSerial {
144 StatusUpdateSerial(id)
145 }
146
147 pub const MIN: Self = Self(1);
149 pub const MAX: Self = Self(u32::MAX - 1);
151
152 pub fn to_u32(self) -> u32 {
155 self.0
156 }
157}
158
159impl rusqlite::types::ToSql for StatusUpdateSerial {
160 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
161 let val = rusqlite::types::Value::Integer(i64::from(self.0));
162 let out = rusqlite::types::ToSqlOutput::Owned(val);
163 Ok(out)
164 }
165}
166
167#[derive(Debug, Deserialize)]
169struct StatusUpdates {
170 updates: Vec<StatusUpdateItem>,
171}
172
173#[derive(Debug, Serialize, Deserialize, Default)]
175pub struct StatusUpdateItem {
176 pub payload: Value,
178
179 #[serde(skip_serializing_if = "Option::is_none")]
182 pub info: Option<String>,
183
184 #[serde(skip_serializing_if = "Option::is_none")]
187 pub href: Option<String>,
188
189 #[serde(skip_serializing_if = "Option::is_none")]
192 pub document: Option<String>,
193
194 #[serde(skip_serializing_if = "Option::is_none")]
198 pub summary: Option<String>,
199
200 #[serde(skip_serializing_if = "Option::is_none")]
205 pub uid: Option<String>,
206
207 #[serde(skip_serializing_if = "Option::is_none")]
209 pub notify: Option<HashMap<String, String>>,
210}
211
212#[derive(Debug, Serialize, Deserialize)]
214pub(crate) struct StatusUpdateItemAndSerial {
215 #[serde(flatten)]
216 item: StatusUpdateItem,
217
218 serial: StatusUpdateSerial,
219 max_serial: StatusUpdateSerial,
220}
221
222fn find_zip_entry<'a>(
224 file: &'a async_zip::ZipFile,
225 name: &str,
226) -> Option<(usize, &'a async_zip::StoredZipEntry)> {
227 for (i, ent) in file.entries().iter().enumerate() {
228 if ent.filename().as_bytes() == name.as_bytes() {
229 return Some((i, ent));
230 }
231 }
232 None
233}
234
235const STATUS_UPDATE_SIZE_MAX: usize = 100 << 10;
237
238impl Context {
239 pub(crate) async fn is_webxdc_file(&self, filename: &str, file: &[u8]) -> Result<bool> {
241 if !filename.ends_with(WEBXDC_SUFFIX) {
242 return Ok(false);
243 }
244
245 let archive = match async_zip::base::read::mem::ZipFileReader::new(file.to_vec()).await {
246 Ok(archive) => archive,
247 Err(_) => {
248 info!(self, "{} cannot be opened as zip-file", &filename);
249 return Ok(false);
250 }
251 };
252
253 if find_zip_entry(archive.file(), "index.html").is_none() {
254 info!(self, "{} misses index.html", &filename);
255 return Ok(false);
256 }
257
258 Ok(true)
259 }
260
261 pub(crate) async fn ensure_sendable_webxdc_file(&self, path: &Path) -> Result<()> {
263 let filename = path.to_str().unwrap_or_default();
264
265 let file = BufReader::new(File::open(path).await?);
266 let valid = match SeekZipFileReader::with_tokio(file).await {
267 Ok(archive) => {
268 if find_zip_entry(archive.file(), "index.html").is_none() {
269 warn!(self, "{} misses index.html", filename);
270 false
271 } else {
272 true
273 }
274 }
275 Err(_) => {
276 warn!(self, "{} cannot be opened as zip-file", filename);
277 false
278 }
279 };
280
281 if !valid {
282 bail!("{filename} is not a valid webxdc file");
283 }
284
285 Ok(())
286 }
287
288 async fn get_overwritable_info_msg_id(
291 &self,
292 instance: &Message,
293 from_id: ContactId,
294 ) -> Result<Option<MsgId>> {
295 if let Some((last_msg_id, last_from_id, last_param, last_in_repl_to)) = self
296 .sql
297 .query_row_optional(
298 r#"SELECT id, from_id, param, mime_in_reply_to
299 FROM msgs
300 WHERE chat_id=?1 AND hidden=0
301 ORDER BY timestamp DESC, id DESC LIMIT 1"#,
302 (instance.chat_id,),
303 |row| {
304 let last_msg_id: MsgId = row.get(0)?;
305 let last_from_id: ContactId = row.get(1)?;
306 let last_param: Params = row.get::<_, String>(2)?.parse().unwrap_or_default();
307 let last_in_repl_to: String = row.get(3)?;
308 Ok((last_msg_id, last_from_id, last_param, last_in_repl_to))
309 },
310 )
311 .await?
312 && last_from_id == from_id
313 && last_param.get_cmd() == SystemMessage::WebxdcInfoMessage
314 && last_in_repl_to == instance.rfc724_mid
315 {
316 return Ok(Some(last_msg_id));
317 }
318 Ok(None)
319 }
320
321 async fn create_status_update_record(
324 &self,
325 instance: &Message,
326 status_update_item: StatusUpdateItem,
327 timestamp: i64,
328 can_info_msg: bool,
329 from_id: ContactId,
330 ) -> Result<Option<StatusUpdateSerial>> {
331 let Some(status_update_serial) = self
332 .write_status_update_inner(&instance.id, &status_update_item, timestamp)
333 .await?
334 else {
335 return Ok(None);
336 };
337
338 let mut notify_msg_id = instance.id;
339 let mut param_changed = false;
340
341 let mut instance = instance.clone();
342 if let Some(ref document) = status_update_item.document
343 && instance
344 .param
345 .update_timestamp(Param::WebxdcDocumentTimestamp, timestamp)?
346 {
347 instance.param.set(Param::WebxdcDocument, document);
348 param_changed = true;
349 }
350
351 if let Some(ref summary) = status_update_item.summary
352 && instance
353 .param
354 .update_timestamp(Param::WebxdcSummaryTimestamp, timestamp)?
355 {
356 let summary = sanitize_bidi_characters(summary);
357 instance.param.set(Param::WebxdcSummary, summary.clone());
358 param_changed = true;
359 }
360
361 if can_info_msg && let Some(ref info) = status_update_item.info {
362 let info_msg_id = self
363 .get_overwritable_info_msg_id(&instance, from_id)
364 .await?;
365
366 if let (Some(info_msg_id), None) = (info_msg_id, &status_update_item.href) {
367 chat::update_msg_text_and_timestamp(
368 self,
369 instance.chat_id,
370 info_msg_id,
371 info.as_str(),
372 timestamp,
373 )
374 .await?;
375 notify_msg_id = info_msg_id;
376 } else {
377 notify_msg_id = chat::add_info_msg_with_cmd(
378 self,
379 instance.chat_id,
380 info.as_str(),
381 SystemMessage::WebxdcInfoMessage,
382 Some(timestamp),
383 timestamp,
384 Some(&instance),
385 Some(from_id),
386 None,
387 )
388 .await?;
389 }
390
391 if let Some(ref href) = status_update_item.href {
392 let mut notify_msg = Message::load_from_db(self, notify_msg_id).await?;
393 notify_msg.param.set(Param::Arg, href);
394 notify_msg.update_param(self).await?;
395 }
396 }
397
398 if param_changed {
399 instance.update_param(self).await?;
400 self.emit_msgs_changed(instance.chat_id, instance.id);
401 }
402
403 if instance.viewtype == Viewtype::Webxdc {
404 self.emit_event(EventType::WebxdcStatusUpdate {
405 msg_id: instance.id,
406 status_update_serial,
407 });
408 }
409
410 if from_id != ContactId::SELF
411 && let Some(notify_list) = status_update_item.notify
412 {
413 let self_addr = instance.get_webxdc_self_addr(self).await?;
414 if let Some(notify_text) = notify_list.get(&self_addr).or_else(|| notify_list.get("*"))
415 {
416 self.emit_event(EventType::IncomingWebxdcNotify {
417 chat_id: instance.chat_id,
418 contact_id: from_id,
419 msg_id: notify_msg_id,
420 text: notify_text.clone(),
421 href: status_update_item.href,
422 });
423 }
424 }
425
426 Ok(Some(status_update_serial))
427 }
428
429 pub(crate) async fn write_status_update_inner(
433 &self,
434 instance_id: &MsgId,
435 status_update_item: &StatusUpdateItem,
436 timestamp: i64,
437 ) -> Result<Option<StatusUpdateSerial>> {
438 let uid = status_update_item.uid.as_deref();
439 let status_update_item = serde_json::to_string(&status_update_item)?;
440 let trans_fn = |t: &mut rusqlite::Transaction| {
441 t.execute(
442 "UPDATE msgs SET timestamp_rcvd=? WHERE id=?",
443 (timestamp, instance_id),
444 )?;
445 let rowid = t
446 .query_row(
447 "INSERT INTO msgs_status_updates (msg_id, update_item, uid) VALUES(?, ?, ?)
448 ON CONFLICT (uid) DO NOTHING
449 RETURNING id",
450 (instance_id, status_update_item, uid),
451 |row| {
452 let id: u32 = row.get(0)?;
453 Ok(id)
454 },
455 )
456 .optional()?;
457 Ok(rowid)
458 };
459 let Some(rowid) = self.sql.transaction(trans_fn).await? else {
460 let uid = uid.unwrap_or("-");
461 info!(self, "Ignoring duplicate status update with uid={uid}");
462 return Ok(None);
463 };
464 let status_update_serial = StatusUpdateSerial(rowid);
465 Ok(Some(status_update_serial))
466 }
467
468 pub async fn get_status_update(
470 &self,
471 msg_id: MsgId,
472 status_update_serial: StatusUpdateSerial,
473 ) -> Result<String> {
474 self.sql
475 .query_get_value(
476 "SELECT update_item FROM msgs_status_updates WHERE id=? AND msg_id=? ",
477 (status_update_serial.0, msg_id),
478 )
479 .await?
480 .context("get_status_update: no update item found.")
481 }
482
483 pub async fn send_webxdc_status_update(
489 &self,
490 instance_msg_id: MsgId,
491 update_str: &str,
492 ) -> Result<()> {
493 let status_update_item: StatusUpdateItem = serde_json::from_str(update_str)
494 .with_context(|| format!("Failed to parse webxdc update item from {update_str:?}"))?;
495 self.send_webxdc_status_update_struct(instance_msg_id, status_update_item)
496 .await?;
497 Ok(())
498 }
499
500 pub async fn send_webxdc_status_update_struct(
503 &self,
504 instance_msg_id: MsgId,
505 mut status_update: StatusUpdateItem,
506 ) -> Result<()> {
507 let instance = Message::load_from_db(self, instance_msg_id)
508 .await
509 .with_context(|| {
510 format!("Failed to load message {instance_msg_id} from the database")
511 })?;
512 let viewtype = instance.viewtype;
513 if viewtype != Viewtype::Webxdc {
514 bail!(
515 "send_webxdc_status_update: message {instance_msg_id} is not a webxdc message, but a {viewtype} message."
516 );
517 }
518
519 if instance.param.get_int(Param::WebxdcIntegration).is_some() {
520 return self
521 .intercept_send_webxdc_status_update(instance, status_update)
522 .await;
523 }
524
525 let chat_id = instance.chat_id;
526 let chat = Chat::load_from_db(self, chat_id)
527 .await
528 .with_context(|| format!("Failed to load chat {chat_id} from the database"))?;
529 if let Some(reason) = chat.why_cant_send(self).await.with_context(|| {
530 format!("Failed to check if webxdc update can be sent to chat {chat_id}")
531 })? {
532 bail!("Cannot send to {chat_id}: {reason}.");
533 }
534
535 let send_now = !matches!(
536 instance.state,
537 MessageState::Undefined | MessageState::OutPreparing | MessageState::OutDraft
538 );
539
540 status_update.uid = Some(create_id());
541 let status_update_serial: StatusUpdateSerial = self
542 .create_status_update_record(
543 &instance,
544 status_update,
545 create_smeared_timestamp(self),
546 send_now,
547 ContactId::SELF,
548 )
549 .await
550 .context("Failed to create status update")?
551 .context("Duplicate status update UID was generated")?;
552
553 if send_now {
554 self.sql.insert(
555 "INSERT INTO smtp_status_updates (msg_id, first_serial, last_serial, descr) VALUES(?, ?, ?, '')
556 ON CONFLICT(msg_id)
557 DO UPDATE SET last_serial=excluded.last_serial",
558 (instance.id, status_update_serial, status_update_serial),
559 ).await.context("Failed to insert webxdc update into SMTP queue")?;
560 self.scheduler.interrupt_smtp().await;
561 }
562 Ok(())
563 }
564
565 async fn smtp_status_update_get(&self) -> Result<Option<(MsgId, i64, StatusUpdateSerial)>> {
567 let res = self
568 .sql
569 .query_row_optional(
570 "SELECT msg_id, first_serial, last_serial \
571 FROM smtp_status_updates LIMIT 1",
572 (),
573 |row| {
574 let instance_id: MsgId = row.get(0)?;
575 let first_serial: i64 = row.get(1)?;
576 let last_serial: StatusUpdateSerial = row.get(2)?;
577 Ok((instance_id, first_serial, last_serial))
578 },
579 )
580 .await?;
581 Ok(res)
582 }
583
584 async fn smtp_status_update_pop_serials(
585 &self,
586 msg_id: MsgId,
587 first: i64,
588 first_new: StatusUpdateSerial,
589 ) -> Result<()> {
590 if self
591 .sql
592 .execute(
593 "DELETE FROM smtp_status_updates \
594 WHERE msg_id=? AND first_serial=? AND last_serial<?",
595 (msg_id, first, first_new),
596 )
597 .await?
598 > 0
599 {
600 return Ok(());
601 }
602 self.sql
603 .execute(
604 "UPDATE smtp_status_updates SET first_serial=? \
605 WHERE msg_id=? AND first_serial=?",
606 (first_new, msg_id, first),
607 )
608 .await?;
609 Ok(())
610 }
611
612 pub(crate) async fn flush_status_updates(&self) -> Result<()> {
614 loop {
615 let (instance_id, first, last) = match self.smtp_status_update_get().await? {
616 Some(res) => res,
617 None => return Ok(()),
618 };
619 let (json, first_new) = self
620 .render_webxdc_status_update_object(
621 instance_id,
622 StatusUpdateSerial(max(first, 1).try_into()?),
623 last,
624 Some(STATUS_UPDATE_SIZE_MAX),
625 )
626 .await?;
627 if let Some(json) = json {
628 let instance = Message::load_from_db(self, instance_id).await?;
629 let mut status_update = Message {
630 chat_id: instance.chat_id,
631 viewtype: Viewtype::Text,
632 text: BODY_DESCR.to_string(),
633 hidden: true,
634 ..Default::default()
635 };
636 status_update
637 .param
638 .set_cmd(SystemMessage::WebxdcStatusUpdate);
639 status_update.param.set(Param::Arg, json);
640 status_update.set_quote(self, Some(&instance)).await?;
641 status_update.param.remove(Param::GuaranteeE2ee); chat::send_msg(self, instance.chat_id, &mut status_update).await?;
643 }
644 self.smtp_status_update_pop_serials(instance_id, first, first_new)
645 .await?;
646 }
647 }
648
649 pub(crate) fn build_status_update_part(&self, json: &str) -> MimePart<'static> {
650 MimePart::new("application/json", json.as_bytes().to_vec()).attachment("status-update.json")
651 }
652
653 pub(crate) async fn receive_status_update(
665 &self,
666 from_id: ContactId,
667 instance: &Message,
668 timestamp: i64,
669 can_info_msg: bool,
670 json: &str,
671 ) -> Result<()> {
672 let chat_id = instance.chat_id;
673
674 if from_id != ContactId::SELF && !chat::is_contact_in_chat(self, chat_id, from_id).await? {
675 let chat_type: Chattype = self
676 .sql
677 .query_get_value("SELECT type FROM chats WHERE id=?", (chat_id,))
678 .await?
679 .with_context(|| format!("Chat type for chat {chat_id} not found"))?;
680 if chat_type != Chattype::Mailinglist {
681 bail!(
682 "receive_status_update: status sender {from_id} is not a member of chat {chat_id}"
683 )
684 }
685 }
686
687 let updates: StatusUpdates = serde_json::from_str(json)?;
688 for update_item in updates.updates {
689 self.create_status_update_record(
690 instance,
691 update_item,
692 timestamp,
693 can_info_msg,
694 from_id,
695 )
696 .await?;
697 }
698
699 Ok(())
700 }
701
702 pub async fn get_webxdc_status_updates(
710 &self,
711 instance_msg_id: MsgId,
712 last_known_serial: StatusUpdateSerial,
713 ) -> Result<String> {
714 let param = instance_msg_id.get_param(self).await?;
715 if param.get_int(Param::WebxdcIntegration).is_some() {
716 let instance = Message::load_from_db(self, instance_msg_id).await?;
717 return self
718 .intercept_get_webxdc_status_updates(instance, last_known_serial)
719 .await;
720 }
721
722 let json = self
723 .sql
724 .query_map(
725 "SELECT update_item, id FROM msgs_status_updates WHERE msg_id=? AND id>? ORDER BY id",
726 (instance_msg_id, last_known_serial),
727 |row| {
728 let update_item_str: String = row.get(0)?;
729 let serial: StatusUpdateSerial = row.get(1)?;
730 Ok((update_item_str, serial))
731 },
732 |rows| {
733 let mut rows_copy : Vec<(String, StatusUpdateSerial)> = Vec::new(); let mut max_serial = StatusUpdateSerial(0);
735 for row in rows {
736 let row = row?;
737 if row.1 > max_serial {
738 max_serial = row.1;
739 }
740 rows_copy.push(row);
741 }
742
743 let mut json = String::default();
744 for row in rows_copy {
745 let (update_item_str, serial) = row;
746 let update_item = StatusUpdateItemAndSerial
747 {
748 item: StatusUpdateItem {
749 uid: None, ..serde_json::from_str(&update_item_str)?
751 },
752 serial,
753 max_serial,
754 };
755
756 if !json.is_empty() {
757 json.push_str(",\n");
758 }
759 json.push_str(&serde_json::to_string(&update_item)?);
760 }
761 Ok(json)
762 },
763 )
764 .await?;
765 Ok(format!("[{json}]"))
766 }
767
768 pub(crate) async fn render_webxdc_status_update_object(
778 &self,
779 instance_msg_id: MsgId,
780 first: StatusUpdateSerial,
781 last: StatusUpdateSerial,
782 size_max: Option<usize>,
783 ) -> Result<(Option<String>, StatusUpdateSerial)> {
784 let (json, first_new) = self
785 .sql
786 .query_map(
787 "SELECT id, update_item FROM msgs_status_updates \
788 WHERE msg_id=? AND id>=? AND id<=? ORDER BY id",
789 (instance_msg_id, first, last),
790 |row| {
791 let id: StatusUpdateSerial = row.get(0)?;
792 let update_item: String = row.get(1)?;
793 Ok((id, update_item))
794 },
795 |rows| {
796 let mut json = String::default();
797 for row in rows {
798 let (id, update_item) = row?;
799 if !json.is_empty()
800 && json.len() + update_item.len() >= size_max.unwrap_or(usize::MAX)
801 {
802 return Ok((json, id));
803 }
804 if !json.is_empty() {
805 json.push_str(",\n");
806 }
807 json.push_str(&update_item);
808 }
809 Ok((
810 json,
811 StatusUpdateSerial::new(last.to_u32().saturating_add(1)),
814 ))
815 },
816 )
817 .await?;
818 let json = match json.is_empty() {
819 true => None,
820 false => Some(format!(r#"{{"updates":[{json}]}}"#)),
821 };
822 Ok((json, first_new))
823 }
824}
825
826fn parse_webxdc_manifest(bytes: &[u8]) -> Result<WebxdcManifest> {
827 let s = std::str::from_utf8(bytes)?;
828 let manifest: WebxdcManifest = toml::from_str(s)?;
829 Ok(manifest)
830}
831
832async fn get_blob(archive: &mut SeekZipFileReader<BufReader<File>>, name: &str) -> Result<Vec<u8>> {
833 let (i, _) =
834 find_zip_entry(archive.file(), name).ok_or_else(|| anyhow!("no entry found for {name}"))?;
835 let mut reader = archive.reader_with_entry(i).await?;
836 let mut buf = Vec::new();
837 reader.read_to_end_checked(&mut buf).await?;
838 Ok(buf)
839}
840
841impl Message {
842 async fn get_webxdc_archive(
845 &self,
846 context: &Context,
847 ) -> Result<SeekZipFileReader<BufReader<File>>> {
848 let path = self
849 .get_file(context)
850 .ok_or_else(|| format_err!("No webxdc instance file."))?;
851 let path_abs = get_abs_path(context, &path);
852 let file = BufReader::new(File::open(path_abs).await?);
853 let archive = SeekZipFileReader::with_tokio(file).await?;
854 Ok(archive)
855 }
856
857 pub async fn get_webxdc_blob(&self, context: &Context, name: &str) -> Result<Vec<u8>> {
862 ensure!(self.viewtype == Viewtype::Webxdc, "No webxdc instance.");
863
864 if name == WEBXDC_DEFAULT_ICON {
865 return Ok(include_bytes!("../assets/icon-webxdc.png").to_vec());
866 }
867
868 let name = if name.starts_with('/') {
871 name.split_at(1).1
872 } else {
873 name
874 };
875
876 let mut archive = self.get_webxdc_archive(context).await?;
877
878 if name == "index.html"
879 && let Ok(bytes) = get_blob(&mut archive, "manifest.toml").await
880 && let Ok(manifest) = parse_webxdc_manifest(&bytes)
881 && let Some(min_api) = manifest.min_api
882 && min_api > WEBXDC_API_VERSION
883 {
884 return Ok(Vec::from(
885 "<!DOCTYPE html>This Webxdc requires a newer Delta Chat version.",
886 ));
887 }
888
889 get_blob(&mut archive, name).await
890 }
891
892 pub async fn get_webxdc_info(&self, context: &Context) -> Result<WebxdcInfo> {
894 ensure!(self.viewtype == Viewtype::Webxdc, "No webxdc instance.");
895 let mut archive = self.get_webxdc_archive(context).await?;
896
897 let mut manifest = get_blob(&mut archive, "manifest.toml")
898 .await
899 .map(|bytes| parse_webxdc_manifest(&bytes).unwrap_or_default())
900 .unwrap_or_default();
901
902 if let Some(ref name) = manifest.name {
903 let name = name.trim();
904 if name.is_empty() {
905 warn!(context, "empty name given in manifest");
906 manifest.name = None;
907 }
908 }
909
910 let request_integration = manifest.request_integration.unwrap_or_default();
911 let is_integrated = self.is_set_as_webxdc_integration(context).await?;
912 let internet_access = is_integrated;
913
914 let self_addr = self.get_webxdc_self_addr(context).await?;
915
916 Ok(WebxdcInfo {
917 name: if let Some(name) = manifest.name {
918 name
919 } else {
920 self.get_filename().unwrap_or_default()
921 },
922 icon: if find_zip_entry(archive.file(), "icon.png").is_some() {
923 "icon.png".to_string()
924 } else if find_zip_entry(archive.file(), "icon.jpg").is_some() {
925 "icon.jpg".to_string()
926 } else {
927 WEBXDC_DEFAULT_ICON.to_string()
928 },
929 document: self
930 .param
931 .get(Param::WebxdcDocument)
932 .unwrap_or_default()
933 .to_string(),
934 summary: if is_integrated {
935 "🌍 Used as map. Delete to use default. Do not enter sensitive data".to_string()
936 } else if request_integration == "map" {
937 "🌏 To use as map, forward to \"Saved Messages\" again. Do not enter sensitive data"
938 .to_string()
939 } else {
940 self.param
941 .get(Param::WebxdcSummary)
942 .unwrap_or_default()
943 .to_string()
944 },
945 source_code_url: if let Some(url) = manifest.source_code_url {
946 url
947 } else {
948 "".to_string()
949 },
950 request_integration,
951 internet_access,
952 self_addr,
953 send_update_interval: context.ratelimit.read().await.update_interval(),
954 send_update_max_size: RECOMMENDED_FILE_SIZE as usize,
955 })
956 }
957
958 async fn get_webxdc_self_addr(&self, context: &Context) -> Result<String> {
959 let fingerprint = self_fingerprint(context).await?;
960 let data = format!("{}-{}", fingerprint, self.rfc724_mid);
961 let hash = Sha256::digest(data.as_bytes());
962 Ok(format!("{hash:x}"))
963 }
964
965 pub fn get_webxdc_href(&self) -> Option<String> {
971 self.param.get(Param::Arg).map(|href| href.to_string())
972 }
973}
974
975#[cfg(test)]
976mod webxdc_tests;