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

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