Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ChatRoom.js 44KB

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