deltachat/
webxdc.rs

1//! # Handle webxdc messages.
2//!
3//! Internally status updates are stored in the `msgs_status_updates` SQL table.
4//! `msgs_status_updates` contains the following columns:
5//! - `id` - status update serial number
6//! - `msg_id` - ID of the message in the `msgs` table
7//! - `update_item` - JSON representation of the status update
8//! - `uid` - "id" field of the update, used for deduplication
9//!
10//! Status updates are scheduled for sending by adding a record
11//! to `smtp_status_updates_table` SQL table.
12//! `smtp_status_updates` contains the following columns:
13//! - `msg_id` - ID of the message in the `msgs` table
14//! - `first_serial` - serial number of the first status update to send
15//! - `last_serial` - serial number of the last status update to send
16//! - `descr` - not used, set to empty string
17
18mod 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
51/// The current API version.
52/// If `min_api` in manifest.toml is set to a larger value,
53/// the Webxdc's index.html is replaced by an error message.
54/// In the future, that may be useful to avoid new Webxdc being loaded on old Delta Chats.
55const WEBXDC_API_VERSION: u32 = 1;
56
57/// Suffix used to recognize webxdc files.
58pub const WEBXDC_SUFFIX: &str = "xdc";
59const WEBXDC_DEFAULT_ICON: &str = "__webxdc__/default-icon.png";
60
61/// Text shown to classic e-mail users in the visible e-mail body.
62const BODY_DESCR: &str = "Webxdc Status Update";
63
64/// Raw information read from manifest.toml
65#[derive(Debug, Deserialize, Default)]
66#[non_exhaustive]
67pub struct WebxdcManifest {
68    /// Webxdc name, used on icons or page titles.
69    pub name: Option<String>,
70
71    /// Minimum API version required to run this webxdc.
72    pub min_api: Option<u32>,
73
74    /// Optional URL of webxdc source code.
75    pub source_code_url: Option<String>,
76
77    /// Set to "map" to request integration.
78    pub request_integration: Option<String>,
79}
80
81/// Parsed information from WebxdcManifest and fallbacks.
82#[derive(Debug, Serialize)]
83pub struct WebxdcInfo {
84    /// The name of the app.
85    /// Defaults to filename if not set in the manifest.
86    pub name: String,
87
88    /// Filename of the app icon.
89    pub icon: String,
90
91    /// If the webxdc represents a document and allows to edit it,
92    /// this is the document name.
93    /// Otherwise an empty string.
94    pub document: String,
95
96    /// Short description of the webxdc state.
97    /// For example, "7 votes".
98    pub summary: String,
99
100    /// URL of webxdc source code or an empty string.
101    pub source_code_url: String,
102
103    /// Set to "map" to request integration, otherwise an empty string.
104    pub request_integration: String,
105
106    /// If the webxdc is allowed to access the network.
107    /// It should request access, be encrypted
108    /// and sent to self for this.
109    pub internet_access: bool,
110
111    /// Address to be used for `window.webxdc.selfAddr` in JS land.
112    pub self_addr: String,
113
114    /// Milliseconds to wait before calling `sendUpdate()` again since the last call.
115    /// Should be exposed to `window.sendUpdateInterval` in JS land.
116    pub send_update_interval: usize,
117
118    /// Maximum number of bytes accepted for a serialized update object.
119    /// Should be exposed to `window.sendUpdateMaxSize` in JS land.
120    pub send_update_max_size: usize,
121}
122
123/// Status Update ID.
124#[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    /// Create a new [StatusUpdateSerial].
143    pub fn new(id: u32) -> StatusUpdateSerial {
144        StatusUpdateSerial(id)
145    }
146
147    /// Minimum value.
148    pub const MIN: Self = Self(1);
149    /// Maximum value.
150    pub const MAX: Self = Self(u32::MAX - 1);
151
152    /// Gets StatusUpdateSerial as untyped integer.
153    /// Avoid using this outside ffi.
154    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// Array of update items as sent on the wire.
168#[derive(Debug, Deserialize)]
169struct StatusUpdates {
170    updates: Vec<StatusUpdateItem>,
171}
172
173/// Update items as sent on the wire and as stored in the database.
174#[derive(Debug, Serialize, Deserialize, Default)]
175pub struct StatusUpdateItem {
176    /// The playload of the status update.
177    pub payload: Value,
178
179    /// Optional short info message that will be displayed in the chat.
180    /// For example "Alice added an item" or "Bob voted for option x".
181    #[serde(skip_serializing_if = "Option::is_none")]
182    pub info: Option<String>,
183
184    /// Optional link the info message will point to.
185    /// Used to set `window.location.href` in JS land.
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub href: Option<String>,
188
189    /// The new name of the editing document.
190    /// This is not needed if the webxdc doesn't edit documents.
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub document: Option<String>,
193
194    /// Optional summary of the status update which will be shown next to the
195    /// app icon. This should be short and can be something like "8 votes"
196    /// for a voting app.
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub summary: Option<String>,
199
200    /// Unique ID for deduplication.
201    /// This can be used if the message is sent over multiple transports.
202    ///
203    /// If there is no ID, message is always considered to be unique.
204    #[serde(skip_serializing_if = "Option::is_none")]
205    pub uid: Option<String>,
206
207    /// Array of other users `selfAddr` that should be notified about this update.
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub notify: Option<HashMap<String, String>>,
210}
211
212/// Update items as passed to the UIs.
213#[derive(Debug, Serialize, Deserialize)]
214pub(crate) struct StatusUpdateItemAndSerial {
215    #[serde(flatten)]
216    item: StatusUpdateItem,
217
218    serial: StatusUpdateSerial,
219    max_serial: StatusUpdateSerial,
220}
221
222/// Returns an entry index and a reference.
223fn 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
235/// Status update JSON size soft limit.
236const STATUS_UPDATE_SIZE_MAX: usize = 100 << 10;
237
238impl Context {
239    /// check if a file is an acceptable webxdc for sending or receiving.
240    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    /// Ensure that a file is an acceptable webxdc for sending.
262    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    /// Check if the last message of a chat is an info message belonging to the given instance and sender.
289    /// If so, the id of this message is returned.
290    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    /// Takes an update-json as `{payload: PAYLOAD}`
322    /// writes it to the database and handles events, info-messages, document name and summary.
323    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    /// Inserts a status update item into `msgs_status_updates` table.
430    ///
431    /// Returns serial ID of the status update if a new item is inserted.
432    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    /// Returns the update_item with `status_update_serial` from the webxdc with message id `msg_id`.
469    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    /// Sends a status update for an webxdc instance.
484    ///
485    /// If the instance is a draft,
486    /// the status update is sent once the instance is actually sent.
487    /// Otherwise, the update is sent as soon as possible.
488    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    /// Sends a status update for an webxdc instance.
501    /// Also see [Self::send_webxdc_status_update]
502    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    /// Returns one record of the queued webxdc status updates.
566    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    /// Attempts to send queued webxdc status updates.
613    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); // may be set by set_quote(), if #2985 is done, this line can be removed
642                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    /// Receives status updates from receive_imf to the database
654    /// and sends out an event.
655    ///
656    /// `instance` is a webxdc instance.
657    ///
658    /// `from_id` is the sender.
659    ///
660    /// `timestamp` is the timestamp of the update.
661    ///
662    /// `json` is an array containing one or more update items as created by send_webxdc_status_update(),
663    /// the array is parsed using serde, the single payloads are used as is.
664    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    /// Returns status updates as an JSON-array, ready to be consumed by a webxdc.
703    ///
704    /// Example: `[{"serial":1, "max_serial":3, "payload":"any update data"},
705    ///            {"serial":3, "max_serial":3, "payload":"another update data"}]`
706    /// Updates with serials larger than `last_known_serial` are returned.
707    /// If no last serial is known, set `last_known_serial` to 0.
708    /// If no updates are available, an empty JSON-array is returned.
709    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(); // `rows_copy` needed as `rows` cannot be iterated twice.
734                    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, // Erase UIDs, apps, bots and tests don't need to know them.
750                                ..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    /// Renders JSON-object for status updates as used on the wire.
769    ///
770    /// Returns optional JSON and the first serial of updates not included due to a JSON size
771    /// limit. If all requested updates are included, returns the first not requested serial.
772    ///
773    /// Example JSON: `{"updates": [{"payload":"any update data"},
774    ///                             {"payload":"another update data"}]}`
775    ///
776    /// * `(first, last)`: range of status update serials to send.
777    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                        // Too late to fail here if an overflow happens. It's still better to send
812                        // the updates.
813                        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    /// Get handle to a webxdc ZIP-archive.
843    /// To check for file existence use archive.by_name(), to read a file, use get_blob(archive).
844    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    /// Return file from inside an archive.
858    /// Currently, this works only if the message is an webxdc instance.
859    ///
860    /// `name` is the filename within the archive, e.g. `index.html`.
861    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        // ignore first slash.
869        // this way, files can be accessed absolutely (`/index.html`) as well as relatively (`index.html`)
870        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    /// Return info from manifest.toml or from fallbacks.
893    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    /// Get link attached to an info message.
966    ///
967    /// The info message needs to be of type SystemMessage::WebxdcInfoMessage.
968    /// Typically, this is used to start the corresponding webxdc app
969    /// with `window.location.href` set in JS land.
970    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;