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 let notify_text = if let Some(notify_text) = notify_list.get(&self_addr) {
415 Some(notify_text)
416 } else if let Some(notify_text) = notify_list.get("*")
417 && !Chat::load_from_db(self, instance.chat_id).await?.is_muted()
418 {
419 Some(notify_text)
420 } else {
421 None
422 };
423 if let Some(notify_text) = notify_text {
424 self.emit_event(EventType::IncomingWebxdcNotify {
425 chat_id: instance.chat_id,
426 contact_id: from_id,
427 msg_id: notify_msg_id,
428 text: notify_text.clone(),
429 href: status_update_item.href,
430 });
431 }
432 }
433
434 Ok(Some(status_update_serial))
435 }
436
437 pub(crate) async fn write_status_update_inner(
441 &self,
442 instance_id: &MsgId,
443 status_update_item: &StatusUpdateItem,
444 timestamp: i64,
445 ) -> Result<Option<StatusUpdateSerial>> {
446 let uid = status_update_item.uid.as_deref();
447 let status_update_item = serde_json::to_string(&status_update_item)?;
448 let trans_fn = |t: &mut rusqlite::Transaction| {
449 t.execute(
450 "UPDATE msgs SET timestamp_rcvd=? WHERE id=?",
451 (timestamp, instance_id),
452 )?;
453 let rowid = t
454 .query_row(
455 "INSERT INTO msgs_status_updates (msg_id, update_item, uid) VALUES(?, ?, ?)
456 ON CONFLICT (uid) DO NOTHING
457 RETURNING id",
458 (instance_id, status_update_item, uid),
459 |row| {
460 let id: u32 = row.get(0)?;
461 Ok(id)
462 },
463 )
464 .optional()?;
465 Ok(rowid)
466 };
467 let Some(rowid) = self.sql.transaction(trans_fn).await? else {
468 let uid = uid.unwrap_or("-");
469 info!(self, "Ignoring duplicate status update with uid={uid}");
470 return Ok(None);
471 };
472 let status_update_serial = StatusUpdateSerial(rowid);
473 Ok(Some(status_update_serial))
474 }
475
476 pub async fn get_status_update(
478 &self,
479 msg_id: MsgId,
480 status_update_serial: StatusUpdateSerial,
481 ) -> Result<String> {
482 self.sql
483 .query_get_value(
484 "SELECT update_item FROM msgs_status_updates WHERE id=? AND msg_id=? ",
485 (status_update_serial.0, msg_id),
486 )
487 .await?
488 .context("get_status_update: no update item found.")
489 }
490
491 pub async fn send_webxdc_status_update(
497 &self,
498 instance_msg_id: MsgId,
499 update_str: &str,
500 ) -> Result<()> {
501 let status_update_item: StatusUpdateItem = serde_json::from_str(update_str)
502 .with_context(|| format!("Failed to parse webxdc update item from {update_str:?}"))?;
503 self.send_webxdc_status_update_struct(instance_msg_id, status_update_item)
504 .await?;
505 Ok(())
506 }
507
508 pub async fn send_webxdc_status_update_struct(
511 &self,
512 instance_msg_id: MsgId,
513 mut status_update: StatusUpdateItem,
514 ) -> Result<()> {
515 let instance = Message::load_from_db(self, instance_msg_id)
516 .await
517 .with_context(|| {
518 format!("Failed to load message {instance_msg_id} from the database")
519 })?;
520 let viewtype = instance.viewtype;
521 if viewtype != Viewtype::Webxdc {
522 bail!(
523 "send_webxdc_status_update: message {instance_msg_id} is not a webxdc message, but a {viewtype} message."
524 );
525 }
526
527 if instance.param.get_int(Param::WebxdcIntegration).is_some() {
528 return self
529 .intercept_send_webxdc_status_update(instance, status_update)
530 .await;
531 }
532
533 let chat_id = instance.chat_id;
534 let chat = Chat::load_from_db(self, chat_id)
535 .await
536 .with_context(|| format!("Failed to load chat {chat_id} from the database"))?;
537 if let Some(reason) = chat.why_cant_send(self).await.with_context(|| {
538 format!("Failed to check if webxdc update can be sent to chat {chat_id}")
539 })? {
540 bail!("Cannot send to {chat_id}: {reason}.");
541 }
542
543 let send_now = !matches!(
544 instance.state,
545 MessageState::Undefined | MessageState::OutPreparing | MessageState::OutDraft
546 );
547
548 status_update.uid = Some(create_id());
549 let status_update_serial: StatusUpdateSerial = self
550 .create_status_update_record(
551 &instance,
552 status_update,
553 create_smeared_timestamp(self),
554 send_now,
555 ContactId::SELF,
556 )
557 .await
558 .context("Failed to create status update")?
559 .context("Duplicate status update UID was generated")?;
560
561 if send_now {
562 self.sql.insert(
563 "INSERT INTO smtp_status_updates (msg_id, first_serial, last_serial, descr) VALUES(?, ?, ?, '')
564 ON CONFLICT(msg_id)
565 DO UPDATE SET last_serial=excluded.last_serial",
566 (instance.id, status_update_serial, status_update_serial),
567 ).await.context("Failed to insert webxdc update into SMTP queue")?;
568 self.scheduler.interrupt_smtp().await;
569 }
570 Ok(())
571 }
572
573 async fn smtp_status_update_get(&self) -> Result<Option<(MsgId, i64, StatusUpdateSerial)>> {
575 let res = self
576 .sql
577 .query_row_optional(
578 "SELECT msg_id, first_serial, last_serial \
579 FROM smtp_status_updates LIMIT 1",
580 (),
581 |row| {
582 let instance_id: MsgId = row.get(0)?;
583 let first_serial: i64 = row.get(1)?;
584 let last_serial: StatusUpdateSerial = row.get(2)?;
585 Ok((instance_id, first_serial, last_serial))
586 },
587 )
588 .await?;
589 Ok(res)
590 }
591
592 async fn smtp_status_update_pop_serials(
593 &self,
594 msg_id: MsgId,
595 first: i64,
596 first_new: StatusUpdateSerial,
597 ) -> Result<()> {
598 if self
599 .sql
600 .execute(
601 "DELETE FROM smtp_status_updates \
602 WHERE msg_id=? AND first_serial=? AND last_serial<?",
603 (msg_id, first, first_new),
604 )
605 .await?
606 > 0
607 {
608 return Ok(());
609 }
610 self.sql
611 .execute(
612 "UPDATE smtp_status_updates SET first_serial=? \
613 WHERE msg_id=? AND first_serial=?",
614 (first_new, msg_id, first),
615 )
616 .await?;
617 Ok(())
618 }
619
620 pub(crate) async fn flush_status_updates(&self) -> Result<()> {
622 loop {
623 let (instance_id, first, last) = match self.smtp_status_update_get().await? {
624 Some(res) => res,
625 None => return Ok(()),
626 };
627 let (json, first_new) = self
628 .render_webxdc_status_update_object(
629 instance_id,
630 StatusUpdateSerial(max(first, 1).try_into()?),
631 last,
632 Some(STATUS_UPDATE_SIZE_MAX),
633 )
634 .await?;
635 if let Some(json) = json {
636 let instance = Message::load_from_db(self, instance_id).await?;
637 let mut status_update = Message {
638 chat_id: instance.chat_id,
639 viewtype: Viewtype::Text,
640 text: BODY_DESCR.to_string(),
641 hidden: true,
642 ..Default::default()
643 };
644 status_update
645 .param
646 .set_cmd(SystemMessage::WebxdcStatusUpdate);
647 status_update.param.set(Param::Arg, json);
648 status_update.set_quote(self, Some(&instance)).await?;
649 status_update.param.remove(Param::GuaranteeE2ee); chat::send_msg(self, instance.chat_id, &mut status_update).await?;
651 }
652 self.smtp_status_update_pop_serials(instance_id, first, first_new)
653 .await?;
654 }
655 }
656
657 pub(crate) fn build_status_update_part(&self, json: &str) -> MimePart<'static> {
658 MimePart::new("application/json", json.as_bytes().to_vec()).attachment("status-update.json")
659 }
660
661 pub(crate) async fn receive_status_update(
673 &self,
674 from_id: ContactId,
675 instance: &Message,
676 timestamp: i64,
677 can_info_msg: bool,
678 json: &str,
679 ) -> Result<()> {
680 let chat_id = instance.chat_id;
681
682 if from_id != ContactId::SELF && !chat::is_contact_in_chat(self, chat_id, from_id).await? {
683 let chat_type: Chattype = self
684 .sql
685 .query_get_value("SELECT type FROM chats WHERE id=?", (chat_id,))
686 .await?
687 .with_context(|| format!("Chat type for chat {chat_id} not found"))?;
688 if chat_type != Chattype::Mailinglist {
689 bail!(
690 "receive_status_update: status sender {from_id} is not a member of chat {chat_id}"
691 )
692 }
693 }
694
695 let updates: StatusUpdates = serde_json::from_str(json)?;
696 for update_item in updates.updates {
697 self.create_status_update_record(
698 instance,
699 update_item,
700 timestamp,
701 can_info_msg,
702 from_id,
703 )
704 .await?;
705 }
706
707 Ok(())
708 }
709
710 pub async fn get_webxdc_status_updates(
718 &self,
719 instance_msg_id: MsgId,
720 last_known_serial: StatusUpdateSerial,
721 ) -> Result<String> {
722 let param = instance_msg_id.get_param(self).await?;
723 if param.get_int(Param::WebxdcIntegration).is_some() {
724 let instance = Message::load_from_db(self, instance_msg_id).await?;
725 return self
726 .intercept_get_webxdc_status_updates(instance, last_known_serial)
727 .await;
728 }
729
730 let json = self
731 .sql
732 .query_map(
733 "SELECT update_item, id FROM msgs_status_updates WHERE msg_id=? AND id>? ORDER BY id",
734 (instance_msg_id, last_known_serial),
735 |row| {
736 let update_item_str: String = row.get(0)?;
737 let serial: StatusUpdateSerial = row.get(1)?;
738 Ok((update_item_str, serial))
739 },
740 |rows| {
741 let mut rows_copy : Vec<(String, StatusUpdateSerial)> = Vec::new(); let mut max_serial = StatusUpdateSerial(0);
743 for row in rows {
744 let row = row?;
745 if row.1 > max_serial {
746 max_serial = row.1;
747 }
748 rows_copy.push(row);
749 }
750
751 let mut json = String::default();
752 for row in rows_copy {
753 let (update_item_str, serial) = row;
754 let update_item = StatusUpdateItemAndSerial
755 {
756 item: StatusUpdateItem {
757 uid: None, ..serde_json::from_str(&update_item_str)?
759 },
760 serial,
761 max_serial,
762 };
763
764 if !json.is_empty() {
765 json.push_str(",\n");
766 }
767 json.push_str(&serde_json::to_string(&update_item)?);
768 }
769 Ok(json)
770 },
771 )
772 .await?;
773 Ok(format!("[{json}]"))
774 }
775
776 pub(crate) async fn render_webxdc_status_update_object(
786 &self,
787 instance_msg_id: MsgId,
788 first: StatusUpdateSerial,
789 last: StatusUpdateSerial,
790 size_max: Option<usize>,
791 ) -> Result<(Option<String>, StatusUpdateSerial)> {
792 let (json, first_new) = self
793 .sql
794 .query_map(
795 "SELECT id, update_item FROM msgs_status_updates \
796 WHERE msg_id=? AND id>=? AND id<=? ORDER BY id",
797 (instance_msg_id, first, last),
798 |row| {
799 let id: StatusUpdateSerial = row.get(0)?;
800 let update_item: String = row.get(1)?;
801 Ok((id, update_item))
802 },
803 |rows| {
804 let mut json = String::default();
805 for row in rows {
806 let (id, update_item) = row?;
807 if !json.is_empty()
808 && json.len() + update_item.len() >= size_max.unwrap_or(usize::MAX)
809 {
810 return Ok((json, id));
811 }
812 if !json.is_empty() {
813 json.push_str(",\n");
814 }
815 json.push_str(&update_item);
816 }
817 Ok((
818 json,
819 StatusUpdateSerial::new(last.to_u32().saturating_add(1)),
822 ))
823 },
824 )
825 .await?;
826 let json = match json.is_empty() {
827 true => None,
828 false => Some(format!(r#"{{"updates":[{json}]}}"#)),
829 };
830 Ok((json, first_new))
831 }
832}
833
834fn parse_webxdc_manifest(bytes: &[u8]) -> Result<WebxdcManifest> {
835 let s = std::str::from_utf8(bytes)?;
836 let manifest: WebxdcManifest = toml::from_str(s)?;
837 Ok(manifest)
838}
839
840async fn get_blob(archive: &mut SeekZipFileReader<BufReader<File>>, name: &str) -> Result<Vec<u8>> {
841 let (i, _) =
842 find_zip_entry(archive.file(), name).ok_or_else(|| anyhow!("no entry found for {name}"))?;
843 let mut reader = archive.reader_with_entry(i).await?;
844 let mut buf = Vec::new();
845 reader.read_to_end_checked(&mut buf).await?;
846 Ok(buf)
847}
848
849impl Message {
850 async fn get_webxdc_archive(
853 &self,
854 context: &Context,
855 ) -> Result<SeekZipFileReader<BufReader<File>>> {
856 let path = self
857 .get_file(context)
858 .ok_or_else(|| format_err!("No webxdc instance file."))?;
859 let path_abs = get_abs_path(context, &path);
860 let file = BufReader::new(File::open(path_abs).await?);
861 let archive = SeekZipFileReader::with_tokio(file).await?;
862 Ok(archive)
863 }
864
865 pub async fn get_webxdc_blob(&self, context: &Context, name: &str) -> Result<Vec<u8>> {
870 ensure!(self.viewtype == Viewtype::Webxdc, "No webxdc instance.");
871
872 if name == WEBXDC_DEFAULT_ICON {
873 return Ok(include_bytes!("../assets/icon-webxdc.png").to_vec());
874 }
875
876 let name = if name.starts_with('/') {
879 name.split_at(1).1
880 } else {
881 name
882 };
883
884 let mut archive = self.get_webxdc_archive(context).await?;
885
886 if name == "index.html"
887 && let Ok(bytes) = get_blob(&mut archive, "manifest.toml").await
888 && let Ok(manifest) = parse_webxdc_manifest(&bytes)
889 && let Some(min_api) = manifest.min_api
890 && min_api > WEBXDC_API_VERSION
891 {
892 return Ok(Vec::from(
893 "<!DOCTYPE html>This Webxdc requires a newer Delta Chat version.",
894 ));
895 }
896
897 get_blob(&mut archive, name).await
898 }
899
900 pub async fn get_webxdc_info(&self, context: &Context) -> Result<WebxdcInfo> {
902 ensure!(self.viewtype == Viewtype::Webxdc, "No webxdc instance.");
903 let mut archive = self.get_webxdc_archive(context).await?;
904
905 let mut manifest = get_blob(&mut archive, "manifest.toml")
906 .await
907 .map(|bytes| parse_webxdc_manifest(&bytes).unwrap_or_default())
908 .unwrap_or_default();
909
910 if let Some(ref name) = manifest.name {
911 let name = name.trim();
912 if name.is_empty() {
913 warn!(context, "empty name given in manifest");
914 manifest.name = None;
915 }
916 }
917
918 let request_integration = manifest.request_integration.unwrap_or_default();
919 let is_integrated = self.is_set_as_webxdc_integration(context).await?;
920 let internet_access = is_integrated;
921
922 let self_addr = self.get_webxdc_self_addr(context).await?;
923
924 Ok(WebxdcInfo {
925 name: if let Some(name) = manifest.name {
926 name
927 } else {
928 self.get_filename().unwrap_or_default()
929 },
930 icon: if find_zip_entry(archive.file(), "icon.png").is_some() {
931 "icon.png".to_string()
932 } else if find_zip_entry(archive.file(), "icon.jpg").is_some() {
933 "icon.jpg".to_string()
934 } else {
935 WEBXDC_DEFAULT_ICON.to_string()
936 },
937 document: self
938 .param
939 .get(Param::WebxdcDocument)
940 .unwrap_or_default()
941 .to_string(),
942 summary: if is_integrated {
943 "🌍 Used as map. Delete to use default. Do not enter sensitive data".to_string()
944 } else if request_integration == "map" {
945 "🌏 To use as map, forward to \"Saved Messages\" again. Do not enter sensitive data"
946 .to_string()
947 } else {
948 self.param
949 .get(Param::WebxdcSummary)
950 .unwrap_or_default()
951 .to_string()
952 },
953 source_code_url: if let Some(url) = manifest.source_code_url {
954 url
955 } else {
956 "".to_string()
957 },
958 request_integration,
959 internet_access,
960 self_addr,
961 send_update_interval: context.ratelimit.read().await.update_interval(),
962 send_update_max_size: RECOMMENDED_FILE_SIZE as usize,
963 })
964 }
965
966 async fn get_webxdc_self_addr(&self, context: &Context) -> Result<String> {
967 let fingerprint = self_fingerprint(context).await?;
968 let data = format!("{}-{}", fingerprint, self.rfc724_mid);
969 let hash = Sha256::digest(data.as_bytes());
970 Ok(format!("{hash:x}"))
971 }
972
973 pub fn get_webxdc_href(&self) -> Option<String> {
979 self.param.get(Param::Arg).map(|href| href.to_string())
980 }
981}
982
983#[cfg(test)]
984mod webxdc_tests;