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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. /* global Strophe, $, $pres, $iq, $msg */
  2. /* jshint -W101,-W069 */
  3. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5. var Moderator = require("./moderator");
  6. var EventEmitter = require("events");
  7. var Recorder = require("./recording");
  8. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  9. var parser = {
  10. packet2JSON: function (packet, nodes) {
  11. var self = this;
  12. $(packet).children().each(function (index) {
  13. var tagName = $(this).prop("tagName");
  14. var node = {
  15. tagName: tagName
  16. };
  17. node.attributes = {};
  18. $($(this)[0].attributes).each(function( index, attr ) {
  19. node.attributes[ attr.name ] = attr.value;
  20. });
  21. var text = Strophe.getText($(this)[0]);
  22. if (text) {
  23. node.value = text;
  24. }
  25. node.children = [];
  26. nodes.push(node);
  27. self.packet2JSON($(this), node.children);
  28. });
  29. },
  30. JSON2packet: function (nodes, packet) {
  31. for(var i = 0; i < nodes.length; i++) {
  32. var node = nodes[i];
  33. if(!node || node === null){
  34. continue;
  35. }
  36. packet.c(node.tagName, node.attributes);
  37. if(node.value)
  38. packet.t(node.value);
  39. if(node.children)
  40. this.JSON2packet(node.children, packet);
  41. packet.up();
  42. }
  43. // packet.up();
  44. }
  45. };
  46. /**
  47. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  48. * @param pres the presence JSON
  49. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  50. */
  51. function filterNodeFromPresenceJSON(pres, nodeName){
  52. var res = [];
  53. for(var i = 0; i < pres.length; i++)
  54. if(pres[i].tagName === nodeName)
  55. res.push(pres[i]);
  56. return res;
  57. }
  58. function ChatRoom(connection, jid, password, XMPP, options, settings) {
  59. this.eventEmitter = new EventEmitter();
  60. this.xmpp = XMPP;
  61. this.connection = connection;
  62. this.roomjid = Strophe.getBareJidFromJid(jid);
  63. this.myroomjid = jid;
  64. this.password = password;
  65. logger.info("Joined MUC as " + this.myroomjid);
  66. this.members = {};
  67. this.presMap = {};
  68. this.presHandlers = {};
  69. this.joined = false;
  70. this.role = 'none';
  71. this.focusMucJid = null;
  72. this.bridgeIsDown = false;
  73. this.options = options || {};
  74. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
  75. settings);
  76. this.initPresenceMap();
  77. this.session = null;
  78. var self = this;
  79. this.lastPresences = {};
  80. this.phoneNumber = null;
  81. this.phonePin = null;
  82. }
  83. ChatRoom.prototype.initPresenceMap = function () {
  84. this.presMap['to'] = this.myroomjid;
  85. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  86. this.presMap["nodes"] = [];
  87. this.presMap["nodes"].push( {
  88. "tagName": "user-agent",
  89. "value": navigator.userAgent,
  90. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  91. });
  92. };
  93. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  94. this.presMap["nodes"].push( {
  95. "tagName": "devices",
  96. "children": [
  97. {
  98. "tagName": "audio",
  99. "value": devices.audio,
  100. },
  101. {
  102. "tagName": "video",
  103. "value": devices.video,
  104. }
  105. ]
  106. });
  107. };
  108. ChatRoom.prototype.join = function (password) {
  109. if(password)
  110. this.password = password;
  111. var self = this;
  112. this.moderator.allocateConferenceFocus(function () {
  113. self.sendPresence(true);
  114. });
  115. };
  116. ChatRoom.prototype.sendPresence = function (fromJoin) {
  117. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  118. // Too early to send presence - not initialized
  119. return;
  120. }
  121. var pres = $pres({to: this.presMap['to'] });
  122. pres.c('x', {xmlns: this.presMap['xns']});
  123. if (this.password) {
  124. pres.c('password').t(this.password).up();
  125. }
  126. pres.up();
  127. // Send XEP-0115 'c' stanza that contains our capabilities info
  128. if (this.connection.caps) {
  129. this.connection.caps.node = this.xmpp.options.clientNode;
  130. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  131. }
  132. parser.JSON2packet(this.presMap.nodes, pres);
  133. this.connection.send(pres);
  134. };
  135. ChatRoom.prototype.doLeave = function () {
  136. logger.log("do leave", this.myroomjid);
  137. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  138. this.presMap.length = 0;
  139. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  140. // means that there may not be enough time to send the unavailable presence.
  141. // Switching Strophe to synchronous sending is not much of an option because
  142. // it may lead to a noticeable delay in navigating away from the current
  143. // location. As a compromise, we will try to increase the chances of sending
  144. // the unavailable presence within the short time span that we have upon
  145. // unloading by invoking flush() on the connection. We flush() once before
  146. // sending/queuing the unavailable presence in order to attemtp to have the
  147. // unavailable presence at the top of the send queue. We flush() once more
  148. // after sending/queuing the unavailable presence in order to attempt to
  149. // have it sent as soon as possible.
  150. this.connection.flush();
  151. this.connection.send(pres);
  152. this.connection.flush();
  153. };
  154. ChatRoom.prototype.createNonAnonymousRoom = function () {
  155. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  156. var getForm = $iq({type: 'get', to: this.roomjid})
  157. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  158. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  159. var self = this;
  160. this.connection.sendIQ(getForm, function (form) {
  161. if (!$(form).find(
  162. '>query>x[xmlns="jabber:x:data"]' +
  163. '>field[var="muc#roomconfig_whois"]').length) {
  164. logger.error('non-anonymous rooms not supported');
  165. return;
  166. }
  167. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  168. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  169. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  170. formSubmit.c('field', {'var': 'FORM_TYPE'})
  171. .c('value')
  172. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  173. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  174. .c('value').t('anyone').up().up();
  175. self.connection.sendIQ(formSubmit);
  176. }, function (error) {
  177. logger.error("Error getting room configuration form");
  178. });
  179. };
  180. ChatRoom.prototype.onPresence = function (pres) {
  181. var from = pres.getAttribute('from');
  182. // Parse roles.
  183. var member = {};
  184. member.show = $(pres).find('>show').text();
  185. member.status = $(pres).find('>status').text();
  186. var mucUserItem
  187. = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  188. member.affiliation = mucUserItem.attr('affiliation');
  189. member.role = mucUserItem.attr('role');
  190. // Focus recognition
  191. var jid = mucUserItem.attr('jid');
  192. member.jid = jid;
  193. member.isFocus
  194. = !!jid && jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0;
  195. $(pres).find(">x").remove();
  196. var nodes = [];
  197. parser.packet2JSON(pres, nodes);
  198. this.lastPresences[from] = nodes;
  199. var jibri = null;
  200. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  201. // events
  202. for(var i = 0; i < nodes.length; i++)
  203. {
  204. var node = nodes[i];
  205. switch(node.tagName)
  206. {
  207. case "nick":
  208. member.nick = node.value;
  209. break;
  210. case "userId":
  211. member.id = node.value;
  212. break;
  213. }
  214. }
  215. if (from == this.myroomjid) {
  216. if (member.affiliation == 'owner' && this.role !== member.role) {
  217. this.role = member.role;
  218. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  219. }
  220. if (!this.joined) {
  221. this.joined = true;
  222. console.log("(TIME) MUC joined:\t", window.performance.now());
  223. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  224. }
  225. } else if (this.members[from] === undefined) {
  226. // new participant
  227. this.members[from] = member;
  228. logger.log('entered', from, member);
  229. if (member.isFocus) {
  230. this.focusMucJid = from;
  231. if(!this.recording) {
  232. this.recording = new Recorder(this.options.recordingType,
  233. this.eventEmitter, this.connection, this.focusMucJid,
  234. this.options.jirecon, this.roomjid);
  235. if(this.lastJibri)
  236. this.recording.handleJibriPresence(this.lastJibri);
  237. }
  238. logger.info("Ignore focus: " + from + ", real JID: " + jid);
  239. }
  240. else {
  241. this.eventEmitter.emit(
  242. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  243. }
  244. } else {
  245. // Presence update for existing participant
  246. // Watch role change:
  247. var memberOfThis = this.members[from];
  248. if (memberOfThis.role != member.role) {
  249. memberOfThis.role = member.role;
  250. this.eventEmitter.emit(
  251. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  252. }
  253. // store the new display name
  254. if(member.displayName)
  255. memberOfThis.displayName = member.displayName;
  256. }
  257. // after we had fired member or room joined events, lets fire events
  258. // for the rest info we got in presence
  259. for(var i = 0; i < nodes.length; i++)
  260. {
  261. var node = nodes[i];
  262. switch(node.tagName)
  263. {
  264. case "nick":
  265. if(!member.isFocus) {
  266. var displayName = !this.xmpp.options.displayJids
  267. ? member.nick : Strophe.getResourceFromJid(from);
  268. if (displayName && displayName.length > 0) {
  269. this.eventEmitter.emit(
  270. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  271. }
  272. }
  273. break;
  274. case "bridgeIsDown":
  275. if(!this.bridgeIsDown) {
  276. this.bridgeIsDown = true;
  277. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  278. }
  279. break;
  280. case "jibri-recording-status":
  281. var jibri = node;
  282. break;
  283. case "call-control":
  284. var att = node.attributes;
  285. if(!att)
  286. break;
  287. this.phoneNumber = att.phone || null;
  288. this.phonePin = att.pin || null;
  289. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  290. break;
  291. default :
  292. this.processNode(node, from);
  293. }
  294. }
  295. // Trigger status message update
  296. if (member.status) {
  297. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member.status);
  298. }
  299. if(jibri)
  300. {
  301. this.lastJibri = jibri;
  302. if(this.recording)
  303. this.recording.handleJibriPresence(jibri);
  304. }
  305. };
  306. ChatRoom.prototype.processNode = function (node, from) {
  307. if(this.presHandlers[node.tagName])
  308. this.presHandlers[node.tagName](
  309. node, Strophe.getResourceFromJid(from), from);
  310. };
  311. ChatRoom.prototype.sendMessage = function (body, nickname) {
  312. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  313. msg.c('body', body).up();
  314. if (nickname) {
  315. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  316. }
  317. this.connection.send(msg);
  318. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  319. };
  320. ChatRoom.prototype.setSubject = function (subject) {
  321. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  322. msg.c('subject', subject);
  323. this.connection.send(msg);
  324. };
  325. ChatRoom.prototype.onParticipantLeft = function (jid) {
  326. delete this.lastPresences[jid];
  327. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  328. this.moderator.onMucMemberLeft(jid);
  329. };
  330. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  331. // room destroyed ?
  332. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  333. '>destroy').length) {
  334. var reason;
  335. var reasonSelect = $(pres).find(
  336. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  337. '>destroy>reason');
  338. if (reasonSelect.length) {
  339. reason = reasonSelect.text();
  340. }
  341. this.xmpp.leaveRoom(this.roomjid);
  342. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  343. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  344. return true;
  345. }
  346. // Status code 110 indicates that this notification is "self-presence".
  347. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  348. delete this.members[from];
  349. this.onParticipantLeft(from);
  350. }
  351. // If the status code is 110 this means we're leaving and we would like
  352. // to remove everyone else from our view, so we trigger the event.
  353. else if (Object.keys(this.members).length > 1) {
  354. for (var i in this.members) {
  355. var member = this.members[i];
  356. delete this.members[i];
  357. this.onParticipantLeft(member);
  358. }
  359. }
  360. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  361. if (this.myroomjid === from) {
  362. this.xmpp.leaveRoom(this.roomjid);
  363. this.eventEmitter.emit(XMPPEvents.KICKED);
  364. }
  365. }
  366. };
  367. ChatRoom.prototype.onMessage = function (msg, from) {
  368. var nick =
  369. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  370. .text() ||
  371. Strophe.getResourceFromJid(from);
  372. var txt = $(msg).find('>body').text();
  373. var type = msg.getAttribute("type");
  374. if (type == "error") {
  375. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  376. $(msg).find('>text').text(), txt);
  377. return true;
  378. }
  379. var subject = $(msg).find('>subject');
  380. if (subject.length) {
  381. var subjectText = subject.text();
  382. if (subjectText || subjectText === "") {
  383. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  384. logger.log("Subject is changed to " + subjectText);
  385. }
  386. }
  387. // xep-0203 delay
  388. var stamp = $(msg).find('>delay').attr('stamp');
  389. if (!stamp) {
  390. // or xep-0091 delay, UTC timestamp
  391. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  392. if (stamp) {
  393. // the format is CCYYMMDDThh:mm:ss
  394. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  395. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  396. }
  397. }
  398. if (txt) {
  399. logger.log('chat', nick, txt);
  400. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  401. from, nick, txt, this.myroomjid, stamp);
  402. }
  403. };
  404. ChatRoom.prototype.onPresenceError = function (pres, from) {
  405. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  406. logger.log('on password required', from);
  407. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  408. } else if ($(pres).find(
  409. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  410. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  411. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  412. // enter the room by replying with 'not-authorized'. This would
  413. // result in reconnection from authorized domain.
  414. // We're either missing Jicofo/Prosody config for anonymous
  415. // domains or something is wrong.
  416. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  417. } else {
  418. logger.warn('onPresError ', pres);
  419. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  420. }
  421. } else if($(pres).find('>error>service-unavailable').length) {
  422. logger.warn('Maximum users limit for the room has been reached',
  423. pres);
  424. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR, pres);
  425. } else {
  426. logger.warn('onPresError ', pres);
  427. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  428. }
  429. };
  430. ChatRoom.prototype.kick = function (jid) {
  431. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  432. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  433. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  434. .c('reason').t('You have been kicked.').up().up().up();
  435. this.connection.sendIQ(
  436. kickIQ,
  437. function (result) {
  438. logger.log('Kick participant with jid: ', jid, result);
  439. },
  440. function (error) {
  441. logger.log('Kick participant error: ', error);
  442. });
  443. };
  444. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  445. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  446. var ob = this;
  447. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  448. function (res) {
  449. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  450. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  451. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  452. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  453. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  454. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  455. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  456. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  457. ob.connection.sendIQ(formsubmit,
  458. onSuccess,
  459. onError);
  460. } else {
  461. onNotSupported();
  462. }
  463. }, onError);
  464. };
  465. ChatRoom.prototype.addToPresence = function (key, values) {
  466. values.tagName = key;
  467. this.presMap["nodes"].push(values);
  468. };
  469. ChatRoom.prototype.removeFromPresence = function (key) {
  470. for(var i = 0; i < this.presMap.nodes.length; i++)
  471. {
  472. if(key === this.presMap.nodes[i].tagName)
  473. this.presMap.nodes.splice(i, 1);
  474. }
  475. };
  476. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  477. this.presHandlers[name] = handler;
  478. };
  479. ChatRoom.prototype.removePresenceListener = function (name) {
  480. delete this.presHandlers[name];
  481. };
  482. /**
  483. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  484. * focus.
  485. * @param mucJid the full MUC address of the user to be checked.
  486. * @returns {boolean} <tt>true</tt> if MUC user is the conference focus.
  487. */
  488. ChatRoom.prototype.isFocus = function (mucJid) {
  489. var member = this.members[mucJid];
  490. if (member) {
  491. return member.isFocus;
  492. } else {
  493. return null;
  494. }
  495. };
  496. ChatRoom.prototype.isModerator = function () {
  497. return this.role === 'moderator';
  498. };
  499. ChatRoom.prototype.getMemberRole = function (peerJid) {
  500. if (this.members[peerJid]) {
  501. return this.members[peerJid].role;
  502. }
  503. return null;
  504. };
  505. ChatRoom.prototype.setJingleSession = function(session){
  506. this.session = session;
  507. };
  508. ChatRoom.prototype.removeStream = function (stream, callback, ssrcInfo) {
  509. if(!this.session) {
  510. callback();
  511. return;
  512. }
  513. this.session.removeStream(stream, callback, ssrcInfo);
  514. };
  515. /**
  516. * Adds stream.
  517. * @param stream new stream that will be added.
  518. * @param callback callback executed after successful stream addition.
  519. * @param ssrcInfo object with information about the SSRCs associated with the
  520. * stream.
  521. * @param dontModifySources {boolean} if true _modifySources won't be called.
  522. * Used for streams added before the call start.
  523. */
  524. ChatRoom.prototype.addStream = function (stream, callback, ssrcInfo,
  525. dontModifySources) {
  526. if(this.session) {
  527. // FIXME: will block switchInProgress on true value in case of exception
  528. this.session.addStream(stream, callback, ssrcInfo, dontModifySources);
  529. } else {
  530. // We are done immediately
  531. logger.warn("No conference handler or conference not started yet");
  532. callback();
  533. }
  534. };
  535. /**
  536. * Generate ssrc info object for a stream with the following properties:
  537. * - ssrcs - Array of the ssrcs associated with the stream.
  538. * - groups - Array of the groups associated with the stream.
  539. */
  540. ChatRoom.prototype.generateNewStreamSSRCInfo = function () {
  541. if(!this.session) {
  542. logger.warn("The call haven't been started. " +
  543. "Cannot generate ssrc info at the moment!");
  544. return null;
  545. }
  546. return this.session.generateNewStreamSSRCInfo();
  547. };
  548. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  549. var self = this;
  550. this.sendVideoInfoPresence(mute);
  551. if(callback)
  552. callback(mute);
  553. };
  554. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  555. return this.sendAudioInfoPresence(mute, callback);
  556. };
  557. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  558. this.removeFromPresence("audiomuted");
  559. this.addToPresence("audiomuted",
  560. {attributes:
  561. {"audions": "http://jitsi.org/jitmeet/audio"},
  562. value: mute.toString()});
  563. };
  564. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  565. this.addAudioInfoToPresence(mute);
  566. if(this.connection) {
  567. this.sendPresence();
  568. }
  569. if(callback)
  570. callback();
  571. };
  572. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  573. this.removeFromPresence("videomuted");
  574. this.addToPresence("videomuted",
  575. {attributes:
  576. {"videons": "http://jitsi.org/jitmeet/video"},
  577. value: mute.toString()});
  578. };
  579. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  580. this.addVideoInfoToPresence(mute);
  581. if(!this.connection)
  582. return;
  583. this.sendPresence();
  584. };
  585. ChatRoom.prototype.addListener = function(type, listener) {
  586. this.eventEmitter.on(type, listener);
  587. };
  588. ChatRoom.prototype.removeListener = function (type, listener) {
  589. this.eventEmitter.removeListener(type, listener);
  590. };
  591. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  592. if(this.lastPresences[data.peerjid])
  593. {
  594. var pres = this.lastPresences[data.peerjid];
  595. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  596. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  597. data.videomuted = ((videomuted.length > 0
  598. && videomuted[0]
  599. && videomuted[0]["value"] === "true")? true : false);
  600. data.audiomuted = ((audiomuted.length > 0
  601. && audiomuted[0]
  602. && audiomuted[0]["value"] === "true")? true : false);
  603. }
  604. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  605. };
  606. /**
  607. * Returns true if the recording is supproted and false if not.
  608. */
  609. ChatRoom.prototype.isRecordingSupported = function () {
  610. if(this.recording)
  611. return this.recording.isSupported();
  612. return false;
  613. };
  614. /**
  615. * Returns null if the recording is not supported, "on" if the recording started
  616. * and "off" if the recording is not started.
  617. */
  618. ChatRoom.prototype.getRecordingState = function () {
  619. if(this.recording)
  620. return this.recording.getState();
  621. return "off";
  622. }
  623. /**
  624. * Returns the url of the recorded video.
  625. */
  626. ChatRoom.prototype.getRecordingURL = function () {
  627. if(this.recording)
  628. return this.recording.getURL();
  629. return null;
  630. }
  631. /**
  632. * Starts/stops the recording
  633. * @param token token for authentication
  634. * @param statusChangeHandler {function} receives the new status as argument.
  635. */
  636. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  637. if(this.recording)
  638. return this.recording.toggleRecording(options, statusChangeHandler);
  639. return statusChangeHandler("error",
  640. new Error("The conference is not created yet!"));
  641. }
  642. /**
  643. * Returns true if the SIP calls are supported and false otherwise
  644. */
  645. ChatRoom.prototype.isSIPCallingSupported = function () {
  646. if(this.moderator)
  647. return this.moderator.isSipGatewayEnabled();
  648. return false;
  649. }
  650. /**
  651. * Dials a number.
  652. * @param number the number
  653. */
  654. ChatRoom.prototype.dial = function (number) {
  655. return this.connection.rayo.dial(number, "fromnumber",
  656. Strophe.getNodeFromJid(this.myroomjid), this.password,
  657. this.focusMucJid);
  658. }
  659. /**
  660. * Hangup an existing call
  661. */
  662. ChatRoom.prototype.hangup = function () {
  663. return this.connection.rayo.hangup();
  664. }
  665. /**
  666. * Returns the phone number for joining the conference.
  667. */
  668. ChatRoom.prototype.getPhoneNumber = function () {
  669. return this.phoneNumber;
  670. }
  671. /**
  672. * Returns the pin for joining the conference with phone.
  673. */
  674. ChatRoom.prototype.getPhonePin = function () {
  675. return this.phonePin;
  676. }
  677. /**
  678. * Returns the connection state for the current session.
  679. */
  680. ChatRoom.prototype.getConnectionState = function () {
  681. if(!this.session)
  682. return null;
  683. return this.session.getIceConnectionState();
  684. }
  685. /**
  686. * Mutes remote participant.
  687. * @param jid of the participant
  688. * @param mute
  689. */
  690. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  691. logger.info("set mute", mute);
  692. var iqToFocus = $iq(
  693. {to: this.focusMucJid, type: 'set'})
  694. .c('mute', {
  695. xmlns: 'http://jitsi.org/jitmeet/audio',
  696. jid: jid
  697. })
  698. .t(mute.toString())
  699. .up();
  700. this.connection.sendIQ(
  701. iqToFocus,
  702. function (result) {
  703. logger.log('set mute', result);
  704. },
  705. function (error) {
  706. logger.log('set mute error', error);
  707. });
  708. }
  709. ChatRoom.prototype.onMute = function (iq) {
  710. var from = iq.getAttribute('from');
  711. if (from !== this.focusMucJid) {
  712. logger.warn("Ignored mute from non focus peer");
  713. return false;
  714. }
  715. var mute = $(iq).find('mute');
  716. if (mute.length) {
  717. var doMuteAudio = mute.text() === "true";
  718. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  719. }
  720. return true;
  721. }
  722. module.exports = ChatRoom;