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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  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 (this.members[from] === undefined) {
  406. // new participant
  407. this.members[from] = member;
  408. logger.log('entered', from, member);
  409. hasStatusUpdate = member.status !== undefined;
  410. hasVersionUpdate = member.version !== undefined;
  411. if (member.isFocus) {
  412. this._initFocus(from, jid);
  413. } else {
  414. // identity is being added to member joined, so external
  415. // services can be notified for that (currently identity is
  416. // not used inside library)
  417. this.eventEmitter.emit(
  418. XMPPEvents.MUC_MEMBER_JOINED,
  419. from,
  420. member.nick,
  421. member.role,
  422. member.isHiddenDomain,
  423. member.statsID,
  424. member.status,
  425. member.identity,
  426. member.botType);
  427. // we are reporting the status with the join
  428. // so we do not want a second event about status update
  429. hasStatusUpdate = false;
  430. }
  431. } else {
  432. // Presence update for existing participant
  433. // Watch role change:
  434. const memberOfThis = this.members[from];
  435. if (memberOfThis.role !== member.role) {
  436. memberOfThis.role = member.role;
  437. this.eventEmitter.emit(
  438. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  439. }
  440. // fire event that botType had changed
  441. if (memberOfThis.botType !== member.botType) {
  442. memberOfThis.botType = member.botType;
  443. this.eventEmitter.emit(
  444. XMPPEvents.MUC_MEMBER_BOT_TYPE_CHANGED,
  445. from,
  446. member.botType);
  447. }
  448. if (member.isFocus) {
  449. // From time to time first few presences of the focus are not
  450. // containing it's jid. That way we can mark later the focus
  451. // member instead of not marking it at all and not starting the
  452. // conference.
  453. // FIXME: Maybe there is a better way to handle this issue. It
  454. // seems there is some period of time in prosody that the
  455. // configuration form is received but not applied. And if any
  456. // participant joins during that period of time the first
  457. // presence from the focus won't contain
  458. // <item jid="focus..." />.
  459. memberOfThis.isFocus = true;
  460. this._initFocus(from, jid);
  461. }
  462. // store the new display name
  463. if (member.displayName) {
  464. memberOfThis.displayName = member.displayName;
  465. }
  466. // update stored status message to be able to detect changes
  467. if (memberOfThis.status !== member.status) {
  468. hasStatusUpdate = true;
  469. memberOfThis.status = member.status;
  470. }
  471. if (memberOfThis.version !== member.version) {
  472. hasVersionUpdate = true;
  473. memberOfThis.version = member.version;
  474. }
  475. }
  476. // after we had fired member or room joined events, lets fire events
  477. // for the rest info we got in presence
  478. for (let i = 0; i < nodes.length; i++) {
  479. const node = nodes[i];
  480. switch (node.tagName) {
  481. case 'nick':
  482. if (!member.isFocus) {
  483. const displayName
  484. = this.xmpp.options.displayJids
  485. ? Strophe.getResourceFromJid(from)
  486. : member.nick;
  487. this.eventEmitter.emit(
  488. XMPPEvents.DISPLAY_NAME_CHANGED,
  489. from,
  490. displayName);
  491. }
  492. break;
  493. case 'bridgeNotAvailable':
  494. if (member.isFocus && !this.noBridgeAvailable) {
  495. this.noBridgeAvailable = true;
  496. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  497. }
  498. break;
  499. case 'conference-properties':
  500. if (member.isFocus) {
  501. const properties = {};
  502. for (let j = 0; j < node.children.length; j++) {
  503. const { attributes } = node.children[j];
  504. if (attributes && attributes.key) {
  505. properties[attributes.key] = attributes.value;
  506. }
  507. }
  508. this.eventEmitter.emit(
  509. XMPPEvents.CONFERENCE_PROPERTIES_CHANGED, properties);
  510. }
  511. break;
  512. case 'transcription-status': {
  513. const { attributes } = node;
  514. if (!attributes) {
  515. break;
  516. }
  517. const { status } = attributes;
  518. if (status && status !== this.transcriptionStatus) {
  519. this.transcriptionStatus = status;
  520. this.eventEmitter.emit(
  521. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  522. status
  523. );
  524. }
  525. break;
  526. }
  527. case 'call-control': {
  528. const att = node.attributes;
  529. if (!att) {
  530. break;
  531. }
  532. this.phoneNumber = att.phone || null;
  533. this.phonePin = att.pin || null;
  534. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  535. break;
  536. }
  537. default:
  538. this.processNode(node, from);
  539. }
  540. }
  541. // Trigger status message update if necessary
  542. if (hasStatusUpdate) {
  543. this.eventEmitter.emit(
  544. XMPPEvents.PRESENCE_STATUS,
  545. from,
  546. member.status);
  547. }
  548. if (hasVersionUpdate) {
  549. logger.info(`Received version for ${jid}: ${member.version}`);
  550. }
  551. }
  552. /**
  553. * Initialize some properties when the focus participant is verified.
  554. * @param from jid of the focus
  555. * @param mucJid the jid of the focus in the muc
  556. */
  557. _initFocus(from, mucJid) {
  558. this.focusMucJid = from;
  559. logger.info(`Ignore focus: ${from}, real JID: ${mucJid}`);
  560. }
  561. /**
  562. * Sets the special listener to be used for "command"s whose name starts
  563. * with "jitsi_participant_".
  564. */
  565. setParticipantPropertyListener(listener) {
  566. this.participantPropertyListener = listener;
  567. }
  568. /**
  569. *
  570. * @param node
  571. * @param from
  572. */
  573. processNode(node, from) {
  574. // make sure we catch all errors coming from any handler
  575. // otherwise we can remove the presence handler from strophe
  576. try {
  577. let tagHandlers = this.presHandlers[node.tagName];
  578. if (node.tagName.startsWith('jitsi_participant_')) {
  579. tagHandlers = [ this.participantPropertyListener ];
  580. }
  581. if (tagHandlers) {
  582. tagHandlers.forEach(handler => {
  583. handler(node, Strophe.getResourceFromJid(from), from);
  584. });
  585. }
  586. } catch (e) {
  587. GlobalOnErrorHandler.callErrorHandler(e);
  588. logger.error(`Error processing:${node.tagName} node.`, e);
  589. }
  590. }
  591. /**
  592. * Send text message to the other participants in the conference
  593. * @param message
  594. * @param elementName
  595. * @param nickname
  596. */
  597. sendMessage(message, elementName, nickname) {
  598. const msg = $msg({ to: this.roomjid,
  599. type: 'groupchat' });
  600. // We are adding the message in a packet extension. If this element
  601. // is different from 'body', we add a custom namespace.
  602. // e.g. for 'json-message' extension of message stanza.
  603. if (elementName === 'body') {
  604. msg.c(elementName, message).up();
  605. } else {
  606. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  607. .up();
  608. }
  609. if (nickname) {
  610. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  611. .t(nickname)
  612. .up()
  613. .up();
  614. }
  615. this.connection.send(msg);
  616. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, message);
  617. }
  618. /* eslint-disable max-params */
  619. /**
  620. * Send private text message to another participant of the conference
  621. * @param id id/muc resource of the receiver
  622. * @param message
  623. * @param elementName
  624. * @param nickname
  625. */
  626. sendPrivateMessage(id, message, elementName, nickname) {
  627. const msg = $msg({ to: `${this.roomjid}/${id}`,
  628. type: 'chat' });
  629. // We are adding the message in packet. If this element is different
  630. // from 'body', we add our custom namespace for the same.
  631. // e.g. for 'json-message' message extension.
  632. if (elementName === 'body') {
  633. msg.c(elementName, message).up();
  634. } else {
  635. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  636. .up();
  637. }
  638. if (nickname) {
  639. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  640. .t(nickname)
  641. .up()
  642. .up();
  643. }
  644. this.connection.send(msg);
  645. this.eventEmitter.emit(
  646. XMPPEvents.SENDING_PRIVATE_CHAT_MESSAGE, message);
  647. }
  648. /* eslint-enable max-params */
  649. /**
  650. *
  651. * @param subject
  652. */
  653. setSubject(subject) {
  654. const msg = $msg({ to: this.roomjid,
  655. type: 'groupchat' });
  656. msg.c('subject', subject);
  657. this.connection.send(msg);
  658. }
  659. /**
  660. * Called when participant leaves.
  661. * @param jid the jid of the participant that leaves
  662. * @param skipEvents optional params to skip any events, including check
  663. * whether this is the focus that left
  664. */
  665. onParticipantLeft(jid, skipEvents) {
  666. delete this.lastPresences[jid];
  667. if (skipEvents) {
  668. return;
  669. }
  670. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  671. this.moderator.onMucMemberLeft(jid);
  672. }
  673. /**
  674. *
  675. * @param pres
  676. * @param from
  677. */
  678. onPresenceUnavailable(pres, from) {
  679. // ignore presence
  680. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  681. return true;
  682. }
  683. // room destroyed ?
  684. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]'
  685. + '>destroy').length) {
  686. let reason;
  687. const reasonSelect
  688. = $(pres).find(
  689. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  690. + '>destroy>reason');
  691. if (reasonSelect.length) {
  692. reason = reasonSelect.text();
  693. }
  694. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  695. this.connection.emuc.doLeave(this.roomjid);
  696. return true;
  697. }
  698. // Status code 110 indicates that this notification is "self-presence".
  699. const isSelfPresence
  700. = $(pres)
  701. .find(
  702. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  703. + 'status[code="110"]')
  704. .length;
  705. const isKick
  706. = $(pres)
  707. .find(
  708. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  709. + '>status[code="307"]')
  710. .length;
  711. const membersKeys = Object.keys(this.members);
  712. if (isKick) {
  713. const actorSelect
  714. = $(pres)
  715. .find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item>actor');
  716. let actorNick;
  717. if (actorSelect.length) {
  718. actorNick = actorSelect.attr('nick');
  719. }
  720. // if no member is found this is the case we had kicked someone
  721. // and we are not in the list of members
  722. if (membersKeys.find(jid => Strophe.getResourceFromJid(jid) === actorNick)) {
  723. // we first fire the kicked so we can show the participant
  724. // who kicked, before notifying that participant left
  725. // we fire kicked for us and for any participant kicked
  726. this.eventEmitter.emit(
  727. XMPPEvents.KICKED,
  728. isSelfPresence,
  729. actorNick,
  730. Strophe.getResourceFromJid(from));
  731. }
  732. }
  733. if (!isSelfPresence) {
  734. delete this.members[from];
  735. this.onParticipantLeft(from, false);
  736. } else if (membersKeys.length > 0) {
  737. // If the status code is 110 this means we're leaving and we would
  738. // like to remove everyone else from our view, so we trigger the
  739. // event.
  740. membersKeys.forEach(jid => {
  741. const member = this.members[jid];
  742. delete this.members[jid];
  743. this.onParticipantLeft(jid, member.isFocus);
  744. });
  745. this.connection.emuc.doLeave(this.roomjid);
  746. // we fire muc_left only if this is not a kick,
  747. // kick has both statuses 110 and 307.
  748. if (!isKick) {
  749. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  750. }
  751. }
  752. }
  753. /**
  754. *
  755. * @param msg
  756. * @param from
  757. */
  758. onMessage(msg, from) {
  759. const nick
  760. = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  761. .text()
  762. || Strophe.getResourceFromJid(from);
  763. const txt = $(msg).find('>body').text();
  764. const type = msg.getAttribute('type');
  765. if (type === 'error') {
  766. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  767. $(msg).find('>text').text(), txt);
  768. return true;
  769. }
  770. const subject = $(msg).find('>subject');
  771. if (subject.length) {
  772. const subjectText = subject.text();
  773. if (subjectText || subjectText === '') {
  774. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  775. logger.log(`Subject is changed to ${subjectText}`);
  776. }
  777. }
  778. // xep-0203 delay
  779. let stamp = $(msg).find('>delay').attr('stamp');
  780. if (!stamp) {
  781. // or xep-0091 delay, UTC timestamp
  782. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  783. if (stamp) {
  784. // the format is CCYYMMDDThh:mm:ss
  785. const dateParts
  786. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  787. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  788. }
  789. }
  790. if (from === this.roomjid
  791. && $(msg)
  792. .find(
  793. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  794. + '>status[code="104"]')
  795. .length) {
  796. this.discoRoomInfo();
  797. }
  798. const jsonMessage = $(msg).find('>json-message').text();
  799. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  800. // We emit this event if the message is a valid json, and is not
  801. // delivered after a delay, i.e. stamp is undefined.
  802. // e.g. - subtitles should not be displayed if delayed.
  803. if (parsedJson && stamp === undefined) {
  804. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  805. from, parsedJson);
  806. return;
  807. }
  808. if (txt) {
  809. if (type === 'chat') {
  810. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  811. from, nick, txt, this.myroomjid, stamp);
  812. } else if (type === 'groupchat') {
  813. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  814. from, nick, txt, this.myroomjid, stamp);
  815. }
  816. }
  817. }
  818. /**
  819. *
  820. * @param pres
  821. * @param from
  822. */
  823. onPresenceError(pres, from) {
  824. if ($(pres)
  825. .find(
  826. '>error[type="auth"]'
  827. + '>not-authorized['
  828. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  829. .length) {
  830. logger.log('on password required', from);
  831. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  832. } else if ($(pres)
  833. .find(
  834. '>error[type="cancel"]'
  835. + '>not-allowed['
  836. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  837. .length) {
  838. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  839. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  840. // enter the room by replying with 'not-authorized'. This would
  841. // result in reconnection from authorized domain.
  842. // We're either missing Jicofo/Prosody config for anonymous
  843. // domains or something is wrong.
  844. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  845. } else {
  846. logger.warn('onPresError ', pres);
  847. this.eventEmitter.emit(
  848. XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  849. }
  850. } else if ($(pres).find('>error>service-unavailable').length) {
  851. logger.warn('Maximum users limit for the room has been reached',
  852. pres);
  853. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  854. } else {
  855. logger.warn('onPresError ', pres);
  856. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  857. }
  858. }
  859. /**
  860. *
  861. * @param jid
  862. */
  863. kick(jid) {
  864. const kickIQ = $iq({ to: this.roomjid,
  865. type: 'set' })
  866. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  867. .c('item', { nick: Strophe.getResourceFromJid(jid),
  868. role: 'none' })
  869. .c('reason').t('You have been kicked.').up().up().up();
  870. this.connection.sendIQ(
  871. kickIQ,
  872. result => logger.log('Kick participant with jid: ', jid, result),
  873. error => logger.log('Kick participant error: ', error));
  874. }
  875. /* eslint-disable max-params */
  876. /**
  877. *
  878. * @param key
  879. * @param onSuccess
  880. * @param onError
  881. * @param onNotSupported
  882. */
  883. lockRoom(key, onSuccess, onError, onNotSupported) {
  884. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  885. this.connection.sendIQ(
  886. $iq({
  887. to: this.roomjid,
  888. type: 'get'
  889. })
  890. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  891. res => {
  892. if ($(res)
  893. .find(
  894. '>query>x[xmlns="jabber:x:data"]'
  895. + '>field[var="muc#roomconfig_roomsecret"]')
  896. .length) {
  897. const formsubmit
  898. = $iq({
  899. to: this.roomjid,
  900. type: 'set'
  901. })
  902. .c('query', {
  903. xmlns: 'http://jabber.org/protocol/muc#owner'
  904. });
  905. formsubmit.c('x', {
  906. xmlns: 'jabber:x:data',
  907. type: 'submit'
  908. });
  909. formsubmit
  910. .c('field', { 'var': 'FORM_TYPE' })
  911. .c('value')
  912. .t('http://jabber.org/protocol/muc#roomconfig')
  913. .up()
  914. .up();
  915. formsubmit
  916. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  917. .c('value')
  918. .t(key)
  919. .up()
  920. .up();
  921. // Fixes a bug in prosody 0.9.+
  922. // https://prosody.im/issues/issue/373
  923. formsubmit
  924. .c('field', { 'var': 'muc#roomconfig_whois' })
  925. .c('value')
  926. .t('anyone')
  927. .up()
  928. .up();
  929. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  930. this.connection.sendIQ(formsubmit, onSuccess, onError);
  931. } else {
  932. onNotSupported();
  933. }
  934. },
  935. onError);
  936. }
  937. /* eslint-enable max-params */
  938. /**
  939. *
  940. * @param key
  941. * @param values
  942. */
  943. addToPresence(key, values) {
  944. values.tagName = key;
  945. this.removeFromPresence(key);
  946. this.presMap.nodes.push(values);
  947. }
  948. /**
  949. * Retreives a value from the presence map.
  950. *
  951. * @param {string} key - The key to find the value for.
  952. * @returns {Object?}
  953. */
  954. getFromPresence(key) {
  955. return this.presMap.nodes.find(node => key === node.tagName);
  956. }
  957. /**
  958. *
  959. * @param key
  960. */
  961. removeFromPresence(key) {
  962. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  963. this.presMap.nodes = nodes;
  964. }
  965. /**
  966. *
  967. * @param name
  968. * @param handler
  969. */
  970. addPresenceListener(name, handler) {
  971. if (typeof handler !== 'function') {
  972. throw new Error('"handler" is not a function');
  973. }
  974. let tagHandlers = this.presHandlers[name];
  975. if (!tagHandlers) {
  976. this.presHandlers[name] = tagHandlers = [];
  977. }
  978. if (tagHandlers.indexOf(handler) === -1) {
  979. tagHandlers.push(handler);
  980. } else {
  981. logger.warn(
  982. `Trying to add the same handler more than once for: ${name}`);
  983. }
  984. }
  985. /**
  986. *
  987. * @param name
  988. * @param handler
  989. */
  990. removePresenceListener(name, handler) {
  991. const tagHandlers = this.presHandlers[name];
  992. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  993. // eslint-disable-next-line no-negated-condition
  994. if (handlerIdx !== -1) {
  995. tagHandlers.splice(handlerIdx, 1);
  996. } else {
  997. logger.warn(`Handler for: ${name} was not registered`);
  998. }
  999. }
  1000. /**
  1001. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1002. * focus.
  1003. * @param mucJid the full MUC address of the user to be checked.
  1004. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  1005. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  1006. * the MUC then <tt>null</tt> is returned.
  1007. */
  1008. isFocus(mucJid) {
  1009. const member = this.members[mucJid];
  1010. if (member) {
  1011. return member.isFocus;
  1012. }
  1013. return null;
  1014. }
  1015. /**
  1016. *
  1017. */
  1018. isModerator() {
  1019. return this.role === 'moderator';
  1020. }
  1021. /**
  1022. *
  1023. * @param peerJid
  1024. */
  1025. getMemberRole(peerJid) {
  1026. if (this.members[peerJid]) {
  1027. return this.members[peerJid].role;
  1028. }
  1029. return null;
  1030. }
  1031. /**
  1032. *
  1033. * @param mute
  1034. * @param callback
  1035. */
  1036. setVideoMute(mute, callback) {
  1037. this.sendVideoInfoPresence(mute);
  1038. if (callback) {
  1039. callback(mute);
  1040. }
  1041. }
  1042. /**
  1043. *
  1044. * @param mute
  1045. * @param callback
  1046. */
  1047. setAudioMute(mute, callback) {
  1048. return this.sendAudioInfoPresence(mute, callback);
  1049. }
  1050. /**
  1051. *
  1052. * @param mute
  1053. */
  1054. addAudioInfoToPresence(mute) {
  1055. this.removeFromPresence('audiomuted');
  1056. this.addToPresence(
  1057. 'audiomuted',
  1058. {
  1059. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/audio' },
  1060. value: mute.toString()
  1061. });
  1062. }
  1063. /**
  1064. *
  1065. * @param mute
  1066. * @param callback
  1067. */
  1068. sendAudioInfoPresence(mute, callback) {
  1069. this.addAudioInfoToPresence(mute);
  1070. if (this.connection) {
  1071. this.sendPresence();
  1072. }
  1073. if (callback) {
  1074. callback();
  1075. }
  1076. }
  1077. /**
  1078. *
  1079. * @param mute
  1080. */
  1081. addVideoInfoToPresence(mute) {
  1082. this.removeFromPresence('videomuted');
  1083. this.addToPresence(
  1084. 'videomuted',
  1085. {
  1086. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/video' },
  1087. value: mute.toString()
  1088. });
  1089. }
  1090. /**
  1091. *
  1092. * @param mute
  1093. */
  1094. sendVideoInfoPresence(mute) {
  1095. this.addVideoInfoToPresence(mute);
  1096. if (!this.connection) {
  1097. return;
  1098. }
  1099. this.sendPresence();
  1100. }
  1101. /**
  1102. * Obtains the info about given media advertised in the MUC presence of
  1103. * the participant identified by the given endpoint JID.
  1104. * @param {string} endpointId the endpoint ID mapped to the participant
  1105. * which corresponds to MUC nickname.
  1106. * @param {MediaType} mediaType the type of the media for which presence
  1107. * info will be obtained.
  1108. * @return {PeerMediaInfo} presenceInfo an object with media presence
  1109. * info or <tt>null</tt> either if there is no presence available or if
  1110. * the media type given is invalid.
  1111. */
  1112. getMediaPresenceInfo(endpointId, mediaType) {
  1113. // Will figure out current muted status by looking up owner's presence
  1114. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1115. if (!pres) {
  1116. // No presence available
  1117. return null;
  1118. }
  1119. const data = {
  1120. muted: false, // unmuted by default
  1121. videoType: undefined // no video type by default
  1122. };
  1123. let mutedNode = null;
  1124. if (mediaType === MediaType.AUDIO) {
  1125. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1126. } else if (mediaType === MediaType.VIDEO) {
  1127. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1128. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1129. if (videoTypeNode.length > 0) {
  1130. data.videoType = videoTypeNode[0].value;
  1131. }
  1132. } else {
  1133. logger.error(`Unsupported media type: ${mediaType}`);
  1134. return null;
  1135. }
  1136. data.muted = mutedNode.length > 0 && mutedNode[0].value === 'true';
  1137. return data;
  1138. }
  1139. /**
  1140. * Returns true if the SIP calls are supported and false otherwise
  1141. */
  1142. isSIPCallingSupported() {
  1143. if (this.moderator) {
  1144. return this.moderator.isSipGatewayEnabled();
  1145. }
  1146. return false;
  1147. }
  1148. /**
  1149. * Dials a number.
  1150. * @param number the number
  1151. */
  1152. dial(number) {
  1153. return this.connection.rayo.dial(number, 'fromnumber',
  1154. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1155. this.focusMucJid);
  1156. }
  1157. /**
  1158. * Hangup an existing call
  1159. */
  1160. hangup() {
  1161. return this.connection.rayo.hangup();
  1162. }
  1163. /**
  1164. * Returns the phone number for joining the conference.
  1165. */
  1166. getPhoneNumber() {
  1167. return this.phoneNumber;
  1168. }
  1169. /**
  1170. * Returns the pin for joining the conference with phone.
  1171. */
  1172. getPhonePin() {
  1173. return this.phonePin;
  1174. }
  1175. /**
  1176. * Mutes remote participant.
  1177. * @param jid of the participant
  1178. * @param mute
  1179. */
  1180. muteParticipant(jid, mute) {
  1181. logger.info('set mute', mute);
  1182. const iqToFocus = $iq(
  1183. { to: this.focusMucJid,
  1184. type: 'set' })
  1185. .c('mute', {
  1186. xmlns: 'http://jitsi.org/jitmeet/audio',
  1187. jid
  1188. })
  1189. .t(mute.toString())
  1190. .up();
  1191. this.connection.sendIQ(
  1192. iqToFocus,
  1193. result => logger.log('set mute', result),
  1194. error => logger.log('set mute error', error));
  1195. }
  1196. /**
  1197. * TODO: Document
  1198. * @param iq
  1199. */
  1200. onMute(iq) {
  1201. const from = iq.getAttribute('from');
  1202. if (from !== this.focusMucJid) {
  1203. logger.warn('Ignored mute from non focus peer');
  1204. return;
  1205. }
  1206. const mute = $(iq).find('mute');
  1207. if (mute.length && mute.text() === 'true') {
  1208. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, mute.attr('actor'));
  1209. } else {
  1210. // XXX Why do we support anything but muting? Why do we encode the
  1211. // value in the text of the element? Why do we use a separate XML
  1212. // namespace?
  1213. logger.warn('Ignoring a mute request which does not explicitly '
  1214. + 'specify a positive mute command.');
  1215. }
  1216. }
  1217. /**
  1218. * Leaves the room. Closes the jingle session.
  1219. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1220. * less than 5s after sending presence unavailable. Otherwise the promise is
  1221. * rejected.
  1222. */
  1223. leave() {
  1224. return new Promise((resolve, reject) => {
  1225. const timeout = setTimeout(() => onMucLeft(true), 5000);
  1226. const eventEmitter = this.eventEmitter;
  1227. /**
  1228. *
  1229. * @param doReject
  1230. */
  1231. function onMucLeft(doReject = false) {
  1232. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1233. clearTimeout(timeout);
  1234. if (doReject) {
  1235. // the timeout expired
  1236. reject(new Error('The timeout for the confirmation about '
  1237. + 'leaving the room expired.'));
  1238. } else {
  1239. resolve();
  1240. }
  1241. }
  1242. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1243. this.doLeave();
  1244. });
  1245. }
  1246. }
  1247. /* eslint-enable newline-per-chained-call */