You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 28KB

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