選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ChatRoom.js 42KB

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