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

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