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

ChatRoom.js 27KB

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