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 45KB

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