您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ChatRoom.js 26KB

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