您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ChatRoom.js 60KB

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