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

ChatRoom.js 32KB

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