Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ChatRoom.js 26KB

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