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

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