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: function (packet, nodes) {
  12. var self = this;
  13. $(packet).children().each(function () {
  14. var tagName = $(this).prop("tagName");
  15. const node = {
  16. tagName: 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: function (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: 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. if (!isSelfPresence) {
  453. delete this.members[from];
  454. this.onParticipantLeft(from, false);
  455. } else if (Object.keys(this.members).length > 0) {
  456. // If the status code is 110 this means we're leaving and we would
  457. // like to remove everyone else from our view, so we trigger the
  458. // event.
  459. for (const i in this.members) {
  460. const member = this.members[i];
  461. delete this.members[i];
  462. this.onParticipantLeft(i, member.isFocus);
  463. }
  464. this.connection.emuc.doLeave(this.roomjid);
  465. // we fire muc_left only if this is not a kick,
  466. // kick has both statuses 110 and 307.
  467. if (!isKick) {
  468. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  469. }
  470. }
  471. if (isKick && this.myroomjid === from) {
  472. this._dispose();
  473. this.eventEmitter.emit(XMPPEvents.KICKED);
  474. }
  475. }
  476. onMessage (msg, from) {
  477. var nick =
  478. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  479. .text() ||
  480. Strophe.getResourceFromJid(from);
  481. var txt = $(msg).find('>body').text();
  482. var type = msg.getAttribute("type");
  483. if (type == "error") {
  484. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  485. $(msg).find('>text').text(), txt);
  486. return true;
  487. }
  488. var subject = $(msg).find('>subject');
  489. if (subject.length) {
  490. var subjectText = subject.text();
  491. if (subjectText || subjectText === "") {
  492. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  493. logger.log("Subject is changed to " + subjectText);
  494. }
  495. }
  496. // xep-0203 delay
  497. var stamp = $(msg).find('>delay').attr('stamp');
  498. if (!stamp) {
  499. // or xep-0091 delay, UTC timestamp
  500. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  501. if (stamp) {
  502. // the format is CCYYMMDDThh:mm:ss
  503. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  504. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  505. }
  506. }
  507. if (from==this.roomjid && $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  508. this.discoRoomInfo();
  509. }
  510. if (txt) {
  511. logger.log('chat', nick, txt);
  512. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  513. from, nick, txt, this.myroomjid, stamp);
  514. }
  515. }
  516. onPresenceError (pres, from) {
  517. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  518. logger.log('on password required', from);
  519. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  520. } else if ($(pres).find(
  521. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  522. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  523. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  524. // enter the room by replying with 'not-authorized'. This would
  525. // result in reconnection from authorized domain.
  526. // We're either missing Jicofo/Prosody config for anonymous
  527. // domains or something is wrong.
  528. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  529. } else {
  530. logger.warn('onPresError ', pres);
  531. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  532. }
  533. } else if($(pres).find('>error>service-unavailable').length) {
  534. logger.warn('Maximum users limit for the room has been reached',
  535. pres);
  536. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  537. } else {
  538. logger.warn('onPresError ', pres);
  539. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  540. }
  541. }
  542. kick (jid) {
  543. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  544. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  545. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  546. .c('reason').t('You have been kicked.').up().up().up();
  547. this.connection.sendIQ(
  548. kickIQ,
  549. function (result) {
  550. logger.log('Kick participant with jid: ', jid, result);
  551. },
  552. function (error) {
  553. logger.log('Kick participant error: ', error);
  554. });
  555. }
  556. lockRoom (key, onSuccess, onError, onNotSupported) {
  557. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  558. var ob = this;
  559. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  560. function (res) {
  561. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  562. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  563. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  564. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  565. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  566. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  567. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  568. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  569. ob.connection.sendIQ(formsubmit,
  570. onSuccess,
  571. onError);
  572. } else {
  573. onNotSupported();
  574. }
  575. }, onError);
  576. }
  577. addToPresence (key, values) {
  578. values.tagName = key;
  579. this.removeFromPresence(key);
  580. this.presMap.nodes.push(values);
  581. }
  582. removeFromPresence (key) {
  583. var nodes = this.presMap.nodes.filter(function(node) {
  584. return key !== node.tagName;
  585. });
  586. this.presMap.nodes = nodes;
  587. }
  588. addPresenceListener (name, handler) {
  589. this.presHandlers[name] = handler;
  590. }
  591. removePresenceListener (name) {
  592. delete this.presHandlers[name];
  593. }
  594. /**
  595. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  596. * focus.
  597. * @param mucJid the full MUC address of the user to be checked.
  598. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus or
  599. * <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  600. * the MUC then <tt>null</tt> is returned.
  601. */
  602. isFocus (mucJid) {
  603. var member = this.members[mucJid];
  604. if (member) {
  605. return member.isFocus;
  606. } else {
  607. return null;
  608. }
  609. }
  610. isModerator () {
  611. return this.role === 'moderator';
  612. }
  613. getMemberRole (peerJid) {
  614. if (this.members[peerJid]) {
  615. return this.members[peerJid].role;
  616. }
  617. return null;
  618. }
  619. setVideoMute (mute, callback) {
  620. this.sendVideoInfoPresence(mute);
  621. if(callback) {
  622. callback(mute);
  623. }
  624. }
  625. setAudioMute (mute, callback) {
  626. return this.sendAudioInfoPresence(mute, callback);
  627. }
  628. addAudioInfoToPresence (mute) {
  629. this.removeFromPresence("audiomuted");
  630. this.addToPresence("audiomuted",
  631. {attributes:
  632. {"xmlns": "http://jitsi.org/jitmeet/audio"},
  633. value: mute.toString()});
  634. }
  635. sendAudioInfoPresence (mute, callback) {
  636. this.addAudioInfoToPresence(mute);
  637. if(this.connection) {
  638. this.sendPresence();
  639. }
  640. if(callback) {
  641. callback();
  642. }
  643. }
  644. addVideoInfoToPresence (mute) {
  645. this.removeFromPresence("videomuted");
  646. this.addToPresence("videomuted",
  647. {attributes:
  648. {"xmlns": "http://jitsi.org/jitmeet/video"},
  649. value: mute.toString()});
  650. }
  651. sendVideoInfoPresence (mute) {
  652. this.addVideoInfoToPresence(mute);
  653. if(!this.connection) {
  654. return;
  655. }
  656. this.sendPresence();
  657. }
  658. /**
  659. * Obtains the info about given media advertised in the MUC presence of
  660. * the participant identified by the given endpoint JID.
  661. * @param {string} endpointId the endpoint ID mapped to the participant
  662. * which corresponds to MUC nickname.
  663. * @param {MediaType} mediaType the type of the media for which presence
  664. * info will be obtained.
  665. * @return {PeerMediaInfo} presenceInfo an object with media presence
  666. * info or <tt>null</tt> either if there is no presence available or if
  667. * the media type given is invalid.
  668. */
  669. getMediaPresenceInfo (endpointId, mediaType) {
  670. // Will figure out current muted status by looking up owner's presence
  671. const pres = this.lastPresences[this.roomjid + "/" + endpointId];
  672. if (!pres) {
  673. // No presence available
  674. return null;
  675. }
  676. const data = {
  677. muted: false, // unmuted by default
  678. videoType: undefined // no video type by default
  679. };
  680. let mutedNode = null;
  681. if (mediaType === MediaType.AUDIO) {
  682. mutedNode = filterNodeFromPresenceJSON(pres, "audiomuted");
  683. } else if (mediaType === MediaType.VIDEO) {
  684. mutedNode = filterNodeFromPresenceJSON(pres, "videomuted");
  685. const videoTypeNode = filterNodeFromPresenceJSON(pres, "videoType");
  686. if(videoTypeNode.length > 0) {
  687. data.videoType = videoTypeNode[0]["value"];
  688. }
  689. } else {
  690. logger.error("Unsupported media type: " + mediaType);
  691. return null;
  692. }
  693. data.muted = mutedNode.length > 0 && mutedNode[0]["value"] === "true";
  694. return data;
  695. }
  696. /**
  697. * Returns true if the recording is supproted and false if not.
  698. */
  699. isRecordingSupported () {
  700. if(this.recording) {
  701. return this.recording.isSupported();
  702. }
  703. return false;
  704. }
  705. /**
  706. * Returns null if the recording is not supported, "on" if the recording started
  707. * and "off" if the recording is not started.
  708. */
  709. getRecordingState () {
  710. return this.recording ? this.recording.getState() : undefined;
  711. }
  712. /**
  713. * Returns the url of the recorded video.
  714. */
  715. getRecordingURL () {
  716. return this.recording ? this.recording.getURL() : null;
  717. }
  718. /**
  719. * Starts/stops the recording
  720. * @param token token for authentication
  721. * @param statusChangeHandler {function} receives the new status as argument.
  722. */
  723. toggleRecording (options, statusChangeHandler) {
  724. if(this.recording) {
  725. return this.recording.toggleRecording(options, statusChangeHandler);
  726. }
  727. return statusChangeHandler("error",
  728. new Error("The conference is not created yet!"));
  729. }
  730. /**
  731. * Returns true if the SIP calls are supported and false otherwise
  732. */
  733. isSIPCallingSupported () {
  734. if(this.moderator) {
  735. return this.moderator.isSipGatewayEnabled();
  736. }
  737. return false;
  738. }
  739. /**
  740. * Dials a number.
  741. * @param number the number
  742. */
  743. dial (number) {
  744. return this.connection.rayo.dial(number, "fromnumber",
  745. Strophe.getNodeFromJid(this.myroomjid), this.password,
  746. this.focusMucJid);
  747. }
  748. /**
  749. * Hangup an existing call
  750. */
  751. hangup () {
  752. return this.connection.rayo.hangup();
  753. }
  754. /**
  755. * Returns the phone number for joining the conference.
  756. */
  757. getPhoneNumber () {
  758. return this.phoneNumber;
  759. }
  760. /**
  761. * Returns the pin for joining the conference with phone.
  762. */
  763. getPhonePin () {
  764. return this.phonePin;
  765. }
  766. /**
  767. * Mutes remote participant.
  768. * @param jid of the participant
  769. * @param mute
  770. */
  771. muteParticipant (jid, mute) {
  772. logger.info("set mute", mute);
  773. var iqToFocus = $iq(
  774. {to: this.focusMucJid, type: 'set'})
  775. .c('mute', {
  776. xmlns: 'http://jitsi.org/jitmeet/audio',
  777. jid: jid
  778. })
  779. .t(mute.toString())
  780. .up();
  781. this.connection.sendIQ(
  782. iqToFocus,
  783. function (result) {
  784. logger.log('set mute', result);
  785. },
  786. function (error) {
  787. logger.log('set mute error', error);
  788. });
  789. }
  790. onMute (iq) {
  791. var from = iq.getAttribute('from');
  792. if (from !== this.focusMucJid) {
  793. logger.warn("Ignored mute from non focus peer");
  794. return false;
  795. }
  796. var mute = $(iq).find('mute');
  797. if (mute.length) {
  798. var doMuteAudio = mute.text() === "true";
  799. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  800. }
  801. return true;
  802. }
  803. /**
  804. * Leaves the room. Closes the jingle session.
  805. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received less
  806. * than 5s after sending presence unavailable. Otherwise the promise is
  807. * rejected.
  808. */
  809. leave () {
  810. return new Promise((resolve, reject) => {
  811. const timeout = setTimeout(() => onMucLeft(true), 5000);
  812. const eventEmitter = this.eventEmitter;
  813. function onMucLeft(doReject = false) {
  814. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  815. clearTimeout(timeout);
  816. if(doReject) {
  817. // the timeout expired
  818. reject(new Error("The timeout for the confirmation about " +
  819. "leaving the room expired."));
  820. } else {
  821. resolve();
  822. }
  823. }
  824. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  825. this.doLeave();
  826. });
  827. }
  828. }