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

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