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

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