modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3. var Moderator = require("./moderator");
  4. var EventEmitter = require("events");
  5. var parser = {
  6. packet2JSON: function (packet, nodes) {
  7. var self = this;
  8. $(packet).children().each(function (index) {
  9. var tagName = $(this).prop("tagName");
  10. var node = {}
  11. node["tagName"] = tagName;
  12. node.attributes = {};
  13. $($(this)[0].attributes).each(function( index, attr ) {
  14. node.attributes[ attr.name ] = attr.value;
  15. } );
  16. var text = Strophe.getText($(this)[0]);
  17. if(text)
  18. node.value = text;
  19. node.children = [];
  20. nodes.push(node);
  21. self.packet2JSON($(this), node.children);
  22. })
  23. },
  24. JSON2packet: function (nodes, packet) {
  25. for(var i = 0; i < nodes.length; i++)
  26. {
  27. var node = nodes[i];
  28. if(!node || node === null){
  29. continue;
  30. }
  31. packet.c(node.tagName, node.attributes);
  32. if(node.value)
  33. packet.t(node.value);
  34. if(node.children)
  35. this.JSON2packet(node.children, packet);
  36. packet.up();
  37. }
  38. packet.up();
  39. }
  40. };
  41. /**
  42. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  43. * @param pres the presence JSON
  44. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  45. */
  46. function filterNodeFromPresenceJSON(pres, nodeName){
  47. var res = [];
  48. for(var i = 0; i < pres.length; i++)
  49. if(pres[i].tagName === nodeName)
  50. res.push(pres[i]);
  51. return res;
  52. }
  53. function ChatRoom(connection, jid, password, XMPP, options) {
  54. this.eventEmitter = new EventEmitter();
  55. this.xmpp = XMPP;
  56. this.connection = connection;
  57. this.roomjid = Strophe.getBareJidFromJid(jid);
  58. this.myroomjid = jid;
  59. this.password = password;
  60. logger.info("Joined MUC as " + this.myroomjid);
  61. this.members = {};
  62. this.presMap = {};
  63. this.presHandlers = {};
  64. this.joined = false;
  65. this.role = null;
  66. this.focusMucJid = null;
  67. this.bridgeIsDown = false;
  68. this.options = options || {};
  69. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  70. this.initPresenceMap();
  71. this.session = null;
  72. var self = this;
  73. this.lastPresences = {};
  74. }
  75. ChatRoom.prototype.initPresenceMap = function () {
  76. this.presMap['to'] = this.myroomjid;
  77. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  78. this.presMap["nodes"] = [];
  79. this.presMap["nodes"].push( {
  80. "tagName": "user-agent",
  81. "value": navigator.userAgent,
  82. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  83. });
  84. };
  85. ChatRoom.prototype.join = function (password, tokenPassword) {
  86. if(password)
  87. this.password = password;
  88. var self = this;
  89. this.moderator.allocateConferenceFocus(function()
  90. {
  91. self.sendPresence(tokenPassword);
  92. }.bind(this));
  93. };
  94. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  95. if (!this.presMap['to']) {
  96. // Too early to send presence - not initialized
  97. return;
  98. }
  99. var pres = $pres({to: this.presMap['to'] });
  100. pres.c('x', {xmlns: this.presMap['xns']});
  101. if (this.password) {
  102. pres.c('password').t(this.password).up();
  103. }
  104. pres.up();
  105. // Send XEP-0115 'c' stanza that contains our capabilities info
  106. if (this.connection.caps) {
  107. this.connection.caps.node = this.xmpp.options.clientNode;
  108. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  109. }
  110. if (tokenPassword) {
  111. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  112. .t(tokenPassword).up();
  113. }
  114. parser.JSON2packet(this.presMap.nodes, pres);
  115. this.connection.send(pres);
  116. };
  117. ChatRoom.prototype.doLeave = function () {
  118. logger.log("do leave", this.myroomjid);
  119. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  120. this.presMap.length = 0;
  121. this.connection.send(pres);
  122. };
  123. ChatRoom.prototype.createNonAnonymousRoom = function () {
  124. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  125. var getForm = $iq({type: 'get', to: this.roomjid})
  126. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  127. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  128. var self = this;
  129. this.connection.sendIQ(getForm, function (form) {
  130. if (!$(form).find(
  131. '>query>x[xmlns="jabber:x:data"]' +
  132. '>field[var="muc#roomconfig_whois"]').length) {
  133. logger.error('non-anonymous rooms not supported');
  134. return;
  135. }
  136. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  137. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  138. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  139. formSubmit.c('field', {'var': 'FORM_TYPE'})
  140. .c('value')
  141. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  142. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  143. .c('value').t('anyone').up().up();
  144. self.connection.sendIQ(formSubmit);
  145. }, function (error) {
  146. logger.error("Error getting room configuration form");
  147. });
  148. };
  149. ChatRoom.prototype.onPresence = function (pres) {
  150. var from = pres.getAttribute('from');
  151. // Parse roles.
  152. var member = {};
  153. member.show = $(pres).find('>show').text();
  154. member.status = $(pres).find('>status').text();
  155. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  156. member.affiliation = tmp.attr('affiliation');
  157. member.role = tmp.attr('role');
  158. // Focus recognition
  159. member.jid = tmp.attr('jid');
  160. member.isFocus = false;
  161. if (member.jid
  162. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  163. member.isFocus = true;
  164. }
  165. $(pres).find(">x").remove();
  166. var nodes = [];
  167. parser.packet2JSON(pres, nodes);
  168. this.lastPresences[from] = nodes;
  169. for(var i = 0; i < nodes.length; i++)
  170. {
  171. var node = nodes[i];
  172. switch(node.tagName)
  173. {
  174. case "nick":
  175. member.nick = node.value;
  176. if(!member.isFocus) {
  177. var displayName = !this.xmpp.options.displayJids
  178. ? member.nick : Strophe.getResourceFromJid(from);
  179. if (displayName && displayName.length > 0) {
  180. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  181. }
  182. logger.info("Display name: " + displayName, pres);
  183. }
  184. break;
  185. case "userId":
  186. member.id = node.value;
  187. break;
  188. case "email":
  189. member.email = node.value;
  190. break;
  191. case "bridgeIsDown":
  192. if(!this.bridgeIsDown) {
  193. this.bridgeIsDown = true;
  194. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  195. }
  196. break;
  197. default :
  198. this.processNode(node, from);
  199. }
  200. }
  201. if (from == this.myroomjid) {
  202. if (member.affiliation == 'owner')
  203. if (this.role !== member.role) {
  204. this.role = member.role;
  205. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  206. member, this.isModerator());
  207. }
  208. if (!this.joined) {
  209. this.joined = true;
  210. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  211. }
  212. } else if (this.members[from] === undefined) {
  213. // new participant
  214. this.members[from] = member;
  215. logger.log('entered', from, member);
  216. if (member.isFocus) {
  217. this.focusMucJid = from;
  218. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  219. }
  220. else {
  221. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  222. }
  223. } else {
  224. // Presence update for existing participant
  225. // Watch role change:
  226. if (this.members[from].role != member.role) {
  227. this.members[from].role = member.role;
  228. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  229. member.role, member.nick);
  230. }
  231. }
  232. if(!member.isFocus)
  233. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  234. // Trigger status message update
  235. if (member.status) {
  236. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  237. }
  238. };
  239. ChatRoom.prototype.processNode = function (node, from) {
  240. if(this.presHandlers[node.tagName])
  241. this.presHandlers[node.tagName](node, from);
  242. };
  243. ChatRoom.prototype.sendMessage = function (body, nickname) {
  244. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  245. msg.c('body', body).up();
  246. if (nickname) {
  247. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  248. }
  249. this.connection.send(msg);
  250. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  251. };
  252. ChatRoom.prototype.setSubject = function (subject) {
  253. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  254. msg.c('subject', subject);
  255. this.connection.send(msg);
  256. logger.log("topic changed to " + subject);
  257. };
  258. ChatRoom.prototype.onParticipantLeft = function (jid) {
  259. delete this.lastPresences[jid];
  260. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  261. this.moderator.onMucMemberLeft(jid);
  262. };
  263. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  264. // room destroyed ?
  265. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  266. '>destroy').length) {
  267. var reason;
  268. var reasonSelect = $(pres).find(
  269. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  270. '>destroy>reason');
  271. if (reasonSelect.length) {
  272. reason = reasonSelect.text();
  273. }
  274. this.xmpp.disposeConference(false);
  275. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  276. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  277. return true;
  278. }
  279. // Status code 110 indicates that this notification is "self-presence".
  280. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  281. delete this.members[from];
  282. this.onParticipantLeft(from);
  283. }
  284. // If the status code is 110 this means we're leaving and we would like
  285. // to remove everyone else from our view, so we trigger the event.
  286. else if (Object.keys(this.members).length > 1) {
  287. for (var i in this.members) {
  288. var member = this.members[i];
  289. delete this.members[i];
  290. this.onParticipantLeft(member);
  291. }
  292. }
  293. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  294. if (this.myroomjid === from) {
  295. this.xmpp.disposeConference(false);
  296. this.eventEmitter.emit(XMPPEvents.KICKED);
  297. }
  298. }
  299. };
  300. ChatRoom.prototype.onMessage = function (msg, from) {
  301. var nick =
  302. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  303. .text() ||
  304. Strophe.getResourceFromJid(from);
  305. var txt = $(msg).find('>body').text();
  306. var type = msg.getAttribute("type");
  307. if (type == "error") {
  308. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  309. $(msg).find('>text').text(), txt);
  310. return true;
  311. }
  312. var subject = $(msg).find('>subject');
  313. if (subject.length) {
  314. var subjectText = subject.text();
  315. if (subjectText || subjectText == "") {
  316. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  317. logger.log("Subject is changed to " + subjectText);
  318. }
  319. }
  320. // xep-0203 delay
  321. var stamp = $(msg).find('>delay').attr('stamp');
  322. if (!stamp) {
  323. // or xep-0091 delay, UTC timestamp
  324. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  325. if (stamp) {
  326. // the format is CCYYMMDDThh:mm:ss
  327. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  328. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  329. }
  330. }
  331. if (txt) {
  332. logger.log('chat', nick, txt);
  333. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  334. from, nick, txt, this.myroomjid, stamp);
  335. }
  336. }
  337. ChatRoom.prototype.onPresenceError = function (pres, from) {
  338. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  339. logger.log('on password required', from);
  340. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  341. } else if ($(pres).find(
  342. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  343. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  344. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  345. // enter the room by replying with 'not-authorized'. This would
  346. // result in reconnection from authorized domain.
  347. // We're either missing Jicofo/Prosody config for anonymous
  348. // domains or something is wrong.
  349. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  350. } else {
  351. logger.warn('onPresError ', pres);
  352. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  353. }
  354. } else {
  355. logger.warn('onPresError ', pres);
  356. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  357. }
  358. };
  359. ChatRoom.prototype.kick = function (jid) {
  360. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  361. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  362. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  363. .c('reason').t('You have been kicked.').up().up().up();
  364. this.connection.sendIQ(
  365. kickIQ,
  366. function (result) {
  367. logger.log('Kick participant with jid: ', jid, result);
  368. },
  369. function (error) {
  370. logger.log('Kick participant error: ', error);
  371. });
  372. };
  373. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  374. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  375. var ob = this;
  376. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  377. function (res) {
  378. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  379. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  380. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  381. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  382. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  383. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  384. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  385. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  386. ob.connection.sendIQ(formsubmit,
  387. onSuccess,
  388. onError);
  389. } else {
  390. onNotSupported();
  391. }
  392. }, onError);
  393. };
  394. ChatRoom.prototype.addToPresence = function (key, values) {
  395. values.tagName = key;
  396. this.presMap["nodes"].push(values);
  397. };
  398. ChatRoom.prototype.removeFromPresence = function (key) {
  399. for(var i = 0; i < this.presMap.nodes.length; i++)
  400. {
  401. if(key === this.presMap.nodes[i].tagName)
  402. this.presMap.nodes.splice(i, 1);
  403. }
  404. };
  405. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  406. this.presHandlers[name] = handler;
  407. }
  408. ChatRoom.prototype.removePresenceListener = function (name) {
  409. delete this.presHandlers[name];
  410. }
  411. ChatRoom.prototype.isModerator = function (jid) {
  412. return this.role === 'moderator';
  413. };
  414. ChatRoom.prototype.getMemberRole = function (peerJid) {
  415. if (this.members[peerJid]) {
  416. return this.members[peerJid].role;
  417. }
  418. return null;
  419. };
  420. ChatRoom.prototype.setJingleSession = function(session){
  421. this.session = session;
  422. this.session.room = this;
  423. };
  424. ChatRoom.prototype.removeStream = function (stream) {
  425. if(!this.session)
  426. return;
  427. this.session.peerconnection.removeStream(stream)
  428. }
  429. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  430. if(this.session) {
  431. // FIXME: will block switchInProgress on true value in case of exception
  432. this.session.switchStreams(stream, oldStream, callback, isAudio);
  433. } else {
  434. // We are done immediately
  435. logger.warn("No conference handler or conference not started yet");
  436. callback();
  437. }
  438. };
  439. ChatRoom.prototype.addStream = function (stream, callback) {
  440. if(this.session) {
  441. // FIXME: will block switchInProgress on true value in case of exception
  442. this.session.addStream(stream, callback);
  443. } else {
  444. // We are done immediately
  445. logger.warn("No conference handler or conference not started yet");
  446. callback();
  447. }
  448. }
  449. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  450. var self = this;
  451. var localCallback = function (mute) {
  452. self.sendVideoInfoPresence(mute);
  453. if(callback)
  454. callback(mute)
  455. };
  456. if(this.session)
  457. {
  458. this.session.setVideoMute(
  459. mute, localCallback, options);
  460. }
  461. else {
  462. localCallback(mute);
  463. }
  464. };
  465. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  466. //This will be for remote streams only
  467. // if (this.forceMuted && !mute) {
  468. // logger.info("Asking focus for unmute");
  469. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  470. // // FIXME: wait for result before resetting muted status
  471. // this.forceMuted = false;
  472. // }
  473. return this.sendAudioInfoPresence(mute, callback);
  474. };
  475. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  476. this.removeFromPresence("audiomuted");
  477. this.addToPresence("audiomuted",
  478. {attributes:
  479. {"audions": "http://jitsi.org/jitmeet/audio"},
  480. value: mute.toString()});
  481. }
  482. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  483. this.addAudioInfoToPresence(mute);
  484. if(this.connection) {
  485. this.sendPresence();
  486. }
  487. if(callback)
  488. callback();
  489. };
  490. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  491. this.removeFromPresence("videomuted");
  492. this.addToPresence("videomuted",
  493. {attributes:
  494. {"videons": "http://jitsi.org/jitmeet/video"},
  495. value: mute.toString()});
  496. }
  497. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  498. this.addVideoInfoToPresence(mute);
  499. if(!this.connection)
  500. return;
  501. this.sendPresence();
  502. };
  503. ChatRoom.prototype.addListener = function(type, listener) {
  504. this.eventEmitter.on(type, listener);
  505. };
  506. ChatRoom.prototype.removeListener = function (type, listener) {
  507. this.eventEmitter.removeListener(type, listener);
  508. };
  509. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  510. if(this.lastPresences[data.peerjid])
  511. {
  512. var pres = this.lastPresences[data.peerjid];
  513. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  514. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  515. data.videomuted = ((videomuted.length > 0
  516. && videomuted[0]
  517. && videomuted[0]["value"] === "true")? true : false);
  518. data.audiomuted = ((audiomuted.length > 0
  519. && audiomuted[0]
  520. && audiomuted[0]["value"] === "true")? true : false);
  521. }
  522. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  523. }
  524. ChatRoom.prototype.addLocalStreams = function (localStreams) {
  525. this.session.addLocalStreams(localStreams);
  526. }
  527. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  528. if (!this.session)
  529. return null;
  530. return this.session.getSsrcOwner(ssrc);
  531. };
  532. module.exports = ChatRoom;