Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ChatRoom.js 30KB

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