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

ChatRoom.js 56KB

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