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

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