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

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