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

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