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

ChatRoom.js 45KB

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