選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

xmpp.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /* global $, APP, config, Strophe*/
  2. var Moderator = require("./moderator");
  3. var EventEmitter = require("events");
  4. var Recording = require("./recording");
  5. var SDP = require("./SDP");
  6. var Settings = require("../settings/Settings");
  7. var Pako = require("pako");
  8. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  9. var RTCEvents = require("../../service/RTC/RTCEvents");
  10. var UIEvents = require("../../service/UI/UIEvents");
  11. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12. var eventEmitter = new EventEmitter();
  13. var connection = null;
  14. var authenticatedUser = false;
  15. function connect(jid, password) {
  16. connection = XMPP.createConnection();
  17. Moderator.setConnection(connection);
  18. if (connection.disco) {
  19. // for chrome, add multistream cap
  20. }
  21. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  22. if (config.useIPv6) {
  23. // https://code.google.com/p/webrtc/issues/detail?id=2828
  24. if (!connection.jingle.pc_constraints.optional)
  25. connection.jingle.pc_constraints.optional = [];
  26. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  27. }
  28. // Include user info in MUC presence
  29. var settings = Settings.getSettings();
  30. if (settings.email) {
  31. connection.emuc.addEmailToPresence(settings.email);
  32. }
  33. if (settings.uid) {
  34. connection.emuc.addUserIdToPresence(settings.uid);
  35. }
  36. if (settings.displayName) {
  37. connection.emuc.addDisplayNameToPresence(settings.displayName);
  38. }
  39. var anonymousConnectionFailed = false;
  40. connection.connect(jid, password, function (status, msg) {
  41. console.log('Strophe status changed to',
  42. Strophe.getStatusString(status));
  43. if (status === Strophe.Status.CONNECTED) {
  44. if (config.useStunTurn) {
  45. connection.jingle.getStunAndTurnCredentials();
  46. }
  47. console.info("My Jabber ID: " + connection.jid);
  48. if(password)
  49. authenticatedUser = true;
  50. maybeDoJoin();
  51. } else if (status === Strophe.Status.CONNFAIL) {
  52. if(msg === 'x-strophe-bad-non-anon-jid') {
  53. anonymousConnectionFailed = true;
  54. }
  55. } else if (status === Strophe.Status.DISCONNECTED) {
  56. if(anonymousConnectionFailed) {
  57. // prompt user for username and password
  58. XMPP.promptLogin();
  59. }
  60. } else if (status === Strophe.Status.AUTHFAIL) {
  61. // wrong password or username, prompt user
  62. XMPP.promptLogin();
  63. }
  64. });
  65. }
  66. function maybeDoJoin() {
  67. if (connection && connection.connected &&
  68. Strophe.getResourceFromJid(connection.jid)
  69. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  70. // .connected is true while connecting?
  71. doJoin();
  72. }
  73. }
  74. function doJoin() {
  75. var roomName = APP.UI.generateRoomName();
  76. Moderator.allocateConferenceFocus(
  77. roomName, APP.UI.checkForNicknameAndJoin);
  78. }
  79. function initStrophePlugins()
  80. {
  81. require("./strophe.emuc")(XMPP, eventEmitter);
  82. require("./strophe.jingle")(XMPP, eventEmitter);
  83. require("./strophe.moderate")(XMPP);
  84. require("./strophe.util")();
  85. require("./strophe.rayo")();
  86. require("./strophe.logger")();
  87. }
  88. function registerListeners() {
  89. APP.RTC.addStreamListener(maybeDoJoin,
  90. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  91. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  92. XMPP.addToPresence("devices", devices);
  93. })
  94. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  95. XMPP.addToPresence("displayName", nickname);
  96. });
  97. }
  98. function setupEvents() {
  99. $(window).bind('beforeunload', function () {
  100. if (connection && connection.connected) {
  101. // ensure signout
  102. $.ajax({
  103. type: 'POST',
  104. url: config.bosh,
  105. async: false,
  106. cache: false,
  107. contentType: 'application/xml',
  108. data: "<body rid='" + (connection.rid || connection._proto.rid)
  109. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  110. + (connection.sid || connection._proto.sid)
  111. + "' type='terminate'>" +
  112. "<presence xmlns='jabber:client' type='unavailable'/>" +
  113. "</body>",
  114. success: function (data) {
  115. console.log('signed out');
  116. console.log(data);
  117. },
  118. error: function (XMLHttpRequest, textStatus, errorThrown) {
  119. console.log('signout error',
  120. textStatus + ' (' + errorThrown + ')');
  121. }
  122. });
  123. }
  124. XMPP.disposeConference(true);
  125. });
  126. }
  127. var XMPP = {
  128. sessionTerminated: false,
  129. /**
  130. * XMPP connection status
  131. */
  132. Status: Strophe.Status,
  133. /**
  134. * Remembers if we were muted by the focus.
  135. * @type {boolean}
  136. */
  137. forceMuted: false,
  138. start: function () {
  139. setupEvents();
  140. initStrophePlugins();
  141. registerListeners();
  142. Moderator.init(this, eventEmitter);
  143. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  144. // Force authenticated domain if room is appended with '?login=true'
  145. if (config.hosts.anonymousdomain &&
  146. window.location.search.indexOf("login=true") !== -1) {
  147. configDomain = config.hosts.domain;
  148. }
  149. var jid = configDomain || window.location.hostname;
  150. connect(jid, null);
  151. },
  152. createConnection: function () {
  153. var bosh = config.bosh || '/http-bind';
  154. return new Strophe.Connection(bosh);
  155. },
  156. getStatusString: function (status) {
  157. return Strophe.getStatusString(status);
  158. },
  159. promptLogin: function () {
  160. // FIXME: re-use LoginDialog which supports retries
  161. APP.UI.showLoginPopup(connect);
  162. },
  163. joinRoom: function(roomName, useNicks, nick)
  164. {
  165. var roomjid;
  166. roomjid = roomName;
  167. if (useNicks) {
  168. if (nick) {
  169. roomjid += '/' + nick;
  170. } else {
  171. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  172. }
  173. } else {
  174. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  175. if(!authenticatedUser)
  176. tmpJid = tmpJid.substr(0, 8);
  177. roomjid += '/' + tmpJid;
  178. }
  179. connection.emuc.doJoin(roomjid);
  180. },
  181. myJid: function () {
  182. if(!connection)
  183. return null;
  184. return connection.emuc.myroomjid;
  185. },
  186. myResource: function () {
  187. if(!connection || ! connection.emuc.myroomjid)
  188. return null;
  189. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  190. },
  191. disposeConference: function (onUnload) {
  192. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  193. var handler = connection.jingle.activecall;
  194. if (handler && handler.peerconnection) {
  195. // FIXME: probably removing streams is not required and close() should
  196. // be enough
  197. if (APP.RTC.localAudio) {
  198. handler.peerconnection.removeStream(
  199. APP.RTC.localAudio.getOriginalStream(), onUnload);
  200. }
  201. if (APP.RTC.localVideo) {
  202. handler.peerconnection.removeStream(
  203. APP.RTC.localVideo.getOriginalStream(), onUnload);
  204. }
  205. handler.peerconnection.close();
  206. }
  207. connection.jingle.activecall = null;
  208. if(!onUnload)
  209. {
  210. this.sessionTerminated = true;
  211. connection.emuc.doLeave();
  212. }
  213. },
  214. addListener: function(type, listener)
  215. {
  216. eventEmitter.on(type, listener);
  217. },
  218. removeListener: function (type, listener) {
  219. eventEmitter.removeListener(type, listener);
  220. },
  221. allocateConferenceFocus: function(roomName, callback) {
  222. Moderator.allocateConferenceFocus(roomName, callback);
  223. },
  224. getLoginUrl: function (roomName, callback) {
  225. Moderator.getLoginUrl(roomName, callback);
  226. },
  227. getPopupLoginUrl: function (roomName, callback) {
  228. Moderator.getPopupLoginUrl(roomName, callback);
  229. },
  230. isModerator: function () {
  231. return Moderator.isModerator();
  232. },
  233. isSipGatewayEnabled: function () {
  234. return Moderator.isSipGatewayEnabled();
  235. },
  236. isExternalAuthEnabled: function () {
  237. return Moderator.isExternalAuthEnabled();
  238. },
  239. switchStreams: function (stream, oldStream, callback) {
  240. if (connection && connection.jingle.activecall) {
  241. // FIXME: will block switchInProgress on true value in case of exception
  242. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  243. } else {
  244. // We are done immediately
  245. console.warn("No conference handler or conference not started yet");
  246. callback();
  247. }
  248. },
  249. sendVideoInfoPresence: function (mute) {
  250. connection.emuc.addVideoInfoToPresence(mute);
  251. connection.emuc.sendPresence();
  252. },
  253. setVideoMute: function (mute, callback, options) {
  254. if(!connection)
  255. return;
  256. var self = this;
  257. var localCallback = function (mute) {
  258. self.sendVideoInfoPresence(mute);
  259. return callback(mute);
  260. };
  261. if(connection.jingle.activecall)
  262. {
  263. connection.jingle.activecall.setVideoMute(
  264. mute, localCallback, options);
  265. }
  266. else {
  267. localCallback(mute);
  268. }
  269. },
  270. setAudioMute: function (mute, callback) {
  271. if (!(connection && APP.RTC.localAudio)) {
  272. return false;
  273. }
  274. if (this.forceMuted && !mute) {
  275. console.info("Asking focus for unmute");
  276. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  277. // FIXME: wait for result before resetting muted status
  278. this.forceMuted = false;
  279. }
  280. if (mute == APP.RTC.localAudio.isMuted()) {
  281. // Nothing to do
  282. return true;
  283. }
  284. // It is not clear what is the right way to handle multiple tracks.
  285. // So at least make sure that they are all muted or all unmuted and
  286. // that we send presence just once.
  287. APP.RTC.localAudio.mute();
  288. // isMuted is the opposite of audioEnabled
  289. connection.emuc.addAudioInfoToPresence(mute);
  290. connection.emuc.sendPresence();
  291. callback();
  292. return true;
  293. },
  294. // Really mute video, i.e. dont even send black frames
  295. muteVideo: function (pc, unmute) {
  296. // FIXME: this probably needs another of those lovely state safeguards...
  297. // which checks for iceconn == connected and sigstate == stable
  298. pc.setRemoteDescription(pc.remoteDescription,
  299. function () {
  300. pc.createAnswer(
  301. function (answer) {
  302. var sdp = new SDP(answer.sdp);
  303. if (sdp.media.length > 1) {
  304. if (unmute)
  305. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  306. else
  307. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  308. sdp.raw = sdp.session + sdp.media.join('');
  309. answer.sdp = sdp.raw;
  310. }
  311. pc.setLocalDescription(answer,
  312. function () {
  313. console.log('mute SLD ok');
  314. },
  315. function (error) {
  316. console.log('mute SLD error');
  317. APP.UI.messageHandler.showError("dialog.error",
  318. "dialog.SLDFailure");
  319. }
  320. );
  321. },
  322. function (error) {
  323. console.log(error);
  324. APP.UI.messageHandler.showError();
  325. }
  326. );
  327. },
  328. function (error) {
  329. console.log('muteVideo SRD error');
  330. APP.UI.messageHandler.showError("dialog.error",
  331. "dialog.SRDFailure");
  332. }
  333. );
  334. },
  335. toggleRecording: function (tokenEmptyCallback,
  336. startingCallback, startedCallback) {
  337. Recording.toggleRecording(tokenEmptyCallback,
  338. startingCallback, startedCallback, connection);
  339. },
  340. addToPresence: function (name, value, dontSend) {
  341. switch (name)
  342. {
  343. case "displayName":
  344. connection.emuc.addDisplayNameToPresence(value);
  345. break;
  346. case "etherpad":
  347. connection.emuc.addEtherpadToPresence(value);
  348. break;
  349. case "prezi":
  350. connection.emuc.addPreziToPresence(value, 0);
  351. break;
  352. case "preziSlide":
  353. connection.emuc.addCurrentSlideToPresence(value);
  354. break;
  355. case "connectionQuality":
  356. connection.emuc.addConnectionInfoToPresence(value);
  357. break;
  358. case "email":
  359. connection.emuc.addEmailToPresence(value);
  360. break;
  361. case "devices":
  362. connection.emuc.addDevicesToPresence(value);
  363. break;
  364. default :
  365. console.log("Unknown tag for presence: " + name);
  366. return;
  367. }
  368. if (!dontSend)
  369. connection.emuc.sendPresence();
  370. },
  371. /**
  372. * Sends 'data' as a log message to the focus. Returns true iff a message
  373. * was sent.
  374. * @param data
  375. * @returns {boolean} true iff a message was sent.
  376. */
  377. sendLogs: function (data) {
  378. if(!connection.emuc.focusMucJid)
  379. return false;
  380. var deflate = true;
  381. var content = JSON.stringify(data);
  382. if (deflate) {
  383. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  384. }
  385. content = Base64.encode(content);
  386. // XEP-0337-ish
  387. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  388. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  389. id: 'PeerConnectionStats'});
  390. message.c('message').t(content).up();
  391. if (deflate) {
  392. message.c('tag', {name: "deflated", value: "true"}).up();
  393. }
  394. message.up();
  395. connection.send(message);
  396. return true;
  397. },
  398. populateData: function () {
  399. var data = {};
  400. if (connection.jingle) {
  401. data = connection.jingle.populateData();
  402. }
  403. return data;
  404. },
  405. getLogger: function () {
  406. if(connection.logger)
  407. return connection.logger.log;
  408. return null;
  409. },
  410. getPrezi: function () {
  411. return connection.emuc.getPrezi(this.myJid());
  412. },
  413. removePreziFromPresence: function () {
  414. connection.emuc.removePreziFromPresence();
  415. connection.emuc.sendPresence();
  416. },
  417. sendChatMessage: function (message, nickname) {
  418. connection.emuc.sendMessage(message, nickname);
  419. },
  420. setSubject: function (topic) {
  421. connection.emuc.setSubject(topic);
  422. },
  423. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  424. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  425. },
  426. dial: function (to, from, roomName,roomPass) {
  427. connection.rayo.dial(to, from, roomName,roomPass);
  428. },
  429. setMute: function (jid, mute) {
  430. connection.moderate.setMute(jid, mute);
  431. },
  432. eject: function (jid) {
  433. connection.moderate.eject(jid);
  434. },
  435. logout: function (callback) {
  436. Moderator.logout(callback);
  437. },
  438. findJidFromResource: function (resource) {
  439. return connection.emuc.findJidFromResource(resource);
  440. },
  441. getMembers: function () {
  442. return connection.emuc.members;
  443. },
  444. getJidFromSSRC: function (ssrc) {
  445. if(!connection)
  446. return null;
  447. return connection.emuc.ssrc2jid[ssrc];
  448. },
  449. getMUCJoined: function () {
  450. return connection.emuc.joined;
  451. },
  452. getSessions: function () {
  453. return connection.jingle.sessions;
  454. },
  455. removeStream: function (stream) {
  456. if(!connection || !connection.jingle.activecall ||
  457. !connection.jingle.activecall.peerconnection)
  458. return;
  459. connection.jingle.activecall.peerconnection.removeStream(stream);
  460. }
  461. };
  462. module.exports = XMPP;