Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

ChatRoom.js 44KB

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