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

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