You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 57KB

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