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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  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. hasStatusUpdate = member.status !== undefined;
  411. if (member.isFocus) {
  412. this._initFocus(from, jid);
  413. } else {
  414. this.eventEmitter.emit(
  415. XMPPEvents.MUC_MEMBER_JOINED,
  416. from,
  417. member.nick,
  418. member.role,
  419. member.isHiddenDomain,
  420. member.statsID,
  421. member.status);
  422. // we are reporting the status with the join
  423. // so we do not want a second event about status update
  424. hasStatusUpdate = false;
  425. }
  426. } else {
  427. // Presence update for existing participant
  428. // Watch role change:
  429. const memberOfThis = this.members[from];
  430. if (memberOfThis.role !== member.role) {
  431. memberOfThis.role = member.role;
  432. this.eventEmitter.emit(
  433. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  434. }
  435. if (member.isFocus) {
  436. // From time to time first few presences of the focus are not
  437. // containing it's jid. That way we can mark later the focus
  438. // member instead of not marking it at all and not starting the
  439. // conference.
  440. // FIXME: Maybe there is a better way to handle this issue. It
  441. // seems there is some period of time in prosody that the
  442. // configuration form is received but not applied. And if any
  443. // participant joins during that period of time the first
  444. // presence from the focus won't conain <item jid="focus..." />.
  445. memberOfThis.isFocus = true;
  446. this._initFocus(from, jid);
  447. }
  448. // store the new display name
  449. if (member.displayName) {
  450. memberOfThis.displayName = member.displayName;
  451. }
  452. // update stored status message to be able to detect changes
  453. if (memberOfThis.status !== member.status) {
  454. hasStatusUpdate = true;
  455. memberOfThis.status = member.status;
  456. }
  457. }
  458. // after we had fired member or room joined events, lets fire events
  459. // for the rest info we got in presence
  460. for (let i = 0; i < nodes.length; i++) {
  461. const node = nodes[i];
  462. switch (node.tagName) {
  463. case 'nick':
  464. if (!member.isFocus) {
  465. const displayName
  466. = this.xmpp.options.displayJids
  467. ? Strophe.getResourceFromJid(from)
  468. : member.nick;
  469. if (displayName && displayName.length > 0) {
  470. this.eventEmitter.emit(
  471. XMPPEvents.DISPLAY_NAME_CHANGED,
  472. from,
  473. displayName);
  474. }
  475. }
  476. break;
  477. case 'bridgeNotAvailable':
  478. if (member.isFocus && !this.noBridgeAvailable) {
  479. this.noBridgeAvailable = true;
  480. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  481. }
  482. break;
  483. case 'jibri-recording-status':
  484. jibri = node;
  485. break;
  486. case 'transcription-status': {
  487. const { attributes } = node;
  488. if (!attributes) {
  489. break;
  490. }
  491. const { status } = attributes;
  492. if (status && status !== this.transcriptionStatus) {
  493. this.transcriptionStatus = status;
  494. this.eventEmitter.emit(
  495. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  496. status
  497. );
  498. }
  499. break;
  500. }
  501. case 'call-control': {
  502. const att = node.attributes;
  503. if (!att) {
  504. break;
  505. }
  506. this.phoneNumber = att.phone || null;
  507. this.phonePin = att.pin || null;
  508. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  509. break;
  510. }
  511. default:
  512. this.processNode(node, from);
  513. }
  514. }
  515. // Trigger status message update if necessary
  516. if (hasStatusUpdate) {
  517. this.eventEmitter.emit(
  518. XMPPEvents.PRESENCE_STATUS,
  519. from,
  520. member.status);
  521. }
  522. if (jibri) {
  523. this.lastJibri = jibri;
  524. if (this.recording) {
  525. this.recording.handleJibriPresence(jibri);
  526. }
  527. }
  528. }
  529. /**
  530. * Initialize some properties when the focus participant is verified.
  531. * @param from jid of the focus
  532. * @param mucJid the jid of the focus in the muc
  533. */
  534. _initFocus(from, mucJid) {
  535. this.focusMucJid = from;
  536. if (!this.recording) {
  537. this.recording = new Recorder(this.options.recordingType,
  538. this.eventEmitter, this.connection, this.focusMucJid,
  539. this.options.jirecon, this.roomjid);
  540. if (this.lastJibri) {
  541. this.recording.handleJibriPresence(this.lastJibri);
  542. }
  543. }
  544. logger.info(`Ignore focus: ${from}, real JID: ${mucJid}`);
  545. }
  546. /**
  547. * Sets the special listener to be used for "command"s whose name starts
  548. * with "jitsi_participant_".
  549. */
  550. setParticipantPropertyListener(listener) {
  551. this.participantPropertyListener = listener;
  552. }
  553. /**
  554. *
  555. * @param node
  556. * @param from
  557. */
  558. processNode(node, from) {
  559. // make sure we catch all errors coming from any handler
  560. // otherwise we can remove the presence handler from strophe
  561. try {
  562. let tagHandlers = this.presHandlers[node.tagName];
  563. if (node.tagName.startsWith('jitsi_participant_')) {
  564. tagHandlers = [ this.participantPropertyListener ];
  565. }
  566. if (tagHandlers) {
  567. tagHandlers.forEach(handler => {
  568. handler(node, Strophe.getResourceFromJid(from), from);
  569. });
  570. }
  571. } catch (e) {
  572. GlobalOnErrorHandler.callErrorHandler(e);
  573. logger.error(`Error processing:${node.tagName} node.`, e);
  574. }
  575. }
  576. /**
  577. *
  578. * @param body
  579. * @param nickname
  580. */
  581. sendMessage(body, nickname) {
  582. const msg = $msg({ to: this.roomjid,
  583. type: 'groupchat' });
  584. msg.c('body', body).up();
  585. if (nickname) {
  586. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  587. .t(nickname)
  588. .up()
  589. .up();
  590. }
  591. this.connection.send(msg);
  592. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  593. }
  594. /**
  595. *
  596. * @param subject
  597. */
  598. setSubject(subject) {
  599. const msg = $msg({ to: this.roomjid,
  600. type: 'groupchat' });
  601. msg.c('subject', subject);
  602. this.connection.send(msg);
  603. }
  604. /**
  605. * Called when participant leaves.
  606. * @param jid the jid of the participant that leaves
  607. * @param skipEvents optional params to skip any events, including check
  608. * whether this is the focus that left
  609. */
  610. onParticipantLeft(jid, skipEvents) {
  611. delete this.lastPresences[jid];
  612. if (skipEvents) {
  613. return;
  614. }
  615. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  616. this.moderator.onMucMemberLeft(jid);
  617. }
  618. /**
  619. *
  620. * @param pres
  621. * @param from
  622. */
  623. onPresenceUnavailable(pres, from) {
  624. // ignore presence
  625. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  626. return true;
  627. }
  628. // room destroyed ?
  629. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]'
  630. + '>destroy').length) {
  631. let reason;
  632. const reasonSelect
  633. = $(pres).find(
  634. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  635. + '>destroy>reason');
  636. if (reasonSelect.length) {
  637. reason = reasonSelect.text();
  638. }
  639. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  640. this.connection.emuc.doLeave(this.roomjid);
  641. return true;
  642. }
  643. // Status code 110 indicates that this notification is "self-presence".
  644. const isSelfPresence
  645. = $(pres)
  646. .find(
  647. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  648. + 'status[code="110"]')
  649. .length;
  650. const isKick
  651. = $(pres)
  652. .find(
  653. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  654. + '>status[code="307"]')
  655. .length;
  656. const membersKeys = Object.keys(this.members);
  657. if (!isSelfPresence) {
  658. delete this.members[from];
  659. this.onParticipantLeft(from, false);
  660. } else if (membersKeys.length > 0) {
  661. // If the status code is 110 this means we're leaving and we would
  662. // like to remove everyone else from our view, so we trigger the
  663. // event.
  664. membersKeys.forEach(jid => {
  665. const member = this.members[jid];
  666. delete this.members[jid];
  667. this.onParticipantLeft(jid, member.isFocus);
  668. });
  669. this.connection.emuc.doLeave(this.roomjid);
  670. // we fire muc_left only if this is not a kick,
  671. // kick has both statuses 110 and 307.
  672. if (!isKick) {
  673. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  674. }
  675. }
  676. if (isKick && this.myroomjid === from) {
  677. this.eventEmitter.emit(XMPPEvents.KICKED);
  678. }
  679. }
  680. /**
  681. *
  682. * @param msg
  683. * @param from
  684. */
  685. onMessage(msg, from) {
  686. const nick
  687. = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  688. .text()
  689. || Strophe.getResourceFromJid(from);
  690. const txt = $(msg).find('>body').text();
  691. const type = msg.getAttribute('type');
  692. if (type === 'error') {
  693. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  694. $(msg).find('>text').text(), txt);
  695. return true;
  696. }
  697. const subject = $(msg).find('>subject');
  698. if (subject.length) {
  699. const subjectText = subject.text();
  700. if (subjectText || subjectText === '') {
  701. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  702. logger.log(`Subject is changed to ${subjectText}`);
  703. }
  704. }
  705. // xep-0203 delay
  706. let stamp = $(msg).find('>delay').attr('stamp');
  707. if (!stamp) {
  708. // or xep-0091 delay, UTC timestamp
  709. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  710. if (stamp) {
  711. // the format is CCYYMMDDThh:mm:ss
  712. const dateParts
  713. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  714. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  715. }
  716. }
  717. if (from === this.roomjid
  718. && $(msg)
  719. .find(
  720. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  721. + '>status[code="104"]')
  722. .length) {
  723. this.discoRoomInfo();
  724. }
  725. const json = tryParseJSONAndVerify(txt);
  726. if (json) {
  727. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  728. from, json);
  729. return;
  730. }
  731. if (txt) {
  732. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  733. from, nick, txt, this.myroomjid, stamp);
  734. }
  735. }
  736. /**
  737. *
  738. * @param pres
  739. * @param from
  740. */
  741. onPresenceError(pres, from) {
  742. if ($(pres)
  743. .find(
  744. '>error[type="auth"]'
  745. + '>not-authorized['
  746. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  747. .length) {
  748. logger.log('on password required', from);
  749. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  750. } else if ($(pres)
  751. .find(
  752. '>error[type="cancel"]'
  753. + '>not-allowed['
  754. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  755. .length) {
  756. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  757. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  758. // enter the room by replying with 'not-authorized'. This would
  759. // result in reconnection from authorized domain.
  760. // We're either missing Jicofo/Prosody config for anonymous
  761. // domains or something is wrong.
  762. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  763. } else {
  764. logger.warn('onPresError ', pres);
  765. this.eventEmitter.emit(
  766. XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  767. }
  768. } else if ($(pres).find('>error>service-unavailable').length) {
  769. logger.warn('Maximum users limit for the room has been reached',
  770. pres);
  771. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  772. } else {
  773. logger.warn('onPresError ', pres);
  774. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  775. }
  776. }
  777. /**
  778. *
  779. * @param jid
  780. */
  781. kick(jid) {
  782. const kickIQ = $iq({ to: this.roomjid,
  783. type: 'set' })
  784. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  785. .c('item', { nick: Strophe.getResourceFromJid(jid),
  786. role: 'none' })
  787. .c('reason').t('You have been kicked.').up().up().up();
  788. this.connection.sendIQ(
  789. kickIQ,
  790. result => logger.log('Kick participant with jid: ', jid, result),
  791. error => logger.log('Kick participant error: ', error));
  792. }
  793. /* eslint-disable max-params */
  794. /**
  795. *
  796. * @param key
  797. * @param onSuccess
  798. * @param onError
  799. * @param onNotSupported
  800. */
  801. lockRoom(key, onSuccess, onError, onNotSupported) {
  802. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  803. this.connection.sendIQ(
  804. $iq({
  805. to: this.roomjid,
  806. type: 'get'
  807. })
  808. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  809. res => {
  810. if ($(res)
  811. .find(
  812. '>query>x[xmlns="jabber:x:data"]'
  813. + '>field[var="muc#roomconfig_roomsecret"]')
  814. .length) {
  815. const formsubmit
  816. = $iq({
  817. to: this.roomjid,
  818. type: 'set'
  819. })
  820. .c('query', {
  821. xmlns: 'http://jabber.org/protocol/muc#owner'
  822. });
  823. formsubmit.c('x', {
  824. xmlns: 'jabber:x:data',
  825. type: 'submit'
  826. });
  827. formsubmit
  828. .c('field', { 'var': 'FORM_TYPE' })
  829. .c('value')
  830. .t('http://jabber.org/protocol/muc#roomconfig')
  831. .up()
  832. .up();
  833. formsubmit
  834. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  835. .c('value')
  836. .t(key)
  837. .up()
  838. .up();
  839. // Fixes a bug in prosody 0.9.+
  840. // https://code.google.com/p/lxmppd/issues/detail?id=373
  841. formsubmit
  842. .c('field', { 'var': 'muc#roomconfig_whois' })
  843. .c('value')
  844. .t('anyone')
  845. .up()
  846. .up();
  847. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  848. this.connection.sendIQ(formsubmit, onSuccess, onError);
  849. } else {
  850. onNotSupported();
  851. }
  852. },
  853. onError);
  854. }
  855. /* eslint-enable max-params */
  856. /**
  857. *
  858. * @param key
  859. * @param values
  860. */
  861. addToPresence(key, values) {
  862. values.tagName = key;
  863. this.removeFromPresence(key);
  864. this.presMap.nodes.push(values);
  865. }
  866. /**
  867. *
  868. * @param key
  869. */
  870. removeFromPresence(key) {
  871. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  872. this.presMap.nodes = nodes;
  873. }
  874. /**
  875. *
  876. * @param name
  877. * @param handler
  878. */
  879. addPresenceListener(name, handler) {
  880. if (typeof handler !== 'function') {
  881. throw new Error('"handler" is not a function');
  882. }
  883. let tagHandlers = this.presHandlers[name];
  884. if (!tagHandlers) {
  885. this.presHandlers[name] = tagHandlers = [];
  886. }
  887. if (tagHandlers.indexOf(handler) === -1) {
  888. tagHandlers.push(handler);
  889. } else {
  890. logger.warn(
  891. `Trying to add the same handler more than once for: ${name}`);
  892. }
  893. }
  894. /**
  895. *
  896. * @param name
  897. * @param handler
  898. */
  899. removePresenceListener(name, handler) {
  900. const tagHandlers = this.presHandlers[name];
  901. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  902. // eslint-disable-next-line no-negated-condition
  903. if (handlerIdx !== -1) {
  904. tagHandlers.splice(handlerIdx, 1);
  905. } else {
  906. logger.warn(`Handler for: ${name} was not registered`);
  907. }
  908. }
  909. /**
  910. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  911. * focus.
  912. * @param mucJid the full MUC address of the user to be checked.
  913. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  914. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  915. * the MUC then <tt>null</tt> is returned.
  916. */
  917. isFocus(mucJid) {
  918. const member = this.members[mucJid];
  919. if (member) {
  920. return member.isFocus;
  921. }
  922. return null;
  923. }
  924. /**
  925. *
  926. */
  927. isModerator() {
  928. return this.role === 'moderator';
  929. }
  930. /**
  931. *
  932. * @param peerJid
  933. */
  934. getMemberRole(peerJid) {
  935. if (this.members[peerJid]) {
  936. return this.members[peerJid].role;
  937. }
  938. return null;
  939. }
  940. /**
  941. *
  942. * @param mute
  943. * @param callback
  944. */
  945. setVideoMute(mute, callback) {
  946. this.sendVideoInfoPresence(mute);
  947. if (callback) {
  948. callback(mute);
  949. }
  950. }
  951. /**
  952. *
  953. * @param mute
  954. * @param callback
  955. */
  956. setAudioMute(mute, callback) {
  957. return this.sendAudioInfoPresence(mute, callback);
  958. }
  959. /**
  960. *
  961. * @param mute
  962. */
  963. addAudioInfoToPresence(mute) {
  964. this.removeFromPresence('audiomuted');
  965. this.addToPresence(
  966. 'audiomuted',
  967. {
  968. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/audio' },
  969. value: mute.toString()
  970. });
  971. }
  972. /**
  973. *
  974. * @param mute
  975. * @param callback
  976. */
  977. sendAudioInfoPresence(mute, callback) {
  978. this.addAudioInfoToPresence(mute);
  979. if (this.connection) {
  980. this.sendPresence();
  981. }
  982. if (callback) {
  983. callback();
  984. }
  985. }
  986. /**
  987. *
  988. * @param mute
  989. */
  990. addVideoInfoToPresence(mute) {
  991. this.removeFromPresence('videomuted');
  992. this.addToPresence(
  993. 'videomuted',
  994. {
  995. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/video' },
  996. value: mute.toString()
  997. });
  998. }
  999. /**
  1000. *
  1001. * @param mute
  1002. */
  1003. sendVideoInfoPresence(mute) {
  1004. this.addVideoInfoToPresence(mute);
  1005. if (!this.connection) {
  1006. return;
  1007. }
  1008. this.sendPresence();
  1009. }
  1010. /**
  1011. * Obtains the info about given media advertised in the MUC presence of
  1012. * the participant identified by the given endpoint JID.
  1013. * @param {string} endpointId the endpoint ID mapped to the participant
  1014. * which corresponds to MUC nickname.
  1015. * @param {MediaType} mediaType the type of the media for which presence
  1016. * info will be obtained.
  1017. * @return {PeerMediaInfo} presenceInfo an object with media presence
  1018. * info or <tt>null</tt> either if there is no presence available or if
  1019. * the media type given is invalid.
  1020. */
  1021. getMediaPresenceInfo(endpointId, mediaType) {
  1022. // Will figure out current muted status by looking up owner's presence
  1023. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1024. if (!pres) {
  1025. // No presence available
  1026. return null;
  1027. }
  1028. const data = {
  1029. muted: false, // unmuted by default
  1030. videoType: undefined // no video type by default
  1031. };
  1032. let mutedNode = null;
  1033. if (mediaType === MediaType.AUDIO) {
  1034. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1035. } else if (mediaType === MediaType.VIDEO) {
  1036. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1037. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1038. if (videoTypeNode.length > 0) {
  1039. data.videoType = videoTypeNode[0].value;
  1040. }
  1041. } else {
  1042. logger.error(`Unsupported media type: ${mediaType}`);
  1043. return null;
  1044. }
  1045. data.muted = mutedNode.length > 0 && mutedNode[0].value === 'true';
  1046. return data;
  1047. }
  1048. /**
  1049. * Returns true if the recording is supproted and false if not.
  1050. */
  1051. isRecordingSupported() {
  1052. if (this.recording) {
  1053. return this.recording.isSupported();
  1054. }
  1055. return false;
  1056. }
  1057. /**
  1058. * Returns null if the recording is not supported, "on" if the recording
  1059. * started and "off" if the recording is not started.
  1060. */
  1061. getRecordingState() {
  1062. return this.recording ? this.recording.getState() : undefined;
  1063. }
  1064. /**
  1065. * Returns the url of the recorded video.
  1066. */
  1067. getRecordingURL() {
  1068. return this.recording ? this.recording.getURL() : null;
  1069. }
  1070. /**
  1071. * Starts/stops the recording
  1072. * @param token token for authentication
  1073. * @param statusChangeHandler {function} receives the new status as
  1074. * argument.
  1075. */
  1076. toggleRecording(options, statusChangeHandler) {
  1077. if (this.recording) {
  1078. return this.recording.toggleRecording(options, statusChangeHandler);
  1079. }
  1080. return statusChangeHandler('error',
  1081. new Error('The conference is not created yet!'));
  1082. }
  1083. /**
  1084. * Returns true if the SIP calls are supported and false otherwise
  1085. */
  1086. isSIPCallingSupported() {
  1087. if (this.moderator) {
  1088. return this.moderator.isSipGatewayEnabled();
  1089. }
  1090. return false;
  1091. }
  1092. /**
  1093. * Dials a number.
  1094. * @param number the number
  1095. */
  1096. dial(number) {
  1097. return this.connection.rayo.dial(number, 'fromnumber',
  1098. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1099. this.focusMucJid);
  1100. }
  1101. /**
  1102. * Hangup an existing call
  1103. */
  1104. hangup() {
  1105. return this.connection.rayo.hangup();
  1106. }
  1107. /**
  1108. * Returns the phone number for joining the conference.
  1109. */
  1110. getPhoneNumber() {
  1111. return this.phoneNumber;
  1112. }
  1113. /**
  1114. * Returns the pin for joining the conference with phone.
  1115. */
  1116. getPhonePin() {
  1117. return this.phonePin;
  1118. }
  1119. /**
  1120. * Mutes remote participant.
  1121. * @param jid of the participant
  1122. * @param mute
  1123. */
  1124. muteParticipant(jid, mute) {
  1125. logger.info('set mute', mute);
  1126. const iqToFocus = $iq(
  1127. { to: this.focusMucJid,
  1128. type: 'set' })
  1129. .c('mute', {
  1130. xmlns: 'http://jitsi.org/jitmeet/audio',
  1131. jid
  1132. })
  1133. .t(mute.toString())
  1134. .up();
  1135. this.connection.sendIQ(
  1136. iqToFocus,
  1137. result => logger.log('set mute', result),
  1138. error => logger.log('set mute error', error));
  1139. }
  1140. /**
  1141. * TODO: Document
  1142. * @param iq
  1143. */
  1144. onMute(iq) {
  1145. const from = iq.getAttribute('from');
  1146. if (from !== this.focusMucJid) {
  1147. logger.warn('Ignored mute from non focus peer');
  1148. return;
  1149. }
  1150. const mute = $(iq).find('mute');
  1151. if (mute.length && mute.text() === 'true') {
  1152. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS);
  1153. } else {
  1154. // XXX Why do we support anything but muting? Why do we encode the
  1155. // value in the text of the element? Why do we use a separate XML
  1156. // namespace?
  1157. logger.warn('Ignoring a mute request which does not explicitly '
  1158. + 'specify a positive mute command.');
  1159. }
  1160. }
  1161. /**
  1162. * Leaves the room. Closes the jingle session.
  1163. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1164. * less than 5s after sending presence unavailable. Otherwise the promise is
  1165. * rejected.
  1166. */
  1167. leave() {
  1168. return new Promise((resolve, reject) => {
  1169. const timeout = setTimeout(() => onMucLeft(true), 5000);
  1170. const eventEmitter = this.eventEmitter;
  1171. /**
  1172. *
  1173. * @param doReject
  1174. */
  1175. function onMucLeft(doReject = false) {
  1176. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1177. clearTimeout(timeout);
  1178. if (doReject) {
  1179. // the timeout expired
  1180. reject(new Error('The timeout for the confirmation about '
  1181. + 'leaving the room expired.'));
  1182. } else {
  1183. resolve();
  1184. }
  1185. }
  1186. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1187. this.doLeave();
  1188. });
  1189. }
  1190. }
  1191. /* eslint-enable newline-per-chained-call */