summaryrefslogtreecommitdiffstats
path: root/comm/chat/protocols/matrix/matrixMessageContent.sys.mjs
blob: 27e0ff6680ed22138d4f0aebb06bc92307f4c0ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
import { l10nHelper } from "resource:///modules/imXPCOMUtils.sys.mjs";
import { MatrixSDK } from "resource:///modules/matrix-sdk.sys.mjs";

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  getMatrixTextForEvent: "resource:///modules/matrixTextForEvent.sys.mjs",
});
XPCOMUtils.defineLazyGetter(lazy, "domParser", () => new DOMParser());
XPCOMUtils.defineLazyGetter(lazy, "TXTToHTML", function () {
  let cs = Cc["@mozilla.org/txttohtmlconv;1"].getService(Ci.mozITXTToHTMLConv);
  return aTxt => cs.scanTXT(aTxt, cs.kEntities);
});
XPCOMUtils.defineLazyGetter(lazy, "_", () =>
  l10nHelper("chrome://chat/locale/matrix.properties")
);

const kRichBodiedTypes = [
  MatrixSDK.MsgType.Text,
  MatrixSDK.MsgType.Notice,
  MatrixSDK.MsgType.Emote,
];
const kHtmlFormat = "org.matrix.custom.html";
const kAttachmentTypes = [
  MatrixSDK.MsgType.Image,
  MatrixSDK.MsgType.File,
  MatrixSDK.MsgType.Audio,
  MatrixSDK.MsgType.Video,
];

/**
 * Gets the user-consumable URI to an attachment from an mxc URI and
 * potentially encrypted file.
 *
 * @param {IContent} content - Event content to get the attachment URL from.
 * @param {string} homeserverUrl - Homeserver URL to load the attachment from.
 * @returns {string} https or data URI to the attachment file.
 */
function getAttachmentUrl(content, homeserverUrl) {
  if (content.file?.v == "v2") {
    return MatrixSDK.getHttpUriForMxc(homeserverUrl, content.file.url);
    //TODO Actually handle encrypted file contents.
  }
  if (!content.url.startsWith("mxc:")) {
    // Ignore content not served by the homeserver's media repo
    return "";
  }
  return MatrixSDK.getHttpUriForMxc(homeserverUrl, content.url);
}

/**
 * Turn an attachment event into a link to the attached file.
 *
 * @param {IContent} content - The event contents.
 * @param {string} homeserverUrl - The base URL of the homeserver.
 * @returns {string} HTML string to link to the attachment.
 */
function formatMediaAttachment(content, homeserverUrl) {
  const realUrl = getAttachmentUrl(content, homeserverUrl);
  if (!realUrl) {
    return content.body;
  }
  return `<a href="${realUrl}">${content.body}</a>`;
}

/**
 * Format a user ID so it always gets a user tooltip.
 *
 * @param {string} userId - User ID to mention.
 * @param {DOMDocument} doc - DOM Document the mention will appear in.
 * @returns {HTMLSpanElement} Element to insert for the mention.
 */
function formatMention(userId, doc) {
  const ibPerson = doc.createElement("span");
  ibPerson.classList.add("ib-person");
  ibPerson.textContent = userId;
  return ibPerson;
}

/**
 * Get the raw text content of the reply event.
 *
 * @param {MatrixEvent} replyEvent - Event to quote.
 * @param {string} homeserverUrl - The base URL of the homeserver.
 * @param {string => MatrixEvent} getEvent - Get the event with the given ID.
 *  Used to fetch the replied to event.
 * @param {boolean} rich - When true prefers the HTML representation of the
 *  event body.
 * @returns {string} Formatted text body of the event to quote.
 */
function getReplyContent(replyEvent, homeserverUrl, getEvent, rich) {
  let replyContent =
    (rich &&
      MatrixMessageContent.getIncomingHTML(
        replyEvent,
        homeserverUrl,
        getEvent,
        false
      )) ||
    MatrixMessageContent.getIncomingPlain(
      replyEvent,
      homeserverUrl,
      getEvent,
      false
    );
  if (replyEvent.getContent()?.msgtype === MatrixSDK.MsgType.Emote) {
    replyContent = `* ${replyEvent.getSender()} ${replyContent} *`;
  }
  return replyContent;
}

/**
 * Adapts the plain text body of an event for display.
 *
 * @param {MatrixEvent} event - The event to format the body of.
 * @param {string} homeserverUrl - The base URL of the homeserver.
 * @param {(string) => MatrixEvent} getEvent - Get the event with the given ID.
 * @param {boolean} [includeReply=true] - If the message should contain the message it's replying to.
 * @returns {string} Plain text message for the event.
 */
function formatPlainBody(event, homeserverUrl, getEvent, includeReply = true) {
  const content = event.getContent();
  let body = lazy.TXTToHTML(content.body);
  const eventId = event.replyEventId;
  if (body.startsWith("&gt;") && eventId) {
    let nonQuote = Number.MAX_SAFE_INTEGER;
    const replyEvent = getEvent(eventId);
    if (!includeReply || replyEvent) {
      // Strip the fallback quote
      body = body
        .split("\n")
        .filter((line, index) => {
          const isQuoteLine = line.startsWith("&gt;");
          if (!isQuoteLine && nonQuote > index) {
            nonQuote = index;
          }
          return nonQuote < index || !isQuoteLine;
        })
        .join("\n");
    }
    if (
      includeReply &&
      replyEvent &&
      content.msgtype != MatrixSDK.MsgType.Emote
    ) {
      let replyContent = getReplyContent(
        replyEvent,
        homeserverUrl,
        getEvent,
        false
      );
      const isEmoteReply =
        replyEvent.getContent()?.msgtype == MatrixSDK.MsgType.Emote;
      replyContent = replyContent
        .split("\n")
        .map(line => `&gt; ${line}`)
        .join("\n");
      if (!isEmoteReply) {
        replyContent = `${replyEvent.getSender()}:
${replyContent}`;
      }
      body = replyContent + "\n" + body;
    }
  }
  return body;
}

/**
 * Adapts the formatted body of an event for display.
 *
 * @param {MatrixEvent} event - The event to format the body of.
 * @param {string} homeserverUrl - The base URL of the homeserver.
 * @param {(string) => MatrixEvent} getEvent - Get the event with the given ID.
 *  Used to fetch the replied to event.
 * @param {boolean} [includeReply=true] - If the message should contain the
 *  message it's replying to.
 * @returns {string} Formatted body of the event.
 */
function formatHTMLBody(event, homeserverUrl, getEvent, includeReply = true) {
  const content = event.getContent();
  const parsedBody = lazy.domParser.parseFromString(
    `<!DOCTYPE html><html><body>${content.formatted_body}</body></html>`,
    "text/html"
  );
  const textColors = parsedBody.querySelectorAll(
    "span[data-mx-color], font[data-mx-color]"
  );
  for (const coloredElement of textColors) {
    coloredElement.style.color = `#${coloredElement.dataset.mxColor}`;
    delete coloredElement.dataset.mxColor;
  }
  //TODO background color
  const userMentions = parsedBody.querySelectorAll(
    'a[href^="https://matrix.to/#/@"],a[href^="https://matrix.to/#/%40"]'
  );
  for (const mention of userMentions) {
    let endIndex = mention.hash.indexOf("?");
    if (endIndex == -1) {
      endIndex = undefined;
    }
    const userId = decodeURIComponent(mention.hash.slice(2, endIndex));
    const ibPerson = formatMention(userId, parsedBody);
    mention.replaceWith(ibPerson);
  }
  //TODO handle room mentions but avoid event permalinks
  const inlineImages = parsedBody.querySelectorAll("img");
  for (const image of inlineImages) {
    if (image.alt) {
      if (image.src.startsWith("mxc:")) {
        const link = parsedBody.createElement("a");
        link.href = MatrixSDK.getHttpUriForMxc(homeserverUrl, image.src);
        link.textContent = image.alt;
        if (image.title) {
          link.title = image.title;
        }
        image.replaceWith(link);
      } else {
        image.replaceWith(image.alt);
      }
    }
  }
  const reply = parsedBody.querySelector("mx-reply");
  if (reply) {
    if (includeReply && content.msgtype != MatrixSDK.MsgType.Emote) {
      const eventId = event.replyEventId;
      const replyEvent = getEvent(eventId);
      if (replyEvent) {
        let replyContent = getReplyContent(
          replyEvent,
          homeserverUrl,
          getEvent,
          true
        );
        const isEmoteReply =
          replyEvent.getContent()?.msgtype == MatrixSDK.MsgType.Emote;
        const newReply = parsedBody.createDocumentFragment();
        if (!isEmoteReply) {
          const replyTo = formatMention(replyEvent.getSender(), parsedBody);
          newReply.append(replyTo, ":");
        }
        const quote = parsedBody.createElement("blockquote");
        newReply.append(quote);
        // eslint-disable-next-line no-unsanitized/method
        quote.insertAdjacentHTML("afterbegin", replyContent);
        reply.replaceWith(newReply);
      } else {
        // Strip mx-reply from DOM
        reply.normalize();
        reply.replaceWith(...reply.childNodes);
      }
    } else {
      reply.remove();
    }
  }
  //TODO spoilers
  return parsedBody.body.innerHTML;
}

export var MatrixMessageContent = {
  /**
   * Format the plain text body of an incoming message for display.
   *
   * @param {MatrixEvent} event - Event to format the body of.
   * @param {string} homeserverUrl - The base URL of the homserver used to
   *  resolve mxc URIs.
   * @param {string => MatrixEvent} getEvent - Get the event with the given ID.
   *  Used to fetch the replied to event.
   * @param {boolean} [includeReply=true] - If the message should contain the
   *  message it's replying to.
   * @returns {string} Returns the formatted body ready for display or an empty
   *  string if formatting wasn't possible.
   */
  getIncomingPlain(event, homeserverUrl, getEvent, includeReply = true) {
    if (
      !event ||
      (event.status !== null && event.status !== MatrixSDK.EventStatus.SENT)
    ) {
      return "";
    }
    const type = event.getType();
    const content = event.getContent();
    if (event.isRedacted()) {
      return lazy._("message.redacted");
    }
    const textForEvent = lazy.getMatrixTextForEvent(event);
    if (textForEvent) {
      return textForEvent;
    } else if (
      type == MatrixSDK.EventType.RoomMessage ||
      type == MatrixSDK.EventType.RoomMessageEncrypted
    ) {
      if (kRichBodiedTypes.includes(content?.msgtype)) {
        return formatPlainBody(event, homeserverUrl, getEvent, includeReply);
      } else if (kAttachmentTypes.includes(content?.msgtype)) {
        const attachmentUrl = getAttachmentUrl(content, homeserverUrl);
        if (attachmentUrl) {
          return attachmentUrl;
        }
      } else if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {
        return lazy._("message.decrypting");
      }
    } else if (type == MatrixSDK.EventType.Sticker) {
      const attachmentUrl = getAttachmentUrl(content, homeserverUrl);
      if (attachmentUrl) {
        return attachmentUrl;
      }
    } else if (type == MatrixSDK.EventType.Reaction) {
      let annotatedEvent = getEvent(content["m.relates_to"]?.event_id);
      if (annotatedEvent && content["m.relates_to"]?.key) {
        return lazy._(
          "message.reaction",
          event.getSender(),
          annotatedEvent.getSender(),
          lazy.TXTToHTML(content["m.relates_to"].key)
        );
      }
    }
    return lazy.TXTToHTML(content.body ?? "");
  },
  /**
   * Format the HTML body of an incoming message for display.
   *
   * @param {MatrixEvent} event - Event to format the body of.
   * @param {string} homeserverUrl - The base URL of the homserver used to
   *  resolve mxc URIs.
   * @param {string => MatrixEvent} getEvent - Get the event with the given ID.
   * @param {boolean} [includeReply=true] - If the message should contain the
   *  message it's replying to.
   * @returns {string} Returns a formatted body ready for display or an empty
   *  string if formatting wasn't possible.
   */
  getIncomingHTML(event, homeserverUrl, getEvent, includeReply = true) {
    if (
      !event ||
      (event.status !== null && event.status !== MatrixSDK.EventStatus.SENT)
    ) {
      return "";
    }
    const type = event.getType();
    const content = event.getContent();
    if (event.isRedacted()) {
      return lazy._("message.redacted");
    }
    if (type == MatrixSDK.EventType.RoomMessage) {
      if (
        kRichBodiedTypes.includes(content.msgtype) &&
        content.format == kHtmlFormat &&
        content.formatted_body
      ) {
        return formatHTMLBody(event, homeserverUrl, getEvent, includeReply);
      } else if (kAttachmentTypes.includes(content.msgtype)) {
        return formatMediaAttachment(content, homeserverUrl);
      }
    } else if (type == MatrixSDK.EventType.Sticker) {
      return formatMediaAttachment(content, homeserverUrl);
    } else if (type == MatrixSDK.EventType.Reaction) {
      let annotatedEvent = getEvent(content["m.relates_to"]?.event_id);
      if (annotatedEvent && content["m.relates_to"]?.key) {
        return lazy._(
          "message.reaction",
          `<span class="ib-person">${event.getSender()}</span>`,
          `<span class="ib-person">${annotatedEvent.getSender()}</span>`,
          lazy.TXTToHTML(content["m.relates_to"].key)
        );
      }
    }
    return MatrixMessageContent.getIncomingPlain(
      event,
      homeserverUrl,
      getEvent
    );
  },
};