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