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

ChatRoom.js 42KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  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. * Send text message to the other participants in the conference
  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. * Send private text message to another participant of the conference
  596. * @param id id/muc resource of the receiver
  597. * @param body
  598. * @param nickname
  599. */
  600. sendPrivateMessage(id, body, nickname) {
  601. const msg = $msg({ to: `${this.roomjid}/${id}`,
  602. type: 'chat' });
  603. msg.c('body', body).up();
  604. if (nickname) {
  605. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  606. .t(nickname)
  607. .up()
  608. .up();
  609. }
  610. this.connection.send(msg);
  611. this.eventEmitter.emit(XMPPEvents.SENDING_PRIVATE_CHAT_MESSAGE, body);
  612. }
  613. /**
  614. *
  615. * @param subject
  616. */
  617. setSubject(subject) {
  618. const msg = $msg({ to: this.roomjid,
  619. type: 'groupchat' });
  620. msg.c('subject', subject);
  621. this.connection.send(msg);
  622. }
  623. /**
  624. * Called when participant leaves.
  625. * @param jid the jid of the participant that leaves
  626. * @param skipEvents optional params to skip any events, including check
  627. * whether this is the focus that left
  628. */
  629. onParticipantLeft(jid, skipEvents) {
  630. delete this.lastPresences[jid];
  631. if (skipEvents) {
  632. return;
  633. }
  634. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  635. this.moderator.onMucMemberLeft(jid);
  636. }
  637. /**
  638. *
  639. * @param pres
  640. * @param from
  641. */
  642. onPresenceUnavailable(pres, from) {
  643. // ignore presence
  644. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  645. return true;
  646. }
  647. // room destroyed ?
  648. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]'
  649. + '>destroy').length) {
  650. let reason;
  651. const reasonSelect
  652. = $(pres).find(
  653. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  654. + '>destroy>reason');
  655. if (reasonSelect.length) {
  656. reason = reasonSelect.text();
  657. }
  658. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  659. this.connection.emuc.doLeave(this.roomjid);
  660. return true;
  661. }
  662. // Status code 110 indicates that this notification is "self-presence".
  663. const isSelfPresence
  664. = $(pres)
  665. .find(
  666. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  667. + 'status[code="110"]')
  668. .length;
  669. const isKick
  670. = $(pres)
  671. .find(
  672. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  673. + '>status[code="307"]')
  674. .length;
  675. const membersKeys = Object.keys(this.members);
  676. if (!isSelfPresence) {
  677. delete this.members[from];
  678. this.onParticipantLeft(from, false);
  679. } else if (membersKeys.length > 0) {
  680. // If the status code is 110 this means we're leaving and we would
  681. // like to remove everyone else from our view, so we trigger the
  682. // event.
  683. membersKeys.forEach(jid => {
  684. const member = this.members[jid];
  685. delete this.members[jid];
  686. this.onParticipantLeft(jid, member.isFocus);
  687. });
  688. this.connection.emuc.doLeave(this.roomjid);
  689. // we fire muc_left only if this is not a kick,
  690. // kick has both statuses 110 and 307.
  691. if (!isKick) {
  692. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  693. }
  694. }
  695. if (isKick && this.myroomjid === from) {
  696. this.eventEmitter.emit(XMPPEvents.KICKED);
  697. }
  698. }
  699. /**
  700. *
  701. * @param msg
  702. * @param from
  703. */
  704. onMessage(msg, from) {
  705. const nick
  706. = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  707. .text()
  708. || Strophe.getResourceFromJid(from);
  709. const txt = $(msg).find('>body').text();
  710. const type = msg.getAttribute('type');
  711. if (type === 'error') {
  712. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  713. $(msg).find('>text').text(), txt);
  714. return true;
  715. }
  716. const subject = $(msg).find('>subject');
  717. if (subject.length) {
  718. const subjectText = subject.text();
  719. if (subjectText || subjectText === '') {
  720. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  721. logger.log(`Subject is changed to ${subjectText}`);
  722. }
  723. }
  724. // xep-0203 delay
  725. let stamp = $(msg).find('>delay').attr('stamp');
  726. if (!stamp) {
  727. // or xep-0091 delay, UTC timestamp
  728. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  729. if (stamp) {
  730. // the format is CCYYMMDDThh:mm:ss
  731. const dateParts
  732. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  733. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  734. }
  735. }
  736. if (from === this.roomjid
  737. && $(msg)
  738. .find(
  739. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  740. + '>status[code="104"]')
  741. .length) {
  742. this.discoRoomInfo();
  743. }
  744. const json = tryParseJSONAndVerify(txt);
  745. if (json) {
  746. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  747. from, json);
  748. return;
  749. }
  750. if (txt) {
  751. if (type === 'chat') {
  752. logger.log('privatechat', nick, txt);
  753. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  754. from, nick, txt, this.myroomjid, stamp);
  755. }
  756. if (type === 'groupchat') {
  757. logger.log('chat', nick, txt);
  758. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  759. from, nick, txt, this.myroomjid, stamp);
  760. }
  761. }
  762. }
  763. /**
  764. *
  765. * @param pres
  766. * @param from
  767. */
  768. onPresenceError(pres, from) {
  769. if ($(pres)
  770. .find(
  771. '>error[type="auth"]'
  772. + '>not-authorized['
  773. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  774. .length) {
  775. logger.log('on password required', from);
  776. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  777. } else if ($(pres)
  778. .find(
  779. '>error[type="cancel"]'
  780. + '>not-allowed['
  781. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  782. .length) {
  783. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  784. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  785. // enter the room by replying with 'not-authorized'. This would
  786. // result in reconnection from authorized domain.
  787. // We're either missing Jicofo/Prosody config for anonymous
  788. // domains or something is wrong.
  789. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  790. } else {
  791. logger.warn('onPresError ', pres);
  792. this.eventEmitter.emit(
  793. XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  794. }
  795. } else if ($(pres).find('>error>service-unavailable').length) {
  796. logger.warn('Maximum users limit for the room has been reached',
  797. pres);
  798. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  799. } else {
  800. logger.warn('onPresError ', pres);
  801. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  802. }
  803. }
  804. /**
  805. *
  806. * @param jid
  807. */
  808. kick(jid) {
  809. const kickIQ = $iq({ to: this.roomjid,
  810. type: 'set' })
  811. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  812. .c('item', { nick: Strophe.getResourceFromJid(jid),
  813. role: 'none' })
  814. .c('reason').t('You have been kicked.').up().up().up();
  815. this.connection.sendIQ(
  816. kickIQ,
  817. result => logger.log('Kick participant with jid: ', jid, result),
  818. error => logger.log('Kick participant error: ', error));
  819. }
  820. /* eslint-disable max-params */
  821. /**
  822. *
  823. * @param key
  824. * @param onSuccess
  825. * @param onError
  826. * @param onNotSupported
  827. */
  828. lockRoom(key, onSuccess, onError, onNotSupported) {
  829. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  830. this.connection.sendIQ(
  831. $iq({
  832. to: this.roomjid,
  833. type: 'get'
  834. })
  835. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  836. res => {
  837. if ($(res)
  838. .find(
  839. '>query>x[xmlns="jabber:x:data"]'
  840. + '>field[var="muc#roomconfig_roomsecret"]')
  841. .length) {
  842. const formsubmit
  843. = $iq({
  844. to: this.roomjid,
  845. type: 'set'
  846. })
  847. .c('query', {
  848. xmlns: 'http://jabber.org/protocol/muc#owner'
  849. });
  850. formsubmit.c('x', {
  851. xmlns: 'jabber:x:data',
  852. type: 'submit'
  853. });
  854. formsubmit
  855. .c('field', { 'var': 'FORM_TYPE' })
  856. .c('value')
  857. .t('http://jabber.org/protocol/muc#roomconfig')
  858. .up()
  859. .up();
  860. formsubmit
  861. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  862. .c('value')
  863. .t(key)
  864. .up()
  865. .up();
  866. // Fixes a bug in prosody 0.9.+
  867. // https://code.google.com/p/lxmppd/issues/detail?id=373
  868. formsubmit
  869. .c('field', { 'var': 'muc#roomconfig_whois' })
  870. .c('value')
  871. .t('anyone')
  872. .up()
  873. .up();
  874. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  875. this.connection.sendIQ(formsubmit, onSuccess, onError);
  876. } else {
  877. onNotSupported();
  878. }
  879. },
  880. onError);
  881. }
  882. /* eslint-enable max-params */
  883. /**
  884. *
  885. * @param key
  886. * @param values
  887. */
  888. addToPresence(key, values) {
  889. values.tagName = key;
  890. this.removeFromPresence(key);
  891. this.presMap.nodes.push(values);
  892. }
  893. /**
  894. *
  895. * @param key
  896. */
  897. removeFromPresence(key) {
  898. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  899. this.presMap.nodes = nodes;
  900. }
  901. /**
  902. *
  903. * @param name
  904. * @param handler
  905. */
  906. addPresenceListener(name, handler) {
  907. if (typeof handler !== 'function') {
  908. throw new Error('"handler" is not a function');
  909. }
  910. let tagHandlers = this.presHandlers[name];
  911. if (!tagHandlers) {
  912. this.presHandlers[name] = tagHandlers = [];
  913. }
  914. if (tagHandlers.indexOf(handler) === -1) {
  915. tagHandlers.push(handler);
  916. } else {
  917. logger.warn(
  918. `Trying to add the same handler more than once for: ${name}`);
  919. }
  920. }
  921. /**
  922. *
  923. * @param name
  924. * @param handler
  925. */
  926. removePresenceListener(name, handler) {
  927. const tagHandlers = this.presHandlers[name];
  928. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  929. // eslint-disable-next-line no-negated-condition
  930. if (handlerIdx !== -1) {
  931. tagHandlers.splice(handlerIdx, 1);
  932. } else {
  933. logger.warn(`Handler for: ${name} was not registered`);
  934. }
  935. }
  936. /**
  937. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  938. * focus.
  939. * @param mucJid the full MUC address of the user to be checked.
  940. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  941. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  942. * the MUC then <tt>null</tt> is returned.
  943. */
  944. isFocus(mucJid) {
  945. const member = this.members[mucJid];
  946. if (member) {
  947. return member.isFocus;
  948. }
  949. return null;
  950. }
  951. /**
  952. *
  953. */
  954. isModerator() {
  955. return this.role === 'moderator';
  956. }
  957. /**
  958. *
  959. * @param peerJid
  960. */
  961. getMemberRole(peerJid) {
  962. if (this.members[peerJid]) {
  963. return this.members[peerJid].role;
  964. }
  965. return null;
  966. }
  967. /**
  968. *
  969. * @param mute
  970. * @param callback
  971. */
  972. setVideoMute(mute, callback) {
  973. this.sendVideoInfoPresence(mute);
  974. if (callback) {
  975. callback(mute);
  976. }
  977. }
  978. /**
  979. *
  980. * @param mute
  981. * @param callback
  982. */
  983. setAudioMute(mute, callback) {
  984. return this.sendAudioInfoPresence(mute, callback);
  985. }
  986. /**
  987. *
  988. * @param mute
  989. */
  990. addAudioInfoToPresence(mute) {
  991. this.removeFromPresence('audiomuted');
  992. this.addToPresence(
  993. 'audiomuted',
  994. {
  995. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/audio' },
  996. value: mute.toString()
  997. });
  998. }
  999. /**
  1000. *
  1001. * @param mute
  1002. * @param callback
  1003. */
  1004. sendAudioInfoPresence(mute, callback) {
  1005. this.addAudioInfoToPresence(mute);
  1006. if (this.connection) {
  1007. this.sendPresence();
  1008. }
  1009. if (callback) {
  1010. callback();
  1011. }
  1012. }
  1013. /**
  1014. *
  1015. * @param mute
  1016. */
  1017. addVideoInfoToPresence(mute) {
  1018. this.removeFromPresence('videomuted');
  1019. this.addToPresence(
  1020. 'videomuted',
  1021. {
  1022. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/video' },
  1023. value: mute.toString()
  1024. });
  1025. }
  1026. /**
  1027. *
  1028. * @param mute
  1029. */
  1030. sendVideoInfoPresence(mute) {
  1031. this.addVideoInfoToPresence(mute);
  1032. if (!this.connection) {
  1033. return;
  1034. }
  1035. this.sendPresence();
  1036. }
  1037. /**
  1038. * Obtains the info about given media advertised in the MUC presence of
  1039. * the participant identified by the given endpoint JID.
  1040. * @param {string} endpointId the endpoint ID mapped to the participant
  1041. * which corresponds to MUC nickname.
  1042. * @param {MediaType} mediaType the type of the media for which presence
  1043. * info will be obtained.
  1044. * @return {PeerMediaInfo} presenceInfo an object with media presence
  1045. * info or <tt>null</tt> either if there is no presence available or if
  1046. * the media type given is invalid.
  1047. */
  1048. getMediaPresenceInfo(endpointId, mediaType) {
  1049. // Will figure out current muted status by looking up owner's presence
  1050. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1051. if (!pres) {
  1052. // No presence available
  1053. return null;
  1054. }
  1055. const data = {
  1056. muted: false, // unmuted by default
  1057. videoType: undefined // no video type by default
  1058. };
  1059. let mutedNode = null;
  1060. if (mediaType === MediaType.AUDIO) {
  1061. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1062. } else if (mediaType === MediaType.VIDEO) {
  1063. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1064. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1065. if (videoTypeNode.length > 0) {
  1066. data.videoType = videoTypeNode[0].value;
  1067. }
  1068. } else {
  1069. logger.error(`Unsupported media type: ${mediaType}`);
  1070. return null;
  1071. }
  1072. data.muted = mutedNode.length > 0 && mutedNode[0].value === 'true';
  1073. return data;
  1074. }
  1075. /**
  1076. * Returns true if the recording is supproted and false if not.
  1077. */
  1078. isRecordingSupported() {
  1079. if (this.recording) {
  1080. return this.recording.isSupported();
  1081. }
  1082. return false;
  1083. }
  1084. /**
  1085. * Returns null if the recording is not supported, "on" if the recording
  1086. * started and "off" if the recording is not started.
  1087. */
  1088. getRecordingState() {
  1089. return this.recording ? this.recording.getState() : undefined;
  1090. }
  1091. /**
  1092. * Returns the url of the recorded video.
  1093. */
  1094. getRecordingURL() {
  1095. return this.recording ? this.recording.getURL() : null;
  1096. }
  1097. /**
  1098. * Starts/stops the recording
  1099. * @param token token for authentication
  1100. * @param statusChangeHandler {function} receives the new status as
  1101. * argument.
  1102. */
  1103. toggleRecording(options, statusChangeHandler) {
  1104. if (this.recording) {
  1105. return this.recording.toggleRecording(options, statusChangeHandler);
  1106. }
  1107. return statusChangeHandler('error',
  1108. new Error('The conference is not created yet!'));
  1109. }
  1110. /**
  1111. * Returns true if the SIP calls are supported and false otherwise
  1112. */
  1113. isSIPCallingSupported() {
  1114. if (this.moderator) {
  1115. return this.moderator.isSipGatewayEnabled();
  1116. }
  1117. return false;
  1118. }
  1119. /**
  1120. * Dials a number.
  1121. * @param number the number
  1122. */
  1123. dial(number) {
  1124. return this.connection.rayo.dial(number, 'fromnumber',
  1125. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1126. this.focusMucJid);
  1127. }
  1128. /**
  1129. * Hangup an existing call
  1130. */
  1131. hangup() {
  1132. return this.connection.rayo.hangup();
  1133. }
  1134. /**
  1135. * Returns the phone number for joining the conference.
  1136. */
  1137. getPhoneNumber() {
  1138. return this.phoneNumber;
  1139. }
  1140. /**
  1141. * Returns the pin for joining the conference with phone.
  1142. */
  1143. getPhonePin() {
  1144. return this.phonePin;
  1145. }
  1146. /**
  1147. * Mutes remote participant.
  1148. * @param jid of the participant
  1149. * @param mute
  1150. */
  1151. muteParticipant(jid, mute) {
  1152. logger.info('set mute', mute);
  1153. const iqToFocus = $iq(
  1154. { to: this.focusMucJid,
  1155. type: 'set' })
  1156. .c('mute', {
  1157. xmlns: 'http://jitsi.org/jitmeet/audio',
  1158. jid
  1159. })
  1160. .t(mute.toString())
  1161. .up();
  1162. this.connection.sendIQ(
  1163. iqToFocus,
  1164. result => logger.log('set mute', result),
  1165. error => logger.log('set mute error', error));
  1166. }
  1167. /**
  1168. * TODO: Document
  1169. * @param iq
  1170. */
  1171. onMute(iq) {
  1172. const from = iq.getAttribute('from');
  1173. if (from !== this.focusMucJid) {
  1174. logger.warn('Ignored mute from non focus peer');
  1175. return;
  1176. }
  1177. const mute = $(iq).find('mute');
  1178. if (mute.length && mute.text() === 'true') {
  1179. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS);
  1180. } else {
  1181. // XXX Why do we support anything but muting? Why do we encode the
  1182. // value in the text of the element? Why do we use a separate XML
  1183. // namespace?
  1184. logger.warn('Ignoring a mute request which does not explicitly '
  1185. + 'specify a positive mute command.');
  1186. }
  1187. }
  1188. /**
  1189. * Leaves the room. Closes the jingle session.
  1190. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1191. * less than 5s after sending presence unavailable. Otherwise the promise is
  1192. * rejected.
  1193. */
  1194. leave() {
  1195. return new Promise((resolve, reject) => {
  1196. const timeout = setTimeout(() => onMucLeft(true), 5000);
  1197. const eventEmitter = this.eventEmitter;
  1198. /**
  1199. *
  1200. * @param doReject
  1201. */
  1202. function onMucLeft(doReject = false) {
  1203. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1204. clearTimeout(timeout);
  1205. if (doReject) {
  1206. // the timeout expired
  1207. reject(new Error('The timeout for the confirmation about '
  1208. + 'leaving the room expired.'));
  1209. } else {
  1210. resolve();
  1211. }
  1212. }
  1213. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1214. this.doLeave();
  1215. });
  1216. }
  1217. }
  1218. /* eslint-enable newline-per-chained-call */