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

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