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.

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