Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ChatRoom.js 45KB

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