converse-message-view.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /**
  2. * @module converse-message-view
  3. * @copyright 2020, the Converse.js contributors
  4. * @license Mozilla Public License (MPLv2)
  5. */
  6. import "./utils/html";
  7. import "@converse/headless/converse-emoji";
  8. import URI from "urijs";
  9. import converse from "@converse/headless/converse-core";
  10. import { BootstrapModal } from "./converse-modal.js";
  11. import { debounce } from 'lodash'
  12. import { render } from "lit-html";
  13. import filesize from "filesize";
  14. import log from "@converse/headless/log";
  15. import tpl_csn from "templates/csn.html";
  16. import tpl_file_progress from "templates/file_progress.html";
  17. import tpl_info from "templates/info.html";
  18. import tpl_message from "templates/message.html";
  19. import tpl_message_versions_modal from "templates/message_versions_modal.js";
  20. import tpl_spinner from "templates/spinner.html";
  21. import xss from "xss/dist/xss";
  22. const { Strophe, dayjs } = converse.env;
  23. const u = converse.env.utils;
  24. converse.plugins.add('converse-message-view', {
  25. dependencies: ["converse-modal", "converse-chatboxviews"],
  26. initialize () {
  27. /* The initialize function gets called as soon as the plugin is
  28. * loaded by converse.js's plugin machinery.
  29. */
  30. const { _converse } = this;
  31. const { __ } = _converse;
  32. function onTagFoundDuringXSSFilter (tag, html, options) {
  33. /* This function gets called by the XSS library whenever it finds
  34. * what it thinks is a new HTML tag.
  35. *
  36. * It thinks that something like <https://example.com> is an HTML
  37. * tag and then escapes the <> chars.
  38. *
  39. * We want to avoid this, because it prevents these URLs from being
  40. * shown properly (whithout the trailing &gt;).
  41. *
  42. * The URI lib correctly trims a trailing >, but not a trailing &gt;
  43. */
  44. if (options.isClosing) {
  45. // Closing tags don't match our use-case
  46. return;
  47. }
  48. const uri = new URI(tag);
  49. const protocol = uri.protocol().toLowerCase();
  50. if (!["https", "http", "xmpp", "ftp"].includes(protocol)) {
  51. // Not a URL, the tag will get filtered as usual
  52. return;
  53. }
  54. if (uri.equals(tag) && `<${tag}>` === html.toLocaleLowerCase()) {
  55. // We have something like <https://example.com>, and don't want
  56. // to filter it.
  57. return html;
  58. }
  59. }
  60. _converse.api.settings.update({
  61. 'show_images_inline': true,
  62. 'allow_message_retraction': 'all'
  63. });
  64. _converse.MessageVersionsModal = BootstrapModal.extend({
  65. id: "message-versions-modal",
  66. toHTML () {
  67. return tpl_message_versions_modal(this.model.toJSON());
  68. }
  69. });
  70. /**
  71. * @class
  72. * @namespace _converse.MessageView
  73. * @memberOf _converse
  74. */
  75. _converse.MessageView = _converse.ViewWithAvatar.extend({
  76. events: {
  77. 'click .chat-msg__edit-modal': 'showMessageVersionsModal',
  78. 'click .retry': 'onRetryClicked'
  79. },
  80. initialize () {
  81. this.debouncedRender = debounce(() => {
  82. // If the model gets destroyed in the meantime,
  83. // it no longer has a collection
  84. if (this.model.collection) {
  85. this.render();
  86. }
  87. }, 50);
  88. if (this.model.rosterContactAdded) {
  89. this.model.rosterContactAdded.then(() => {
  90. this.listenTo(this.model.contact, 'change:nickname', this.debouncedRender);
  91. this.debouncedRender();
  92. });
  93. }
  94. if (this.model.occupant) {
  95. this.listenTo(this.model.occupant, 'change:role', this.debouncedRender);
  96. this.listenTo(this.model.occupant, 'change:affiliation', this.debouncedRender);
  97. this.debouncedRender();
  98. }
  99. this.listenTo(this.model, 'change', this.onChanged);
  100. this.listenTo(this.model, 'destroy', this.fadeOut);
  101. this.listenTo(this.model, 'vcard:change', this.debouncedRender);
  102. },
  103. async render () {
  104. const is_followup = u.hasClass('chat-msg--followup', this.el);
  105. if (this.model.isOnlyChatStateNotification()) {
  106. this.renderChatStateNotification()
  107. } else if (this.model.get('file') && !this.model.get('oob_url')) {
  108. if (!this.model.file) {
  109. log.error("Attempted to render a file upload message with no file data");
  110. return this.el;
  111. }
  112. this.renderFileUploadProgresBar();
  113. } else if (this.model.get('type') === 'error') {
  114. this.renderErrorMessage();
  115. } else if (this.model.get('type') === 'info') {
  116. this.renderInfoMessage();
  117. } else {
  118. await this.renderChatMessage();
  119. }
  120. is_followup && u.addClass('chat-msg--followup', this.el);
  121. return this.el;
  122. },
  123. async onChanged (item) {
  124. // Jot down whether it was edited because the `changed`
  125. // attr gets removed when this.render() gets called further down.
  126. const edited = item.changed.edited;
  127. if (this.model.changed.progress) {
  128. return this.renderFileUploadProgresBar();
  129. }
  130. const isValidChange = prop => Object.prototype.hasOwnProperty.call(this.model.changed, prop);
  131. const props = ['moderated', 'retracted', 'correcting', 'message', 'type', 'upload', 'received', 'editable'];
  132. if (props.filter(isValidChange).length) {
  133. await this.debouncedRender();
  134. }
  135. if (edited) {
  136. this.onMessageEdited();
  137. }
  138. },
  139. fadeOut () {
  140. if (_converse.animate) {
  141. setTimeout(() => this.remove(), 600);
  142. u.addClass('fade-out', this.el);
  143. } else {
  144. this.remove();
  145. }
  146. },
  147. async onRetryClicked () {
  148. this.showSpinner();
  149. await this.model.error.retry();
  150. this.model.destroy();
  151. },
  152. showSpinner () {
  153. this.el.innerHTML = tpl_spinner();
  154. },
  155. onMessageEdited () {
  156. if (this.model.get('is_archived')) {
  157. return;
  158. }
  159. this.el.addEventListener(
  160. 'animationend',
  161. () => u.removeClass('onload', this.el),
  162. {'once': true}
  163. );
  164. u.addClass('onload', this.el);
  165. },
  166. replaceElement (msg) {
  167. if (this.el.parentElement) {
  168. this.el.parentElement.replaceChild(msg, this.el);
  169. }
  170. this.setElement(msg);
  171. return this.el;
  172. },
  173. transformOOBURL (url) {
  174. return u.getOOBURLMarkup(_converse, url);
  175. },
  176. async transformBodyText (text) {
  177. /**
  178. * Synchronous event which provides a hook for transforming a chat message's body text
  179. * before the default transformations have been applied.
  180. * @event _converse#beforeMessageBodyTransformed
  181. * @param { _converse.MessageView } view - The view representing the message
  182. * @param { string } text - The message text
  183. * @example _converse.api.listen.on('beforeMessageBodyTransformed', (view, text) => { ... });
  184. */
  185. await _converse.api.trigger('beforeMessageBodyTransformed', this, text, {'Synchronous': true});
  186. text = this.model.isMeCommand() ? text.substring(4) : text;
  187. text = xss.filterXSS(text, {'whiteList': {}, 'onTag': onTagFoundDuringXSSFilter});
  188. text = u.geoUriToHttp(text, _converse.geouri_replacement);
  189. text = u.addMentionsMarkup(text, this.model.get('references'), this.model.collection.chatbox);
  190. text = u.addHyperlinks(text);
  191. text = u.renderNewLines(text);
  192. text = u.addEmoji(text);
  193. /**
  194. * Synchronous event which provides a hook for transforming a chat message's body text
  195. * after the default transformations have been applied.
  196. * @event _converse#afterMessageBodyTransformed
  197. * @param { _converse.MessageView } view - The view representing the message
  198. * @param { string } text - The message text
  199. * @example _converse.api.listen.on('afterMessageBodyTransformed', (view, text) => { ... });
  200. */
  201. await _converse.api.trigger('afterMessageBodyTransformed', this, text, {'Synchronous': true});
  202. return text;
  203. },
  204. async renderChatMessage () {
  205. await _converse.api.waitUntil('emojisInitialized');
  206. const time = dayjs(this.model.get('time'));
  207. const role = this.model.vcard ? this.model.vcard.get('role') : null;
  208. const roles = role ? role.split(',') : [];
  209. const is_retracted = this.model.get('retracted') || this.model.get('moderated') === 'retracted';
  210. const is_groupchat = this.model.get('type') === 'groupchat';
  211. const is_own_message = this.model.get('sender') === 'me';
  212. const chatbox = this.model.collection.chatbox;
  213. const may_retract_own_message = is_own_message && (
  214. ['all', 'own'].includes(_converse.allow_message_retraction) || await chatbox.canModerateMessages()
  215. );
  216. const may_moderate_message = !is_own_message && is_groupchat &&
  217. ['all', 'moderator'].includes(_converse.allow_message_retraction) &&
  218. await chatbox.canModerateMessages();
  219. const retractable= !is_retracted && (may_moderate_message || may_retract_own_message);
  220. const msg = u.stringToElement(tpl_message(
  221. Object.assign(
  222. this.model.toJSON(), {
  223. __,
  224. is_retracted,
  225. retractable,
  226. 'extra_classes': this.getExtraMessageClasses(),
  227. 'is_groupchat_message': is_groupchat,
  228. 'is_me_message': this.model.isMeCommand(),
  229. 'label_show': __('Show more'),
  230. 'occupant': this.model.occupant,
  231. 'pretty_time': time.format(_converse.time_format),
  232. 'retraction_text': is_retracted ? this.getRetractionText() : null,
  233. 'roles': roles,
  234. 'time': time.toISOString(),
  235. 'username': this.model.getDisplayName()
  236. })
  237. ));
  238. const url = this.model.get('oob_url');
  239. url && render(this.transformOOBURL(url), msg.querySelector('.chat-msg__media'));
  240. if (!is_retracted) {
  241. const text = this.model.getMessageText();
  242. const msg_content = msg.querySelector('.chat-msg__text');
  243. if (text && text !== url) {
  244. msg_content.innerHTML = await this.transformBodyText(text);
  245. if (_converse.show_images_inline) {
  246. u.renderImageURLs(_converse, msg_content).then(() => this.triggerRendered());
  247. }
  248. }
  249. }
  250. if (this.model.get('type') !== 'headline') {
  251. this.renderAvatar(msg);
  252. }
  253. this.replaceElement(msg);
  254. this.triggerRendered();
  255. },
  256. triggerRendered () {
  257. if (this.model.collection) {
  258. // If the model gets destroyed in the meantime, it no
  259. // longer has a collection.
  260. this.model.collection.trigger('rendered', this);
  261. }
  262. },
  263. renderInfoMessage () {
  264. const msg = u.stringToElement(
  265. tpl_info(Object.assign(this.model.toJSON(), {
  266. 'extra_classes': 'chat-info',
  267. 'isodate': dayjs(this.model.get('time')).toISOString()
  268. }))
  269. );
  270. return this.replaceElement(msg);
  271. },
  272. getRetractionText () {
  273. if (this.model.get('type') === 'groupchat' && this.model.get('moderated_by')) {
  274. const retracted_by_mod = this.model.get('moderated_by');
  275. const chatbox = this.model.collection.chatbox;
  276. if (!this.model.mod) {
  277. this.model.mod =
  278. chatbox.occupants.findOccupant({'jid': retracted_by_mod}) ||
  279. chatbox.occupants.findOccupant({'nick': Strophe.getResourceFromJid(retracted_by_mod)});
  280. }
  281. const modname = this.model.mod ? this.model.mod.getDisplayName() : 'A moderator';
  282. return __('%1$s has removed this message', modname);
  283. } else {
  284. return __('%1$s has removed this message', this.model.getDisplayName());
  285. }
  286. },
  287. renderErrorMessage () {
  288. const msg = u.stringToElement(
  289. tpl_info(Object.assign(this.model.toJSON(), {
  290. 'extra_classes': 'chat-error',
  291. 'isodate': dayjs(this.model.get('time')).toISOString()
  292. }))
  293. );
  294. return this.replaceElement(msg);
  295. },
  296. renderChatStateNotification () {
  297. let text;
  298. const from = this.model.get('from');
  299. const name = this.model.getDisplayName();
  300. if (this.model.get('chat_state') === _converse.COMPOSING) {
  301. if (this.model.get('sender') === 'me') {
  302. text = __('Typing from another device');
  303. } else {
  304. text = __('%1$s is typing', name);
  305. }
  306. } else if (this.model.get('chat_state') === _converse.PAUSED) {
  307. if (this.model.get('sender') === 'me') {
  308. text = __('Stopped typing on the other device');
  309. } else {
  310. text = __('%1$s has stopped typing', name);
  311. }
  312. } else if (this.model.get('chat_state') === _converse.GONE) {
  313. text = __('%1$s has gone away', name);
  314. } else {
  315. return;
  316. }
  317. const isodate = (new Date()).toISOString();
  318. this.replaceElement(
  319. u.stringToElement(
  320. tpl_csn({
  321. 'message': text,
  322. 'from': from,
  323. 'isodate': isodate
  324. })));
  325. },
  326. renderFileUploadProgresBar () {
  327. const msg = u.stringToElement(tpl_file_progress(
  328. Object.assign(this.model.toJSON(), {
  329. '__': __,
  330. 'filename': this.model.file.name,
  331. 'filesize': filesize(this.model.file.size)
  332. })));
  333. this.replaceElement(msg);
  334. this.renderAvatar();
  335. },
  336. showMessageVersionsModal (ev) {
  337. ev.preventDefault();
  338. if (this.model.message_versions_modal === undefined) {
  339. this.model.message_versions_modal = new _converse.MessageVersionsModal({'model': this.model});
  340. }
  341. this.model.message_versions_modal.show(ev);
  342. },
  343. getExtraMessageClasses () {
  344. const is_retracted = this.model.get('retracted') || this.model.get('moderated') === 'retracted';
  345. const extra_classes = [
  346. ...(this.model.get('is_delayed') ? ['delayed'] : []), ...(is_retracted ? ['chat-msg--retracted'] : [])
  347. ];
  348. if (this.model.get('type') === 'groupchat') {
  349. if (this.model.occupant) {
  350. extra_classes.push(this.model.occupant.get('role'));
  351. extra_classes.push(this.model.occupant.get('affiliation'));
  352. }
  353. if (this.model.get('sender') === 'them' && this.model.collection.chatbox.isUserMentioned(this.model)) {
  354. // Add special class to mark groupchat messages
  355. // in which we are mentioned.
  356. extra_classes.push('mentioned');
  357. }
  358. }
  359. if (this.model.get('correcting')) {
  360. extra_classes.push('correcting');
  361. }
  362. return extra_classes.filter(c => c).join(" ");
  363. }
  364. });
  365. }
  366. });