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

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