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::{anyhow, bail, ensure, format_err, Context as _, Result};
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::{load_self_public_key, DcKey};
43use crate::message::{Message, MessageState, MsgId, Viewtype};
44use crate::mimefactory::RECOMMENDED_FILE_SIZE;
45use crate::mimeparser::SystemMessage;
46use crate::param::Param;
47use crate::param::Params;
48use crate::tools::create_id;
49use crate::tools::{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!("{} is not a valid webxdc file", filename);
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        {
313            if last_from_id == from_id
314                && last_param.get_cmd() == SystemMessage::WebxdcInfoMessage
315                && last_in_repl_to == instance.rfc724_mid
316            {
317                return Ok(Some(last_msg_id));
318            }
319        }
320        Ok(None)
321    }
322
323    /// Takes an update-json as `{payload: PAYLOAD}`
324    /// writes it to the database and handles events, info-messages, document name and summary.
325    async fn create_status_update_record(
326        &self,
327        instance: &Message,
328        status_update_item: StatusUpdateItem,
329        timestamp: i64,
330        can_info_msg: bool,
331        from_id: ContactId,
332    ) -> Result<Option<StatusUpdateSerial>> {
333        let Some(status_update_serial) = self
334            .write_status_update_inner(&instance.id, &status_update_item, timestamp)
335            .await?
336        else {
337            return Ok(None);
338        };
339
340        let mut notify_msg_id = instance.id;
341        let mut param_changed = false;
342
343        let mut instance = instance.clone();
344        if let Some(ref document) = status_update_item.document {
345            if instance
346                .param
347                .update_timestamp(Param::WebxdcDocumentTimestamp, timestamp)?
348            {
349                instance.param.set(Param::WebxdcDocument, document);
350                param_changed = true;
351            }
352        }
353
354        if let Some(ref summary) = status_update_item.summary {
355            if instance
356                .param
357                .update_timestamp(Param::WebxdcSummaryTimestamp, timestamp)?
358            {
359                let summary = sanitize_bidi_characters(summary);
360                instance.param.set(Param::WebxdcSummary, summary.clone());
361                param_changed = true;
362            }
363        }
364
365        if can_info_msg {
366            if let Some(ref info) = status_update_item.info {
367                let info_msg_id = self
368                    .get_overwritable_info_msg_id(&instance, from_id)
369                    .await?;
370
371                if let (Some(info_msg_id), None) = (info_msg_id, &status_update_item.href) {
372                    chat::update_msg_text_and_timestamp(
373                        self,
374                        instance.chat_id,
375                        info_msg_id,
376                        info.as_str(),
377                        timestamp,
378                    )
379                    .await?;
380                    notify_msg_id = info_msg_id;
381                } else {
382                    notify_msg_id = chat::add_info_msg_with_cmd(
383                        self,
384                        instance.chat_id,
385                        info.as_str(),
386                        SystemMessage::WebxdcInfoMessage,
387                        timestamp,
388                        None,
389                        Some(&instance),
390                        Some(from_id),
391                        None,
392                    )
393                    .await?;
394                }
395
396                if let Some(ref href) = status_update_item.href {
397                    let mut notify_msg = Message::load_from_db(self, notify_msg_id).await?;
398                    notify_msg.param.set(Param::Arg, href);
399                    notify_msg.update_param(self).await?;
400                }
401            }
402        }
403
404        if param_changed {
405            instance.update_param(self).await?;
406            self.emit_msgs_changed(instance.chat_id, instance.id);
407        }
408
409        if instance.viewtype == Viewtype::Webxdc {
410            self.emit_event(EventType::WebxdcStatusUpdate {
411                msg_id: instance.id,
412                status_update_serial,
413            });
414        }
415
416        if from_id != ContactId::SELF {
417            if let Some(notify_list) = status_update_item.notify {
418                let self_addr = instance.get_webxdc_self_addr(self).await?;
419                if let Some(notify_text) =
420                    notify_list.get(&self_addr).or_else(|| notify_list.get("*"))
421                {
422                    self.emit_event(EventType::IncomingWebxdcNotify {
423                        chat_id: instance.chat_id,
424                        contact_id: from_id,
425                        msg_id: notify_msg_id,
426                        text: notify_text.clone(),
427                        href: status_update_item.href,
428                    });
429                }
430            }
431        }
432
433        Ok(Some(status_update_serial))
434    }
435
436    /// Inserts a status update item into `msgs_status_updates` table.
437    ///
438    /// Returns serial ID of the status update if a new item is inserted.
439    pub(crate) async fn write_status_update_inner(
440        &self,
441        instance_id: &MsgId,
442        status_update_item: &StatusUpdateItem,
443        timestamp: i64,
444    ) -> Result<Option<StatusUpdateSerial>> {
445        let uid = status_update_item.uid.as_deref();
446        let status_update_item = serde_json::to_string(&status_update_item)?;
447        let trans_fn = |t: &mut rusqlite::Transaction| {
448            t.execute(
449                "UPDATE msgs SET timestamp_rcvd=? WHERE id=?",
450                (timestamp, instance_id),
451            )?;
452            let rowid = t
453                .query_row(
454                    "INSERT INTO msgs_status_updates (msg_id, update_item, uid) VALUES(?, ?, ?)
455                     ON CONFLICT (uid) DO NOTHING
456                     RETURNING id",
457                    (instance_id, status_update_item, uid),
458                    |row| {
459                        let id: u32 = row.get(0)?;
460                        Ok(id)
461                    },
462                )
463                .optional()?;
464            Ok(rowid)
465        };
466        let Some(rowid) = self.sql.transaction(trans_fn).await? else {
467            let uid = uid.unwrap_or("-");
468            info!(self, "Ignoring duplicate status update with uid={uid}");
469            return Ok(None);
470        };
471        let status_update_serial = StatusUpdateSerial(rowid);
472        Ok(Some(status_update_serial))
473    }
474
475    /// Returns the update_item with `status_update_serial` from the webxdc with message id `msg_id`.
476    pub async fn get_status_update(
477        &self,
478        msg_id: MsgId,
479        status_update_serial: StatusUpdateSerial,
480    ) -> Result<String> {
481        self.sql
482            .query_get_value(
483                "SELECT update_item FROM msgs_status_updates WHERE id=? AND msg_id=? ",
484                (status_update_serial.0, msg_id),
485            )
486            .await?
487            .context("get_status_update: no update item found.")
488    }
489
490    /// Sends a status update for an webxdc instance.
491    ///
492    /// If the instance is a draft,
493    /// the status update is sent once the instance is actually sent.
494    /// Otherwise, the update is sent as soon as possible.
495    pub async fn send_webxdc_status_update(
496        &self,
497        instance_msg_id: MsgId,
498        update_str: &str,
499    ) -> Result<()> {
500        let status_update_item: StatusUpdateItem = serde_json::from_str(update_str)
501            .with_context(|| format!("Failed to parse webxdc update item from {update_str:?}"))?;
502        self.send_webxdc_status_update_struct(instance_msg_id, status_update_item)
503            .await?;
504        Ok(())
505    }
506
507    /// Sends a status update for an webxdc instance.
508    /// Also see [Self::send_webxdc_status_update]
509    pub async fn send_webxdc_status_update_struct(
510        &self,
511        instance_msg_id: MsgId,
512        mut status_update: StatusUpdateItem,
513    ) -> Result<()> {
514        let instance = Message::load_from_db(self, instance_msg_id)
515            .await
516            .with_context(|| {
517                format!("Failed to load message {instance_msg_id} from the database")
518            })?;
519        let viewtype = instance.viewtype;
520        if viewtype != Viewtype::Webxdc {
521            bail!("send_webxdc_status_update: message {instance_msg_id} is not a webxdc message, but a {viewtype} message.");
522        }
523
524        if instance.param.get_int(Param::WebxdcIntegration).is_some() {
525            return self
526                .intercept_send_webxdc_status_update(instance, status_update)
527                .await;
528        }
529
530        let chat_id = instance.chat_id;
531        let chat = Chat::load_from_db(self, chat_id)
532            .await
533            .with_context(|| format!("Failed to load chat {chat_id} from the database"))?;
534        if let Some(reason) = chat.why_cant_send(self).await.with_context(|| {
535            format!("Failed to check if webxdc update can be sent to chat {chat_id}")
536        })? {
537            bail!("Cannot send to {chat_id}: {reason}.");
538        }
539
540        let send_now = !matches!(
541            instance.state,
542            MessageState::Undefined | MessageState::OutPreparing | MessageState::OutDraft
543        );
544
545        status_update.uid = Some(create_id());
546        let status_update_serial: StatusUpdateSerial = self
547            .create_status_update_record(
548                &instance,
549                status_update,
550                create_smeared_timestamp(self),
551                send_now,
552                ContactId::SELF,
553            )
554            .await
555            .context("Failed to create status update")?
556            .context("Duplicate status update UID was generated")?;
557
558        if send_now {
559            self.sql.insert(
560                "INSERT INTO smtp_status_updates (msg_id, first_serial, last_serial, descr) VALUES(?, ?, ?, '')
561                 ON CONFLICT(msg_id)
562                 DO UPDATE SET last_serial=excluded.last_serial",
563                (instance.id, status_update_serial, status_update_serial),
564            ).await.context("Failed to insert webxdc update into SMTP queue")?;
565            self.scheduler.interrupt_smtp().await;
566        }
567        Ok(())
568    }
569
570    /// Returns one record of the queued webxdc status updates.
571    async fn smtp_status_update_get(&self) -> Result<Option<(MsgId, i64, StatusUpdateSerial)>> {
572        let res = self
573            .sql
574            .query_row_optional(
575                "SELECT msg_id, first_serial, last_serial \
576                 FROM smtp_status_updates LIMIT 1",
577                (),
578                |row| {
579                    let instance_id: MsgId = row.get(0)?;
580                    let first_serial: i64 = row.get(1)?;
581                    let last_serial: StatusUpdateSerial = row.get(2)?;
582                    Ok((instance_id, first_serial, last_serial))
583                },
584            )
585            .await?;
586        Ok(res)
587    }
588
589    async fn smtp_status_update_pop_serials(
590        &self,
591        msg_id: MsgId,
592        first: i64,
593        first_new: StatusUpdateSerial,
594    ) -> Result<()> {
595        if self
596            .sql
597            .execute(
598                "DELETE FROM smtp_status_updates \
599                 WHERE msg_id=? AND first_serial=? AND last_serial<?",
600                (msg_id, first, first_new),
601            )
602            .await?
603            > 0
604        {
605            return Ok(());
606        }
607        self.sql
608            .execute(
609                "UPDATE smtp_status_updates SET first_serial=? \
610                 WHERE msg_id=? AND first_serial=?",
611                (first_new, msg_id, first),
612            )
613            .await?;
614        Ok(())
615    }
616
617    /// Attempts to send queued webxdc status updates.
618    pub(crate) async fn flush_status_updates(&self) -> Result<()> {
619        loop {
620            let (instance_id, first, last) = match self.smtp_status_update_get().await? {
621                Some(res) => res,
622                None => return Ok(()),
623            };
624            let (json, first_new) = self
625                .render_webxdc_status_update_object(
626                    instance_id,
627                    StatusUpdateSerial(max(first, 1).try_into()?),
628                    last,
629                    Some(STATUS_UPDATE_SIZE_MAX),
630                )
631                .await?;
632            if let Some(json) = json {
633                let instance = Message::load_from_db(self, instance_id).await?;
634                let mut status_update = Message {
635                    chat_id: instance.chat_id,
636                    viewtype: Viewtype::Text,
637                    text: BODY_DESCR.to_string(),
638                    hidden: true,
639                    ..Default::default()
640                };
641                status_update
642                    .param
643                    .set_cmd(SystemMessage::WebxdcStatusUpdate);
644                status_update.param.set(Param::Arg, json);
645                status_update.set_quote(self, Some(&instance)).await?;
646                status_update.param.remove(Param::GuaranteeE2ee); // may be set by set_quote(), if #2985 is done, this line can be removed
647                chat::send_msg(self, instance.chat_id, &mut status_update).await?;
648            }
649            self.smtp_status_update_pop_serials(instance_id, first, first_new)
650                .await?;
651        }
652    }
653
654    pub(crate) fn build_status_update_part(&self, json: &str) -> MimePart<'static> {
655        MimePart::new("application/json", json.as_bytes().to_vec()).attachment("status-update.json")
656    }
657
658    /// Receives status updates from receive_imf to the database
659    /// and sends out an event.
660    ///
661    /// `instance` is a webxdc instance.
662    ///
663    /// `from_id` is the sender.
664    ///
665    /// `timestamp` is the timestamp of the update.
666    ///
667    /// `json` is an array containing one or more update items as created by send_webxdc_status_update(),
668    /// the array is parsed using serde, the single payloads are used as is.
669    pub(crate) async fn receive_status_update(
670        &self,
671        from_id: ContactId,
672        instance: &Message,
673        timestamp: i64,
674        can_info_msg: bool,
675        json: &str,
676    ) -> Result<()> {
677        let chat_id = instance.chat_id;
678
679        if from_id != ContactId::SELF && !chat::is_contact_in_chat(self, chat_id, from_id).await? {
680            let chat_type: Chattype = self
681                .sql
682                .query_get_value("SELECT type FROM chats WHERE id=?", (chat_id,))
683                .await?
684                .with_context(|| format!("Chat type for chat {chat_id} not found"))?;
685            if chat_type != Chattype::Mailinglist {
686                bail!("receive_status_update: status sender {from_id} is not a member of chat {chat_id}")
687            }
688        }
689
690        let updates: StatusUpdates = serde_json::from_str(json)?;
691        for update_item in updates.updates {
692            self.create_status_update_record(
693                instance,
694                update_item,
695                timestamp,
696                can_info_msg,
697                from_id,
698            )
699            .await?;
700        }
701
702        Ok(())
703    }
704
705    /// Returns status updates as an JSON-array, ready to be consumed by a webxdc.
706    ///
707    /// Example: `[{"serial":1, "max_serial":3, "payload":"any update data"},
708    ///            {"serial":3, "max_serial":3, "payload":"another update data"}]`
709    /// Updates with serials larger than `last_known_serial` are returned.
710    /// If no last serial is known, set `last_known_serial` to 0.
711    /// If no updates are available, an empty JSON-array is returned.
712    pub async fn get_webxdc_status_updates(
713        &self,
714        instance_msg_id: MsgId,
715        last_known_serial: StatusUpdateSerial,
716    ) -> Result<String> {
717        let param = instance_msg_id.get_param(self).await?;
718        if param.get_int(Param::WebxdcIntegration).is_some() {
719            let instance = Message::load_from_db(self, instance_msg_id).await?;
720            return self
721                .intercept_get_webxdc_status_updates(instance, last_known_serial)
722                .await;
723        }
724
725        let json = self
726            .sql
727            .query_map(
728                "SELECT update_item, id FROM msgs_status_updates WHERE msg_id=? AND id>? ORDER BY id",
729                (instance_msg_id, last_known_serial),
730                |row| {
731                    let update_item_str = row.get::<_, String>(0)?;
732                    let serial = row.get::<_, StatusUpdateSerial>(1)?;
733                    Ok((update_item_str, serial))
734                },
735                |rows| {
736                    let mut rows_copy : Vec<(String, StatusUpdateSerial)> = Vec::new(); // `rows_copy` needed as `rows` cannot be iterated twice.
737                    let mut max_serial = StatusUpdateSerial(0);
738                    for row in rows {
739                        let row = row?;
740                        if row.1 > max_serial {
741                            max_serial = row.1;
742                        }
743                        rows_copy.push(row);
744                    }
745
746                    let mut json = String::default();
747                    for row in rows_copy {
748                        let (update_item_str, serial) = row;
749                        let update_item = StatusUpdateItemAndSerial
750                        {
751                            item: StatusUpdateItem {
752                                uid: None, // Erase UIDs, apps, bots and tests don't need to know them.
753                                ..serde_json::from_str(&update_item_str)?
754                            },
755                            serial,
756                            max_serial,
757                        };
758
759                        if !json.is_empty() {
760                            json.push_str(",\n");
761                        }
762                        json.push_str(&serde_json::to_string(&update_item)?);
763                    }
764                    Ok(json)
765                },
766            )
767            .await?;
768        Ok(format!("[{json}]"))
769    }
770
771    /// Renders JSON-object for status updates as used on the wire.
772    ///
773    /// Returns optional JSON and the first serial of updates not included due to a JSON size
774    /// limit. If all requested updates are included, returns the first not requested serial.
775    ///
776    /// Example JSON: `{"updates": [{"payload":"any update data"},
777    ///                             {"payload":"another update data"}]}`
778    ///
779    /// * `(first, last)`: range of status update serials to send.
780    pub(crate) async fn render_webxdc_status_update_object(
781        &self,
782        instance_msg_id: MsgId,
783        first: StatusUpdateSerial,
784        last: StatusUpdateSerial,
785        size_max: Option<usize>,
786    ) -> Result<(Option<String>, StatusUpdateSerial)> {
787        let (json, first_new) = self
788            .sql
789            .query_map(
790                "SELECT id, update_item FROM msgs_status_updates \
791                 WHERE msg_id=? AND id>=? AND id<=? ORDER BY id",
792                (instance_msg_id, first, last),
793                |row| {
794                    let id: StatusUpdateSerial = row.get(0)?;
795                    let update_item: String = row.get(1)?;
796                    Ok((id, update_item))
797                },
798                |rows| {
799                    let mut json = String::default();
800                    for row in rows {
801                        let (id, update_item) = row?;
802                        if !json.is_empty()
803                            && json.len() + update_item.len() >= size_max.unwrap_or(usize::MAX)
804                        {
805                            return Ok((json, id));
806                        }
807                        if !json.is_empty() {
808                            json.push_str(",\n");
809                        }
810                        json.push_str(&update_item);
811                    }
812                    Ok((
813                        json,
814                        // Too late to fail here if an overflow happens. It's still better to send
815                        // the updates.
816                        StatusUpdateSerial::new(last.to_u32().saturating_add(1)),
817                    ))
818                },
819            )
820            .await?;
821        let json = match json.is_empty() {
822            true => None,
823            false => Some(format!(r#"{{"updates":[{json}]}}"#)),
824        };
825        Ok((json, first_new))
826    }
827}
828
829fn parse_webxdc_manifest(bytes: &[u8]) -> Result<WebxdcManifest> {
830    let s = std::str::from_utf8(bytes)?;
831    let manifest: WebxdcManifest = toml::from_str(s)?;
832    Ok(manifest)
833}
834
835async fn get_blob(archive: &mut SeekZipFileReader<BufReader<File>>, name: &str) -> Result<Vec<u8>> {
836    let (i, _) = find_zip_entry(archive.file(), name)
837        .ok_or_else(|| anyhow!("no entry found for {}", name))?;
838    let mut reader = archive.reader_with_entry(i).await?;
839    let mut buf = Vec::new();
840    reader.read_to_end_checked(&mut buf).await?;
841    Ok(buf)
842}
843
844impl Message {
845    /// Get handle to a webxdc ZIP-archive.
846    /// To check for file existence use archive.by_name(), to read a file, use get_blob(archive).
847    async fn get_webxdc_archive(
848        &self,
849        context: &Context,
850    ) -> Result<SeekZipFileReader<BufReader<File>>> {
851        let path = self
852            .get_file(context)
853            .ok_or_else(|| format_err!("No webxdc instance file."))?;
854        let path_abs = get_abs_path(context, &path);
855        let file = BufReader::new(File::open(path_abs).await?);
856        let archive = SeekZipFileReader::with_tokio(file).await?;
857        Ok(archive)
858    }
859
860    /// Return file from inside an archive.
861    /// Currently, this works only if the message is an webxdc instance.
862    ///
863    /// `name` is the filename within the archive, e.g. `index.html`.
864    pub async fn get_webxdc_blob(&self, context: &Context, name: &str) -> Result<Vec<u8>> {
865        ensure!(self.viewtype == Viewtype::Webxdc, "No webxdc instance.");
866
867        if name == WEBXDC_DEFAULT_ICON {
868            return Ok(include_bytes!("../assets/icon-webxdc.png").to_vec());
869        }
870
871        // ignore first slash.
872        // this way, files can be accessed absolutely (`/index.html`) as well as relatively (`index.html`)
873        let name = if name.starts_with('/') {
874            name.split_at(1).1
875        } else {
876            name
877        };
878
879        let mut archive = self.get_webxdc_archive(context).await?;
880
881        if name == "index.html" {
882            if let Ok(bytes) = get_blob(&mut archive, "manifest.toml").await {
883                if let Ok(manifest) = parse_webxdc_manifest(&bytes) {
884                    if let Some(min_api) = manifest.min_api {
885                        if min_api > WEBXDC_API_VERSION {
886                            return Ok(Vec::from(
887                                "<!DOCTYPE html>This Webxdc requires a newer Delta Chat version.",
888                            ));
889                        }
890                    }
891                }
892            }
893        }
894
895        get_blob(&mut archive, name).await
896    }
897
898    /// Return info from manifest.toml or from fallbacks.
899    pub async fn get_webxdc_info(&self, context: &Context) -> Result<WebxdcInfo> {
900        ensure!(self.viewtype == Viewtype::Webxdc, "No webxdc instance.");
901        let mut archive = self.get_webxdc_archive(context).await?;
902
903        let mut manifest = get_blob(&mut archive, "manifest.toml")
904            .await
905            .map(|bytes| parse_webxdc_manifest(&bytes).unwrap_or_default())
906            .unwrap_or_default();
907
908        if let Some(ref name) = manifest.name {
909            let name = name.trim();
910            if name.is_empty() {
911                warn!(context, "empty name given in manifest");
912                manifest.name = None;
913            }
914        }
915
916        let request_integration = manifest.request_integration.unwrap_or_default();
917        let is_integrated = self.is_set_as_webxdc_integration(context).await?;
918        let internet_access = is_integrated;
919
920        let self_addr = self.get_webxdc_self_addr(context).await?;
921
922        Ok(WebxdcInfo {
923            name: if let Some(name) = manifest.name {
924                name
925            } else {
926                self.get_filename().unwrap_or_default()
927            },
928            icon: if find_zip_entry(archive.file(), "icon.png").is_some() {
929                "icon.png".to_string()
930            } else if find_zip_entry(archive.file(), "icon.jpg").is_some() {
931                "icon.jpg".to_string()
932            } else {
933                WEBXDC_DEFAULT_ICON.to_string()
934            },
935            document: self
936                .param
937                .get(Param::WebxdcDocument)
938                .unwrap_or_default()
939                .to_string(),
940            summary: if is_integrated {
941                "🌍 Used as map. Delete to use default. Do not enter sensitive data".to_string()
942            } else if request_integration == "map" {
943                "🌏 To use as map, forward to \"Saved Messages\" again. Do not enter sensitive data"
944                    .to_string()
945            } else {
946                self.param
947                    .get(Param::WebxdcSummary)
948                    .unwrap_or_default()
949                    .to_string()
950            },
951            source_code_url: if let Some(url) = manifest.source_code_url {
952                url
953            } else {
954                "".to_string()
955            },
956            request_integration,
957            internet_access,
958            self_addr,
959            send_update_interval: context.ratelimit.read().await.update_interval(),
960            send_update_max_size: RECOMMENDED_FILE_SIZE as usize,
961        })
962    }
963
964    async fn get_webxdc_self_addr(&self, context: &Context) -> Result<String> {
965        let fingerprint = load_self_public_key(context).await?.dc_fingerprint().hex();
966        let data = format!("{}-{}", fingerprint, self.rfc724_mid);
967        let hash = Sha256::digest(data.as_bytes());
968        Ok(format!("{:x}", hash))
969    }
970
971    /// Get link attached to an info message.
972    ///
973    /// The info message needs to be of type SystemMessage::WebxdcInfoMessage.
974    /// Typically, this is used to start the corresponding webxdc app
975    /// with `window.location.href` set in JS land.
976    pub fn get_webxdc_href(&self) -> Option<String> {
977        self.param.get(Param::Arg).map(|href| href.to_string())
978    }
979}
980
981#[cfg(test)]
982mod webxdc_tests;