You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 32KB

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