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.

muc.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /* jshint -W117 */
  2. /* a simple MUC connection plugin
  3. * can only handle a single MUC room
  4. */
  5. Strophe.addConnectionPlugin('emuc', {
  6. connection: null,
  7. roomjid: null,
  8. myroomjid: null,
  9. members: {},
  10. list_members: [], // so we can elect a new focus
  11. presMap: {},
  12. preziMap: {},
  13. joined: false,
  14. isOwner: false,
  15. role: null,
  16. init: function (conn) {
  17. this.connection = conn;
  18. },
  19. initPresenceMap: function (myroomjid) {
  20. this.presMap['to'] = myroomjid;
  21. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  22. },
  23. doJoin: function (jid, password) {
  24. this.myroomjid = jid;
  25. console.info("Joined MUC as " + this.myroomjid);
  26. this.initPresenceMap(this.myroomjid);
  27. if (!this.roomjid) {
  28. this.roomjid = Strophe.getBareJidFromJid(jid);
  29. // add handlers (just once)
  30. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  31. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  32. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  33. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  34. }
  35. if (password !== undefined) {
  36. this.presMap['password'] = password;
  37. }
  38. this.sendPresence();
  39. },
  40. doLeave: function() {
  41. console.log("do leave", this.myroomjid);
  42. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  43. this.presMap.length = 0;
  44. this.connection.send(pres);
  45. },
  46. onPresence: function (pres) {
  47. var from = pres.getAttribute('from');
  48. var type = pres.getAttribute('type');
  49. if (type != null) {
  50. return true;
  51. }
  52. // Parse etherpad tag.
  53. var etherpad = $(pres).find('>etherpad');
  54. if (etherpad.length) {
  55. $(document).trigger('etherpadadded.muc', [from, etherpad.text()]);
  56. }
  57. // Parse prezi tag.
  58. var presentation = $(pres).find('>prezi');
  59. if (presentation.length)
  60. {
  61. var url = presentation.attr('url');
  62. var current = presentation.find('>current').text();
  63. console.log('presentation info received from', from, url);
  64. if (this.preziMap[from] == null) {
  65. this.preziMap[from] = url;
  66. $(document).trigger('presentationadded.muc', [from, url, current]);
  67. }
  68. else {
  69. $(document).trigger('gotoslide.muc', [from, url, current]);
  70. }
  71. }
  72. else if (this.preziMap[from] != null) {
  73. var url = this.preziMap[from];
  74. delete this.preziMap[from];
  75. $(document).trigger('presentationremoved.muc', [from, url]);
  76. }
  77. // Parse audio info tag.
  78. var audioMuted = $(pres).find('>audiomuted');
  79. if (audioMuted.length) {
  80. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  81. }
  82. // Parse video info tag.
  83. var videoMuted = $(pres).find('>videomuted');
  84. if (videoMuted.length) {
  85. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  86. }
  87. var stats = $(pres).find('>stats');
  88. if(stats.length)
  89. {
  90. var statsObj = {};
  91. Strophe.forEachChild(stats[0], "stat", function (el) {
  92. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  93. });
  94. ConnectionQuality.updateRemoteStats(from, statsObj);
  95. }
  96. // Parse status.
  97. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  98. // http://xmpp.org/extensions/xep-0045.html#createroom-instant
  99. this.isOwner = true;
  100. var create = $iq({type: 'set', to: this.roomjid})
  101. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  102. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  103. this.connection.send(create); // fire away
  104. }
  105. // Parse roles.
  106. var member = {};
  107. member.show = $(pres).find('>show').text();
  108. member.status = $(pres).find('>status').text();
  109. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  110. member.affiliation = tmp.attr('affiliation');
  111. member.role = tmp.attr('role');
  112. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  113. member.displayName = (nicktag.length > 0 ? nicktag.text() : null);
  114. if (from == this.myroomjid) {
  115. if (member.affiliation == 'owner') this.isOwner = true;
  116. if (this.role !== member.role) {
  117. this.role = member.role;
  118. $(document).trigger('local.role.changed.muc', [from, member, pres]);
  119. }
  120. if (!this.joined) {
  121. this.joined = true;
  122. $(document).trigger('joined.muc', [from, member]);
  123. this.list_members.push(from);
  124. }
  125. } else if (this.members[from] === undefined) {
  126. // new participant
  127. this.members[from] = member;
  128. this.list_members.push(from);
  129. $(document).trigger('entered.muc', [from, member, pres]);
  130. } else {
  131. // Presence update for existing participant
  132. // Watch role change:
  133. if (this.members[from].role != member.role) {
  134. this.members[from].role = member.role
  135. $(document).trigger('role.changed.muc', [from, member, pres]);
  136. }
  137. }
  138. // Always trigger presence to update bindings
  139. console.log('presence change from', from, pres);
  140. $(document).trigger('presence.muc', [from, member, pres]);
  141. // Trigger status message update
  142. if (member.status) {
  143. $(document).trigger('presence.status.muc', [from, member, pres]);
  144. }
  145. return true;
  146. },
  147. onPresenceUnavailable: function (pres) {
  148. var from = pres.getAttribute('from');
  149. // Status code 110 indicates that this notification is "self-presence".
  150. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  151. delete this.members[from];
  152. this.list_members.splice(this.list_members.indexOf(from), 1);
  153. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  154. $(document).trigger('kicked.muc', [from]);
  155. } else {
  156. $(document).trigger('left.muc', [from]);
  157. }
  158. }
  159. // If the status code is 110 this means we're leaving and we would like
  160. // to remove everyone else from our view, so we trigger the event.
  161. else if (this.list_members.length > 1) {
  162. for (var i = 0; i < this.list_members.length; i++) {
  163. var member = this.list_members[i];
  164. delete this.members[i];
  165. this.list_members.splice(i, 1);
  166. $(document).trigger('left.muc', member);
  167. }
  168. }
  169. return true;
  170. },
  171. onPresenceError: function (pres) {
  172. var from = pres.getAttribute('from');
  173. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  174. $(document).trigger('passwordrequired.muc', [from]);
  175. } else if ($(pres).find(
  176. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  177. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  178. if(toDomain === config.hosts.anonymousdomain) {
  179. // we are connected with anonymous domain and only non anonymous users can create rooms
  180. // we must authorize the user
  181. $(document).trigger('passwordrequired.main');
  182. } else {
  183. console.warn('onPresError ', pres);
  184. messageHandler.openReportDialog(null,
  185. 'Oops! Something went wrong and we couldn`t connect to the conference.',
  186. pres);
  187. }
  188. } else {
  189. console.warn('onPresError ', pres);
  190. messageHandler.openReportDialog(null,
  191. 'Oops! Something went wrong and we couldn`t connect to the conference.',
  192. pres);
  193. }
  194. return true;
  195. },
  196. sendMessage: function (body, nickname) {
  197. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  198. msg.c('body', body).up();
  199. if (nickname) {
  200. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  201. }
  202. this.connection.send(msg);
  203. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("outgoingMessage"))
  204. {
  205. APIConnector.triggerEvent("outgoingMessage", {"message": body});
  206. }
  207. },
  208. setSubject: function (subject){
  209. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  210. msg.c('subject', subject);
  211. this.connection.send(msg);
  212. console.log("topic changed to " + subject);
  213. },
  214. onMessage: function (msg) {
  215. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  216. var from = msg.getAttribute('from');
  217. var nick = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]').text() || Strophe.getResourceFromJid(from);
  218. var txt = $(msg).find('>body').text();
  219. var type = msg.getAttribute("type");
  220. if(type == "error")
  221. {
  222. Chat.chatAddError($(msg).find('>text').text(), txt);
  223. return true;
  224. }
  225. var subject = $(msg).find('>subject');
  226. if(subject.length)
  227. {
  228. var subjectText = subject.text();
  229. if(subjectText || subjectText == "") {
  230. Chat.chatSetSubject(subjectText);
  231. console.log("Subject is changed to " + subjectText);
  232. }
  233. }
  234. if (txt) {
  235. console.log('chat', nick, txt);
  236. Chat.updateChatConversation(from, nick, txt);
  237. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("incomingMessage"))
  238. {
  239. if(from != this.myroomjid)
  240. APIConnector.triggerEvent("incomingMessage",
  241. {"from": from, "nick": nick, "message": txt});
  242. }
  243. }
  244. return true;
  245. },
  246. lockRoom: function (key) {
  247. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  248. var ob = this;
  249. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  250. function (res) {
  251. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  252. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  253. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  254. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  255. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  256. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  257. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  258. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  259. this.connection.sendIQ(formsubmit,
  260. function (res) {
  261. // password is required
  262. if (sharedKey)
  263. {
  264. console.log('set room password');
  265. Toolbar.lockLockButton();
  266. }
  267. else
  268. {
  269. console.log('removed room password');
  270. Toolbar.unlockLockButton();
  271. }
  272. },
  273. function (err) {
  274. console.warn('setting password failed', err);
  275. messageHandler.showError('Lock failed',
  276. 'Failed to lock conference.',
  277. err);
  278. setSharedKey('');
  279. }
  280. );
  281. } else {
  282. console.warn('room passwords not supported');
  283. messageHandler.showError('Warning',
  284. 'Room passwords are currently not supported.');
  285. setSharedKey('');
  286. }
  287. },
  288. function (err) {
  289. console.warn('setting password failed', err);
  290. messageHandler.showError('Lock failed',
  291. 'Failed to lock conference.',
  292. err);
  293. setSharedKey('');
  294. }
  295. );
  296. },
  297. kick: function (jid) {
  298. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  299. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  300. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  301. .c('reason').t('You have been kicked.').up().up().up();
  302. this.connection.sendIQ(
  303. kickIQ,
  304. function (result) {
  305. console.log('Kick participant with jid: ', jid, result);
  306. },
  307. function (error) {
  308. console.log('Kick participant error: ', error);
  309. });
  310. },
  311. sendPresence: function () {
  312. var pres = $pres({to: this.presMap['to'] });
  313. pres.c('x', {xmlns: this.presMap['xns']});
  314. if (this.presMap['password']) {
  315. pres.c('password').t(this.presMap['password']).up();
  316. }
  317. pres.up();
  318. // Send XEP-0115 'c' stanza that contains our capabilities info
  319. if (connection.caps) {
  320. connection.caps.node = config.clientNode;
  321. pres.c('c', connection.caps.generateCapsAttrs()).up();
  322. }
  323. if(this.presMap['bridgeIsDown']) {
  324. pres.c('bridgeIsDown').up();
  325. }
  326. if (this.presMap['displayName']) {
  327. // XEP-0172
  328. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  329. .t(this.presMap['displayName']).up();
  330. }
  331. if (this.presMap['audions']) {
  332. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  333. .t(this.presMap['audiomuted']).up();
  334. }
  335. if (this.presMap['videons']) {
  336. pres.c('videomuted', {xmlns: this.presMap['videons']})
  337. .t(this.presMap['videomuted']).up();
  338. }
  339. if(this.presMap['statsns'])
  340. {
  341. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  342. for(var stat in this.presMap["stats"])
  343. if(this.presMap["stats"][stat] != null)
  344. stats.c("stat",{name: stat, value: this.presMap["stats"][stat]}).up();
  345. pres.up();
  346. }
  347. if (this.presMap['prezins']) {
  348. pres.c('prezi',
  349. {xmlns: this.presMap['prezins'],
  350. 'url': this.presMap['preziurl']})
  351. .c('current').t(this.presMap['prezicurrent']).up().up();
  352. }
  353. if (this.presMap['etherpadns']) {
  354. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  355. .t(this.presMap['etherpadname']).up();
  356. }
  357. if (this.presMap['medians'])
  358. {
  359. pres.c('media', {xmlns: this.presMap['medians']});
  360. var sourceNumber = 0;
  361. Object.keys(this.presMap).forEach(function (key) {
  362. if (key.indexOf('source') >= 0) {
  363. sourceNumber++;
  364. }
  365. });
  366. if (sourceNumber > 0)
  367. for (var i = 1; i <= sourceNumber/3; i ++) {
  368. pres.c('source',
  369. {type: this.presMap['source' + i + '_type'],
  370. ssrc: this.presMap['source' + i + '_ssrc'],
  371. direction: this.presMap['source'+ i + '_direction']
  372. || 'sendrecv' }
  373. ).up();
  374. }
  375. }
  376. pres.up();
  377. connection.send(pres);
  378. },
  379. addDisplayNameToPresence: function (displayName) {
  380. this.presMap['displayName'] = displayName;
  381. },
  382. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  383. if (!this.presMap['medians'])
  384. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  385. this.presMap['source' + sourceNumber + '_type'] = mtype;
  386. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  387. this.presMap['source' + sourceNumber + '_direction'] = direction;
  388. },
  389. clearPresenceMedia: function () {
  390. var self = this;
  391. Object.keys(this.presMap).forEach( function(key) {
  392. if(key.indexOf('source') != -1) {
  393. delete self.presMap[key];
  394. }
  395. });
  396. },
  397. addPreziToPresence: function (url, currentSlide) {
  398. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  399. this.presMap['preziurl'] = url;
  400. this.presMap['prezicurrent'] = currentSlide;
  401. },
  402. removePreziFromPresence: function () {
  403. delete this.presMap['prezins'];
  404. delete this.presMap['preziurl'];
  405. delete this.presMap['prezicurrent'];
  406. },
  407. addCurrentSlideToPresence: function (currentSlide) {
  408. this.presMap['prezicurrent'] = currentSlide;
  409. },
  410. getPrezi: function (roomjid) {
  411. return this.preziMap[roomjid];
  412. },
  413. addEtherpadToPresence: function(etherpadName) {
  414. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  415. this.presMap['etherpadname'] = etherpadName;
  416. },
  417. addAudioInfoToPresence: function(isMuted) {
  418. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  419. this.presMap['audiomuted'] = isMuted.toString();
  420. },
  421. addVideoInfoToPresence: function(isMuted) {
  422. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  423. this.presMap['videomuted'] = isMuted.toString();
  424. },
  425. addConnectionInfoToPresence: function(stats) {
  426. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  427. this.presMap['stats'] = stats;
  428. },
  429. findJidFromResource: function(resourceJid) {
  430. var peerJid = null;
  431. Object.keys(this.members).some(function (jid) {
  432. peerJid = jid;
  433. return Strophe.getResourceFromJid(jid) === resourceJid;
  434. });
  435. return peerJid;
  436. },
  437. addBridgeIsDownToPresence: function() {
  438. this.presMap['bridgeIsDown'] = true;
  439. },
  440. isModerator: function() {
  441. return this.role === 'moderator';
  442. }
  443. });