Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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