Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ChatRoom.js 43KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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. const xElement
  296. = pres.getElementsByTagNameNS(
  297. 'http://jabber.org/protocol/muc#user', 'x')[0];
  298. const mucUserItem
  299. = xElement && xElement.getElementsByTagName('item')[0];
  300. member.affiliation
  301. = mucUserItem && mucUserItem.getAttribute('affiliation');
  302. member.role = mucUserItem && mucUserItem.getAttribute('role');
  303. // Focus recognition
  304. const jid = mucUserItem && mucUserItem.getAttribute('jid');
  305. member.jid = jid;
  306. member.isFocus
  307. = jid && jid.indexOf(`${this.moderator.getFocusUserJid()}/`) === 0;
  308. member.isHiddenDomain
  309. = jid && jid.indexOf('@') > 0
  310. && this.options.hiddenDomain
  311. === jid.substring(jid.indexOf('@') + 1, jid.indexOf('/'));
  312. this.eventEmitter.emit(XMPPEvents.PRESENCE_RECEIVED, {
  313. fromHiddenDomain: member.isHiddenDomain,
  314. presence: pres
  315. });
  316. const xEl = pres.querySelector('x');
  317. if (xEl) {
  318. xEl.remove();
  319. }
  320. const nodes = [];
  321. parser.packet2JSON(pres, nodes);
  322. this.lastPresences[from] = nodes;
  323. // process nodes to extract data needed for MUC_JOINED and
  324. // MUC_MEMBER_JOINED events
  325. const extractIdentityInformation = node => {
  326. const identity = {};
  327. const userInfo = node.children.find(c => c.tagName === 'user');
  328. if (userInfo) {
  329. identity.user = {};
  330. for (const tag of [ 'id', 'name', 'avatar' ]) {
  331. const child
  332. = userInfo.children.find(c => c.tagName === tag);
  333. if (child) {
  334. identity.user[tag] = child.value;
  335. }
  336. }
  337. }
  338. const groupInfo = node.children.find(c => c.tagName === 'group');
  339. if (groupInfo) {
  340. identity.group = groupInfo.value;
  341. }
  342. return identity;
  343. };
  344. for (let i = 0; i < nodes.length; i++) {
  345. const node = nodes[i];
  346. switch (node.tagName) {
  347. case 'bot': {
  348. const { attributes } = node;
  349. if (!attributes) {
  350. break;
  351. }
  352. const { type } = attributes;
  353. member.botType = type;
  354. break;
  355. }
  356. case 'nick':
  357. member.nick = node.value;
  358. break;
  359. case 'userId':
  360. member.id = node.value;
  361. break;
  362. case 'stats-id':
  363. member.statsID = node.value;
  364. break;
  365. case 'identity':
  366. member.identity = extractIdentityInformation(node);
  367. break;
  368. }
  369. }
  370. if (from === this.myroomjid) {
  371. const newRole
  372. = member.affiliation === 'owner' ? member.role : 'none';
  373. if (this.role !== newRole) {
  374. this.role = newRole;
  375. this.eventEmitter.emit(
  376. XMPPEvents.LOCAL_ROLE_CHANGED,
  377. this.role);
  378. }
  379. if (!this.joined) {
  380. this.joined = true;
  381. const now = this.connectionTimes['muc.joined']
  382. = window.performance.now();
  383. logger.log('(TIME) MUC joined:\t', now);
  384. // set correct initial state of locked
  385. if (this.password) {
  386. this.locked = true;
  387. }
  388. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  389. }
  390. } else if (this.members[from] === undefined) {
  391. // new participant
  392. this.members[from] = member;
  393. logger.log('entered', from, member);
  394. hasStatusUpdate = member.status !== undefined;
  395. if (member.isFocus) {
  396. this._initFocus(from, jid);
  397. } else {
  398. // identity is being added to member joined, so external
  399. // services can be notified for that (currently identity is
  400. // not used inside library)
  401. this.eventEmitter.emit(
  402. XMPPEvents.MUC_MEMBER_JOINED,
  403. from,
  404. member.nick,
  405. member.role,
  406. member.isHiddenDomain,
  407. member.statsID,
  408. member.status,
  409. member.identity,
  410. member.botType);
  411. // we are reporting the status with the join
  412. // so we do not want a second event about status update
  413. hasStatusUpdate = false;
  414. }
  415. } else {
  416. // Presence update for existing participant
  417. // Watch role change:
  418. const memberOfThis = this.members[from];
  419. if (memberOfThis.role !== member.role) {
  420. memberOfThis.role = member.role;
  421. this.eventEmitter.emit(
  422. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  423. }
  424. // fire event that botType had changed
  425. if (memberOfThis.botType !== member.botType) {
  426. memberOfThis.botType = member.botType;
  427. this.eventEmitter.emit(
  428. XMPPEvents.MUC_MEMBER_BOT_TYPE_CHANGED,
  429. from,
  430. member.botType);
  431. }
  432. if (member.isFocus) {
  433. // From time to time first few presences of the focus are not
  434. // containing it's jid. That way we can mark later the focus
  435. // member instead of not marking it at all and not starting the
  436. // conference.
  437. // FIXME: Maybe there is a better way to handle this issue. It
  438. // seems there is some period of time in prosody that the
  439. // configuration form is received but not applied. And if any
  440. // participant joins during that period of time the first
  441. // presence from the focus won't contain
  442. // <item jid="focus..." />.
  443. memberOfThis.isFocus = true;
  444. this._initFocus(from, jid);
  445. }
  446. // store the new display name
  447. if (member.displayName) {
  448. memberOfThis.displayName = member.displayName;
  449. }
  450. // update stored status message to be able to detect changes
  451. if (memberOfThis.status !== member.status) {
  452. hasStatusUpdate = true;
  453. memberOfThis.status = member.status;
  454. }
  455. }
  456. // after we had fired member or room joined events, lets fire events
  457. // for the rest info we got in presence
  458. for (let i = 0; i < nodes.length; i++) {
  459. const node = nodes[i];
  460. switch (node.tagName) {
  461. case 'nick':
  462. if (!member.isFocus) {
  463. const displayName
  464. = this.xmpp.options.displayJids
  465. ? Strophe.getResourceFromJid(from)
  466. : member.nick;
  467. this.eventEmitter.emit(
  468. XMPPEvents.DISPLAY_NAME_CHANGED,
  469. from,
  470. displayName);
  471. }
  472. break;
  473. case 'bridgeNotAvailable':
  474. if (member.isFocus && !this.noBridgeAvailable) {
  475. this.noBridgeAvailable = true;
  476. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  477. }
  478. break;
  479. case 'conference-properties':
  480. if (member.isFocus) {
  481. const properties = {};
  482. for (let j = 0; j < node.children.length; j++) {
  483. const { attributes } = node.children[j];
  484. if (attributes && attributes.key) {
  485. properties[attributes.key] = attributes.value;
  486. }
  487. }
  488. this.eventEmitter.emit(
  489. XMPPEvents.CONFERENCE_PROPERTIES_CHANGED, properties);
  490. }
  491. break;
  492. case 'transcription-status': {
  493. const { attributes } = node;
  494. if (!attributes) {
  495. break;
  496. }
  497. const { status } = attributes;
  498. if (status && status !== this.transcriptionStatus) {
  499. this.transcriptionStatus = status;
  500. this.eventEmitter.emit(
  501. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  502. status
  503. );
  504. }
  505. break;
  506. }
  507. case 'call-control': {
  508. const att = node.attributes;
  509. if (!att) {
  510. break;
  511. }
  512. this.phoneNumber = att.phone || null;
  513. this.phonePin = att.pin || null;
  514. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  515. break;
  516. }
  517. default:
  518. this.processNode(node, from);
  519. }
  520. }
  521. // Trigger status message update if necessary
  522. if (hasStatusUpdate) {
  523. this.eventEmitter.emit(
  524. XMPPEvents.PRESENCE_STATUS,
  525. from,
  526. member.status);
  527. }
  528. }
  529. /**
  530. * Initialize some properties when the focus participant is verified.
  531. * @param from jid of the focus
  532. * @param mucJid the jid of the focus in the muc
  533. */
  534. _initFocus(from, mucJid) {
  535. this.focusMucJid = from;
  536. logger.info(`Ignore focus: ${from}, real JID: ${mucJid}`);
  537. }
  538. /**
  539. * Sets the special listener to be used for "command"s whose name starts
  540. * with "jitsi_participant_".
  541. */
  542. setParticipantPropertyListener(listener) {
  543. this.participantPropertyListener = listener;
  544. }
  545. /**
  546. *
  547. * @param node
  548. * @param from
  549. */
  550. processNode(node, from) {
  551. // make sure we catch all errors coming from any handler
  552. // otherwise we can remove the presence handler from strophe
  553. try {
  554. let tagHandlers = this.presHandlers[node.tagName];
  555. if (node.tagName.startsWith('jitsi_participant_')) {
  556. tagHandlers = [ this.participantPropertyListener ];
  557. }
  558. if (tagHandlers) {
  559. tagHandlers.forEach(handler => {
  560. handler(node, Strophe.getResourceFromJid(from), from);
  561. });
  562. }
  563. } catch (e) {
  564. GlobalOnErrorHandler.callErrorHandler(e);
  565. logger.error(`Error processing:${node.tagName} node.`, e);
  566. }
  567. }
  568. /**
  569. * Send text message to the other participants in the conference
  570. * @param message
  571. * @param elementName
  572. * @param nickname
  573. */
  574. sendMessage(message, elementName, nickname) {
  575. const msg = $msg({ to: this.roomjid,
  576. type: 'groupchat' });
  577. // We are adding the message in a packet extension. If this element
  578. // is different from 'body', we add a custom namespace.
  579. // e.g. for 'json-message' extension of message stanza.
  580. if (elementName === 'body') {
  581. msg.c(elementName, message).up();
  582. } else {
  583. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  584. .up();
  585. }
  586. if (nickname) {
  587. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  588. .t(nickname)
  589. .up()
  590. .up();
  591. }
  592. this.connection.send(msg);
  593. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, message);
  594. }
  595. /* eslint-disable max-params */
  596. /**
  597. * Send private text message to another participant of the conference
  598. * @param id id/muc resource of the receiver
  599. * @param message
  600. * @param elementName
  601. * @param nickname
  602. */
  603. sendPrivateMessage(id, message, elementName, nickname) {
  604. const msg = $msg({ to: `${this.roomjid}/${id}`,
  605. type: 'chat' });
  606. // We are adding the message in packet. If this element is different
  607. // from 'body', we add our custom namespace for the same.
  608. // e.g. for 'json-message' message extension.
  609. if (elementName === 'body') {
  610. msg.c(elementName, message).up();
  611. } else {
  612. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  613. .up();
  614. }
  615. if (nickname) {
  616. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  617. .t(nickname)
  618. .up()
  619. .up();
  620. }
  621. this.connection.send(msg);
  622. this.eventEmitter.emit(
  623. XMPPEvents.SENDING_PRIVATE_CHAT_MESSAGE, message);
  624. }
  625. /* eslint-enable max-params */
  626. /**
  627. *
  628. * @param subject
  629. */
  630. setSubject(subject) {
  631. const msg = $msg({ to: this.roomjid,
  632. type: 'groupchat' });
  633. msg.c('subject', subject);
  634. this.connection.send(msg);
  635. }
  636. /**
  637. * Called when participant leaves.
  638. * @param jid the jid of the participant that leaves
  639. * @param skipEvents optional params to skip any events, including check
  640. * whether this is the focus that left
  641. */
  642. onParticipantLeft(jid, skipEvents) {
  643. delete this.lastPresences[jid];
  644. if (skipEvents) {
  645. return;
  646. }
  647. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  648. this.moderator.onMucMemberLeft(jid);
  649. }
  650. /**
  651. *
  652. * @param pres
  653. * @param from
  654. */
  655. onPresenceUnavailable(pres, from) {
  656. // ignore presence
  657. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  658. return true;
  659. }
  660. // room destroyed ?
  661. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]'
  662. + '>destroy').length) {
  663. let reason;
  664. const reasonSelect
  665. = $(pres).find(
  666. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  667. + '>destroy>reason');
  668. if (reasonSelect.length) {
  669. reason = reasonSelect.text();
  670. }
  671. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  672. this.connection.emuc.doLeave(this.roomjid);
  673. return true;
  674. }
  675. // Status code 110 indicates that this notification is "self-presence".
  676. const isSelfPresence
  677. = $(pres)
  678. .find(
  679. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  680. + 'status[code="110"]')
  681. .length;
  682. const isKick
  683. = $(pres)
  684. .find(
  685. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  686. + '>status[code="307"]')
  687. .length;
  688. const membersKeys = Object.keys(this.members);
  689. if (!isSelfPresence) {
  690. delete this.members[from];
  691. this.onParticipantLeft(from, false);
  692. } else if (membersKeys.length > 0) {
  693. // If the status code is 110 this means we're leaving and we would
  694. // like to remove everyone else from our view, so we trigger the
  695. // event.
  696. membersKeys.forEach(jid => {
  697. const member = this.members[jid];
  698. delete this.members[jid];
  699. this.onParticipantLeft(jid, member.isFocus);
  700. });
  701. this.connection.emuc.doLeave(this.roomjid);
  702. // we fire muc_left only if this is not a kick,
  703. // kick has both statuses 110 and 307.
  704. if (!isKick) {
  705. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  706. }
  707. }
  708. if (isKick && this.myroomjid === from) {
  709. this.eventEmitter.emit(XMPPEvents.KICKED);
  710. }
  711. }
  712. /**
  713. *
  714. * @param msg
  715. * @param from
  716. */
  717. onMessage(msg, from) {
  718. const nick
  719. = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  720. .text()
  721. || Strophe.getResourceFromJid(from);
  722. const txt = $(msg).find('>body').text();
  723. const type = msg.getAttribute('type');
  724. if (type === 'error') {
  725. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  726. $(msg).find('>text').text(), txt);
  727. return true;
  728. }
  729. const subject = $(msg).find('>subject');
  730. if (subject.length) {
  731. const subjectText = subject.text();
  732. if (subjectText || subjectText === '') {
  733. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  734. logger.log(`Subject is changed to ${subjectText}`);
  735. }
  736. }
  737. // xep-0203 delay
  738. let stamp = $(msg).find('>delay').attr('stamp');
  739. if (!stamp) {
  740. // or xep-0091 delay, UTC timestamp
  741. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  742. if (stamp) {
  743. // the format is CCYYMMDDThh:mm:ss
  744. const dateParts
  745. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  746. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  747. }
  748. }
  749. if (from === this.roomjid
  750. && $(msg)
  751. .find(
  752. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  753. + '>status[code="104"]')
  754. .length) {
  755. this.discoRoomInfo();
  756. }
  757. const jsonMessage = $(msg).find('>json-message').text();
  758. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  759. // We emit this event if the message is a valid json, and is not
  760. // delivered after a delay, i.e. stamp is undefined.
  761. // e.g. - subtitles should not be displayed if delayed.
  762. if (parsedJson && stamp === undefined) {
  763. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  764. from, parsedJson);
  765. return;
  766. }
  767. if (txt) {
  768. if (type === 'chat') {
  769. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  770. from, nick, txt, this.myroomjid, stamp);
  771. } else if (type === 'groupchat') {
  772. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  773. from, nick, txt, this.myroomjid, stamp);
  774. }
  775. }
  776. }
  777. /**
  778. *
  779. * @param pres
  780. * @param from
  781. */
  782. onPresenceError(pres, from) {
  783. if ($(pres)
  784. .find(
  785. '>error[type="auth"]'
  786. + '>not-authorized['
  787. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  788. .length) {
  789. logger.log('on password required', from);
  790. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  791. } else if ($(pres)
  792. .find(
  793. '>error[type="cancel"]'
  794. + '>not-allowed['
  795. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  796. .length) {
  797. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  798. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  799. // enter the room by replying with 'not-authorized'. This would
  800. // result in reconnection from authorized domain.
  801. // We're either missing Jicofo/Prosody config for anonymous
  802. // domains or something is wrong.
  803. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  804. } else {
  805. logger.warn('onPresError ', pres);
  806. this.eventEmitter.emit(
  807. XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  808. }
  809. } else if ($(pres).find('>error>service-unavailable').length) {
  810. logger.warn('Maximum users limit for the room has been reached',
  811. pres);
  812. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  813. } else {
  814. logger.warn('onPresError ', pres);
  815. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  816. }
  817. }
  818. /**
  819. *
  820. * @param jid
  821. */
  822. kick(jid) {
  823. const kickIQ = $iq({ to: this.roomjid,
  824. type: 'set' })
  825. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  826. .c('item', { nick: Strophe.getResourceFromJid(jid),
  827. role: 'none' })
  828. .c('reason').t('You have been kicked.').up().up().up();
  829. this.connection.sendIQ(
  830. kickIQ,
  831. result => logger.log('Kick participant with jid: ', jid, result),
  832. error => logger.log('Kick participant error: ', error));
  833. }
  834. /* eslint-disable max-params */
  835. /**
  836. *
  837. * @param key
  838. * @param onSuccess
  839. * @param onError
  840. * @param onNotSupported
  841. */
  842. lockRoom(key, onSuccess, onError, onNotSupported) {
  843. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  844. this.connection.sendIQ(
  845. $iq({
  846. to: this.roomjid,
  847. type: 'get'
  848. })
  849. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  850. res => {
  851. if ($(res)
  852. .find(
  853. '>query>x[xmlns="jabber:x:data"]'
  854. + '>field[var="muc#roomconfig_roomsecret"]')
  855. .length) {
  856. const formsubmit
  857. = $iq({
  858. to: this.roomjid,
  859. type: 'set'
  860. })
  861. .c('query', {
  862. xmlns: 'http://jabber.org/protocol/muc#owner'
  863. });
  864. formsubmit.c('x', {
  865. xmlns: 'jabber:x:data',
  866. type: 'submit'
  867. });
  868. formsubmit
  869. .c('field', { 'var': 'FORM_TYPE' })
  870. .c('value')
  871. .t('http://jabber.org/protocol/muc#roomconfig')
  872. .up()
  873. .up();
  874. formsubmit
  875. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  876. .c('value')
  877. .t(key)
  878. .up()
  879. .up();
  880. // Fixes a bug in prosody 0.9.+
  881. // https://prosody.im/issues/issue/373
  882. formsubmit
  883. .c('field', { 'var': 'muc#roomconfig_whois' })
  884. .c('value')
  885. .t('anyone')
  886. .up()
  887. .up();
  888. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  889. this.connection.sendIQ(formsubmit, onSuccess, onError);
  890. } else {
  891. onNotSupported();
  892. }
  893. },
  894. onError);
  895. }
  896. /* eslint-enable max-params */
  897. /**
  898. *
  899. * @param key
  900. * @param values
  901. */
  902. addToPresence(key, values) {
  903. values.tagName = key;
  904. this.removeFromPresence(key);
  905. this.presMap.nodes.push(values);
  906. }
  907. /**
  908. *
  909. * @param key
  910. */
  911. removeFromPresence(key) {
  912. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  913. this.presMap.nodes = nodes;
  914. }
  915. /**
  916. *
  917. * @param name
  918. * @param handler
  919. */
  920. addPresenceListener(name, handler) {
  921. if (typeof handler !== 'function') {
  922. throw new Error('"handler" is not a function');
  923. }
  924. let tagHandlers = this.presHandlers[name];
  925. if (!tagHandlers) {
  926. this.presHandlers[name] = tagHandlers = [];
  927. }
  928. if (tagHandlers.indexOf(handler) === -1) {
  929. tagHandlers.push(handler);
  930. } else {
  931. logger.warn(
  932. `Trying to add the same handler more than once for: ${name}`);
  933. }
  934. }
  935. /**
  936. *
  937. * @param name
  938. * @param handler
  939. */
  940. removePresenceListener(name, handler) {
  941. const tagHandlers = this.presHandlers[name];
  942. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  943. // eslint-disable-next-line no-negated-condition
  944. if (handlerIdx !== -1) {
  945. tagHandlers.splice(handlerIdx, 1);
  946. } else {
  947. logger.warn(`Handler for: ${name} was not registered`);
  948. }
  949. }
  950. /**
  951. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  952. * focus.
  953. * @param mucJid the full MUC address of the user to be checked.
  954. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  955. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  956. * the MUC then <tt>null</tt> is returned.
  957. */
  958. isFocus(mucJid) {
  959. const member = this.members[mucJid];
  960. if (member) {
  961. return member.isFocus;
  962. }
  963. return null;
  964. }
  965. /**
  966. *
  967. */
  968. isModerator() {
  969. return this.role === 'moderator';
  970. }
  971. /**
  972. *
  973. * @param peerJid
  974. */
  975. getMemberRole(peerJid) {
  976. if (this.members[peerJid]) {
  977. return this.members[peerJid].role;
  978. }
  979. return null;
  980. }
  981. /**
  982. *
  983. * @param mute
  984. * @param callback
  985. */
  986. setVideoMute(mute, callback) {
  987. this.sendVideoInfoPresence(mute);
  988. if (callback) {
  989. callback(mute);
  990. }
  991. }
  992. /**
  993. *
  994. * @param mute
  995. * @param callback
  996. */
  997. setAudioMute(mute, callback) {
  998. return this.sendAudioInfoPresence(mute, callback);
  999. }
  1000. /**
  1001. *
  1002. * @param mute
  1003. */
  1004. addAudioInfoToPresence(mute) {
  1005. this.removeFromPresence('audiomuted');
  1006. this.addToPresence(
  1007. 'audiomuted',
  1008. {
  1009. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/audio' },
  1010. value: mute.toString()
  1011. });
  1012. }
  1013. /**
  1014. *
  1015. * @param mute
  1016. * @param callback
  1017. */
  1018. sendAudioInfoPresence(mute, callback) {
  1019. this.addAudioInfoToPresence(mute);
  1020. if (this.connection) {
  1021. this.sendPresence();
  1022. }
  1023. if (callback) {
  1024. callback();
  1025. }
  1026. }
  1027. /**
  1028. *
  1029. * @param mute
  1030. */
  1031. addVideoInfoToPresence(mute) {
  1032. this.removeFromPresence('videomuted');
  1033. this.addToPresence(
  1034. 'videomuted',
  1035. {
  1036. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/video' },
  1037. value: mute.toString()
  1038. });
  1039. }
  1040. /**
  1041. *
  1042. * @param mute
  1043. */
  1044. sendVideoInfoPresence(mute) {
  1045. this.addVideoInfoToPresence(mute);
  1046. if (!this.connection) {
  1047. return;
  1048. }
  1049. this.sendPresence();
  1050. }
  1051. /**
  1052. * Obtains the info about given media advertised in the MUC presence of
  1053. * the participant identified by the given endpoint JID.
  1054. * @param {string} endpointId the endpoint ID mapped to the participant
  1055. * which corresponds to MUC nickname.
  1056. * @param {MediaType} mediaType the type of the media for which presence
  1057. * info will be obtained.
  1058. * @return {PeerMediaInfo} presenceInfo an object with media presence
  1059. * info or <tt>null</tt> either if there is no presence available or if
  1060. * the media type given is invalid.
  1061. */
  1062. getMediaPresenceInfo(endpointId, mediaType) {
  1063. // Will figure out current muted status by looking up owner's presence
  1064. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1065. if (!pres) {
  1066. // No presence available
  1067. return null;
  1068. }
  1069. const data = {
  1070. muted: false, // unmuted by default
  1071. videoType: undefined // no video type by default
  1072. };
  1073. let mutedNode = null;
  1074. if (mediaType === MediaType.AUDIO) {
  1075. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1076. } else if (mediaType === MediaType.VIDEO) {
  1077. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1078. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1079. if (videoTypeNode.length > 0) {
  1080. data.videoType = videoTypeNode[0].value;
  1081. }
  1082. } else {
  1083. logger.error(`Unsupported media type: ${mediaType}`);
  1084. return null;
  1085. }
  1086. data.muted = mutedNode.length > 0 && mutedNode[0].value === 'true';
  1087. return data;
  1088. }
  1089. /**
  1090. * Returns true if the SIP calls are supported and false otherwise
  1091. */
  1092. isSIPCallingSupported() {
  1093. if (this.moderator) {
  1094. return this.moderator.isSipGatewayEnabled();
  1095. }
  1096. return false;
  1097. }
  1098. /**
  1099. * Dials a number.
  1100. * @param number the number
  1101. */
  1102. dial(number) {
  1103. return this.connection.rayo.dial(number, 'fromnumber',
  1104. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1105. this.focusMucJid);
  1106. }
  1107. /**
  1108. * Hangup an existing call
  1109. */
  1110. hangup() {
  1111. return this.connection.rayo.hangup();
  1112. }
  1113. /**
  1114. * Returns the phone number for joining the conference.
  1115. */
  1116. getPhoneNumber() {
  1117. return this.phoneNumber;
  1118. }
  1119. /**
  1120. * Returns the pin for joining the conference with phone.
  1121. */
  1122. getPhonePin() {
  1123. return this.phonePin;
  1124. }
  1125. /**
  1126. * Mutes remote participant.
  1127. * @param jid of the participant
  1128. * @param mute
  1129. */
  1130. muteParticipant(jid, mute) {
  1131. logger.info('set mute', mute);
  1132. const iqToFocus = $iq(
  1133. { to: this.focusMucJid,
  1134. type: 'set' })
  1135. .c('mute', {
  1136. xmlns: 'http://jitsi.org/jitmeet/audio',
  1137. jid
  1138. })
  1139. .t(mute.toString())
  1140. .up();
  1141. this.connection.sendIQ(
  1142. iqToFocus,
  1143. result => logger.log('set mute', result),
  1144. error => logger.log('set mute error', error));
  1145. }
  1146. /**
  1147. * TODO: Document
  1148. * @param iq
  1149. */
  1150. onMute(iq) {
  1151. const from = iq.getAttribute('from');
  1152. if (from !== this.focusMucJid) {
  1153. logger.warn('Ignored mute from non focus peer');
  1154. return;
  1155. }
  1156. const mute = $(iq).find('mute');
  1157. if (mute.length && mute.text() === 'true') {
  1158. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS);
  1159. } else {
  1160. // XXX Why do we support anything but muting? Why do we encode the
  1161. // value in the text of the element? Why do we use a separate XML
  1162. // namespace?
  1163. logger.warn('Ignoring a mute request which does not explicitly '
  1164. + 'specify a positive mute command.');
  1165. }
  1166. }
  1167. /**
  1168. * Leaves the room. Closes the jingle session.
  1169. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1170. * less than 5s after sending presence unavailable. Otherwise the promise is
  1171. * rejected.
  1172. */
  1173. leave() {
  1174. return new Promise((resolve, reject) => {
  1175. const timeout = setTimeout(() => onMucLeft(true), 5000);
  1176. const eventEmitter = this.eventEmitter;
  1177. /**
  1178. *
  1179. * @param doReject
  1180. */
  1181. function onMucLeft(doReject = false) {
  1182. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1183. clearTimeout(timeout);
  1184. if (doReject) {
  1185. // the timeout expired
  1186. reject(new Error('The timeout for the confirmation about '
  1187. + 'leaving the room expired.'));
  1188. } else {
  1189. resolve();
  1190. }
  1191. }
  1192. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1193. this.doLeave();
  1194. });
  1195. }
  1196. }
  1197. /* eslint-enable newline-per-chained-call */