Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ChatRoom.js 54KB

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