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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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. var parser = {
  11. packet2JSON(packet, nodes) {
  12. var self = this;
  13. $(packet).children().each(function() {
  14. var 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. var 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. var 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. var self = this;
  121. this.moderator.allocateConferenceFocus(function() {
  122. self.sendPresence(true);
  123. });
  124. }
  125. sendPresence(fromJoin) {
  126. var to = this.presMap.to;
  127. if (!to || (!this.joined && !fromJoin)) {
  128. // Too early to send presence - not initialized
  129. return;
  130. }
  131. var 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. var 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. var getInfo = $iq({type: 'get', to: this.roomjid})
  180. .c('query', {xmlns: Strophe.NS.DISCO_INFO});
  181. this.connection.sendIQ(getInfo, function(result) {
  182. var 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. }.bind(this));
  192. }
  193. createNonAnonymousRoom() {
  194. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  195. var 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. var 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. var errmsg = 'non-anonymous rooms not supported';
  204. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  205. logger.error(errmsg);
  206. return;
  207. }
  208. var 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. var from = pres.getAttribute('from');
  224. // Parse roles.
  225. var member = {};
  226. member.show = $(pres).find('>show').text();
  227. member.status = $(pres).find('>status').text();
  228. var 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. var 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. var 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. var 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. var 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. var 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. var 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. var 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. default:
  347. this.processNode(node, from);
  348. }
  349. }
  350. // Trigger status message update
  351. if (member.status) {
  352. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member.status);
  353. }
  354. if(jibri) {
  355. this.lastJibri = jibri;
  356. if(this.recording) {
  357. this.recording.handleJibriPresence(jibri);
  358. }
  359. }
  360. }
  361. /**
  362. * Initialize some properties when the focus participant is verified.
  363. * @param from jid of the focus
  364. * @param mucJid the jid of the focus in the muc
  365. */
  366. _initFocus(from, mucJid) {
  367. this.focusMucJid = from;
  368. if(!this.recording) {
  369. this.recording = new Recorder(this.options.recordingType,
  370. this.eventEmitter, this.connection, this.focusMucJid,
  371. this.options.jirecon, this.roomjid);
  372. if(this.lastJibri) {
  373. this.recording.handleJibriPresence(this.lastJibri);
  374. }
  375. }
  376. logger.info('Ignore focus: ' + from + ', real JID: ' + mucJid);
  377. }
  378. /**
  379. * Sets the special listener to be used for "command"s whose name starts with
  380. * "jitsi_participant_".
  381. */
  382. setParticipantPropertyListener(listener) {
  383. this.participantPropertyListener = listener;
  384. }
  385. processNode(node, from) {
  386. // make sure we catch all errors coming from any handler
  387. // otherwise we can remove the presence handler from strophe
  388. try {
  389. var tagHandler = this.presHandlers[node.tagName];
  390. if (node.tagName.startsWith('jitsi_participant_')) {
  391. tagHandler = this.participantPropertyListener;
  392. }
  393. if(tagHandler) {
  394. tagHandler(node, Strophe.getResourceFromJid(from), from);
  395. }
  396. } catch (e) {
  397. GlobalOnErrorHandler.callErrorHandler(e);
  398. logger.error('Error processing:' + node.tagName + ' node.', e);
  399. }
  400. }
  401. sendMessage(body, nickname) {
  402. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  403. msg.c('body', body).up();
  404. if (nickname) {
  405. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  406. }
  407. this.connection.send(msg);
  408. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  409. }
  410. setSubject(subject) {
  411. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  412. msg.c('subject', subject);
  413. this.connection.send(msg);
  414. }
  415. /**
  416. * Called when participant leaves.
  417. * @param jid the jid of the participant that leaves
  418. * @param skipEvents optional params to skip any events, including check
  419. * whether this is the focus that left
  420. */
  421. onParticipantLeft(jid, skipEvents) {
  422. delete this.lastPresences[jid];
  423. if(skipEvents) {
  424. return;
  425. }
  426. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  427. this.moderator.onMucMemberLeft(jid);
  428. }
  429. onPresenceUnavailable(pres, from) {
  430. // room destroyed ?
  431. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]'
  432. + '>destroy').length) {
  433. var reason;
  434. var reasonSelect = $(pres).find(
  435. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  436. + '>destroy>reason');
  437. if (reasonSelect.length) {
  438. reason = reasonSelect.text();
  439. }
  440. this._dispose();
  441. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  442. this.connection.emuc.doLeave(this.roomjid);
  443. return true;
  444. }
  445. // Status code 110 indicates that this notification is "self-presence".
  446. var isSelfPresence = $(pres).find(
  447. '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]'
  448. ).length !== 0;
  449. var isKick = $(pres).find(
  450. '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]'
  451. ).length !== 0;
  452. const membersKeys = Object.keys(this.members);
  453. if (!isSelfPresence) {
  454. delete this.members[from];
  455. this.onParticipantLeft(from, false);
  456. } else if (membersKeys.length > 0) {
  457. // If the status code is 110 this means we're leaving and we would
  458. // like to remove everyone else from our view, so we trigger the
  459. // event.
  460. membersKeys.forEach(jid => {
  461. const member = this.members[jid];
  462. delete this.members[jid];
  463. this.onParticipantLeft(jid, member.isFocus);
  464. });
  465. this.connection.emuc.doLeave(this.roomjid);
  466. // we fire muc_left only if this is not a kick,
  467. // kick has both statuses 110 and 307.
  468. if (!isKick) {
  469. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  470. }
  471. }
  472. if (isKick && this.myroomjid === from) {
  473. this._dispose();
  474. this.eventEmitter.emit(XMPPEvents.KICKED);
  475. }
  476. }
  477. onMessage(msg, from) {
  478. var nick
  479. = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  480. .text()
  481. || Strophe.getResourceFromJid(from);
  482. var txt = $(msg).find('>body').text();
  483. var type = msg.getAttribute('type');
  484. if (type == 'error') {
  485. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  486. $(msg).find('>text').text(), txt);
  487. return true;
  488. }
  489. var subject = $(msg).find('>subject');
  490. if (subject.length) {
  491. var subjectText = subject.text();
  492. if (subjectText || subjectText === '') {
  493. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  494. logger.log('Subject is changed to ' + subjectText);
  495. }
  496. }
  497. // xep-0203 delay
  498. var stamp = $(msg).find('>delay').attr('stamp');
  499. if (!stamp) {
  500. // or xep-0091 delay, UTC timestamp
  501. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  502. if (stamp) {
  503. // the format is CCYYMMDDThh:mm:ss
  504. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  505. stamp = dateParts[1] + '-' + dateParts[2] + '-' + dateParts[3] + 'Z';
  506. }
  507. }
  508. if (from == this.roomjid && $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  509. this.discoRoomInfo();
  510. }
  511. if (txt) {
  512. logger.log('chat', nick, txt);
  513. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  514. from, nick, txt, this.myroomjid, stamp);
  515. }
  516. }
  517. onPresenceError(pres, from) {
  518. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  519. logger.log('on password required', from);
  520. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  521. } else if ($(pres).find(
  522. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  523. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  524. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  525. // enter the room by replying with 'not-authorized'. This would
  526. // result in reconnection from authorized domain.
  527. // We're either missing Jicofo/Prosody config for anonymous
  528. // domains or something is wrong.
  529. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  530. } else {
  531. logger.warn('onPresError ', pres);
  532. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  533. }
  534. } else if($(pres).find('>error>service-unavailable').length) {
  535. logger.warn('Maximum users limit for the room has been reached',
  536. pres);
  537. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  538. } else {
  539. logger.warn('onPresError ', pres);
  540. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  541. }
  542. }
  543. kick(jid) {
  544. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  545. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  546. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  547. .c('reason').t('You have been kicked.').up().up().up();
  548. this.connection.sendIQ(
  549. kickIQ,
  550. function(result) {
  551. logger.log('Kick participant with jid: ', jid, result);
  552. },
  553. function(error) {
  554. logger.log('Kick participant error: ', error);
  555. });
  556. }
  557. lockRoom(key, onSuccess, onError, onNotSupported) {
  558. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  559. var ob = this;
  560. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  561. function(res) {
  562. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  563. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  564. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  565. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  566. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  567. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  568. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  569. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  570. ob.connection.sendIQ(formsubmit,
  571. onSuccess,
  572. onError);
  573. } else {
  574. onNotSupported();
  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. var nodes = this.presMap.nodes.filter(function(node) {
  585. return key !== node.tagName;
  586. });
  587. this.presMap.nodes = nodes;
  588. }
  589. addPresenceListener(name, handler) {
  590. this.presHandlers[name] = handler;
  591. }
  592. removePresenceListener(name) {
  593. delete this.presHandlers[name];
  594. }
  595. /**
  596. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  597. * focus.
  598. * @param mucJid the full MUC address of the user to be checked.
  599. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus or
  600. * <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  601. * the MUC then <tt>null</tt> is returned.
  602. */
  603. isFocus(mucJid) {
  604. var member = this.members[mucJid];
  605. if (member) {
  606. return member.isFocus;
  607. } else {
  608. return null;
  609. }
  610. }
  611. isModerator() {
  612. return this.role === 'moderator';
  613. }
  614. getMemberRole(peerJid) {
  615. if (this.members[peerJid]) {
  616. return this.members[peerJid].role;
  617. }
  618. return null;
  619. }
  620. setVideoMute(mute, callback) {
  621. this.sendVideoInfoPresence(mute);
  622. if(callback) {
  623. callback(mute);
  624. }
  625. }
  626. setAudioMute(mute, callback) {
  627. return this.sendAudioInfoPresence(mute, callback);
  628. }
  629. addAudioInfoToPresence(mute) {
  630. this.removeFromPresence('audiomuted');
  631. this.addToPresence('audiomuted',
  632. {attributes:
  633. {'xmlns': 'http://jitsi.org/jitmeet/audio'},
  634. value: mute.toString()});
  635. }
  636. sendAudioInfoPresence(mute, callback) {
  637. this.addAudioInfoToPresence(mute);
  638. if(this.connection) {
  639. this.sendPresence();
  640. }
  641. if(callback) {
  642. callback();
  643. }
  644. }
  645. addVideoInfoToPresence(mute) {
  646. this.removeFromPresence('videomuted');
  647. this.addToPresence('videomuted',
  648. {attributes:
  649. {'xmlns': 'http://jitsi.org/jitmeet/video'},
  650. value: mute.toString()});
  651. }
  652. sendVideoInfoPresence(mute) {
  653. this.addVideoInfoToPresence(mute);
  654. if(!this.connection) {
  655. return;
  656. }
  657. this.sendPresence();
  658. }
  659. /**
  660. * Obtains the info about given media advertised in the MUC presence of
  661. * the participant identified by the given endpoint JID.
  662. * @param {string} endpointId the endpoint ID mapped to the participant
  663. * which corresponds to MUC nickname.
  664. * @param {MediaType} mediaType the type of the media for which presence
  665. * info will be obtained.
  666. * @return {PeerMediaInfo} presenceInfo an object with media presence
  667. * info or <tt>null</tt> either if there is no presence available or if
  668. * the media type given is invalid.
  669. */
  670. getMediaPresenceInfo(endpointId, mediaType) {
  671. // Will figure out current muted status by looking up owner's presence
  672. const pres = this.lastPresences[this.roomjid + '/' + endpointId];
  673. if (!pres) {
  674. // No presence available
  675. return null;
  676. }
  677. const data = {
  678. muted: false, // unmuted by default
  679. videoType: undefined // no video type by default
  680. };
  681. let mutedNode = null;
  682. if (mediaType === MediaType.AUDIO) {
  683. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  684. } else if (mediaType === MediaType.VIDEO) {
  685. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  686. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  687. if(videoTypeNode.length > 0) {
  688. data.videoType = videoTypeNode[0].value;
  689. }
  690. } else {
  691. logger.error('Unsupported media type: ' + mediaType);
  692. return null;
  693. }
  694. data.muted = mutedNode.length > 0 && mutedNode[0].value === 'true';
  695. return data;
  696. }
  697. /**
  698. * Returns true if the recording is supproted and false if not.
  699. */
  700. isRecordingSupported() {
  701. if(this.recording) {
  702. return this.recording.isSupported();
  703. }
  704. return false;
  705. }
  706. /**
  707. * Returns null if the recording is not supported, "on" if the recording started
  708. * and "off" if the recording is not started.
  709. */
  710. getRecordingState() {
  711. return this.recording ? this.recording.getState() : undefined;
  712. }
  713. /**
  714. * Returns the url of the recorded video.
  715. */
  716. getRecordingURL() {
  717. return this.recording ? this.recording.getURL() : null;
  718. }
  719. /**
  720. * Starts/stops the recording
  721. * @param token token for authentication
  722. * @param statusChangeHandler {function} receives the new status as argument.
  723. */
  724. toggleRecording(options, statusChangeHandler) {
  725. if(this.recording) {
  726. return this.recording.toggleRecording(options, statusChangeHandler);
  727. }
  728. return statusChangeHandler('error',
  729. new Error('The conference is not created yet!'));
  730. }
  731. /**
  732. * Returns true if the SIP calls are supported and false otherwise
  733. */
  734. isSIPCallingSupported() {
  735. if(this.moderator) {
  736. return this.moderator.isSipGatewayEnabled();
  737. }
  738. return false;
  739. }
  740. /**
  741. * Dials a number.
  742. * @param number the number
  743. */
  744. dial(number) {
  745. return this.connection.rayo.dial(number, 'fromnumber',
  746. Strophe.getNodeFromJid(this.myroomjid), this.password,
  747. this.focusMucJid);
  748. }
  749. /**
  750. * Hangup an existing call
  751. */
  752. hangup() {
  753. return this.connection.rayo.hangup();
  754. }
  755. /**
  756. * Returns the phone number for joining the conference.
  757. */
  758. getPhoneNumber() {
  759. return this.phoneNumber;
  760. }
  761. /**
  762. * Returns the pin for joining the conference with phone.
  763. */
  764. getPhonePin() {
  765. return this.phonePin;
  766. }
  767. /**
  768. * Mutes remote participant.
  769. * @param jid of the participant
  770. * @param mute
  771. */
  772. muteParticipant(jid, mute) {
  773. logger.info('set mute', mute);
  774. var iqToFocus = $iq(
  775. {to: this.focusMucJid, type: 'set'})
  776. .c('mute', {
  777. xmlns: 'http://jitsi.org/jitmeet/audio',
  778. jid
  779. })
  780. .t(mute.toString())
  781. .up();
  782. this.connection.sendIQ(
  783. iqToFocus,
  784. function(result) {
  785. logger.log('set mute', result);
  786. },
  787. function(error) {
  788. logger.log('set mute error', error);
  789. });
  790. }
  791. onMute(iq) {
  792. var from = iq.getAttribute('from');
  793. if (from !== this.focusMucJid) {
  794. logger.warn('Ignored mute from non focus peer');
  795. return false;
  796. }
  797. var mute = $(iq).find('mute');
  798. if (mute.length) {
  799. var doMuteAudio = mute.text() === 'true';
  800. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  801. }
  802. return true;
  803. }
  804. /**
  805. * Leaves the room. Closes the jingle session.
  806. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received less
  807. * than 5s after sending presence unavailable. Otherwise the promise is
  808. * rejected.
  809. */
  810. leave() {
  811. return new Promise((resolve, reject) => {
  812. const timeout = setTimeout(() => onMucLeft(true), 5000);
  813. const eventEmitter = this.eventEmitter;
  814. function onMucLeft(doReject = false) {
  815. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  816. clearTimeout(timeout);
  817. if(doReject) {
  818. // the timeout expired
  819. reject(new Error('The timeout for the confirmation about '
  820. + 'leaving the room expired.'));
  821. } else {
  822. resolve();
  823. }
  824. }
  825. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  826. this.doLeave();
  827. });
  828. }
  829. }