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

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