modified lib-jitsi-meet dev repo
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 45KB

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