// Converse.js
// https://conversejs.org
//
// Copyright (c) 2013-2019, the Converse.js developers
// Licensed under the Mozilla Public License (MPLv2)
//
// XEP-0045 Multi-User Chat Views
import "converse-modal";
import "backbone.overview/backbone.orderedlistview";
import "backbone.overview/backbone.overview";
import "backbone.vdomview";
import _FormData from "formdata-polyfill";
import converse from "@converse/headless/converse-core";
import muc_utils from "@converse/headless/utils/muc";
import tpl_add_chatroom_modal from "templates/add_chatroom_modal.html";
import tpl_chatarea from "templates/chatarea.html";
import tpl_chatroom from "templates/chatroom.html";
import tpl_chatroom_bottom_panel from "templates/chatroom_bottom_panel.html";
import tpl_chatroom_destroyed from "templates/chatroom_destroyed.html";
import tpl_chatroom_details_modal from "templates/chatroom_details_modal.html";
import tpl_chatroom_disconnect from "templates/chatroom_disconnect.html";
import tpl_chatroom_features from "templates/chatroom_features.html";
import tpl_chatroom_form from "templates/chatroom_form.html";
import tpl_chatroom_head from "templates/chatroom_head.html";
import tpl_chatroom_invite from "templates/chatroom_invite.html";
import tpl_chatroom_nickname_form from "templates/chatroom_nickname_form.html";
import tpl_chatroom_password_form from "templates/chatroom_password_form.html";
import tpl_chatroom_sidebar from "templates/chatroom_sidebar.html";
import tpl_info from "templates/info.html";
import tpl_list_chatrooms_modal from "templates/list_chatrooms_modal.html";
import tpl_occupant from "templates/occupant.html";
import tpl_room_description from "templates/room_description.html";
import tpl_room_item from "templates/room_item.html";
import tpl_room_panel from "templates/room_panel.html";
import tpl_rooms_results from "templates/rooms_results.html";
import tpl_spinner from "templates/spinner.html";
import xss from "xss";
const { Backbone, Promise, Strophe, moment, f, sizzle, _, $build, $iq, $msg, $pres } = converse.env;
const u = converse.env.utils;
const AFFILIATION_CHANGE_COMANDS = ['admin', 'ban', 'owner', 'member', 'revoke'];
converse.plugins.add('converse-muc-views', {
/* Dependencies are other plugins which might be
* overridden or relied upon, and therefore need to be loaded before
* this plugin. They are "optional" because they might not be
* available, in which case any overrides applicable to them will be
* ignored.
*
* NB: These plugins need to have already been loaded via require.js.
*
* It's possible to make these dependencies "non-optional".
* If the setting "strict_plugin_dependencies" is set to true,
* an error will be raised if the plugin is not found.
*/
dependencies: ["converse-autocomplete", "converse-modal", "converse-controlbox", "converse-chatview"],
overrides: {
ControlBoxView: {
renderRoomsPanel () {
const { _converse } = this.__super__;
if (this.roomspanel && u.isVisible(this.roomspanel.el)) {
return;
}
this.roomspanel = new _converse.RoomsPanel({
'model': new (_converse.RoomsPanelModel.extend({
'id': `converse.roomspanel${_converse.bare_jid}`, // Required by web storage
'browserStorage': new Backbone.BrowserStorage[_converse.config.get('storage')](
`converse.roomspanel${_converse.bare_jid}`)
}))()
});
this.roomspanel.model.fetch();
this.el.querySelector('.controlbox-pane').insertAdjacentElement(
'beforeEnd', this.roomspanel.render().el);
/**
* Triggered once the section of the _converse.ControlBoxView
* which shows gropuchats has been rendered.
* @event _converse#roomsPanelRendered
* @example _converse.api.listen.on('roomsPanelRendered', () => { ... });
*/
_converse.api.trigger('roomsPanelRendered');
},
renderControlBoxPane () {
const { _converse } = this.__super__;
this.__super__.renderControlBoxPane.apply(this, arguments);
if (_converse.allow_muc) {
this.renderRoomsPanel();
}
},
}
},
initialize () {
const { _converse } = this,
{ __ } = _converse;
_converse.api.promises.add(['roomsPanelRendered']);
// Configuration values for this plugin
// ====================================
// Refer to docs/source/configuration.rst for explanations of these
// configuration settings.
_converse.api.settings.update({
'auto_list_rooms': false,
'cache_muc_messages': true,
'locked_muc_domain': false,
'locked_muc_nickname': false,
'muc_disable_moderator_commands': false,
'muc_domain': undefined,
'muc_show_join_leave': true,
'roomconfig_whitelist': [],
'visible_toolbar_buttons': {
'toggle_occupants': true
}
});
if (_converse.locked_muc_domain && !_.isString(_converse.muc_domain)) {
throw new Error("Config Error: it makes no sense to set locked_muc_domain "+
"to true when muc_domain is not set");
}
function ___ (str) {
/* This is part of a hack to get gettext to scan strings to be
* translated. Strings we cannot send to the function above because
* they require variable interpolation and we don't yet have the
* variables at scan time.
*
* See actionInfoMessages further below.
*/
return str;
}
/* https://xmpp.org/extensions/xep-0045.html
* ----------------------------------------
* 100 message Entering a groupchat Inform user that any occupant is allowed to see the user's full JID
* 101 message (out of band) Affiliation change Inform user that his or her affiliation changed while not in the groupchat
* 102 message Configuration change Inform occupants that groupchat now shows unavailable members
* 103 message Configuration change Inform occupants that groupchat now does not show unavailable members
* 104 message Configuration change Inform occupants that a non-privacy-related groupchat configuration change has occurred
* 110 presence Any groupchat presence Inform user that presence refers to one of its own groupchat occupants
* 170 message or initial presence Configuration change Inform occupants that groupchat logging is now enabled
* 171 message Configuration change Inform occupants that groupchat logging is now disabled
* 172 message Configuration change Inform occupants that the groupchat is now non-anonymous
* 173 message Configuration change Inform occupants that the groupchat is now semi-anonymous
* 174 message Configuration change Inform occupants that the groupchat is now fully-anonymous
* 201 presence Entering a groupchat Inform user that a new groupchat has been created
* 210 presence Entering a groupchat Inform user that the service has assigned or modified the occupant's roomnick
* 301 presence Removal from groupchat Inform user that he or she has been banned from the groupchat
* 303 presence Exiting a groupchat Inform all occupants of new groupchat nickname
* 307 presence Removal from groupchat Inform user that he or she has been kicked from the groupchat
* 321 presence Removal from groupchat Inform user that he or she is being removed from the groupchat because of an affiliation change
* 322 presence Removal from groupchat Inform user that he or she is being removed from the groupchat because the groupchat has been changed to members-only and the user is not a member
* 332 presence Removal from groupchat Inform user that he or she is being removed from the groupchat because of a system shutdown
*/
_converse.muc = {
info_messages: {
100: __('This groupchat is not anonymous'),
102: __('This groupchat now shows unavailable members'),
103: __('This groupchat does not show unavailable members'),
104: __('The groupchat configuration has changed'),
170: __('groupchat logging is now enabled'),
171: __('groupchat logging is now disabled'),
172: __('This groupchat is now no longer anonymous'),
173: __('This groupchat is now semi-anonymous'),
174: __('This groupchat is now fully-anonymous'),
201: __('A new groupchat has been created')
},
disconnect_messages: {
301: __('You have been banned from this groupchat'),
307: __('You have been kicked from this groupchat'),
321: __("You have been removed from this groupchat because of an affiliation change"),
322: __("You have been removed from this groupchat because the groupchat has changed to members-only and you're not a member"),
332: __("You have been removed from this groupchat because the service hosting it is being shut down")
},
action_info_messages: {
/* XXX: Note the triple underscore function and not double
* underscore.
*
* This is a hack. We can't pass the strings to __ because we
* don't yet know what the variable to interpolate is.
*
* Triple underscore will just return the string again, but we
* can then at least tell gettext to scan for it so that these
* strings are picked up by the translation machinery.
*/
301: ___("%1$s has been banned"),
303: ___("%1$s's nickname has changed"),
307: ___("%1$s has been kicked out"),
321: ___("%1$s has been removed because of an affiliation change"),
322: ___("%1$s has been removed for not being a member")
},
new_nickname_messages: {
210: ___('Your nickname has been automatically set to %1$s'),
303: ___('Your nickname has been changed to %1$s')
}
};
/* Insert groupchat info (based on returned #disco IQ stanza)
* @function insertRoomInfo
* @param { HTMLElement } el - The HTML DOM element that contains the info.
* @param { XMLElement } stanza - The IQ stanza containing the groupchat info.
*/
function insertRoomInfo (el, stanza) {
// All MUC features found here: https://xmpp.org/registrar/disco-features.html
el.querySelector('span.spinner').remove();
el.querySelector('a.room-info').classList.add('selected');
el.insertAdjacentHTML(
'beforeEnd',
tpl_room_description({
'jid': stanza.getAttribute('from'),
'desc': _.get(_.head(sizzle('field[var="muc#roominfo_description"] value', stanza)), 'textContent'),
'occ': _.get(_.head(sizzle('field[var="muc#roominfo_occupants"] value', stanza)), 'textContent'),
'hidden': sizzle('feature[var="muc_hidden"]', stanza).length,
'membersonly': sizzle('feature[var="muc_membersonly"]', stanza).length,
'moderated': sizzle('feature[var="muc_moderated"]', stanza).length,
'nonanonymous': sizzle('feature[var="muc_nonanonymous"]', stanza).length,
'open': sizzle('feature[var="muc_open"]', stanza).length,
'passwordprotected': sizzle('feature[var="muc_passwordprotected"]', stanza).length,
'persistent': sizzle('feature[var="muc_persistent"]', stanza).length,
'publicroom': sizzle('feature[var="muc_publicroom"]', stanza).length,
'semianonymous': sizzle('feature[var="muc_semianonymous"]', stanza).length,
'temporary': sizzle('feature[var="muc_temporary"]', stanza).length,
'unmoderated': sizzle('feature[var="muc_unmoderated"]', stanza).length,
'label_desc': __('Description:'),
'label_jid': __('Groupchat Address (JID):'),
'label_occ': __('Participants:'),
'label_features': __('Features:'),
'label_requires_auth': __('Requires authentication'),
'label_hidden': __('Hidden'),
'label_requires_invite': __('Requires an invitation'),
'label_moderated': __('Moderated'),
'label_non_anon': __('Non-anonymous'),
'label_open_room': __('Open'),
'label_permanent_room': __('Permanent'),
'label_public': __('Public'),
'label_semi_anon': __('Semi-anonymous'),
'label_temp_room': __('Temporary'),
'label_unmoderated': __('Unmoderated')
}));
}
function toggleRoomInfo (ev) {
/* Show/hide extra information about a groupchat in a listing. */
const parent_el = u.ancestor(ev.target, '.room-item'),
div_el = parent_el.querySelector('div.room-info');
if (div_el) {
u.slideIn(div_el).then(u.removeElement)
parent_el.querySelector('a.room-info').classList.remove('selected');
} else {
parent_el.insertAdjacentHTML('beforeend', tpl_spinner());
_converse.api.disco.info(ev.target.getAttribute('data-room-jid'), null)
.then(stanza => insertRoomInfo(parent_el, stanza))
.catch(_.partial(_converse.log, _, Strophe.LogLevel.ERROR));
}
}
_converse.ListChatRoomsModal = _converse.BootstrapModal.extend({
events: {
'submit form': 'showRooms',
'click a.room-info': 'toggleRoomInfo',
'change input[name=nick]': 'setNick',
'change input[name=server]': 'setDomainFromEvent',
'click .open-room': 'openRoom'
},
initialize () {
_converse.BootstrapModal.prototype.initialize.apply(this, arguments);
if (_converse.muc_domain && !this.model.get('muc_domain')) {
this.model.save('muc_domain', _converse.muc_domain);
}
this.model.on('change:muc_domain', this.onDomainChange, this);
},
toHTML () {
const muc_domain = this.model.get('muc_domain') || _converse.muc_domain;
return tpl_list_chatrooms_modal(_.extend(this.model.toJSON(), {
'heading_list_chatrooms': __('Query for Groupchats'),
'label_server_address': __('Server address'),
'label_query': __('Show groupchats'),
'show_form': !_converse.locked_muc_domain,
'server_placeholder': muc_domain ? muc_domain : __('conference.example.org')
}));
},
afterRender () {
if (_converse.locked_muc_domain) {
this.updateRoomsList();
} else {
this.el.addEventListener('shown.bs.modal',
() => this.el.querySelector('input[name="server"]').focus(),
false
);
}
},
openRoom (ev) {
ev.preventDefault();
const jid = ev.target.getAttribute('data-room-jid');
const name = ev.target.getAttribute('data-room-name');
this.modal.hide();
_converse.api.rooms.open(jid, {'name': name});
},
toggleRoomInfo (ev) {
ev.preventDefault();
toggleRoomInfo(ev);
},
onDomainChange (model) {
if (_converse.auto_list_rooms) {
this.updateRoomsList();
}
},
roomStanzaItemToHTMLElement (groupchat) {
const name = Strophe.unescapeNode(groupchat.getAttribute('name') || groupchat.getAttribute('jid'));
const div = document.createElement('div');
div.innerHTML = tpl_room_item({
'name': Strophe.xmlunescape(name),
'jid': groupchat.getAttribute('jid'),
'open_title': __('Click to open this groupchat'),
'info_title': __('Show more information on this groupchat')
});
return div.firstElementChild;
},
removeSpinner () {
_.each(this.el.querySelectorAll('span.spinner'),
(el) => el.parentNode.removeChild(el)
);
},
informNoRoomsFound () {
const chatrooms_el = this.el.querySelector('.available-chatrooms');
chatrooms_el.innerHTML = tpl_rooms_results({'feedback_text': __('No groupchats found')});
const input_el = this.el.querySelector('input[name="server"]');
input_el.classList.remove('hidden')
this.removeSpinner();
},
onRoomsFound (iq) {
/* Handle the IQ stanza returned from the server, containing
* all its public groupchats.
*/
const available_chatrooms = this.el.querySelector('.available-chatrooms');
this.rooms = iq.querySelectorAll('query item');
if (this.rooms.length) {
available_chatrooms.innerHTML = tpl_rooms_results({'feedback_text': __('Groupchats found:')});
const fragment = document.createDocumentFragment();
const children = _.reject(_.map(this.rooms, this.roomStanzaItemToHTMLElement), _.isNil)
_.each(children, (child) => fragment.appendChild(child));
available_chatrooms.appendChild(fragment);
this.removeSpinner();
} else {
this.informNoRoomsFound();
}
return true;
},
updateRoomsList () {
/* Send an IQ stanza to the server asking for all groupchats
*/
const iq = $iq({
'to': this.model.get('muc_domain'),
'from': _converse.connection.jid,
'type': "get"
}).c("query", {xmlns: Strophe.NS.DISCO_ITEMS});
_converse.api.sendIQ(iq)
.then(iq => this.onRoomsFound(iq))
.catch(iq => this.informNoRoomsFound())
},
showRooms (ev) {
ev.preventDefault();
const data = new FormData(ev.target);
this.model.setDomain(data.get('server'));
this.updateRoomsList();
},
setDomainFromEvent (ev) {
this.model.setDomain(ev.target.value);
},
setNick (ev) {
this.model.save({nick: ev.target.value});
}
});
_converse.AddChatRoomModal = _converse.BootstrapModal.extend({
events: {
'submit form.add-chatroom': 'openChatRoom'
},
initialize () {
_converse.BootstrapModal.prototype.initialize.apply(this, arguments);
this.model.on('change:muc_domain', this.render, this);
},
toHTML () {
let placeholder = '';
if (!_converse.locked_muc_domain) {
const muc_domain = this.model.get('muc_domain') || _converse.muc_domain;
placeholder = muc_domain ? `name@${muc_domain}` : __('name@conference.example.org');
}
return tpl_add_chatroom_modal(_.extend(this.model.toJSON(), {
'__': _converse.__,
'_converse': _converse,
'label_room_address': _converse.muc_domain ? __('Groupchat name') : __('Groupchat address'),
'chatroom_placeholder': placeholder
}));
},
afterRender () {
this.el.addEventListener('shown.bs.modal', () => {
this.el.querySelector('input[name="chatroom"]').focus();
}, false);
},
parseRoomDataFromEvent (form) {
const data = new FormData(form);
const jid = data.get('chatroom');
let nick;
if (_converse.locked_muc_nickname) {
nick = _converse.getDefaultMUCNickname();
if (!nick) {
throw new Error("Using locked_muc_nickname but no nickname found!");
}
} else {
nick = data.get('nickname').trim();
}
return {
'jid': jid,
'nick': nick
}
},
openChatRoom (ev) {
ev.preventDefault();
const data = this.parseRoomDataFromEvent(ev.target);
if (data.nick === "") {
// Make sure defaults apply if no nick is provided.
data.nick = undefined;
}
let jid;
if (_converse.locked_muc_domain || (_converse.muc_domain && !u.isValidJID(data.jid))) {
jid = `${Strophe.escapeNode(data.jid)}@${_converse.muc_domain}`;
} else {
jid = data.jid
this.model.setDomain(jid);
}
_converse.api.rooms.open(jid, _.extend(data, {jid}));
this.modal.hide();
ev.target.reset();
}
});
_converse.RoomDetailsModal = _converse.BootstrapModal.extend({
initialize () {
_converse.BootstrapModal.prototype.initialize.apply(this, arguments);
this.model.on('change', this.render, this);
this.model.occupants.on('add', this.render, this);
this.model.occupants.on('change', this.render, this);
},
toHTML () {
return tpl_chatroom_details_modal(_.extend(
this.model.toJSON(), {
'_': _,
'__': __,
'display_name': __('Groupchat info for %1$s', this.model.getDisplayName()),
'features': this.model.features.toJSON(),
'num_occupants': this.model.occupants.length,
'topic': u.addHyperlinks(xss.filterXSS(_.get(this.model.get('subject'), 'text'), {'whiteList': {}}))
})
);
}
});
/**
* The View of an open/ongoing groupchat conversation
*
* @class
* @namespace _converse.ChatRoomView
* @memberOf _converse
*/
_converse.ChatRoomView = _converse.ChatBoxView.extend({
/* Backbone.NativeView which renders a groupchat, based upon the view
* for normal one-on-one chat boxes.
*/
length: 300,
tagName: 'div',
className: 'chatbox chatroom hidden',
is_chatroom: true,
events: {
'change input.fileupload': 'onFileSelection',
'click .chat-msg__action-edit': 'onMessageEditButtonClicked',
'click .chatbox-navback': 'showControlBox',
'click .close-chatbox-button': 'close',
'click .configure-chatroom-button': 'getAndRenderConfigurationForm',
'click .hide-occupants': 'hideOccupants',
'click .new-msgs-indicator': 'viewUnreadMessages',
'click .occupant-nick': 'onOccupantClicked',
'click .send-button': 'onFormSubmitted',
'click .show-room-details-modal': 'showRoomDetailsModal',
'click .toggle-call': 'toggleCall',
'click .toggle-occupants': 'toggleOccupants',
'click .toggle-smiley ul.emoji-picker li': 'insertEmoji',
'click .toggle-smiley': 'toggleEmojiMenu',
'click .upload-file': 'toggleFileUpload',
'keydown .chat-textarea': 'keyPressed',
'keyup .chat-textarea': 'keyUp',
'input .chat-textarea': 'inputChanged',
'dragover .chat-textarea': 'onDragOver',
'drop .chat-textarea': 'onDrop',
},
initialize () {
this.initDebounced();
this.model.messages.on('add', this.onMessageAdded, this);
this.model.messages.on('rendered', this.scrollDown, this);
this.model.on('change:affiliation', this.renderHeading, this);
this.model.on('change:connection_status', this.afterConnected, this);
this.model.on('change:jid', this.renderHeading, this);
this.model.on('change:name', this.renderHeading, this);
this.model.on('change:role', this.renderBottomPanel, this);
this.model.on('change:subject', this.renderHeading, this);
this.model.on('change:subject', this.setChatRoomSubject, this);
this.model.on('configurationNeeded', this.getAndRenderConfigurationForm, this);
this.model.on('destroy', this.hide, this);
this.model.on('show', this.show, this);
this.model.features.on('change:moderated', this.renderBottomPanel, this);
this.model.occupants.on('add', this.onOccupantAdded, this);
this.model.occupants.on('remove', this.onOccupantRemoved, this);
this.model.occupants.on('change:show', this.showJoinOrLeaveNotification, this);
this.model.occupants.on('change:role', this.informOfOccupantsRoleChange, this);
this.model.occupants.on('change:affiliation', this.informOfOccupantsAffiliationChange, this);
this.createEmojiPicker();
this.createOccupantsView();
this.render().insertIntoDOM();
this.registerHandlers();
this.enterRoom();
},
async enterRoom (ev) {
if (ev) { ev.preventDefault(); }
if (this.model.get('connection_status') !== converse.ROOMSTATUS.ENTERED) {
await this.model.getRoomFeatures();
if (!u.isPersistableModel(this.model)) {
// XXX: Happens during tests, nothing to do if this
// is a hanging chatbox (i.e. not in the collection anymore).
return;
}
this.populateAndJoin();
} else {
this.fetchMessages();
}
/**
* Triggered once a groupchat has been opened
* @event _converse#chatRoomOpened
* @type { _converse.ChatRoomView }
* @example _converse.api.listen.on('chatRoomOpened', view => { ... });
*/
_converse.api.trigger('chatRoomOpened', this);
},
render () {
this.el.setAttribute('id', this.model.get('box_id'));
this.el.innerHTML = tpl_chatroom();
this.renderHeading();
this.renderChatArea();
this.renderBottomPanel();
if (this.model.get('connection_status') !== converse.ROOMSTATUS.ENTERED) {
this.showSpinner();
}
return this;
},
renderHeading () {
/* Render the heading UI of the groupchat. */
this.el.querySelector('.chat-head-chatroom').innerHTML = this.generateHeadingHTML();
},
renderBottomPanel () {
const container = this.el.querySelector('.bottom-panel');
if (this.model.features.get('moderated') && this.model.get('role') === 'visitor') {
container.innerHTML = tpl_chatroom_bottom_panel({'__': __});
} else {
if (!container.firstElementChild || !container.querySelector('.sendXMPPMessage')) {
this.renderMessageForm();
this.initMentionAutoComplete();
}
}
},
renderChatArea () {
/* Render the UI container in which groupchat messages will appear.
*/
if (_.isNull(this.el.querySelector('.chat-area'))) {
const container_el = this.el.querySelector('.chatroom-body');
container_el.insertAdjacentHTML('beforeend', tpl_chatarea({
'show_send_button': _converse.show_send_button
}));
container_el.insertAdjacentElement('beforeend', this.occupantsview.el);
this.content = this.el.querySelector('.chat-content');
this.toggleOccupants(null, true);
}
return this;
},
initMentionAutoComplete () {
this.mention_auto_complete = new _converse.AutoComplete(this.el, {
'auto_first': true,
'auto_evaluate': false,
'min_chars': 1,
'match_current_word': true,
'list': () => this.model.occupants.map(o => ({'label': o.getDisplayName(), 'value': `@${o.getDisplayName()}`})),
'filter': _converse.FILTER_STARTSWITH,
'ac_triggers': ["Tab", "@"],
'include_triggers': []
});
this.mention_auto_complete.on('suggestion-box-selectcomplete', () => (this.auto_completing = false));
},
keyPressed (ev) {
if (this.mention_auto_complete.keyPressed(ev)) {
return;
}
return _converse.ChatBoxView.prototype.keyPressed.apply(this, arguments);
},
keyUp (ev) {
this.mention_auto_complete.evaluate(ev);
},
showRoomDetailsModal (ev) {
ev.preventDefault();
if (_.isUndefined(this.model.room_details_modal)) {
this.model.room_details_modal = new _converse.RoomDetailsModal({'model': this.model});
}
this.model.room_details_modal.show(ev);
},
showChatStateNotification (message) {
if (message.get('sender') === 'me') {
return;
}
return _converse.ChatBoxView.prototype.showChatStateNotification.apply(this, arguments);
},
createOccupantsView () {
/* Create the ChatRoomOccupantsView Backbone.NativeView
*/
this.model.occupants.chatroomview = this;
this.occupantsview = new _converse.ChatRoomOccupantsView({'model': this.model.occupants});
return this;
},
informOfOccupantsAffiliationChange(occupant, changed) {
const previous_affiliation = occupant._previousAttributes.affiliation,
current_affiliation = occupant.get('affiliation');
if (previous_affiliation === 'admin') {
this.showChatEvent(__("%1$s is no longer an admin of this groupchat", occupant.get('nick')))
} else if (previous_affiliation === 'owner') {
this.showChatEvent(__("%1$s is no longer an owner of this groupchat", occupant.get('nick')))
} else if (previous_affiliation === 'outcast') {
this.showChatEvent(__("%1$s is no longer banned from this groupchat", occupant.get('nick')))
}
if (current_affiliation === 'none' && previous_affiliation === 'member') {
this.showChatEvent(__("%1$s is no longer a permanent member of this groupchat", occupant.get('nick')))
} if (current_affiliation === 'member') {
this.showChatEvent(__("%1$s is now a permanent member of this groupchat", occupant.get('nick')))
} else if (current_affiliation === 'outcast') {
this.showChatEvent(__("%1$s has been banned from this groupchat", occupant.get('nick')))
} else if (current_affiliation === 'admin' || current_affiliation == 'owner') {
// For example: AppleJack is now an (admin|owner) of this groupchat
this.showChatEvent(__('%1$s is now an %2$s of this groupchat', occupant.get('nick'), current_affiliation))
}
},
informOfOccupantsRoleChange (occupant, changed) {
if (changed === "none") {
return;
}
const previous_role = occupant._previousAttributes.role;
if (previous_role === 'moderator') {
this.showChatEvent(__("%1$s is no longer a moderator", occupant.get('nick')))
}
if (previous_role === 'visitor') {
this.showChatEvent(__("%1$s has been given a voice again", occupant.get('nick')))
}
if (occupant.get('role') === 'visitor') {
this.showChatEvent(__("%1$s has been muted", occupant.get('nick')))
}
if (occupant.get('role') === 'moderator') {
this.showChatEvent(__("%1$s is now a moderator", occupant.get('nick')))
}
},
generateHeadingHTML () {
/* Returns the heading HTML to be rendered.
*/
return tpl_chatroom_head(
_.extend(this.model.toJSON(), {
'_converse': _converse,
'Strophe': Strophe,
'info_close': __('Close and leave this groupchat'),
'info_configure': __('Configure this groupchat'),
'info_details': __('Show more details about this groupchat'),
'description': u.addHyperlinks(xss.filterXSS(_.get(this.model.get('subject'), 'text'), {'whiteList': {}})),
}));
},
afterShown () {
/* Override from converse-chatview, specifically to avoid
* the 'active' chat state from being sent out prematurely.
*
* This is instead done in `afterConnected` below.
*/
if (u.isPersistableModel(this.model)) {
this.model.clearUnreadMsgCounter();
this.model.save();
}
this.occupantsview.setOccupantsHeight();
this.scrollDown();
this.renderEmojiPicker();
},
show () {
if (u.isVisible(this.el)) {
this.focus();
return;
}
// Override from converse-chatview in order to not use
// "fadeIn", which causes flashing.
u.showElement(this.el);
this.afterShown();
},
afterConnected () {
if (this.model.get('connection_status') === converse.ROOMSTATUS.ENTERED) {
this.hideSpinner();
this.setChatState(_converse.ACTIVE);
this.scrollDown();
this.focus();
}
},
getToolbarOptions () {
return _.extend(
_converse.ChatBoxView.prototype.getToolbarOptions.apply(this, arguments),
{
'label_hide_occupants': __('Hide the list of participants'),
'show_occupants_toggle': this.is_chatroom && _converse.visible_toolbar_buttons.toggle_occupants
}
);
},
close (ev) {
/* Close this chat box, which implies leaving the groupchat as
* well.
*/
this.hide();
if (Backbone.history.getFragment() === "converse/room?jid="+this.model.get('jid')) {
_converse.router.navigate('');
}
this.model.leave();
_converse.ChatBoxView.prototype.close.apply(this, arguments);
},
setOccupantsVisibility () {
const icon_el = this.el.querySelector('.toggle-occupants');
if (this.model.get('hidden_occupants')) {
u.removeClass('fa-angle-double-right', icon_el);
u.addClass('fa-angle-double-left', icon_el);
const chat_area = this.el.querySelector('.chat-area');
u.removeClass('col-md-9', chat_area);
u.removeClass('col-8', chat_area);
u.addClass('full', chat_area);
u.addClass('col-12', chat_area);
u.hideElement(this.el.querySelector('.occupants'));
} else {
const chat_area = this.el.querySelector('.chat-area');
u.addClass('fa-angle-double-right', icon_el);
u.removeClass('fa-angle-double-left', icon_el);
u.removeClass('hidden', this.el.querySelector('.occupants'));
u.removeClass('full', chat_area);
u.removeClass('col-12', chat_area);
u.addClass('col-md-9', chat_area);
u.addClass('col-8', chat_area);
}
this.occupantsview.setOccupantsHeight();
},
hideOccupants (ev, preserve_state) {
/* Show or hide the right sidebar containing the chat
* occupants (and the invite widget).
*/
if (ev) {
ev.preventDefault();
ev.stopPropagation();
}
this.model.save({'hidden_occupants': true});
this.setOccupantsVisibility();
this.scrollDown();
},
toggleOccupants (ev, preserve_state) {
/* Show or hide the right sidebar containing the chat
* occupants (and the invite widget).
*/
if (ev) {
ev.preventDefault();
ev.stopPropagation();
}
if (!preserve_state) {
this.model.set({'hidden_occupants': !this.model.get('hidden_occupants')});
}
this.setOccupantsVisibility();
this.scrollDown();
},
onOccupantClicked (ev) {
/* When an occupant is clicked, insert their nickname into
* the chat textarea input.
*/
this.insertIntoTextArea(ev.target.textContent);
},
handleChatStateNotification (message) {
/* Override the method on the ChatBoxView base class to
* ignore
${instructions}
`); } _.each(fields, field => { if (_converse.roomconfig_whitelist.length === 0 || _.includes(_converse.roomconfig_whitelist, field.getAttribute('var'))) { fieldset_el.insertAdjacentHTML('beforeend', u.xForm2webForm(field, stanza)); } }); // Render save/cancel buttons const last_fieldset_el = document.createElement('fieldset'); last_fieldset_el.insertAdjacentHTML( 'beforeend', ``); last_fieldset_el.insertAdjacentHTML( 'beforeend', ``); form_el.insertAdjacentElement('beforeend', last_fieldset_el); last_fieldset_el.querySelector('input[type=button]').addEventListener('click', (ev) => { ev.preventDefault(); this.closeForm(); }); form_el.addEventListener('submit', (ev) => { ev.preventDefault(); this.model.saveConfiguration(ev.target) .then(() => this.model.refreshRoomFeatures()); this.closeForm(); }, false ); }, closeForm () { /* Remove the configuration form without submitting and * return to the chat view. */ u.removeElement(this.el.querySelector('.chatroom-form-container')); this.renderAfterTransition(); }, getAndRenderConfigurationForm (ev) { /* Start the process of configuring a groupchat, either by * rendering a configuration form, or by auto-configuring * based on the "roomconfig" data stored on the * Backbone.Model. * * Stores the new configuration on the Backbone.Model once * completed. * * Paremeters: * (Event) ev: DOM event that might be passed in if this * method is called due to a user action. In this * case, auto-configure won't happen, regardless of * the settings. */ this.showSpinner(); this.model.fetchRoomConfiguration() .then(iq => this.renderConfigurationForm(iq)) .catch(_.partial(_converse.log, _, Strophe.LogLevel.ERROR)); }, submitNickname (ev) { /* Get the nickname value from the form and then join the * groupchat with it. */ ev.preventDefault(); const nick_el = ev.target.nick; const nick = nick_el.value; if (!nick) { nick_el.classList.add('error'); return; } else { nick_el.classList.remove('error'); } this.el.querySelector('.chatroom-form-container').outerHTML = tpl_spinner(); this.join(nick); }, checkForReservedNick () { /* User service-discovery to ask the XMPP server whether * this user has a reserved nickname for this groupchat. * If so, we'll use that, otherwise we render the nickname form. */ this.showSpinner(); this.model.checkForReservedNick() .then(this.onReservedNickFound.bind(this)) .catch(this.onReservedNickNotFound.bind(this)); }, onReservedNickFound (iq) { if (this.model.get('nick')) { this.join(); } else { this.onReservedNickNotFound(); } }, onReservedNickNotFound (message) { const nick = _converse.getDefaultMUCNickname(); if (nick) { this.join(nick); } else { this.renderNicknameForm(message); } }, onNicknameClash (presence) { /* When the nickname is already taken, we either render a * form for the user to choose a new nickname, or we * try to make the nickname unique by adding an integer to * it. So john will become john-2, and then john-3 and so on. * * Which option is take depends on the value of * muc_nickname_from_jid. */ if (_converse.muc_nickname_from_jid) { const nick = presence.getAttribute('from').split('/')[1]; if (nick === _converse.getDefaultMUCNickname()) { this.join(nick + '-2'); } else { const del= nick.lastIndexOf("-"); const num = nick.substring(del+1, nick.length); this.join(nick.substring(0, del+1) + String(Number(num)+1)); } } else { this.renderNicknameForm( __("The nickname you chose is reserved or "+ "currently in use, please choose a different one.") ); } }, hideChatRoomContents () { const container_el = this.el.querySelector('.chatroom-body'); if (!_.isNull(container_el)) { _.each(container_el.children, (child) => { child.classList.add('hidden'); }); } }, renderNicknameForm (message) { /* Render a form which allows the user to choose their * nickname. */ this.hideChatRoomContents(); _.each(this.el.querySelectorAll('span.centered.spinner'), u.removeElement); if (!_.isString(message)) { message = ''; } const container_el = this.el.querySelector('.chatroom-body'); container_el.insertAdjacentHTML( 'beforeend', tpl_chatroom_nickname_form({ heading: __('Please choose your nickname'), label_nickname: __('Nickname'), label_join: __('Enter groupchat'), validation_message: message })); this.model.save('connection_status', converse.ROOMSTATUS.NICKNAME_REQUIRED); const form_el = this.el.querySelector('.chatroom-form'); form_el.addEventListener('submit', this.submitNickname.bind(this), false); }, submitPassword (ev) { ev.preventDefault(); const password = this.el.querySelector('.chatroom-form input[type=password]').value; this.showSpinner(); this.join(this.model.get('nick'), password); }, renderPasswordForm () { const container_el = this.el.querySelector('.chatroom-body'); _.each(container_el.children, u.hideElement); _.each(this.el.querySelectorAll('.spinner'), u.removeElement); _.each(this.el.querySelectorAll('.chatroom-form-container'), u.removeElement); container_el.insertAdjacentHTML('beforeend', tpl_chatroom_password_form({ 'heading': __('This groupchat requires a password'), 'label_password': __('Password: '), 'label_submit': __('Submit') })); this.model.save('connection_status', converse.ROOMSTATUS.PASSWORD_REQUIRED); this.el.querySelector('.chatroom-form') .addEventListener('submit', ev => this.submitPassword(ev), false); }, showDestroyedMessage (error) { u.hideElement(this.el.querySelector('.chat-area')); u.hideElement(this.el.querySelector('.occupants')); _.each(this.el.querySelectorAll('.spinner'), u.removeElement); const container = this.el.querySelector('.disconnect-container'); const moved_jid = _.get( sizzle('gone[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]', error).pop(), 'textContent' ).replace(/^xmpp:/, '').replace(/\?join$/, ''); const reason = _.get( sizzle('text[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]', error).pop(), 'textContent' ); container.innerHTML = tpl_chatroom_destroyed({ '_': _, '__':__, 'jid': moved_jid, 'reason': reason ? `"${reason}"` : null }); const switch_el = container.querySelector('a.switch-chat'); if (switch_el) { switch_el.addEventListener('click', ev => { ev.preventDefault(); this.model.save('jid', moved_jid); container.innerHTML = ''; this.showSpinner(); this.enterRoom(); }); } u.showElement(container); }, showDisconnectMessages (msgs) { if (_.isString(msgs)) { msgs = [msgs]; } u.hideElement(this.el.querySelector('.chat-area')); u.hideElement(this.el.querySelector('.occupants')); _.each(this.el.querySelectorAll('.spinner'), u.removeElement); const container = this.el.querySelector('.disconnect-container'); container.innerHTML = tpl_chatroom_disconnect({ '_': _, 'disconnect_messages': msgs }) u.showElement(container); }, /** * @private * @method _converse.ChatRoomView#getMessageFromStatus * @param { XMLElement } stat: A