選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ChatRoom.js 62KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import isEqual from 'lodash.isequal';
  4. import { $iq, $msg, $pres, Strophe } from 'strophe.js';
  5. import * as JitsiTranscriptionStatus from '../../JitsiTranscriptionStatus';
  6. import { MediaType } from '../../service/RTC/MediaType';
  7. import { VideoType } from '../../service/RTC/VideoType';
  8. import { XMPPEvents } from '../../service/xmpp/XMPPEvents';
  9. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  10. import Listenable from '../util/Listenable';
  11. import AVModeration from './AVModeration';
  12. import BreakoutRooms from './BreakoutRooms';
  13. import Lobby from './Lobby';
  14. import RoomMetadata from './RoomMetadata';
  15. import XmppConnection from './XmppConnection';
  16. import Moderator from './moderator';
  17. const logger = getLogger(__filename);
  18. export const parser = {
  19. packet2JSON(xmlElement, nodes) {
  20. for (const child of Array.from(xmlElement.children)) {
  21. const node = {
  22. attributes: {},
  23. children: [],
  24. tagName: child.tagName
  25. };
  26. for (const attr of Array.from(child.attributes)) {
  27. node.attributes[attr.name] = attr.value;
  28. }
  29. const text = Strophe.getText(child);
  30. if (text) {
  31. // Using Strophe.getText will do work for traversing all direct
  32. // child text nodes but returns an escaped value, which is not
  33. // desirable at this point.
  34. node.value = Strophe.xmlunescape(text);
  35. }
  36. nodes.push(node);
  37. this.packet2JSON(child, node.children);
  38. }
  39. },
  40. json2packet(nodes, packet) {
  41. for (let i = 0; i < nodes.length; i++) {
  42. const node = nodes[i];
  43. if (node) {
  44. packet.c(node.tagName, node.attributes);
  45. if (node.value) {
  46. packet.t(node.value);
  47. }
  48. if (node.children) {
  49. this.json2packet(node.children, packet);
  50. }
  51. packet.up();
  52. }
  53. }
  54. // packet.up();
  55. }
  56. };
  57. /**
  58. * Returns array of JS objects from the presence JSON associated with the passed
  59. / nodeName
  60. * @param pres the presence JSON
  61. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  62. */
  63. export function filterNodeFromPresenceJSON(pres, nodeName) {
  64. const res = [];
  65. for (let i = 0; i < pres.length; i++) {
  66. if (pres[i].tagName === nodeName) {
  67. res.push(pres[i]);
  68. }
  69. }
  70. return res;
  71. }
  72. // XXX As ChatRoom constructs XMPP stanzas and Strophe is build around the idea
  73. // of chaining function calls, allow long function call chains.
  74. /* eslint-disable newline-per-chained-call */
  75. /**
  76. * Array of affiliations that are allowed in members only room.
  77. * @type {string[]}
  78. */
  79. const MEMBERS_AFFILIATIONS = [ 'owner', 'admin', 'member' ];
  80. /**
  81. *
  82. */
  83. export default class ChatRoom extends Listenable {
  84. /* eslint-disable max-params */
  85. /**
  86. *
  87. * @param {XmppConnection} connection - The XMPP connection instance.
  88. * @param jid
  89. * @param password
  90. * @param XMPP
  91. * @param options
  92. * @param {boolean} options.disableFocus - when set to {@code false} will
  93. * not invite Jicofo into the room.
  94. * @param {boolean} options.disableDiscoInfo - when set to {@code false} will skip disco info.
  95. * This is intended to be used only for lobby rooms.
  96. * @param {boolean} options.enableLobby - when set to {@code false} will skip creating lobby room.
  97. * @param {boolean} options.hiddenFromRecorderFeatureEnabled - when set to {@code true} we will check identity tag
  98. * for node presence.
  99. */
  100. constructor(connection, jid, password, XMPP, options) {
  101. super();
  102. this.xmpp = XMPP;
  103. this.connection = connection;
  104. this.roomjid = Strophe.getBareJidFromJid(jid);
  105. this.myroomjid = jid;
  106. this.password = password;
  107. this.replaceParticipant = false;
  108. logger.info(`Joined MUC as ${this.myroomjid}`);
  109. this.members = {};
  110. this.presMap = {};
  111. this.presHandlers = {};
  112. this._removeConnListeners = [];
  113. this.joined = false;
  114. this.inProgressEmitted = false;
  115. this.role = null;
  116. this.focusMucJid = null;
  117. this.noBridgeAvailable = false;
  118. this.options = options || {};
  119. this.moderator
  120. = new Moderator(this.roomjid, this.xmpp, this.eventEmitter, {
  121. connection: this.xmpp.options,
  122. conference: this.options
  123. });
  124. if (typeof this.options.enableLobby === 'undefined' || this.options.enableLobby) {
  125. this.lobby = new Lobby(this);
  126. }
  127. this.avModeration = new AVModeration(this);
  128. this.breakoutRooms = new BreakoutRooms(this);
  129. this.roomMetadata = new RoomMetadata(this);
  130. this.initPresenceMap(options);
  131. this.lastPresences = {};
  132. this.phoneNumber = null;
  133. this.phonePin = null;
  134. this.connectionTimes = {};
  135. this.participantPropertyListener = null;
  136. this.locked = false;
  137. this.transcriptionStatus = JitsiTranscriptionStatus.OFF;
  138. }
  139. /* eslint-enable max-params */
  140. /**
  141. *
  142. */
  143. initPresenceMap(options = {}) {
  144. this.presMap.to = this.myroomjid;
  145. this.presMap.xns = 'http://jabber.org/protocol/muc';
  146. this.presMap.nodes = [];
  147. if (options.statsId) {
  148. this.presMap.nodes.push({
  149. 'tagName': 'stats-id',
  150. 'value': options.statsId
  151. });
  152. }
  153. this.presenceUpdateTime = Date.now();
  154. }
  155. /**
  156. * Joins the chat room.
  157. * @param {string} password - Password to unlock room on joining.
  158. * @returns {Promise} - resolved when join completes. At the time of this
  159. * writing it's never rejected.
  160. */
  161. join(password, replaceParticipant) {
  162. this.password = password;
  163. this.replaceParticipant = replaceParticipant;
  164. return new Promise(resolve => {
  165. this.options.disableFocus
  166. && logger.info(`Conference focus disabled for ${this.roomjid}`);
  167. const preJoin
  168. = this.options.disableFocus
  169. ? Promise.resolve()
  170. : this.moderator.allocateConferenceFocus();
  171. preJoin.then(() => {
  172. this.sendPresence(true);
  173. this._removeConnListeners.push(
  174. this.connection.addEventListener(
  175. XmppConnection.Events.CONN_STATUS_CHANGED,
  176. this.onConnStatusChanged.bind(this))
  177. );
  178. resolve();
  179. });
  180. });
  181. }
  182. /**
  183. *
  184. * @param fromJoin - Whether this is initial presence to join the room.
  185. */
  186. sendPresence(fromJoin) {
  187. const to = this.presMap.to;
  188. if (!this.connection || !this.connection.connected || !to || (!this.joined && !fromJoin)) {
  189. // Too early to send presence - not initialized
  190. return;
  191. }
  192. const pres = $pres({ to });
  193. // xep-0045 defines: "including in the initial presence stanza an empty
  194. // <x/> element qualified by the 'http://jabber.org/protocol/muc'
  195. // namespace" and subsequent presences should not include that or it can
  196. // be considered as joining, and server can send us the message history
  197. // for the room on every presence
  198. if (fromJoin) {
  199. if (this.replaceParticipant) {
  200. pres.c('flip_device').up();
  201. }
  202. pres.c('x', { xmlns: this.presMap.xns });
  203. if (this.password) {
  204. pres.c('password').t(this.password).up();
  205. }
  206. if (this.options.billingId) {
  207. pres.c('billingid').t(this.options.billingId).up();
  208. }
  209. pres.up();
  210. }
  211. parser.json2packet(this.presMap.nodes, pres);
  212. // we store time we last synced presence state
  213. this.presenceSyncTime = Date.now();
  214. this.connection.send(pres);
  215. if (fromJoin) {
  216. // XXX We're pressed for time here because we're beginning a complex
  217. // and/or lengthy conference-establishment process which supposedly
  218. // involves multiple RTTs. We don't have the time to wait for
  219. // Strophe to decide to send our IQ.
  220. this.connection.flush();
  221. }
  222. }
  223. /**
  224. * Sends the presence unavailable, signaling the server
  225. * we want to leave the room.
  226. */
  227. doLeave(reason) {
  228. logger.log('do leave', this.myroomjid);
  229. const pres = $pres({
  230. to: this.myroomjid,
  231. type: 'unavailable'
  232. });
  233. if (reason) {
  234. pres.c('status').t(reason).up();
  235. }
  236. this.presMap.length = 0;
  237. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  238. // means that there may not be enough time to send the unavailable
  239. // presence. Switching Strophe to synchronous sending is not much of an
  240. // option because it may lead to a noticeable delay in navigating away
  241. // from the current location. As a compromise, we will try to increase
  242. // the chances of sending the unavailable presence within the short time
  243. // span that we have upon unloading by invoking flush() on the
  244. // connection. We flush() once before sending/queuing the unavailable
  245. // presence in order to attemtp to have the unavailable presence at the
  246. // top of the send queue. We flush() once more after sending/queuing the
  247. // unavailable presence in order to attempt to have it sent as soon as
  248. // possible.
  249. // FIXME do not use Strophe.Connection in the ChatRoom directly
  250. !this.connection.isUsingWebSocket && this.connection.flush();
  251. this.connection.send(pres);
  252. this.connection.flush();
  253. }
  254. /**
  255. *
  256. */
  257. discoRoomInfo() {
  258. // https://xmpp.org/extensions/xep-0045.html#disco-roominfo
  259. const getInfo
  260. = $iq({
  261. type: 'get',
  262. to: this.roomjid
  263. })
  264. .c('query', { xmlns: Strophe.NS.DISCO_INFO });
  265. this.connection.sendIQ(getInfo, result => {
  266. const locked
  267. = $(result).find('>query>feature[var="muc_passwordprotected"]')
  268. .length
  269. === 1;
  270. if (locked !== this.locked) {
  271. this.eventEmitter.emit(XMPPEvents.MUC_LOCK_CHANGED, locked);
  272. this.locked = locked;
  273. }
  274. const meetingIdValEl
  275. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_meetingId"]>value');
  276. if (meetingIdValEl.length) {
  277. this.setMeetingId(meetingIdValEl.text());
  278. } else {
  279. logger.warn('No meeting ID from backend');
  280. }
  281. const membersOnly = $(result).find('>query>feature[var="muc_membersonly"]').length === 1;
  282. const lobbyRoomField
  283. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_lobbyroom"]>value');
  284. if (this.lobby) {
  285. this.lobby.setLobbyRoomJid(lobbyRoomField && lobbyRoomField.length ? lobbyRoomField.text() : undefined);
  286. }
  287. const isBreakoutField
  288. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_isbreakout"]>value');
  289. const isBreakoutRoom = Boolean(isBreakoutField?.text());
  290. this.breakoutRooms._setIsBreakoutRoom(isBreakoutRoom);
  291. const breakoutMainRoomField
  292. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_breakout_main_room"]>value');
  293. if (breakoutMainRoomField?.length) {
  294. this.breakoutRooms._setMainRoomJid(breakoutMainRoomField.text());
  295. }
  296. if (membersOnly !== this.membersOnlyEnabled) {
  297. this.membersOnlyEnabled = membersOnly;
  298. this.eventEmitter.emit(XMPPEvents.MUC_MEMBERS_ONLY_CHANGED, membersOnly);
  299. }
  300. const roomMetadataEl
  301. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_jitsimetadata"]>value');
  302. const roomMetadataText = roomMetadataEl?.text();
  303. if (roomMetadataText) {
  304. try {
  305. this.roomMetadata._handleMessages(JSON.parse(roomMetadataText));
  306. } catch (e) {
  307. logger.warn('Failed to set room metadata', e);
  308. }
  309. }
  310. }, error => {
  311. GlobalOnErrorHandler.callErrorHandler(error);
  312. logger.error('Error getting room info: ', error);
  313. });
  314. }
  315. /**
  316. * Sets the meeting unique Id (received from the backend).
  317. *
  318. * @param {string} meetingId - The new meetings id.
  319. * @returns {void}
  320. */
  321. setMeetingId(meetingId) {
  322. if (this.meetingId !== meetingId) {
  323. if (this.meetingId) {
  324. logger.warn(`Meeting Id changed from:${this.meetingId} to:${meetingId}`);
  325. }
  326. this.meetingId = meetingId;
  327. this.eventEmitter.emit(XMPPEvents.MEETING_ID_SET, meetingId);
  328. }
  329. }
  330. /**
  331. *
  332. */
  333. createNonAnonymousRoom() {
  334. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  335. if (this.options.disableDiscoInfo) {
  336. return;
  337. }
  338. const getForm = $iq({ type: 'get',
  339. to: this.roomjid })
  340. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' })
  341. .c('x', { xmlns: 'jabber:x:data',
  342. type: 'submit' });
  343. this.connection.sendIQ(getForm, form => {
  344. if (!$(form).find(
  345. '>query>x[xmlns="jabber:x:data"]'
  346. + '>field[var="muc#roomconfig_whois"]').length) {
  347. const errmsg = 'non-anonymous rooms not supported';
  348. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  349. logger.error(errmsg);
  350. return;
  351. }
  352. const formSubmit = $iq({ to: this.roomjid,
  353. type: 'set' })
  354. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  355. formSubmit.c('x', { xmlns: 'jabber:x:data',
  356. type: 'submit' });
  357. formSubmit.c('field', { 'var': 'FORM_TYPE' })
  358. .c('value')
  359. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  360. formSubmit.c('field', { 'var': 'muc#roomconfig_whois' })
  361. .c('value').t('anyone').up().up();
  362. this.connection.sendIQ(formSubmit);
  363. }, error => {
  364. GlobalOnErrorHandler.callErrorHandler(error);
  365. logger.error('Error getting room configuration form: ', error);
  366. });
  367. }
  368. /**
  369. * Handles Xmpp Connection status updates.
  370. *
  371. * @param {Strophe.Status} status - The Strophe connection status.
  372. */
  373. onConnStatusChanged(status) {
  374. // Send cached presence when the XMPP connection is re-established, only if needed
  375. if (status === XmppConnection.Status.CONNECTED && this.presenceUpdateTime > this.presenceSyncTime) {
  376. this.sendPresence();
  377. }
  378. }
  379. /**
  380. *
  381. * @param pres
  382. */
  383. onPresence(pres) {
  384. const from = pres.getAttribute('from');
  385. const member = {};
  386. const statusEl = pres.getElementsByTagName('status')[0];
  387. if (statusEl) {
  388. member.status = statusEl.textContent || '';
  389. }
  390. let hasStatusUpdate = false;
  391. let hasVersionUpdate = false;
  392. const xElement
  393. = pres.getElementsByTagNameNS(
  394. 'http://jabber.org/protocol/muc#user', 'x')[0];
  395. const mucUserItem
  396. = xElement && xElement.getElementsByTagName('item')[0];
  397. member.isReplaceParticipant
  398. = pres.getElementsByTagName('flip_device').length;
  399. member.affiliation
  400. = mucUserItem && mucUserItem.getAttribute('affiliation');
  401. member.role = mucUserItem && mucUserItem.getAttribute('role');
  402. // Focus recognition
  403. const jid = mucUserItem && mucUserItem.getAttribute('jid');
  404. member.jid = jid;
  405. member.isFocus
  406. = jid && jid.indexOf(`${this.moderator.getFocusUserJid()}/`) === 0;
  407. member.isHiddenDomain
  408. = jid && jid.indexOf('@') > 0
  409. && this.options.hiddenDomain
  410. === jid.substring(jid.indexOf('@') + 1, jid.indexOf('/'));
  411. this.eventEmitter.emit(XMPPEvents.PRESENCE_RECEIVED, {
  412. fromHiddenDomain: member.isHiddenDomain,
  413. presence: pres
  414. });
  415. const xEl = pres.querySelector('x');
  416. if (xEl) {
  417. xEl.remove();
  418. }
  419. const nodes = [];
  420. parser.packet2JSON(pres, nodes);
  421. this.lastPresences[from] = nodes;
  422. // process nodes to extract data needed for MUC_JOINED and
  423. // MUC_MEMBER_JOINED events
  424. const extractIdentityInformation = node => {
  425. const identity = {};
  426. const userInfo = node.children.find(c => c.tagName === 'user');
  427. if (userInfo) {
  428. identity.user = {};
  429. const tags = [ 'id', 'name', 'avatar' ];
  430. if (this.options.hiddenFromRecorderFeatureEnabled) {
  431. tags.push('hidden-from-recorder');
  432. }
  433. for (const tag of tags) {
  434. const child
  435. = userInfo.children.find(c => c.tagName === tag);
  436. if (child) {
  437. identity.user[tag] = child.value;
  438. }
  439. }
  440. }
  441. const groupInfo = node.children.find(c => c.tagName === 'group');
  442. if (groupInfo) {
  443. identity.group = groupInfo.value;
  444. }
  445. return identity;
  446. };
  447. for (let i = 0; i < nodes.length; i++) {
  448. const node = nodes[i];
  449. switch (node.tagName) {
  450. case 'bot': {
  451. const { attributes } = node;
  452. if (!attributes) {
  453. break;
  454. }
  455. const { type } = attributes;
  456. member.botType = type;
  457. break;
  458. }
  459. case 'nick':
  460. member.nick = node.value;
  461. break;
  462. case 'userId':
  463. member.id = node.value;
  464. break;
  465. case 'stats-id':
  466. member.statsID = node.value;
  467. break;
  468. case 'identity':
  469. member.identity = extractIdentityInformation(node);
  470. break;
  471. case 'features': {
  472. member.features = this._extractFeatures(node);
  473. break;
  474. }
  475. case 'stat': {
  476. const { attributes } = node;
  477. if (!attributes) {
  478. break;
  479. }
  480. const { name } = attributes;
  481. if (name === 'version') {
  482. member.version = attributes.value;
  483. }
  484. break;
  485. }
  486. }
  487. }
  488. if (!this.joined && !this.inProgressEmitted) {
  489. const now = this.connectionTimes['muc.join.started'] = window.performance.now();
  490. logger.log('(TIME) MUC join started:\t', now);
  491. this.eventEmitter.emit(XMPPEvents.MUC_JOIN_IN_PROGRESS);
  492. this.inProgressEmitted = true;
  493. }
  494. if (from === this.myroomjid) {
  495. const newRole
  496. = member.affiliation === 'owner' ? member.role : 'none';
  497. if (this.role !== newRole) {
  498. this.role = newRole;
  499. this.eventEmitter.emit(
  500. XMPPEvents.LOCAL_ROLE_CHANGED,
  501. this.role);
  502. }
  503. if (!this.joined) {
  504. this.joined = true;
  505. const now = this.connectionTimes['muc.joined']
  506. = window.performance.now();
  507. logger.log('(TIME) MUC joined:\t', now);
  508. // set correct initial state of locked
  509. if (this.password) {
  510. this.locked = true;
  511. }
  512. // Re-send presence in case any presence updates were added,
  513. // but blocked from sending, during the join process.
  514. // send the presence only if there was a modification after we had synced it
  515. if (this.presenceUpdateTime >= this.presenceSyncTime) {
  516. this.sendPresence();
  517. }
  518. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  519. // Now let's check the disco-info to retrieve the
  520. // meeting Id if any
  521. !this.options.disableDiscoInfo && this.discoRoomInfo();
  522. }
  523. } else if (jid === undefined) {
  524. logger.info('Ignoring member with undefined JID');
  525. } else if (this.members[from] === undefined) {
  526. // new participant
  527. this.members[from] = member;
  528. logger.log('entered', from, member);
  529. hasStatusUpdate = member.status !== undefined;
  530. hasVersionUpdate = member.version !== undefined;
  531. if (member.isFocus) {
  532. this._initFocus(from, member.features);
  533. } else {
  534. // identity is being added to member joined, so external
  535. // services can be notified for that (currently identity is
  536. // not used inside library)
  537. this.eventEmitter.emit(
  538. XMPPEvents.MUC_MEMBER_JOINED,
  539. from,
  540. member.nick,
  541. member.role,
  542. member.isHiddenDomain,
  543. member.statsID,
  544. member.status,
  545. member.identity,
  546. member.botType,
  547. member.jid,
  548. member.features,
  549. member.isReplaceParticipant);
  550. // we are reporting the status with the join
  551. // so we do not want a second event about status update
  552. hasStatusUpdate = false;
  553. }
  554. } else {
  555. // Presence update for existing participant
  556. // Watch role change:
  557. const memberOfThis = this.members[from];
  558. if (memberOfThis.role !== member.role) {
  559. memberOfThis.role = member.role;
  560. this.eventEmitter.emit(
  561. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  562. }
  563. // affiliation changed
  564. if (memberOfThis.affiliation !== member.affiliation) {
  565. memberOfThis.affiliation = member.affiliation;
  566. }
  567. // fire event that botType had changed
  568. if (memberOfThis.botType !== member.botType) {
  569. memberOfThis.botType = member.botType;
  570. this.eventEmitter.emit(
  571. XMPPEvents.MUC_MEMBER_BOT_TYPE_CHANGED,
  572. from,
  573. member.botType);
  574. }
  575. if (member.isFocus) {
  576. // From time to time first few presences of the focus are not
  577. // containing it's jid. That way we can mark later the focus
  578. // member instead of not marking it at all and not starting the
  579. // conference.
  580. // FIXME: Maybe there is a better way to handle this issue. It
  581. // seems there is some period of time in prosody that the
  582. // configuration form is received but not applied. And if any
  583. // participant joins during that period of time the first
  584. // presence from the focus won't contain
  585. // <item jid="focus..." />.
  586. // By default we are disabling the waiting for form submission in order to use the room
  587. // and we had enabled by default that jids are public in the room ,
  588. // so this case should not happen, if public jid is turned off we will receive the jid
  589. // when we become moderator in the room
  590. memberOfThis.isFocus = true;
  591. this._initFocus(from, member.features);
  592. }
  593. // store the new display name
  594. if (member.displayName) {
  595. memberOfThis.displayName = member.displayName;
  596. }
  597. // update stored status message to be able to detect changes
  598. if (memberOfThis.status !== member.status) {
  599. hasStatusUpdate = true;
  600. memberOfThis.status = member.status;
  601. }
  602. if (memberOfThis.version !== member.version) {
  603. hasVersionUpdate = true;
  604. memberOfThis.version = member.version;
  605. }
  606. if (!isEqual(memberOfThis.features, member.features)) {
  607. memberOfThis.features = member.features;
  608. this.eventEmitter.emit(XMPPEvents.PARTICIPANT_FEATURES_CHANGED, from, member.features);
  609. }
  610. }
  611. // after we had fired member or room joined events, lets fire events
  612. // for the rest info we got in presence
  613. for (let i = 0; i < nodes.length; i++) {
  614. const node = nodes[i];
  615. switch (node.tagName) {
  616. case 'nick':
  617. if (!member.isFocus) {
  618. const displayName
  619. = this.xmpp.options.displayJids
  620. ? Strophe.getResourceFromJid(from)
  621. : member.nick;
  622. this.eventEmitter.emit(
  623. XMPPEvents.DISPLAY_NAME_CHANGED,
  624. from,
  625. displayName);
  626. }
  627. break;
  628. case 'bridgeNotAvailable':
  629. if (member.isFocus && !this.noBridgeAvailable) {
  630. this.noBridgeAvailable = true;
  631. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  632. }
  633. break;
  634. case 'conference-properties':
  635. if (member.isFocus) {
  636. const properties = {};
  637. for (let j = 0; j < node.children.length; j++) {
  638. const { attributes } = node.children[j];
  639. if (attributes && attributes.key) {
  640. properties[attributes.key] = attributes.value;
  641. }
  642. }
  643. this.eventEmitter.emit(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED, properties);
  644. // Log if Jicofo supports restart by terminate only once. This conference property does not change
  645. // during the call.
  646. if (typeof this.restartByTerminateSupported === 'undefined') {
  647. this.restartByTerminateSupported = properties['support-terminate-restart'] === 'true';
  648. logger.info(`Jicofo supports restart by terminate: ${this.supportsRestartByTerminate()}`);
  649. }
  650. }
  651. break;
  652. case 'transcription-status': {
  653. const { attributes } = node;
  654. if (!attributes) {
  655. break;
  656. }
  657. const { status } = attributes;
  658. if (status && status !== this.transcriptionStatus) {
  659. this.transcriptionStatus = status;
  660. this.eventEmitter.emit(
  661. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  662. status
  663. );
  664. }
  665. break;
  666. }
  667. case 'call-control': {
  668. const att = node.attributes;
  669. if (!att) {
  670. break;
  671. }
  672. this.phoneNumber = att.phone || null;
  673. this.phonePin = att.pin || null;
  674. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  675. break;
  676. }
  677. default:
  678. this.processNode(node, from);
  679. }
  680. }
  681. // Trigger status message update if necessary
  682. if (hasStatusUpdate) {
  683. this.eventEmitter.emit(
  684. XMPPEvents.PRESENCE_STATUS,
  685. from,
  686. member.status);
  687. }
  688. if (hasVersionUpdate) {
  689. logger.info(`Received version for ${jid}: ${member.version}`);
  690. }
  691. }
  692. /**
  693. * Extracts the features from the presence.
  694. * @param node the node to process.
  695. * @return features the Set of features where extracted data is added.
  696. * @private
  697. */
  698. _extractFeatures(node) {
  699. const features = new Set();
  700. for (let j = 0; j < node.children.length; j++) {
  701. const { attributes } = node.children[j];
  702. if (attributes && attributes.var) {
  703. features.add(attributes.var);
  704. }
  705. }
  706. return features;
  707. }
  708. /**
  709. * Initialize some properties when the focus participant is verified.
  710. * @param from jid of the focus
  711. * @param features the features reported in jicofo presence
  712. */
  713. _initFocus(from, features) {
  714. this.focusMucJid = from;
  715. this.focusFeatures = features;
  716. }
  717. /**
  718. * Sets the special listener to be used for "command"s whose name starts
  719. * with "jitsi_participant_".
  720. */
  721. setParticipantPropertyListener(listener) {
  722. this.participantPropertyListener = listener;
  723. }
  724. /**
  725. * Checks if Jicofo supports restarting Jingle session after 'session-terminate'.
  726. * @returns {boolean}
  727. */
  728. supportsRestartByTerminate() {
  729. return this.restartByTerminateSupported;
  730. }
  731. /**
  732. *
  733. * @param node
  734. * @param from
  735. */
  736. processNode(node, from) {
  737. // make sure we catch all errors coming from any handler
  738. // otherwise we can remove the presence handler from strophe
  739. try {
  740. let tagHandlers = this.presHandlers[node.tagName];
  741. if (node.tagName.startsWith('jitsi_participant_')) {
  742. tagHandlers = [ this.participantPropertyListener ];
  743. }
  744. if (tagHandlers) {
  745. tagHandlers.forEach(handler => {
  746. handler(node, Strophe.getResourceFromJid(from), from);
  747. });
  748. }
  749. } catch (e) {
  750. GlobalOnErrorHandler.callErrorHandler(e);
  751. logger.error(`Error processing:${node.tagName} node.`, e);
  752. }
  753. }
  754. /**
  755. * Send text message to the other participants in the conference
  756. * @param message
  757. * @param elementName
  758. */
  759. sendMessage(message, elementName) {
  760. const msg = $msg({ to: this.roomjid,
  761. type: 'groupchat' });
  762. // We are adding the message in a packet extension. If this element
  763. // is different from 'body', we add a custom namespace.
  764. // e.g. for 'json-message' extension of message stanza.
  765. if (elementName === 'body') {
  766. msg.c(elementName, {}, message);
  767. } else {
  768. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message);
  769. }
  770. this.connection.send(msg);
  771. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, message);
  772. }
  773. /* eslint-disable max-params */
  774. /**
  775. * Send private text message to another participant of the conference
  776. * @param id id/muc resource of the receiver
  777. * @param message
  778. * @param elementName
  779. */
  780. sendPrivateMessage(id, message, elementName) {
  781. const msg = $msg({ to: `${this.roomjid}/${id}`,
  782. type: 'chat' });
  783. // We are adding the message in packet. If this element is different
  784. // from 'body', we add our custom namespace for the same.
  785. // e.g. for 'json-message' message extension.
  786. if (elementName === 'body') {
  787. msg.c(elementName, message).up();
  788. } else {
  789. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  790. .up();
  791. }
  792. this.connection.send(msg);
  793. this.eventEmitter.emit(
  794. XMPPEvents.SENDING_PRIVATE_CHAT_MESSAGE, message);
  795. }
  796. /* eslint-enable max-params */
  797. /**
  798. *
  799. * @param subject
  800. */
  801. setSubject(subject) {
  802. const msg = $msg({ to: this.roomjid,
  803. type: 'groupchat' });
  804. msg.c('subject', subject);
  805. this.connection.send(msg);
  806. }
  807. /**
  808. * Called when participant leaves.
  809. * @param jid the jid of the participant that leaves
  810. * @param skipEvents optional params to skip any events, including check
  811. * whether this is the focus that left
  812. * @param reason the reason for leaving (optional).
  813. */
  814. onParticipantLeft(jid, skipEvents, reason) {
  815. delete this.lastPresences[jid];
  816. if (skipEvents) {
  817. return;
  818. }
  819. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid, reason);
  820. this.moderator.onMucMemberLeft(jid);
  821. }
  822. /**
  823. *
  824. * @param pres
  825. * @param from
  826. */
  827. onPresenceUnavailable(pres, from) {
  828. // ignore presence
  829. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  830. return true;
  831. }
  832. // room destroyed ?
  833. const destroySelect = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>destroy');
  834. if (destroySelect.length) {
  835. let reason;
  836. const reasonSelect
  837. = $(pres).find(
  838. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  839. + '>destroy>reason');
  840. if (reasonSelect.length) {
  841. reason = reasonSelect.text();
  842. }
  843. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason, destroySelect.attr('jid'));
  844. this.connection.emuc.doLeave(this.roomjid);
  845. return true;
  846. }
  847. // Status code 110 indicates that this notification is "self-presence".
  848. const isSelfPresence
  849. = $(pres)
  850. .find(
  851. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  852. + 'status[code="110"]')
  853. .length;
  854. const isKick
  855. = $(pres)
  856. .find(
  857. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  858. + '>status[code="307"]')
  859. .length;
  860. const membersKeys = Object.keys(this.members);
  861. const isReplaceParticipant = $(pres).find('flip_device').length;
  862. if (isKick) {
  863. const actorSelect
  864. = $(pres)
  865. .find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item>actor');
  866. let actorNick;
  867. if (actorSelect.length) {
  868. actorNick = actorSelect.attr('nick');
  869. }
  870. let reason;
  871. const reasonSelect
  872. = $(pres).find(
  873. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  874. + '>item>reason');
  875. if (reasonSelect.length) {
  876. reason = reasonSelect.text();
  877. }
  878. // we first fire the kicked so we can show the participant
  879. // who kicked, before notifying that participant left
  880. // we fire kicked for us and for any participant kicked
  881. this.eventEmitter.emit(
  882. XMPPEvents.KICKED,
  883. isSelfPresence,
  884. actorNick,
  885. Strophe.getResourceFromJid(from),
  886. reason,
  887. isReplaceParticipant);
  888. }
  889. if (isSelfPresence) {
  890. // If the status code is 110 this means we're leaving and we would
  891. // like to remove everyone else from our view, so we trigger the
  892. // event.
  893. membersKeys.forEach(jid => {
  894. const member = this.members[jid];
  895. delete this.members[jid];
  896. this.onParticipantLeft(jid, member.isFocus);
  897. });
  898. this.connection.emuc.doLeave(this.roomjid);
  899. // we fire muc_left only if this is not a kick,
  900. // kick has both statuses 110 and 307.
  901. if (!isKick) {
  902. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  903. }
  904. } else {
  905. const reasonSelect = $(pres).find('>status');
  906. let reason;
  907. if (reasonSelect.length) {
  908. reason = reasonSelect.text();
  909. }
  910. delete this.members[from];
  911. this.onParticipantLeft(from, false, reason);
  912. }
  913. }
  914. /**
  915. *
  916. * @param msg
  917. * @param from
  918. */
  919. onMessage(msg, from) {
  920. const type = msg.getAttribute('type');
  921. if (type === 'error') {
  922. const settingsErrorMsg = $(msg).find('>settings-error>text').text();
  923. if (settingsErrorMsg.length) {
  924. this.eventEmitter.emit(XMPPEvents.SETTINGS_ERROR_RECEIVED, settingsErrorMsg);
  925. return true;
  926. }
  927. const errorMsg = $(msg).find('>error>text').text();
  928. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED, errorMsg);
  929. return true;
  930. }
  931. const txt = $(msg).find('>body').text();
  932. const subject = $(msg).find('>subject');
  933. if (subject.length) {
  934. const subjectText = subject.text();
  935. if (subjectText || subjectText === '') {
  936. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  937. logger.log(`Subject is changed to ${subjectText}`);
  938. }
  939. }
  940. // xep-0203 delay
  941. let stamp = $(msg).find('>delay').attr('stamp');
  942. if (!stamp) {
  943. // or xep-0091 delay, UTC timestamp
  944. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  945. if (stamp) {
  946. // the format is CCYYMMDDThh:mm:ss
  947. const dateParts
  948. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  949. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  950. }
  951. }
  952. if (from === this.roomjid) {
  953. let invite;
  954. if ($(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  955. this.discoRoomInfo();
  956. } else if ((invite = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>invite'))
  957. && invite.length) {
  958. const passwordSelect = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>password');
  959. let password;
  960. if (passwordSelect && passwordSelect.length) {
  961. password = passwordSelect.text();
  962. }
  963. this.eventEmitter.emit(XMPPEvents.INVITE_MESSAGE_RECEIVED,
  964. from, invite.attr('from'), txt, password);
  965. }
  966. }
  967. const jsonMessage = $(msg).find('>json-message').text();
  968. if (jsonMessage) {
  969. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  970. // We emit this event if the message is a valid json, and is not
  971. // delivered after a delay, i.e. stamp is undefined.
  972. // e.g. - subtitles should not be displayed if delayed.
  973. if (parsedJson && stamp === undefined) {
  974. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  975. from, parsedJson);
  976. return;
  977. }
  978. }
  979. if (txt) {
  980. if (type === 'chat') {
  981. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  982. from, txt, this.myroomjid, stamp);
  983. } else if (type === 'groupchat') {
  984. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  985. from, txt, this.myroomjid, stamp);
  986. }
  987. }
  988. }
  989. /**
  990. *
  991. * @param pres
  992. * @param from
  993. */
  994. onPresenceError(pres, from) {
  995. if ($(pres)
  996. .find(
  997. '>error[type="auth"]'
  998. + '>not-authorized['
  999. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  1000. .length) {
  1001. logger.log('on password required', from);
  1002. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  1003. } else if ($(pres)
  1004. .find(
  1005. '>error[type="cancel"]'
  1006. + '>not-allowed['
  1007. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  1008. .length) {
  1009. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  1010. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  1011. // enter the room by replying with 'not-authorized'. This would
  1012. // result in reconnection from authorized domain.
  1013. // We're either missing Jicofo/Prosody config for anonymous
  1014. // domains or something is wrong.
  1015. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  1016. } else {
  1017. logger.warn('onPresError ', pres);
  1018. this.eventEmitter.emit(
  1019. XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  1020. }
  1021. } else if ($(pres).find('>error>service-unavailable').length) {
  1022. logger.warn('Maximum users limit for the room has been reached',
  1023. pres);
  1024. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  1025. } else if ($(pres)
  1026. .find(
  1027. '>error[type="auth"]'
  1028. + '>registration-required['
  1029. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  1030. // let's extract the lobby jid from the custom field
  1031. const lobbyRoomNode = $(pres).find('>error[type="auth"]>lobbyroom');
  1032. let lobbyRoomJid;
  1033. if (lobbyRoomNode.length) {
  1034. lobbyRoomJid = lobbyRoomNode.text();
  1035. } else {
  1036. // let's fallback to old location of lobbyroom node, TODO: to be removed in the future once
  1037. // everything is updated
  1038. const lobbyRoomOldNode = $(pres).find('>lobbyroom');
  1039. if (lobbyRoomOldNode.length) {
  1040. lobbyRoomJid = lobbyRoomOldNode.text();
  1041. }
  1042. }
  1043. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_MEMBERS_ONLY_ERROR, lobbyRoomJid);
  1044. } else {
  1045. logger.warn('onPresError ', pres);
  1046. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  1047. }
  1048. }
  1049. /**
  1050. *
  1051. * @param jid
  1052. * @param affiliation
  1053. */
  1054. setAffiliation(jid, affiliation) {
  1055. const grantIQ = $iq({
  1056. to: this.roomjid,
  1057. type: 'set'
  1058. })
  1059. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1060. .c('item', {
  1061. affiliation,
  1062. jid: Strophe.getBareJidFromJid(jid)
  1063. })
  1064. .c('reason').t(`Your affiliation has been changed to '${affiliation}'.`)
  1065. .up().up().up();
  1066. this.connection.sendIQ(
  1067. grantIQ,
  1068. result => logger.log('Set affiliation of participant with jid: ', jid, 'to', affiliation, result),
  1069. error => logger.log('Set affiliation of participant error: ', error));
  1070. }
  1071. /**
  1072. *
  1073. * @param jid
  1074. * @param reason
  1075. */
  1076. kick(jid, reason = 'You have been kicked.') {
  1077. const kickIQ = $iq({ to: this.roomjid,
  1078. type: 'set' })
  1079. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1080. .c('item', { nick: Strophe.getResourceFromJid(jid),
  1081. role: 'none' })
  1082. .c('reason').t(reason).up().up().up();
  1083. this.connection.sendIQ(
  1084. kickIQ,
  1085. result => logger.log('Kick participant with jid: ', jid, result),
  1086. error => logger.log('Kick participant error: ', error));
  1087. }
  1088. /* eslint-disable max-params */
  1089. /**
  1090. *
  1091. * @param key
  1092. * @param onSuccess
  1093. * @param onError
  1094. * @param onNotSupported
  1095. */
  1096. lockRoom(key, onSuccess, onError, onNotSupported) {
  1097. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  1098. this.connection.sendIQ(
  1099. $iq({
  1100. to: this.roomjid,
  1101. type: 'get'
  1102. })
  1103. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1104. res => {
  1105. if ($(res)
  1106. .find(
  1107. '>query>x[xmlns="jabber:x:data"]'
  1108. + '>field[var="muc#roomconfig_roomsecret"]')
  1109. .length) {
  1110. const formsubmit
  1111. = $iq({
  1112. to: this.roomjid,
  1113. type: 'set'
  1114. })
  1115. .c('query', {
  1116. xmlns: 'http://jabber.org/protocol/muc#owner'
  1117. });
  1118. formsubmit.c('x', {
  1119. xmlns: 'jabber:x:data',
  1120. type: 'submit'
  1121. });
  1122. formsubmit
  1123. .c('field', { 'var': 'FORM_TYPE' })
  1124. .c('value')
  1125. .t('http://jabber.org/protocol/muc#roomconfig')
  1126. .up()
  1127. .up();
  1128. formsubmit
  1129. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  1130. .c('value')
  1131. .t(key)
  1132. .up()
  1133. .up();
  1134. formsubmit
  1135. .c('field',
  1136. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1137. .c('value')
  1138. .t(key === null || key.length === 0 ? '0' : '1')
  1139. .up()
  1140. .up();
  1141. // if members only enabled
  1142. if (this.membersOnlyEnabled) {
  1143. formsubmit
  1144. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1145. .c('value')
  1146. .t('true')
  1147. .up()
  1148. .up();
  1149. }
  1150. // Fixes a bug in prosody 0.9.+
  1151. // https://prosody.im/issues/issue/373
  1152. formsubmit
  1153. .c('field', { 'var': 'muc#roomconfig_whois' })
  1154. .c('value')
  1155. .t('anyone')
  1156. .up()
  1157. .up();
  1158. this.connection.sendIQ(
  1159. formsubmit,
  1160. () => {
  1161. // we set the password in chat room so we can use it
  1162. // later when dialing out
  1163. this.password = key;
  1164. onSuccess();
  1165. },
  1166. onError);
  1167. } else {
  1168. onNotSupported();
  1169. }
  1170. },
  1171. onError);
  1172. }
  1173. /* eslint-enable max-params */
  1174. /**
  1175. * Turns off or on the members only config for the main room.
  1176. *
  1177. * @param {boolean} enabled - Whether to turn it on or off.
  1178. * @param onSuccess - optional callback.
  1179. * @param onError - optional callback.
  1180. */
  1181. setMembersOnly(enabled, onSuccess, onError) {
  1182. if (enabled && Object.values(this.members).filter(m => !m.isFocus).length) {
  1183. // first grant membership to all that are in the room
  1184. // currently there is a bug in prosody where it handles only the first item
  1185. // that's why we will send iq per member
  1186. Object.values(this.members).forEach(m => {
  1187. if (m.jid && !MEMBERS_AFFILIATIONS.includes(m.affiliation)) {
  1188. this.xmpp.connection.sendIQ(
  1189. $iq({
  1190. to: this.roomjid,
  1191. type: 'set' })
  1192. .c('query', {
  1193. xmlns: 'http://jabber.org/protocol/muc#admin' })
  1194. .c('item', {
  1195. 'affiliation': 'member',
  1196. 'jid': Strophe.getBareJidFromJid(m.jid)
  1197. }).up().up());
  1198. }
  1199. });
  1200. }
  1201. const errorCallback = onError ? onError : () => {}; // eslint-disable-line no-empty-function
  1202. this.xmpp.connection.sendIQ(
  1203. $iq({
  1204. to: this.roomjid,
  1205. type: 'get'
  1206. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1207. res => {
  1208. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_membersonly"]').length) {
  1209. const formToSubmit
  1210. = $iq({
  1211. to: this.roomjid,
  1212. type: 'set'
  1213. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  1214. formToSubmit.c('x', {
  1215. xmlns: 'jabber:x:data',
  1216. type: 'submit'
  1217. });
  1218. formToSubmit
  1219. .c('field', { 'var': 'FORM_TYPE' })
  1220. .c('value')
  1221. .t('http://jabber.org/protocol/muc#roomconfig')
  1222. .up()
  1223. .up();
  1224. formToSubmit
  1225. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1226. .c('value')
  1227. .t(enabled ? 'true' : 'false')
  1228. .up()
  1229. .up();
  1230. // if room is locked from other participant or we are locking it
  1231. if (this.locked) {
  1232. formToSubmit
  1233. .c('field',
  1234. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1235. .c('value')
  1236. .t('1')
  1237. .up()
  1238. .up();
  1239. }
  1240. this.xmpp.connection.sendIQ(formToSubmit, onSuccess, errorCallback);
  1241. } else {
  1242. errorCallback(new Error('Setting members only room not supported!'));
  1243. }
  1244. },
  1245. errorCallback);
  1246. }
  1247. /**
  1248. * Adds the key to the presence map, overriding any previous value.
  1249. * This method is used by jibri.
  1250. *
  1251. * @param key The key to add or replace.
  1252. * @param values The new values.
  1253. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replce was
  1254. * performed as the value was already there.
  1255. * @deprecated Use 'addOrReplaceInPresence' instead. TODO: remove it from here and jibri.
  1256. */
  1257. addToPresence(key, values) {
  1258. return this.addOrReplaceInPresence(key, values);
  1259. }
  1260. /**
  1261. * Adds the key to the presence map, overriding any previous value.
  1262. * @param key The key to add or replace.
  1263. * @param values The new values.
  1264. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replace was
  1265. * performed as the value was already there.
  1266. */
  1267. addOrReplaceInPresence(key, values) {
  1268. values.tagName = key;
  1269. const matchingNodes = this.presMap.nodes.filter(node => key === node.tagName);
  1270. // if we have found just one, let's check is it the same
  1271. if (matchingNodes.length === 1 && isEqual(matchingNodes[0], values)) {
  1272. return false;
  1273. }
  1274. this.removeFromPresence(key);
  1275. this.presMap.nodes.push(values);
  1276. this.presenceUpdateTime = Date.now();
  1277. return true;
  1278. }
  1279. /**
  1280. * Retrieves a value from the presence map.
  1281. *
  1282. * @param {string} key - The key to find the value for.
  1283. * @returns {Object?}
  1284. */
  1285. getFromPresence(key) {
  1286. return this.presMap.nodes.find(node => key === node.tagName);
  1287. }
  1288. /**
  1289. * Removes a key from the presence map.
  1290. * @param key
  1291. */
  1292. removeFromPresence(key) {
  1293. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  1294. this.presMap.nodes = nodes;
  1295. this.presenceUpdateTime = Date.now();
  1296. }
  1297. /**
  1298. *
  1299. * @param name
  1300. * @param handler
  1301. */
  1302. addPresenceListener(name, handler) {
  1303. if (typeof handler !== 'function') {
  1304. throw new Error('"handler" is not a function');
  1305. }
  1306. let tagHandlers = this.presHandlers[name];
  1307. if (!tagHandlers) {
  1308. this.presHandlers[name] = tagHandlers = [];
  1309. }
  1310. if (tagHandlers.indexOf(handler) === -1) {
  1311. tagHandlers.push(handler);
  1312. } else {
  1313. logger.warn(
  1314. `Trying to add the same handler more than once for: ${name}`);
  1315. }
  1316. }
  1317. /**
  1318. *
  1319. * @param name
  1320. * @param handler
  1321. */
  1322. removePresenceListener(name, handler) {
  1323. const tagHandlers = this.presHandlers[name];
  1324. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  1325. // eslint-disable-next-line no-negated-condition
  1326. if (handlerIdx !== -1) {
  1327. tagHandlers.splice(handlerIdx, 1);
  1328. } else {
  1329. logger.warn(`Handler for: ${name} was not registered`);
  1330. }
  1331. }
  1332. /**
  1333. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1334. * focus.
  1335. * @param mucJid the full MUC address of the user to be checked.
  1336. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  1337. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  1338. * the MUC then <tt>null</tt> is returned.
  1339. */
  1340. isFocus(mucJid) {
  1341. const member = this.members[mucJid];
  1342. if (member) {
  1343. return member.isFocus;
  1344. }
  1345. return null;
  1346. }
  1347. /**
  1348. *
  1349. */
  1350. isModerator() {
  1351. return this.role === 'moderator';
  1352. }
  1353. /**
  1354. * Obtains the info about given media advertised (in legacy format) in the MUC presence of the participant
  1355. * identified by the given endpoint JID. This is for mantining interop with endpoints that do not support
  1356. * source-name signaling (Jigasi and very old mobile clients).
  1357. *
  1358. * @param {string} endpointId the endpoint ID mapped to the participant which corresponds to MUC nickname.
  1359. * @param {MediaType} mediaType the type of the media for which presence info will be obtained.
  1360. * @return {PeerMediaInfo} presenceInfo an object with media presence info or <tt>null</tt> either if there
  1361. * is no presence available or if the media type given is invalid.
  1362. */
  1363. getMediaPresenceInfo(endpointId, mediaType) {
  1364. // Will figure out current muted status by looking up owner's presence
  1365. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1366. if (!pres) {
  1367. // No presence available
  1368. return null;
  1369. }
  1370. const data = {
  1371. muted: true, // muted by default
  1372. videoType: mediaType === MediaType.VIDEO ? VideoType.CAMERA : undefined // 'camera' by default
  1373. };
  1374. let mutedNode = null;
  1375. if (mediaType === MediaType.AUDIO) {
  1376. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1377. } else if (mediaType === MediaType.VIDEO) {
  1378. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1379. const codecTypeNode = filterNodeFromPresenceJSON(pres, 'jitsi_participant_codecType');
  1380. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1381. if (videoTypeNode.length > 0) {
  1382. data.videoType = videoTypeNode[0].value;
  1383. }
  1384. if (codecTypeNode.length > 0) {
  1385. data.codecType = codecTypeNode[0].value;
  1386. }
  1387. } else {
  1388. logger.error(`Unsupported media type: ${mediaType}`);
  1389. return null;
  1390. }
  1391. if (mutedNode.length > 0) {
  1392. data.muted = mutedNode[0].value === 'true';
  1393. }
  1394. return data;
  1395. }
  1396. /**
  1397. *
  1398. * @param peerJid
  1399. */
  1400. getMemberRole(peerJid) {
  1401. if (this.members[peerJid]) {
  1402. return this.members[peerJid].role;
  1403. }
  1404. return null;
  1405. }
  1406. /**
  1407. * Returns the last presence advertised by a MUC member.
  1408. * @param {string} mucNick
  1409. * @returns {*}
  1410. */
  1411. getLastPresence(mucNick) {
  1412. return this.lastPresences[`${this.roomjid}/${mucNick}`];
  1413. }
  1414. /**
  1415. * Returns true if the SIP calls are supported and false otherwise
  1416. */
  1417. isSIPCallingSupported() {
  1418. if (this.moderator) {
  1419. return this.moderator.isSipGatewayEnabled();
  1420. }
  1421. return false;
  1422. }
  1423. /**
  1424. * Dials a number.
  1425. * @param number the number
  1426. */
  1427. dial(number) {
  1428. return this.connection.rayo.dial(number, 'fromnumber',
  1429. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1430. this.focusMucJid);
  1431. }
  1432. /**
  1433. * Hangup an existing call
  1434. */
  1435. hangup() {
  1436. return this.connection.rayo.hangup();
  1437. }
  1438. /**
  1439. *
  1440. * @returns {Lobby}
  1441. */
  1442. getLobby() {
  1443. return this.lobby;
  1444. }
  1445. /**
  1446. * @returns {AVModeration}
  1447. */
  1448. getAVModeration() {
  1449. return this.avModeration;
  1450. }
  1451. /**
  1452. * @returns {BreakoutRooms}
  1453. */
  1454. getBreakoutRooms() {
  1455. return this.breakoutRooms;
  1456. }
  1457. /**
  1458. * @returns {RoomMetadata}
  1459. */
  1460. getMetadataHandler() {
  1461. return this.roomMetadata;
  1462. }
  1463. /**
  1464. * Returns the phone number for joining the conference.
  1465. */
  1466. getPhoneNumber() {
  1467. return this.phoneNumber;
  1468. }
  1469. /**
  1470. * Returns the pin for joining the conference with phone.
  1471. */
  1472. getPhonePin() {
  1473. return this.phonePin;
  1474. }
  1475. /**
  1476. * Returns the meeting unique ID if any came from backend.
  1477. *
  1478. * @returns {string} - The meeting ID.
  1479. */
  1480. getMeetingId() {
  1481. return this.meetingId;
  1482. }
  1483. /**
  1484. * Mutes remote participant.
  1485. * @param jid of the participant
  1486. * @param mute
  1487. * @param mediaType
  1488. */
  1489. muteParticipant(jid, mute, mediaType) {
  1490. logger.info('set mute', mute, jid);
  1491. const iqToFocus = $iq(
  1492. { to: this.focusMucJid,
  1493. type: 'set' })
  1494. .c('mute', {
  1495. xmlns: `http://jitsi.org/jitmeet/${mediaType}`,
  1496. jid
  1497. })
  1498. .t(mute.toString())
  1499. .up();
  1500. this.connection.sendIQ(
  1501. iqToFocus,
  1502. result => logger.log('set mute', result),
  1503. error => logger.log('set mute error', error));
  1504. }
  1505. /**
  1506. * TODO: Document
  1507. * @param iq
  1508. */
  1509. onMute(iq) {
  1510. const from = iq.getAttribute('from');
  1511. if (from !== this.focusMucJid) {
  1512. logger.warn('Ignored mute from non focus peer');
  1513. return;
  1514. }
  1515. const mute = $(iq).find('mute');
  1516. if (mute.length && mute.text() === 'true') {
  1517. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, mute.attr('actor'));
  1518. } else {
  1519. // XXX Why do we support anything but muting? Why do we encode the
  1520. // value in the text of the element? Why do we use a separate XML
  1521. // namespace?
  1522. logger.warn('Ignoring a mute request which does not explicitly '
  1523. + 'specify a positive mute command.');
  1524. }
  1525. }
  1526. /**
  1527. * TODO: Document
  1528. * @param iq
  1529. */
  1530. onMuteVideo(iq) {
  1531. const from = iq.getAttribute('from');
  1532. if (from !== this.focusMucJid) {
  1533. logger.warn('Ignored mute from non focus peer');
  1534. return;
  1535. }
  1536. const mute = $(iq).find('mute');
  1537. if (mute.length && mute.text() === 'true') {
  1538. this.eventEmitter.emit(XMPPEvents.VIDEO_MUTED_BY_FOCUS, mute.attr('actor'));
  1539. } else {
  1540. // XXX Why do we support anything but muting? Why do we encode the
  1541. // value in the text of the element? Why do we use a separate XML
  1542. // namespace?
  1543. logger.warn('Ignoring a mute request which does not explicitly '
  1544. + 'specify a positive mute command.');
  1545. }
  1546. }
  1547. /**
  1548. * Clean any listeners or resources, executed on leaving.
  1549. */
  1550. clean() {
  1551. this._removeConnListeners.forEach(remove => remove());
  1552. this._removeConnListeners = [];
  1553. this.joined = false;
  1554. this.inProgressEmitted = false;
  1555. }
  1556. /**
  1557. * Leaves the room. Closes the jingle session.
  1558. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1559. * less than 5s after sending presence unavailable. Otherwise the promise is
  1560. * rejected.
  1561. */
  1562. leave(reason) {
  1563. this.avModeration.dispose();
  1564. this.breakoutRooms.dispose();
  1565. this.roomMetadata.dispose();
  1566. const promises = [];
  1567. this.lobby?.lobbyRoom && promises.push(this.lobby.leave());
  1568. promises.push(new Promise((resolve, reject) => {
  1569. let timeout = -1;
  1570. const onMucLeft = (doReject = false) => {
  1571. this.eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1572. clearTimeout(timeout);
  1573. if (doReject) {
  1574. // The timeout expired. Make sure we clean the EMUC state.
  1575. this.connection.emuc.doLeave(this.roomjid);
  1576. reject(new Error('The timeout for the confirmation about leaving the room expired.'));
  1577. } else {
  1578. resolve();
  1579. }
  1580. };
  1581. timeout = setTimeout(() => onMucLeft(true), 5000);
  1582. this.clean();
  1583. this.eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1584. this.doLeave(reason);
  1585. }));
  1586. return Promise.allSettled(promises);
  1587. }
  1588. /**
  1589. * Ends the conference for all participants.
  1590. */
  1591. end() {
  1592. if (this.breakoutRooms.isBreakoutRoom()) {
  1593. logger.warn('Cannot end conference: this is a breakout room.');
  1594. return;
  1595. }
  1596. // Send the end conference message.
  1597. const msg = $msg({ to: this.xmpp.endConferenceComponentAddress });
  1598. msg.c('end_conference').up();
  1599. this.xmpp.connection.send(msg);
  1600. }
  1601. }
  1602. /* eslint-enable newline-per-chained-call */