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

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