123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374 |
- // Converse.js
- // https://conversejs.org
- //
- // Copyright (c) 2013-2019, the Converse.js developers
- // Licensed under the Mozilla Public License (MPLv2)
- /**
- * @module converse-message-view
- */
- import URI from "urijs";
- import converse from "@converse/headless/converse-core";
- import { debounce } from 'lodash'
- import filesize from "filesize";
- import html from "./utils/html";
- import tpl_csn from "templates/csn.html";
- import tpl_file_progress from "templates/file_progress.html";
- import tpl_info from "templates/info.html";
- import tpl_message from "templates/message.html";
- import tpl_message_versions_modal from "templates/message_versions_modal.html";
- import tpl_spinner from "templates/spinner.html";
- import u from "@converse/headless/utils/emoji";
- import xss from "xss/dist/xss";
- const { Backbone, dayjs } = converse.env;
- converse.plugins.add('converse-message-view', {
- dependencies: ["converse-modal", "converse-chatboxviews"],
- initialize () {
- /* The initialize function gets called as soon as the plugin is
- * loaded by converse.js's plugin machinery.
- */
- const { _converse } = this;
- const { __ } = _converse;
- function onTagFoundDuringXSSFilter (tag, html, options) {
- /* This function gets called by the XSS library whenever it finds
- * what it thinks is a new HTML tag.
- *
- * It thinks that something like <https://example.com> is an HTML
- * tag and then escapes the <> chars.
- *
- * We want to avoid this, because it prevents these URLs from being
- * shown properly (whithout the trailing >).
- *
- * The URI lib correctly trims a trailing >, but not a trailing >
- */
- if (options.isClosing) {
- // Closing tags don't match our use-case
- return;
- }
- const uri = new URI(tag);
- const protocol = uri.protocol().toLowerCase();
- if (!["https", "http", "xmpp", "ftp"].includes(protocol)) {
- // Not a URL, the tag will get filtered as usual
- return;
- }
- if (uri.equals(tag) && `<${tag}>` === html.toLocaleLowerCase()) {
- // We have something like <https://example.com>, and don't want
- // to filter it.
- return html;
- }
- }
- _converse.api.settings.update({
- 'show_images_inline': true
- });
- _converse.MessageVersionsModal = _converse.BootstrapModal.extend({
- toHTML () {
- return tpl_message_versions_modal(Object.assign(
- this.model.toJSON(), {
- '__': __,
- 'dayjs': dayjs
- }));
- }
- });
- _converse.MessageView = _converse.ViewWithAvatar.extend({
- events: {
- 'click .chat-msg__edit-modal': 'showMessageVersionsModal',
- 'click .retry': 'onRetryClicked'
- },
- initialize () {
- this.debouncedRender = debounce(() => {
- // If the model gets destroyed in the meantime,
- // it no longer has a collection
- if (this.model.collection) {
- this.render();
- }
- }, 50);
- if (this.model.vcard) {
- this.model.vcard.on('change', this.debouncedRender, this);
- }
- if (this.model.rosterContactAdded) {
- this.model.rosterContactAdded.then(() => {
- this.model.contact.on('change:nickname', this.debouncedRender, this);
- this.debouncedRender();
- });
- }
- if (this.model.occupantAdded) {
- this.model.occupantAdded.then(() => {
- this.model.occupant.on('change:role', this.debouncedRender, this);
- this.model.occupant.on('change:affiliation', this.debouncedRender, this);
- this.debouncedRender();
- });
- }
- this.model.on('change', this.onChanged, this);
- this.model.on('destroy', this.fadeOut, this);
- },
- async render () {
- const is_followup = u.hasClass('chat-msg--followup', this.el);
- if (this.model.isOnlyChatStateNotification()) {
- this.renderChatStateNotification()
- } else if (this.model.get('file') && !this.model.get('oob_url')) {
- if (!this.model.file) {
- _converse.log("Attempted to render a file upload message with no file data");
- return this.el;
- }
- this.renderFileUploadProgresBar();
- } else if (this.model.get('type') === 'error') {
- this.renderErrorMessage();
- } else if (this.model.get('type') === 'info') {
- this.renderInfoMessage();
- } else {
- await this.renderChatMessage();
- }
- if (is_followup) {
- u.addClass('chat-msg--followup', this.el);
- }
- return this.el;
- },
- async onChanged (item) {
- // Jot down whether it was edited because the `changed`
- // attr gets removed when this.render() gets called further
- // down.
- const edited = item.changed.edited;
- if (this.model.changed.progress) {
- return this.renderFileUploadProgresBar();
- }
- const isValidChange = prop => Object.prototype.hasOwnProperty.call(this.model.changed, prop);
- if (['correcting', 'message', 'type', 'upload', 'received'].filter(isValidChange).length) {
- await this.debouncedRender();
- }
- if (edited) {
- this.onMessageEdited();
- }
- },
- fadeOut () {
- if (_converse.animate) {
- setTimeout(() => this.remove(), 600);
- u.addClass('fade-out', this.el);
- } else {
- this.remove();
- }
- },
- async onRetryClicked () {
- this.showSpinner();
- await this.model.error.retry();
- this.model.destroy();
- },
- showSpinner () {
- this.el.innerHTML = tpl_spinner();
- },
- onMessageEdited () {
- if (this.model.get('is_archived')) {
- return;
- }
- this.el.addEventListener(
- 'animationend',
- () => u.removeClass('onload', this.el),
- {'once': true}
- );
- u.addClass('onload', this.el);
- },
- replaceElement (msg) {
- if (this.el.parentElement) {
- this.el.parentElement.replaceChild(msg, this.el);
- }
- this.setElement(msg);
- return this.el;
- },
- transformOOBURL (url) {
- url = u.renderFileURL(_converse, url);
- url = u.renderMovieURL(_converse, url);
- url = u.renderAudioURL(_converse, url);
- return u.renderImageURL(_converse, url);
- },
- transformBodyText (text) {
- text = this.isMeCommand() ? text.substring(4) : text;
- text = xss.filterXSS(text, {'whiteList': {}, 'onTag': onTagFoundDuringXSSFilter});
- text = u.geoUriToHttp(text, _converse.geouri_replacement);
- text = u.addMentionsMarkup(text, this.model.get('references'), this.model.collection.chatbox);
- text = u.addHyperlinks(text);
- text = u.renderNewLines(text);
- return u.addEmoji(_converse, text);
- },
- async renderChatMessage () {
- const is_me_message = this.isMeCommand();
- const time = dayjs(this.model.get('time'));
- const role = this.model.vcard ? this.model.vcard.get('role') : null;
- const roles = role ? role.split(',') : [];
- const msg = u.stringToElement(tpl_message(
- Object.assign(
- this.model.toJSON(), {
- '__': __,
- 'is_groupchat_message': this.model.get('type') === 'groupchat',
- 'occupant': this.model.occupant,
- 'is_me_message': is_me_message,
- 'roles': roles,
- 'pretty_time': time.format(_converse.time_format),
- 'time': time.toISOString(),
- 'extra_classes': this.getExtraMessageClasses(),
- 'label_show': __('Show more'),
- 'username': this.model.getDisplayName()
- })
- ));
- const url = this.model.get('oob_url');
- if (url) {
- msg.querySelector('.chat-msg__media').innerHTML = this.transformOOBURL(url);
- }
- const text = this.getMessageText();
- const msg_content = msg.querySelector('.chat-msg__text');
- if (text && text !== url) {
- msg_content.innerHTML = this.transformBodyText(text);
- }
- const promise = u.renderImageURLs(_converse, msg_content);
- if (this.model.get('type') !== 'headline') {
- this.renderAvatar(msg);
- }
- await promise;
- this.replaceElement(msg);
- if (this.model.collection) {
- // If the model gets destroyed in the meantime, it no
- // longer has a collection.
- this.model.collection.trigger('rendered', this);
- }
- },
- renderInfoMessage () {
- const msg = u.stringToElement(
- tpl_info(Object.assign(this.model.toJSON(), {
- 'extra_classes': 'chat-info',
- 'isodate': dayjs(this.model.get('time')).toISOString()
- }))
- );
- return this.replaceElement(msg);
- },
- renderErrorMessage () {
- const msg = u.stringToElement(
- tpl_info(Object.assign(this.model.toJSON(), {
- 'extra_classes': 'chat-error',
- 'isodate': dayjs(this.model.get('time')).toISOString()
- }))
- );
- return this.replaceElement(msg);
- },
- renderChatStateNotification () {
- let text;
- const from = this.model.get('from'),
- name = this.model.getDisplayName();
- if (this.model.get('chat_state') === _converse.COMPOSING) {
- if (this.model.get('sender') === 'me') {
- text = __('Typing from another device');
- } else {
- text = __('%1$s is typing', name);
- }
- } else if (this.model.get('chat_state') === _converse.PAUSED) {
- if (this.model.get('sender') === 'me') {
- text = __('Stopped typing on the other device');
- } else {
- text = __('%1$s has stopped typing', name);
- }
- } else if (this.model.get('chat_state') === _converse.GONE) {
- text = __('%1$s has gone away', name);
- } else {
- return;
- }
- const isodate = (new Date()).toISOString();
- this.replaceElement(
- u.stringToElement(
- tpl_csn({
- 'message': text,
- 'from': from,
- 'isodate': isodate
- })));
- },
- renderFileUploadProgresBar () {
- const msg = u.stringToElement(tpl_file_progress(
- Object.assign(this.model.toJSON(), {
- '__': __,
- 'filename': this.model.file.name,
- 'filesize': filesize(this.model.file.size)
- })));
- this.replaceElement(msg);
- this.renderAvatar();
- },
- showMessageVersionsModal (ev) {
- ev.preventDefault();
- if (this.model.message_versions_modal === undefined) {
- this.model.message_versions_modal = new _converse.MessageVersionsModal({'model': this.model});
- }
- this.model.message_versions_modal.show(ev);
- },
- getMessageText () {
- if (this.model.get('is_encrypted')) {
- return this.model.get('plaintext') ||
- (_converse.debug ? __('Unencryptable OMEMO message') : null);
- }
- return this.model.get('message');
- },
- isMeCommand () {
- const text = this.getMessageText();
- if (!text) {
- return false;
- }
- return text.startsWith('/me ');
- },
- processMessageText () {
- var text = this.get('message');
- text = u.geoUriToHttp(text, _converse.geouri_replacement);
- },
- getExtraMessageClasses () {
- let extra_classes = this.model.get('is_delayed') && 'delayed' || '';
- if (this.model.get('type') === 'groupchat') {
- if (this.model.occupant) {
- extra_classes += ` ${this.model.occupant.get('role') || ''} ${this.model.occupant.get('affiliation') || ''}`;
- }
- if (this.model.get('sender') === 'them' && this.model.collection.chatbox.isUserMentioned(this.model)) {
- // Add special class to mark groupchat messages
- // in which we are mentioned.
- extra_classes += ' mentioned';
- }
- }
- if (this.model.get('correcting')) {
- extra_classes += ' correcting';
- }
- return extra_classes;
- }
- });
- }
- });
|