您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ChatRoom.js 44KB

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