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

ChatRoom.js 41KB

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