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

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