You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 45KB

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