You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 44KB

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