Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ChatRoom.js 37KB

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