您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

xmpp.js 16KB

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