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

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