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

ChatRoom.js 36KB

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