Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ChatRoom.js 42KB

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