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 42KB

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