Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ChatRoom.js 32KB

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