Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ChatRoom.js 40KB

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