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

ChatRoom.js 56KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  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. memberOfThis.isFocus = true;
  548. this._initFocus(from, jid);
  549. }
  550. // store the new display name
  551. if (member.displayName) {
  552. memberOfThis.displayName = member.displayName;
  553. }
  554. // update stored status message to be able to detect changes
  555. if (memberOfThis.status !== member.status) {
  556. hasStatusUpdate = true;
  557. memberOfThis.status = member.status;
  558. }
  559. if (memberOfThis.version !== member.version) {
  560. hasVersionUpdate = true;
  561. memberOfThis.version = member.version;
  562. }
  563. }
  564. // after we had fired member or room joined events, lets fire events
  565. // for the rest info we got in presence
  566. for (let i = 0; i < nodes.length; i++) {
  567. const node = nodes[i];
  568. switch (node.tagName) {
  569. case 'nick':
  570. if (!member.isFocus) {
  571. const displayName
  572. = this.xmpp.options.displayJids
  573. ? Strophe.getResourceFromJid(from)
  574. : member.nick;
  575. this.eventEmitter.emit(
  576. XMPPEvents.DISPLAY_NAME_CHANGED,
  577. from,
  578. displayName);
  579. }
  580. break;
  581. case 'bridgeNotAvailable':
  582. if (member.isFocus && !this.noBridgeAvailable) {
  583. this.noBridgeAvailable = true;
  584. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  585. }
  586. break;
  587. case 'conference-properties':
  588. if (member.isFocus) {
  589. const properties = {};
  590. for (let j = 0; j < node.children.length; j++) {
  591. const { attributes } = node.children[j];
  592. if (attributes && attributes.key) {
  593. properties[attributes.key] = attributes.value;
  594. }
  595. }
  596. this.eventEmitter.emit(
  597. XMPPEvents.CONFERENCE_PROPERTIES_CHANGED, properties);
  598. }
  599. break;
  600. case 'transcription-status': {
  601. const { attributes } = node;
  602. if (!attributes) {
  603. break;
  604. }
  605. const { status } = attributes;
  606. if (status && status !== this.transcriptionStatus) {
  607. this.transcriptionStatus = status;
  608. this.eventEmitter.emit(
  609. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  610. status
  611. );
  612. }
  613. break;
  614. }
  615. case 'call-control': {
  616. const att = node.attributes;
  617. if (!att) {
  618. break;
  619. }
  620. this.phoneNumber = att.phone || null;
  621. this.phonePin = att.pin || null;
  622. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  623. break;
  624. }
  625. default:
  626. this.processNode(node, from);
  627. }
  628. }
  629. // Trigger status message update if necessary
  630. if (hasStatusUpdate) {
  631. this.eventEmitter.emit(
  632. XMPPEvents.PRESENCE_STATUS,
  633. from,
  634. member.status);
  635. }
  636. if (hasVersionUpdate) {
  637. logger.info(`Received version for ${jid}: ${member.version}`);
  638. }
  639. }
  640. /**
  641. * Initialize some properties when the focus participant is verified.
  642. * @param from jid of the focus
  643. * @param mucJid the jid of the focus in the muc
  644. */
  645. _initFocus(from, mucJid) {
  646. this.focusMucJid = from;
  647. logger.info(`Ignore focus: ${from}, real JID: ${mucJid}`);
  648. this.xmpp.caps.getFeatures(mucJid, 15000).then(features => {
  649. this.focusFeatures = features;
  650. logger.info(`Jicofo supports restart by terminate: ${this.supportsRestartByTerminate()}`);
  651. }, error => {
  652. logger.error('Failed to discover Jicofo features', error && error.message);
  653. });
  654. }
  655. /**
  656. * Sets the special listener to be used for "command"s whose name starts
  657. * with "jitsi_participant_".
  658. */
  659. setParticipantPropertyListener(listener) {
  660. this.participantPropertyListener = listener;
  661. }
  662. /**
  663. * Checks if Jicofo supports restarting Jingle session after 'session-terminate'.
  664. * @returns {boolean}
  665. */
  666. supportsRestartByTerminate() {
  667. return this.focusFeatures
  668. ? this.focusFeatures.has('https://jitsi.org/meet/jicofo/terminate-restart')
  669. : false;
  670. }
  671. /**
  672. *
  673. * @param node
  674. * @param from
  675. */
  676. processNode(node, from) {
  677. // make sure we catch all errors coming from any handler
  678. // otherwise we can remove the presence handler from strophe
  679. try {
  680. let tagHandlers = this.presHandlers[node.tagName];
  681. if (node.tagName.startsWith('jitsi_participant_')) {
  682. tagHandlers = [ this.participantPropertyListener ];
  683. }
  684. if (tagHandlers) {
  685. tagHandlers.forEach(handler => {
  686. handler(node, Strophe.getResourceFromJid(from), from);
  687. });
  688. }
  689. } catch (e) {
  690. GlobalOnErrorHandler.callErrorHandler(e);
  691. logger.error(`Error processing:${node.tagName} node.`, e);
  692. }
  693. }
  694. /**
  695. * Send text message to the other participants in the conference
  696. * @param message
  697. * @param elementName
  698. * @param nickname
  699. */
  700. sendMessage(message, elementName, nickname) {
  701. const msg = $msg({ to: this.roomjid,
  702. type: 'groupchat' });
  703. // We are adding the message in a packet extension. If this element
  704. // is different from 'body', we add a custom namespace.
  705. // e.g. for 'json-message' extension of message stanza.
  706. if (elementName === 'body') {
  707. msg.c(elementName, message).up();
  708. } else {
  709. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  710. .up();
  711. }
  712. if (nickname) {
  713. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  714. .t(nickname)
  715. .up()
  716. .up();
  717. }
  718. this.connection.send(msg);
  719. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, message);
  720. }
  721. /* eslint-disable max-params */
  722. /**
  723. * Send private text message to another participant of the conference
  724. * @param id id/muc resource of the receiver
  725. * @param message
  726. * @param elementName
  727. * @param nickname
  728. */
  729. sendPrivateMessage(id, message, elementName, nickname) {
  730. const msg = $msg({ to: `${this.roomjid}/${id}`,
  731. type: 'chat' });
  732. // We are adding the message in packet. If this element is different
  733. // from 'body', we add our custom namespace for the same.
  734. // e.g. for 'json-message' message extension.
  735. if (elementName === 'body') {
  736. msg.c(elementName, message).up();
  737. } else {
  738. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  739. .up();
  740. }
  741. if (nickname) {
  742. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  743. .t(nickname)
  744. .up()
  745. .up();
  746. }
  747. this.connection.send(msg);
  748. this.eventEmitter.emit(
  749. XMPPEvents.SENDING_PRIVATE_CHAT_MESSAGE, message);
  750. }
  751. /* eslint-enable max-params */
  752. /**
  753. *
  754. * @param subject
  755. */
  756. setSubject(subject) {
  757. const msg = $msg({ to: this.roomjid,
  758. type: 'groupchat' });
  759. msg.c('subject', subject);
  760. this.connection.send(msg);
  761. }
  762. /**
  763. * Called when participant leaves.
  764. * @param jid the jid of the participant that leaves
  765. * @param skipEvents optional params to skip any events, including check
  766. * whether this is the focus that left
  767. */
  768. onParticipantLeft(jid, skipEvents) {
  769. delete this.lastPresences[jid];
  770. if (skipEvents) {
  771. return;
  772. }
  773. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  774. this.moderator.onMucMemberLeft(jid);
  775. }
  776. /**
  777. *
  778. * @param pres
  779. * @param from
  780. */
  781. onPresenceUnavailable(pres, from) {
  782. // ignore presence
  783. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  784. return true;
  785. }
  786. // room destroyed ?
  787. const destroySelect = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>destroy');
  788. if (destroySelect.length) {
  789. let reason;
  790. const reasonSelect
  791. = $(pres).find(
  792. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  793. + '>destroy>reason');
  794. if (reasonSelect.length) {
  795. reason = reasonSelect.text();
  796. }
  797. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason, destroySelect.attr('jid'));
  798. this.connection.emuc.doLeave(this.roomjid);
  799. return true;
  800. }
  801. // Status code 110 indicates that this notification is "self-presence".
  802. const isSelfPresence
  803. = $(pres)
  804. .find(
  805. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  806. + 'status[code="110"]')
  807. .length;
  808. const isKick
  809. = $(pres)
  810. .find(
  811. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  812. + '>status[code="307"]')
  813. .length;
  814. const membersKeys = Object.keys(this.members);
  815. if (isKick) {
  816. const actorSelect
  817. = $(pres)
  818. .find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item>actor');
  819. let actorNick;
  820. if (actorSelect.length) {
  821. actorNick = actorSelect.attr('nick');
  822. }
  823. // we first fire the kicked so we can show the participant
  824. // who kicked, before notifying that participant left
  825. // we fire kicked for us and for any participant kicked
  826. this.eventEmitter.emit(
  827. XMPPEvents.KICKED,
  828. isSelfPresence,
  829. actorNick,
  830. Strophe.getResourceFromJid(from));
  831. }
  832. if (isSelfPresence) {
  833. // If the status code is 110 this means we're leaving and we would
  834. // like to remove everyone else from our view, so we trigger the
  835. // event.
  836. membersKeys.forEach(jid => {
  837. const member = this.members[jid];
  838. delete this.members[jid];
  839. this.onParticipantLeft(jid, member.isFocus);
  840. });
  841. this.connection.emuc.doLeave(this.roomjid);
  842. // we fire muc_left only if this is not a kick,
  843. // kick has both statuses 110 and 307.
  844. if (!isKick) {
  845. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  846. }
  847. } else {
  848. delete this.members[from];
  849. this.onParticipantLeft(from, false);
  850. }
  851. }
  852. /**
  853. *
  854. * @param msg
  855. * @param from
  856. */
  857. onMessage(msg, from) {
  858. const nick
  859. = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  860. .text()
  861. || Strophe.getResourceFromJid(from);
  862. const type = msg.getAttribute('type');
  863. if (type === 'error') {
  864. const errorMsg = $(msg).find('>error>text').text();
  865. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED, errorMsg);
  866. return true;
  867. }
  868. const txt = $(msg).find('>body').text();
  869. const subject = $(msg).find('>subject');
  870. if (subject.length) {
  871. const subjectText = subject.text();
  872. if (subjectText || subjectText === '') {
  873. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  874. logger.log(`Subject is changed to ${subjectText}`);
  875. }
  876. }
  877. // xep-0203 delay
  878. let stamp = $(msg).find('>delay').attr('stamp');
  879. if (!stamp) {
  880. // or xep-0091 delay, UTC timestamp
  881. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  882. if (stamp) {
  883. // the format is CCYYMMDDThh:mm:ss
  884. const dateParts
  885. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  886. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  887. }
  888. }
  889. if (from === this.roomjid) {
  890. let invite;
  891. if ($(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  892. this.discoRoomInfo();
  893. } else if ((invite = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>invite'))
  894. && invite.length) {
  895. const passwordSelect = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>password');
  896. let password;
  897. if (passwordSelect && passwordSelect.length) {
  898. password = passwordSelect.text();
  899. }
  900. this.eventEmitter.emit(XMPPEvents.INVITE_MESSAGE_RECEIVED,
  901. from, invite.attr('from'), txt, password);
  902. }
  903. }
  904. const jsonMessage = $(msg).find('>json-message').text();
  905. if (jsonMessage) {
  906. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  907. // We emit this event if the message is a valid json, and is not
  908. // delivered after a delay, i.e. stamp is undefined.
  909. // e.g. - subtitles should not be displayed if delayed.
  910. if (parsedJson && stamp === undefined) {
  911. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  912. from, parsedJson);
  913. return;
  914. }
  915. }
  916. if (txt) {
  917. if (type === 'chat') {
  918. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  919. from, nick, txt, this.myroomjid, stamp);
  920. } else if (type === 'groupchat') {
  921. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  922. from, nick, txt, this.myroomjid, stamp);
  923. }
  924. }
  925. }
  926. /**
  927. *
  928. * @param pres
  929. * @param from
  930. */
  931. onPresenceError(pres, from) {
  932. if ($(pres)
  933. .find(
  934. '>error[type="auth"]'
  935. + '>not-authorized['
  936. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  937. .length) {
  938. logger.log('on password required', from);
  939. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  940. } else if ($(pres)
  941. .find(
  942. '>error[type="cancel"]'
  943. + '>not-allowed['
  944. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  945. .length) {
  946. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  947. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  948. // enter the room by replying with 'not-authorized'. This would
  949. // result in reconnection from authorized domain.
  950. // We're either missing Jicofo/Prosody config for anonymous
  951. // domains or something is wrong.
  952. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  953. } else {
  954. logger.warn('onPresError ', pres);
  955. this.eventEmitter.emit(
  956. XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  957. }
  958. } else if ($(pres).find('>error>service-unavailable').length) {
  959. logger.warn('Maximum users limit for the room has been reached',
  960. pres);
  961. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  962. } else if ($(pres)
  963. .find(
  964. '>error[type="auth"]'
  965. + '>registration-required['
  966. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  967. // let's extract the lobby jid from the custom field
  968. const lobbyRoomNode = $(pres).find('>lobbyroom');
  969. let lobbyRoomJid;
  970. if (lobbyRoomNode.length) {
  971. lobbyRoomJid = lobbyRoomNode.text();
  972. }
  973. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_MEMBERS_ONLY_ERROR, lobbyRoomJid);
  974. } else {
  975. logger.warn('onPresError ', pres);
  976. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  977. }
  978. }
  979. /**
  980. *
  981. * @param jid
  982. * @param affiliation
  983. */
  984. setAffiliation(jid, affiliation) {
  985. const grantIQ = $iq({
  986. to: this.roomjid,
  987. type: 'set'
  988. })
  989. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  990. .c('item', {
  991. affiliation,
  992. nick: Strophe.getResourceFromJid(jid)
  993. })
  994. .c('reason').t(`Your affiliation has been changed to '${affiliation}'.`)
  995. .up().up().up();
  996. this.connection.sendIQ(
  997. grantIQ,
  998. result => logger.log('Set affiliation of participant with jid: ', jid, 'to', affiliation, result),
  999. error => logger.log('Set affiliation of participant error: ', error));
  1000. }
  1001. /**
  1002. *
  1003. * @param jid
  1004. */
  1005. kick(jid) {
  1006. const kickIQ = $iq({ to: this.roomjid,
  1007. type: 'set' })
  1008. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1009. .c('item', { nick: Strophe.getResourceFromJid(jid),
  1010. role: 'none' })
  1011. .c('reason').t('You have been kicked.').up().up().up();
  1012. this.connection.sendIQ(
  1013. kickIQ,
  1014. result => logger.log('Kick participant with jid: ', jid, result),
  1015. error => logger.log('Kick participant error: ', error));
  1016. }
  1017. /* eslint-disable max-params */
  1018. /**
  1019. *
  1020. * @param key
  1021. * @param onSuccess
  1022. * @param onError
  1023. * @param onNotSupported
  1024. */
  1025. lockRoom(key, onSuccess, onError, onNotSupported) {
  1026. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  1027. this.connection.sendIQ(
  1028. $iq({
  1029. to: this.roomjid,
  1030. type: 'get'
  1031. })
  1032. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1033. res => {
  1034. if ($(res)
  1035. .find(
  1036. '>query>x[xmlns="jabber:x:data"]'
  1037. + '>field[var="muc#roomconfig_roomsecret"]')
  1038. .length) {
  1039. const formsubmit
  1040. = $iq({
  1041. to: this.roomjid,
  1042. type: 'set'
  1043. })
  1044. .c('query', {
  1045. xmlns: 'http://jabber.org/protocol/muc#owner'
  1046. });
  1047. formsubmit.c('x', {
  1048. xmlns: 'jabber:x:data',
  1049. type: 'submit'
  1050. });
  1051. formsubmit
  1052. .c('field', { 'var': 'FORM_TYPE' })
  1053. .c('value')
  1054. .t('http://jabber.org/protocol/muc#roomconfig')
  1055. .up()
  1056. .up();
  1057. formsubmit
  1058. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  1059. .c('value')
  1060. .t(key)
  1061. .up()
  1062. .up();
  1063. formsubmit
  1064. .c('field',
  1065. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1066. .c('value')
  1067. .t(key === null || key.length === 0 ? '0' : '1')
  1068. .up()
  1069. .up();
  1070. // if members only enabled
  1071. if (this.membersOnlyEnabled) {
  1072. formsubmit
  1073. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1074. .c('value')
  1075. .t('true')
  1076. .up()
  1077. .up();
  1078. }
  1079. // Fixes a bug in prosody 0.9.+
  1080. // https://prosody.im/issues/issue/373
  1081. formsubmit
  1082. .c('field', { 'var': 'muc#roomconfig_whois' })
  1083. .c('value')
  1084. .t('anyone')
  1085. .up()
  1086. .up();
  1087. this.connection.sendIQ(formsubmit, onSuccess, onError);
  1088. } else {
  1089. onNotSupported();
  1090. }
  1091. },
  1092. onError);
  1093. }
  1094. /* eslint-enable max-params */
  1095. /**
  1096. * Turns off or on the members only config for the main room.
  1097. *
  1098. * @param {boolean} enabled - Whether to turn it on or off.
  1099. * @param onSuccess - optional callback.
  1100. * @param onError - optional callback.
  1101. */
  1102. setMembersOnly(enabled, onSuccess, onError) {
  1103. if (enabled && Object.values(this.members).filter(m => !m.isFocus).length) {
  1104. // first grant membership to all that are in the room
  1105. // currently there is a bug in prosody where it handles only the first item
  1106. // that's why we will send iq per member
  1107. Object.values(this.members).forEach(m => {
  1108. if (m.jid && !MEMBERS_AFFILIATIONS.includes(m.affiliation)) {
  1109. this.xmpp.connection.sendIQ(
  1110. $iq({
  1111. to: this.roomjid,
  1112. type: 'set' })
  1113. .c('query', {
  1114. xmlns: 'http://jabber.org/protocol/muc#admin' })
  1115. .c('item', {
  1116. 'affiliation': 'member',
  1117. 'jid': m.jid
  1118. }).up().up());
  1119. }
  1120. });
  1121. }
  1122. const errorCallback = onError ? onError : () => {}; // eslint-disable-line no-empty-function
  1123. this.xmpp.connection.sendIQ(
  1124. $iq({
  1125. to: this.roomjid,
  1126. type: 'get'
  1127. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1128. res => {
  1129. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_membersonly"]').length) {
  1130. const formToSubmit
  1131. = $iq({
  1132. to: this.roomjid,
  1133. type: 'set'
  1134. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  1135. formToSubmit.c('x', {
  1136. xmlns: 'jabber:x:data',
  1137. type: 'submit'
  1138. });
  1139. formToSubmit
  1140. .c('field', { 'var': 'FORM_TYPE' })
  1141. .c('value')
  1142. .t('http://jabber.org/protocol/muc#roomconfig')
  1143. .up()
  1144. .up();
  1145. formToSubmit
  1146. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1147. .c('value')
  1148. .t(enabled ? 'true' : 'false')
  1149. .up()
  1150. .up();
  1151. // if room is locked from other participant or we are locking it
  1152. if (this.locked) {
  1153. formToSubmit
  1154. .c('field',
  1155. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1156. .c('value')
  1157. .t('1')
  1158. .up()
  1159. .up();
  1160. }
  1161. this.xmpp.connection.sendIQ(formToSubmit, onSuccess, errorCallback);
  1162. } else {
  1163. errorCallback(new Error('Setting members only room not supported!'));
  1164. }
  1165. },
  1166. errorCallback);
  1167. }
  1168. /**
  1169. * Adds the key to the presence map, overriding any previous value.
  1170. * @param key
  1171. * @param values
  1172. */
  1173. addToPresence(key, values) {
  1174. values.tagName = key;
  1175. this.removeFromPresence(key);
  1176. this.presMap.nodes.push(values);
  1177. this.presenceUpdateTime = Date.now();
  1178. }
  1179. /**
  1180. * Retrieves a value from the presence map.
  1181. *
  1182. * @param {string} key - The key to find the value for.
  1183. * @returns {Object?}
  1184. */
  1185. getFromPresence(key) {
  1186. return this.presMap.nodes.find(node => key === node.tagName);
  1187. }
  1188. /**
  1189. * Removes a key from the presence map.
  1190. * @param key
  1191. */
  1192. removeFromPresence(key) {
  1193. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  1194. this.presMap.nodes = nodes;
  1195. this.presenceUpdateTime = Date.now();
  1196. }
  1197. /**
  1198. *
  1199. * @param name
  1200. * @param handler
  1201. */
  1202. addPresenceListener(name, handler) {
  1203. if (typeof handler !== 'function') {
  1204. throw new Error('"handler" is not a function');
  1205. }
  1206. let tagHandlers = this.presHandlers[name];
  1207. if (!tagHandlers) {
  1208. this.presHandlers[name] = tagHandlers = [];
  1209. }
  1210. if (tagHandlers.indexOf(handler) === -1) {
  1211. tagHandlers.push(handler);
  1212. } else {
  1213. logger.warn(
  1214. `Trying to add the same handler more than once for: ${name}`);
  1215. }
  1216. }
  1217. /**
  1218. *
  1219. * @param name
  1220. * @param handler
  1221. */
  1222. removePresenceListener(name, handler) {
  1223. const tagHandlers = this.presHandlers[name];
  1224. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  1225. // eslint-disable-next-line no-negated-condition
  1226. if (handlerIdx !== -1) {
  1227. tagHandlers.splice(handlerIdx, 1);
  1228. } else {
  1229. logger.warn(`Handler for: ${name} was not registered`);
  1230. }
  1231. }
  1232. /**
  1233. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1234. * focus.
  1235. * @param mucJid the full MUC address of the user to be checked.
  1236. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  1237. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  1238. * the MUC then <tt>null</tt> is returned.
  1239. */
  1240. isFocus(mucJid) {
  1241. const member = this.members[mucJid];
  1242. if (member) {
  1243. return member.isFocus;
  1244. }
  1245. return null;
  1246. }
  1247. /**
  1248. *
  1249. */
  1250. isModerator() {
  1251. return this.role === 'moderator';
  1252. }
  1253. /**
  1254. *
  1255. * @param peerJid
  1256. */
  1257. getMemberRole(peerJid) {
  1258. if (this.members[peerJid]) {
  1259. return this.members[peerJid].role;
  1260. }
  1261. return null;
  1262. }
  1263. /**
  1264. *
  1265. * @param mute
  1266. * @param callback
  1267. */
  1268. setVideoMute(mute, callback) {
  1269. this.sendVideoInfoPresence(mute);
  1270. if (callback) {
  1271. callback(mute);
  1272. }
  1273. }
  1274. /**
  1275. *
  1276. * @param mute
  1277. * @param callback
  1278. */
  1279. setAudioMute(mute, callback) {
  1280. return this.sendAudioInfoPresence(mute, callback);
  1281. }
  1282. /**
  1283. *
  1284. * @param mute
  1285. */
  1286. addAudioInfoToPresence(mute) {
  1287. this.addToPresence(
  1288. 'audiomuted',
  1289. {
  1290. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/audio' },
  1291. value: mute.toString()
  1292. });
  1293. }
  1294. /**
  1295. *
  1296. * @param mute
  1297. * @param callback
  1298. */
  1299. sendAudioInfoPresence(mute, callback) {
  1300. this.addAudioInfoToPresence(mute);
  1301. // FIXME resend presence on CONNECTED
  1302. this.sendPresence();
  1303. if (callback) {
  1304. callback();
  1305. }
  1306. }
  1307. /**
  1308. *
  1309. * @param mute
  1310. */
  1311. addVideoInfoToPresence(mute) {
  1312. this.addToPresence(
  1313. 'videomuted',
  1314. {
  1315. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/video' },
  1316. value: mute.toString()
  1317. });
  1318. }
  1319. /**
  1320. *
  1321. * @param mute
  1322. */
  1323. sendVideoInfoPresence(mute) {
  1324. this.addVideoInfoToPresence(mute);
  1325. this.sendPresence();
  1326. }
  1327. /**
  1328. * Obtains the info about given media advertised in the MUC presence of
  1329. * the participant identified by the given endpoint JID.
  1330. * @param {string} endpointId the endpoint ID mapped to the participant
  1331. * which corresponds to MUC nickname.
  1332. * @param {MediaType} mediaType the type of the media for which presence
  1333. * info will be obtained.
  1334. * @return {PeerMediaInfo} presenceInfo an object with media presence
  1335. * info or <tt>null</tt> either if there is no presence available or if
  1336. * the media type given is invalid.
  1337. */
  1338. getMediaPresenceInfo(endpointId, mediaType) {
  1339. // Will figure out current muted status by looking up owner's presence
  1340. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1341. if (!pres) {
  1342. // No presence available
  1343. return null;
  1344. }
  1345. const data = {
  1346. muted: false, // unmuted by default
  1347. videoType: undefined // no video type by default
  1348. };
  1349. let mutedNode = null;
  1350. if (mediaType === MediaType.AUDIO) {
  1351. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1352. } else if (mediaType === MediaType.VIDEO) {
  1353. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1354. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1355. if (videoTypeNode.length > 0) {
  1356. data.videoType = videoTypeNode[0].value;
  1357. }
  1358. } else {
  1359. logger.error(`Unsupported media type: ${mediaType}`);
  1360. return null;
  1361. }
  1362. data.muted = mutedNode.length > 0 && mutedNode[0].value === 'true';
  1363. return data;
  1364. }
  1365. /**
  1366. * Returns true if the SIP calls are supported and false otherwise
  1367. */
  1368. isSIPCallingSupported() {
  1369. if (this.moderator) {
  1370. return this.moderator.isSipGatewayEnabled();
  1371. }
  1372. return false;
  1373. }
  1374. /**
  1375. * Dials a number.
  1376. * @param number the number
  1377. */
  1378. dial(number) {
  1379. return this.connection.rayo.dial(number, 'fromnumber',
  1380. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1381. this.focusMucJid);
  1382. }
  1383. /**
  1384. * Hangup an existing call
  1385. */
  1386. hangup() {
  1387. return this.connection.rayo.hangup();
  1388. }
  1389. /**
  1390. *
  1391. * @returns {Lobby}
  1392. */
  1393. getLobby() {
  1394. return this.lobby;
  1395. }
  1396. /**
  1397. * Returns the phone number for joining the conference.
  1398. */
  1399. getPhoneNumber() {
  1400. return this.phoneNumber;
  1401. }
  1402. /**
  1403. * Returns the pin for joining the conference with phone.
  1404. */
  1405. getPhonePin() {
  1406. return this.phonePin;
  1407. }
  1408. /**
  1409. * Returns the meeting unique ID if any came from backend.
  1410. *
  1411. * @returns {string} - The meeting ID.
  1412. */
  1413. getMeetingId() {
  1414. return this.meetingId;
  1415. }
  1416. /**
  1417. * Mutes remote participant.
  1418. * @param jid of the participant
  1419. * @param mute
  1420. */
  1421. muteParticipant(jid, mute) {
  1422. logger.info('set mute', mute);
  1423. const iqToFocus = $iq(
  1424. { to: this.focusMucJid,
  1425. type: 'set' })
  1426. .c('mute', {
  1427. xmlns: 'http://jitsi.org/jitmeet/audio',
  1428. jid
  1429. })
  1430. .t(mute.toString())
  1431. .up();
  1432. this.connection.sendIQ(
  1433. iqToFocus,
  1434. result => logger.log('set mute', result),
  1435. error => logger.log('set mute error', error));
  1436. }
  1437. /**
  1438. * TODO: Document
  1439. * @param iq
  1440. */
  1441. onMute(iq) {
  1442. const from = iq.getAttribute('from');
  1443. if (from !== this.focusMucJid) {
  1444. logger.warn('Ignored mute from non focus peer');
  1445. return;
  1446. }
  1447. const mute = $(iq).find('mute');
  1448. if (mute.length && mute.text() === 'true') {
  1449. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, mute.attr('actor'));
  1450. } else {
  1451. // XXX Why do we support anything but muting? Why do we encode the
  1452. // value in the text of the element? Why do we use a separate XML
  1453. // namespace?
  1454. logger.warn('Ignoring a mute request which does not explicitly '
  1455. + 'specify a positive mute command.');
  1456. }
  1457. }
  1458. /**
  1459. * Clean any listeners or resources, executed on leaving.
  1460. */
  1461. clean() {
  1462. this._removeConnListeners.forEach(remove => remove());
  1463. this._removeConnListeners = [];
  1464. this.joined = false;
  1465. }
  1466. /**
  1467. * Leaves the room. Closes the jingle session.
  1468. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1469. * less than 5s after sending presence unavailable. Otherwise the promise is
  1470. * rejected.
  1471. */
  1472. leave() {
  1473. return new Promise((resolve, reject) => {
  1474. const timeout = setTimeout(() => onMucLeft(true), 5000);
  1475. const eventEmitter = this.eventEmitter;
  1476. this.clean();
  1477. /**
  1478. *
  1479. * @param doReject
  1480. */
  1481. function onMucLeft(doReject = false) {
  1482. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1483. clearTimeout(timeout);
  1484. if (doReject) {
  1485. // the timeout expired
  1486. reject(new Error('The timeout for the confirmation about '
  1487. + 'leaving the room expired.'));
  1488. } else {
  1489. resolve();
  1490. }
  1491. }
  1492. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1493. this.doLeave();
  1494. });
  1495. }
  1496. }
  1497. /* eslint-enable newline-per-chained-call */