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 34KB

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