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 29KB

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