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.

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