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.

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