modified lib-jitsi-meet dev repo
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 37KB

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