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

ChatRoom.js 42KB

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