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

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