Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ChatRoom.js 41KB

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