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