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 59KB

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