您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ChatRoom.js 56KB

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