-
-
Notifications
You must be signed in to change notification settings - Fork 763
/
converse-muc-views.js
2444 lines (2234 loc) · 109 KB
/
converse-muc-views.js
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Converse.js
// https://conversejs.org
//
// Copyright (c) 2013-2019, the Converse.js developers
// Licensed under the Mozilla Public License (MPLv2)
//
/**
* @module converse-muc-views
* @description
* XEP-0045 Multi-User Chat Views
*/
import "converse-modal";
import "backbone.vdomview";
import "formdata-polyfill";
import "@converse/headless/utils/muc";
import { OrderedListView } from "backbone.overview";
import converse from "@converse/headless/converse-core";
import log from "@converse/headless/log";
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_moderator_tools_modal from "templates/moderator_tools_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/dist/xss";
const { Backbone, Strophe, sizzle, _, $iq, $pres } = converse.env;
const u = converse.env.utils;
const ROLES = ['moderator', 'participant', 'visitor'];
const AFFILIATIONS = ['admin', 'member', 'outcast', 'owner'];
const OWNER_COMMANDS = ['owner'];
const ADMIN_COMMANDS = ['admin', 'ban', 'deop', 'destroy', 'member', 'op', 'revoke'];
const MODERATOR_COMMANDS = ['kick', 'mute', 'voice', 'modtools'];
const VISITOR_COMMANDS = ['nick'];
const COMMAND_TO_ROLE = {
'deop': 'participant',
'kick': 'none',
'mute': 'visitor',
'op': 'moderator',
'voice': 'participant'
}
const COMMAND_TO_AFFILIATION = {
'admin': 'admin',
'ban': 'outcast',
'member': 'member',
'owner': 'owner',
'revoke': 'none'
}
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: {
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_nickname': false,
'show_retraction_warning': true,
'muc_disable_slash_commands': false,
'muc_show_join_leave': true,
'muc_show_join_leave_status': true,
'muc_mention_autocomplete_min_chars': 0,
'muc_mention_autocomplete_filter': 'contains',
'muc_mention_autocomplete_show_avatar': true,
'roomconfig_whitelist': [],
'visible_toolbar_buttons': {
'toggle_occupants': true
}
});
const viewWithRoomsPanel = {
renderRoomsPanel () {
if (this.roomspanel && u.isInDOM(this.roomspanel.el)) {
return this.roomspanel;
}
const id = `converse.roomspanel${_converse.bare_jid}`;
this.roomspanel = new _converse.RoomsPanel({
'model': new (_converse.RoomsPanelModel.extend({
id,
'browserStorage': _converse.createStore(id)
}))()
});
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');
return this.roomspanel;
},
getRoomsPanel () {
if (this.roomspanel && u.isInDOM(this.roomspanel.el)) {
return this.roomspanel;
} else {
return this.renderRoomsPanel();
}
}
}
if (_converse.ControlBoxView) {
Object.assign(_converse.ControlBoxView.prototype, viewWithRoomsPanel);
}
/* 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')
}));
}
/**
* Show/hide extra information about a groupchat in a listing.
* @function toggleRoomInfo
* @param { Event }
*/
function toggleRoomInfo (ev) {
const parent_el = u.ancestor(ev.target, '.room-item');
const 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(e => log.error(e));
}
}
_converse.ModeratorToolsModal = _converse.BootstrapModal.extend({
events: {
'submit .affiliation-form': 'assignAffiliation',
'submit .role-form': 'assignRole',
'submit .query-affiliation': 'queryAffiliation',
'submit .query-role': 'queryRole',
'click .nav-item .nav-link': 'switchTab',
'click .toggle-form': 'toggleForm',
},
initialize (attrs) {
this.chatroomview = attrs.chatroomview;
_converse.BootstrapModal.prototype.initialize.apply(this, arguments);
this.listenTo(this.model, 'change:role', () => {
this.users_with_role = this.getUsersWithRole();
this.render();
});
this.listenTo(this.model, 'change:affiliation', async () => {
this.loading_users_with_affiliation = true;
this.users_with_affiliation = null;
this.render();
const affiliation = this.model.get('affiliation');
if (!_converse.muc_fetch_members || affiliation === 'outcast') {
this.users_with_affiliation = await this.chatroomview.model.getAffiliationList(affiliation);
} else {
this.users_with_affiliation = this.getUsersWithAffiliation();
}
this.loading_users_with_affiliation = false;
this.render();
});
},
toHTML () {
const allowed_commands = this.chatroomview.getAllowedCommands();
const allowed_affiliations = allowed_commands.map(c => COMMAND_TO_AFFILIATION[c]).filter(c => c);
const allowed_roles = _.uniq(allowed_commands
.map(c => COMMAND_TO_ROLE[c])
.filter(c => c));
allowed_affiliations.sort();
allowed_roles.sort();
return tpl_moderator_tools_modal(Object.assign(this.model.toJSON(), {
'__': __,
'affiliations': [...AFFILIATIONS, 'none'],
'allowed_affiliations': allowed_affiliations,
'allowed_roles': allowed_roles,
'loading_users_with_affiliation': this.loading_users_with_affiliation,
'roles': ROLES,
'users_with_affiliation': this.users_with_affiliation,
'users_with_role': this.users_with_role
}));
},
toggleForm (ev) {
ev.stopPropagation();
ev.preventDefault();
const form_class = ev.target.getAttribute('data-form');
const form = u.ancestor(ev.target, '.list-group-item').querySelector(`.${form_class}`);
if (u.hasClass('hidden', form)) {
u.removeClass('hidden', form);
} else {
u.addClass('hidden', form);
}
},
getUsersWithAffiliation () {
return this.chatroomview.model.occupants
.where({'affiliation': this.model.get('affiliation')})
.map(item => {
return {
'jid': item.get('jid'),
'nick': item.get('nick'),
'affiliation': item.get('affiliation')
}
});
},
getUsersWithRole () {
return this.chatroomview.model.occupants
.where({'role': this.model.get('role')})
.map(item => {
return {
'jid': item.get('jid'),
'nick': item.get('nick'),
'role': item.get('role')
}
});
},
queryRole (ev) {
ev.stopPropagation();
ev.preventDefault();
const data = new FormData(ev.target);
const role = data.get('role');
this.model.set({'role': null}, {'silent': true});
this.model.set({'role': role});
},
queryAffiliation (ev) {
ev.stopPropagation();
ev.preventDefault();
const data = new FormData(ev.target);
const affiliation = data.get('affiliation');
this.model.set({'affiliation': null}, {'silent': true});
this.model.set({'affiliation': affiliation});
},
assignAffiliation (ev) {
ev.stopPropagation();
ev.preventDefault();
const data = new FormData(ev.target);
const affiliation = data.get('affiliation');
const attrs = {
'jid': data.get('jid'),
'reason': data.get('reason')
}
const current_affiliation = this.model.get('affiliation');
this.chatroomview.model.setAffiliation(affiliation, [attrs])
.then(async () => {
this.alert(__('Affiliation changed'), 'primary');
await this.chatroomview.model.occupants.fetchMembers()
this.model.set({'affiliation': null}, {'silent': true});
this.model.set({'affiliation': current_affiliation});
})
.catch(err => {
this.alert(__('Sorry, something went wrong while trying to set the affiliation'), 'danger');
log.error(err);
});
},
assignRole (ev) {
ev.stopPropagation();
ev.preventDefault();
const data = new FormData(ev.target);
const occupant = this.chatroomview.model.getOccupant(data.get('jid') || data.get('nick'));
const role = data.get('role');
const reason = data.get('reason');
const current_role = this.model.get('role');
this.chatroomview.model.setRole(occupant, role, reason,
() => {
this.alert(__('Role changed'), 'primary');
this.model.set({'role': null}, {'silent': true});
this.model.set({'role': current_role});
},
(e) => {
if (sizzle(`not-allowed[xmlns="${Strophe.NS.STANZAS}"]`, e).length) {
this.alert(__('You\'re not allowed to make that change'), 'danger');
} else {
this.alert(__('Sorry, something went wrong while trying to set the role'), 'danger');
if (u.isErrorObject(e)) {
log.error(e);
}
}
}
);
}
});
_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.listenTo(this.model, 'change:muc_domain', this.onDomainChange);
},
toHTML () {
const muc_domain = this.model.get('muc_domain') || _converse.muc_domain;
return tpl_list_chatrooms_modal(Object.assign(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 () {
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 () {
sizzle('.spinner', this.el).forEach(u.removeElement);
},
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');
const rooms = sizzle('query item', iq);
if (rooms.length) {
available_chatrooms.innerHTML = tpl_rooms_results({'feedback_text': __('Groupchats found:')});
const fragment = document.createDocumentFragment();
rooms.map(this.roomStanzaItemToHTMLElement)
.filter(r => r)
.forEach(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(() => 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.listenTo(this.model, 'change:muc_domain', this.render);
},
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(Object.assign(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, Object.assign(data, {jid}));
this.modal.hide();
ev.target.reset();
}
});
_converse.RoomDetailsModal = _converse.BootstrapModal.extend({
initialize () {
_converse.BootstrapModal.prototype.initialize.apply(this, arguments);
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model.occupants, 'add', this.render);
this.listenTo(this.model.occupants, 'change', this.render);
},
toHTML () {
return tpl_chatroom_details_modal(Object.assign(
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': {}}))
})
);
}
});
/**
* Backbone.NativeView which renders a groupchat, based upon
* { @link _converse.ChatBoxView } for normal one-on-one chat boxes.
* @class
* @namespace _converse.ChatRoomView
* @memberOf _converse
*/
_converse.ChatRoomView = _converse.ChatBoxView.extend({
length: 300,
tagName: 'div',
className: 'chatbox chatroom hidden',
is_chatroom: true,
events: {
'change input.fileupload': 'onFileSelection',
'click .chat-msg__action-edit': 'onMessageEditButtonClicked',
'click .chat-msg__action-retract': 'onMessageRetractButtonClicked',
'click .chatbox-navback': 'showControlBox',
'click .close-chatbox-button': 'close',
'click .configure-chatroom-button': 'getAndRenderConfigurationForm',
'click .hide-occupants': 'hideOccupants',
'click .new-msgs-indicator': 'viewUnreadMessages',
// Arrow functions don't work here because you can't bind a different `this` param to them.
'click .occupant-nick': function (ev) {this.insertIntoTextArea(ev.target.textContent) },
'click .send-button': 'onFormSubmitted',
'click .show-room-details-modal': 'showRoomDetailsModal',
'click .toggle-call': 'toggleCall',
'click .toggle-occupants': 'toggleOccupants',
'click .upload-file': 'toggleFileUpload',
'dragover .chat-textarea': 'onDragOver',
'drop .chat-textarea': 'onDrop',
'input .chat-textarea': 'inputChanged',
'keydown .chat-textarea': 'onKeyDown',
'keyup .chat-textarea': 'onKeyUp',
'mousedown .dragresize-occupants-left': 'onStartResizeOccupants',
'paste .chat-textarea': 'onPaste',
'submit .muc-nickname-form': 'submitNickname'
},
async initialize () {
this.initDebounced();
this.listenTo(this.model.messages, 'add', this.onMessageAdded);
this.listenTo(this.model.messages, 'rendered', this.scrollDown);
this.model.messages.on('reset', () => {
this.content.innerHTML = '';
this.removeAll();
});
this.listenTo(this.model, 'change', this.renderHeading);
this.listenTo(this.model.session, 'change:connection_status', this.onConnectionStatusChanged);
this.listenTo(this.model, 'change:hidden_occupants', this.updateOccupantsToggle);
this.listenTo(this.model, 'change:subject', this.setChatRoomSubject);
this.listenTo(this.model, 'configurationNeeded', this.getAndRenderConfigurationForm);
this.listenTo(this.model, 'destroy', this.hide);
this.listenTo(this.model, 'show', this.show);
this.listenTo(this.model.features, 'change:moderated', this.renderBottomPanel);
this.listenTo(this.model.occupants, 'add', this.onOccupantAdded);
this.listenTo(this.model.occupants, 'remove', this.onOccupantRemoved);
this.listenTo(this.model.occupants, 'change:show', this.showJoinOrLeaveNotification);
this.listenTo(this.model.occupants, 'change:role', this.onOccupantRoleChanged);
this.listenTo(this.model.occupants, 'change:affiliation', this.onOccupantAffiliationChanged);
// Bind so that we can pass it to addEventListener and removeEventListener
this.onMouseMove = this.onMouseMove.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
this.render();
this.createOccupantsView();
await this.updateAfterMessagesFetched();
this.onConnectionStatusChanged();
/**
* Triggered once a { @link _converse.ChatRoomView } has been opened
* @event _converse#chatRoomViewInitialized
* @type { _converse.ChatRoomView }
* @example _converse.api.listen.on('chatRoomViewInitialized', view => { ... });
*/
_converse.api.trigger('chatRoomViewInitialized', this);
},
render () {
this.el.setAttribute('id', this.model.get('box_id'));
this.el.innerHTML = tpl_chatroom();
this.renderHeading();
this.renderChatArea();
this.renderBottomPanel();
if (!_converse.muc_show_logs_before_join) {
this.model.session.get('connection_status') !== converse.ROOMSTATUS.ENTERED && this.showSpinner();
}
if (!this.model.get('hidden')) {
this.show();
}
return this;
},
renderHeading (item=null) {
/* Render the heading UI of the groupchat. */
const changed = _.get(item, 'changed', {});
const keys = ['affiliation', 'bookmarked', 'jid', 'name', 'description', 'subject'];
if (item === null || _.intersection(Object.keys(changed), keys).length) {
this.el.querySelector('.chat-head-chatroom').innerHTML = this.generateHeadingHTML();
}
},
renderBottomPanel () {
const container = this.el.querySelector('.bottom-panel');
const entered = this.model.session.get('connection_status') === converse.ROOMSTATUS.ENTERED;
const can_edit = entered && !(this.model.features.get('moderated') && this.model.getOwnRole() === 'visitor');
container.innerHTML = tpl_chatroom_bottom_panel({__, can_edit, entered});
if (entered && can_edit) {
this.renderMessageForm();
this.initMentionAutoComplete();
}
},
renderChatArea () {
// Render the UI container in which groupchat messages will appear.
if (this.el.querySelector('.chat-area') === null) {
const container_el = this.el.querySelector('.chatroom-body');
container_el.insertAdjacentHTML(
'beforeend',
tpl_chatarea({
__,
'muc_show_logs_before_join': _converse.muc_show_logs_before_join,
'show_send_button': _converse.show_send_button
})
);
this.content = this.el.querySelector('.chat-content');
}
return this;
},
createOccupantsView () {
this.model.occupants.chatroomview = this;
this.occupants_view = new _converse.ChatRoomOccupantsView({'model': this.model.occupants});
const container_el = this.el.querySelector('.chatroom-body');
const occupants_width = this.model.get('occupants_width');
if (this.occupants_view && occupants_width !== undefined) {
this.occupants_view.el.style.flex = "0 0 " + occupants_width + "px";
}
container_el.insertAdjacentElement('beforeend', this.occupants_view.el);
},
onStartResizeOccupants (ev) {
this.resizing = true;
this.el.addEventListener('mousemove', this.onMouseMove);
this.el.addEventListener('mouseup', this.onMouseUp);
const style = window.getComputedStyle(this.occupants_view.el);
this.width = parseInt(style.width.replace(/px$/, ''), 10);
this.prev_pageX = ev.pageX;
},
onMouseMove (ev) {
if (this.resizing) {
ev.preventDefault();
const delta = this.prev_pageX - ev.pageX;
this.resizeOccupantsView(delta, ev.pageX);
this.prev_pageX = ev.pageX;
}
},
onMouseUp (ev) {
if (this.resizing) {
ev.preventDefault();
this.resizing = false;
this.el.removeEventListener('mousemove', this.onMouseMove);
this.el.removeEventListener('mouseup', this.onMouseUp);
const element_position = this.occupants_view.el.getBoundingClientRect();
const occupants_width = this.calculateOccupantsWidth(element_position, 0);
const attrs = {occupants_width};
_converse.connection.connected ? this.model.save(attrs) : this.model.set(attrs);
}
},
resizeOccupantsView (delta, current_mouse_position) {
const element_position = this.occupants_view.el.getBoundingClientRect();
if (this.is_minimum) {
this.is_minimum = element_position.left < current_mouse_position;
} else if (this.is_maximum) {
this.is_maximum = element_position.left > current_mouse_position;
} else {
const occupants_width = this.calculateOccupantsWidth(element_position, delta);
this.occupants_view.el.style.flex = "0 0 " + occupants_width + "px";
}
},
calculateOccupantsWidth(element_position, delta) {
let occupants_width = element_position.width + delta;
const room_width = this.el.clientWidth;
// keeping display in boundaries
if (occupants_width < (room_width * 0.20)) {
// set pixel to 20% width
occupants_width = (room_width * 0.20);
this.is_minimum = true;
} else if (occupants_width > (room_width * 0.75)) {
// set pixel to 75% width
occupants_width = (room_width * 0.75);
this.is_maximum = true;
} else if ((room_width - occupants_width) < 250) {
// resize occupants if chat-area becomes smaller than 250px (min-width property set in css)
occupants_width = room_width - 250;
this.is_maximum = true;
} else {
this.is_maximum = false;
this.is_minimum = false;
}
return occupants_width;
},
getAutoCompleteList () {
return this.model.occupants.filter('nick').map(o => ({'label': o.get('nick'), 'value': `@${o.get('nick')}`}));
},
getAutoCompleteListItem(text, input) {
input = input.trim();
const element = document.createElement("li");
element.setAttribute("aria-selected", "false");
if (_converse.muc_mention_autocomplete_show_avatar) {
const img = document.createElement("img");
let dataUri = "data:" + _converse.DEFAULT_IMAGE_TYPE + ";base64," + _converse.DEFAULT_IMAGE;
if (_converse.vcards) {
const vcard = _converse.vcards.findWhere({'nickname': text});
if (vcard) dataUri = "data:" + vcard.get('image_type') + ";base64," + vcard.get('image');
}
img.setAttribute("src", dataUri);
img.setAttribute("width", "22");
img.setAttribute("class", "avatar avatar-autocomplete");
element.appendChild(img);
}
const regex = new RegExp("(" + input + ")", "ig");
const parts = input ? text.split(regex) : [text];
parts.forEach(txt => {
if (input && txt.match(regex)) {
const match = document.createElement("mark");
match.textContent = txt;
element.appendChild(match);
} else {
element.appendChild(document.createTextNode(txt));
}
});
return element;
},
initMentionAutoComplete () {
this.mention_auto_complete = new _converse.AutoComplete(this.el, {
'auto_first': true,
'auto_evaluate': false,
'min_chars': _converse.muc_mention_autocomplete_min_chars,
'match_current_word': true,
'list': () => this.getAutoCompleteList(),
'filter': _converse.muc_mention_autocomplete_filter == 'contains' ? _converse.FILTER_CONTAINS : _converse.FILTER_STARTSWITH,
'ac_triggers': ["Tab", "@"],
'include_triggers': [],
'item': this.getAutoCompleteListItem
});
this.mention_auto_complete.on('suggestion-box-selectcomplete', () => (this.auto_completing = false));
},
/**
* Get the nickname value from the form and then join the groupchat with it.
* @private
* @method _converse.ChatRoomView#submitNickname
* @param { Event }
*/
submitNickname (ev) {
ev.preventDefault();
const nick = ev.target.nick.value.trim();
nick && this.model.join(nick);
},
onKeyDown (ev) {
if (this.mention_auto_complete.onKeyDown(ev)) {
return;
}
return _converse.ChatBoxView.prototype.onKeyDown.call(this, ev);
},
onKeyUp (ev) {
this.mention_auto_complete.evaluate(ev);
return _converse.ChatBoxView.prototype.onKeyUp.call(this, ev);
},
async onMessageRetractButtonClicked (ev) {
ev.preventDefault();
const msg_el = u.ancestor(ev.target, '.message');
const msgid = msg_el.getAttribute('data-msgid');
const time = msg_el.getAttribute('data-isodate');
const message = this.model.messages.findWhere({msgid, time});
const retraction_warning =
__("Be aware that other XMPP/Jabber clients (and servers) may "+
"not yet support retractions and that this message may not "+
"be removed everywhere.");
if (message.get('sender') === 'me') {
const messages = [__('Are you sure you want to retract this message?')];
if (_converse.show_retraction_warning) {
messages[1] = retraction_warning;
}
const result = await _converse.api.confirm(__('Confirm'), messages);
if (result) {
this.retractOwnMessage(message);
}
} else {
let messages = [
__('You are about to retract this message.'),
__('You may optionally include a message, explaining the reason for the retraction.')
];
if (_converse.show_retraction_warning) {
messages = [messages[0], retraction_warning, messages[1]]
}
const reason = await _converse.api.prompt(
__('Message Retraction'),
messages,
__('Optional reason')
);
if (reason !== false) {
this.retractOtherMessage(message, reason);
}
}
},
/**
* Retract one of your messages in this groupchat.
* @private
* @method _converse.ChatRoomView#retractOwnMessage
* @param { _converse.Message } message - The message which we're retracting.
*/
retractOwnMessage(message) {
this.model.sendRetractionMessage(message)
.catch(e => {
message.save({
'retracted': undefined,
'retracted_id': undefined
});
const errmsg = __('Sorry, something went wrong while trying to retract your message.');
if (u.isErrorStanza(e)) {
this.showErrorMessage(errmsg);
} else {
this.showErrorMessage(errmsg);
this.showErrorMessage(e.message);
}
log.error(e);
});
message.save({
'retracted': (new Date()).toISOString(),
'retracted_id': message.get('origin_id')
});
},
/**
* Retract someone else's message in this groupchat.
* @private
* @method _converse.ChatRoomView#retractOtherMessage
* @param { _converse.Message } message - The message which we're retracting.
* @param { string } [reason] - The reason for retracting the message.
*/
async retractOtherMessage (message, reason) {
const result = await this.model.sendRetractionIQ(message, reason);
if (result === null) {
const err_msg = __(`A timeout occurred while trying to retract the message`);
_converse.api.alert('error', __('Error'), err_msg);
_converse.log(err_msg, Strophe.LogLevel.WARN);
} else if (u.isErrorStanza(result)) {
const err_msg = __(`Sorry, you're not allowed to retract this message.`);
_converse.api.alert('error', __('Error'), err_msg);
_converse.log(err_msg, Strophe.LogLevel.WARN);
_converse.log(result, Strophe.LogLevel.WARN);
} else {
message.save({
'moderated': 'retracted',
'moderated_by': _converse.bare_jid,
'moderated_id': message.get('msgid'),
'moderation_reason': reason
});
}