modified lib-jitsi-meet dev repo
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

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