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

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