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

xmpp.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. /* global $, APP, config, Strophe*/
  2. var Moderator = require("./moderator");
  3. var EventEmitter = require("events");
  4. var Pako = require("pako");
  5. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  6. var RTCEvents = require("../../service/RTC/RTCEvents");
  7. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  9. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10. var RTC = require("../RTC/RTC");
  11. var authenticatedUser = false;
  12. var disconnectInProgress = false;
  13. function createConnection(bosh) {
  14. bosh = bosh || '/http-bind';
  15. return new Strophe.Connection(bosh);
  16. };
  17. //!!!!!!!!!! FIXME: ...
  18. function initStrophePlugins()
  19. {
  20. // require("./strophe.emuc")(XMPP, eventEmitter);
  21. // require("./strophe.jingle")(XMPP, eventEmitter);
  22. // require("./strophe.moderate")(XMPP, eventEmitter);
  23. require("./strophe.util")();
  24. require("./strophe.rayo")();
  25. require("./strophe.logger")();
  26. }
  27. //!!!!!!!!!! FIXME: ...
  28. ///**
  29. // * If given <tt>localStream</tt> is video one this method will advertise it's
  30. // * video type in MUC presence.
  31. // * @param localStream new or modified <tt>LocalStream</tt>.
  32. // */
  33. //function broadcastLocalVideoType(localStream) {
  34. // if (localStream.videoType)
  35. // XMPP.addToPresence('videoType', localStream.videoType);
  36. //}
  37. //
  38. //function registerListeners() {
  39. // RTC.addStreamListener(
  40. // broadcastLocalVideoType,
  41. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  42. // );
  43. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  44. // XMPP.addToPresence("devices", devices);
  45. // });
  46. //}
  47. function XMPP(options) {
  48. this.sessionTerminated = false;
  49. this.eventEmitter = new EventEmitter();
  50. this.connection = null;
  51. this.forceMuted = false;
  52. this.options = options;
  53. initStrophePlugins();
  54. // registerListeners();
  55. Moderator.init(this, this.eventEmitter);
  56. this.connection = createConnection(options.bosh);
  57. Moderator.setConnection(this.connection);
  58. }
  59. XMPP.prototype.getConnection = function(){ return connection; };
  60. XMPP.prototype._connect = function (jid, password) {
  61. var self = this;
  62. // connection.connect() starts the connection process.
  63. //
  64. // As the connection process proceeds, the user supplied callback will
  65. // be triggered multiple times with status updates. The callback should
  66. // take two arguments - the status code and the error condition.
  67. //
  68. // The status code will be one of the values in the Strophe.Status
  69. // constants. The error condition will be one of the conditions defined
  70. // in RFC 3920 or the condition ‘strophe-parsererror’.
  71. //
  72. // The Parameters wait, hold and route are optional and only relevant
  73. // for BOSH connections. Please see XEP 124 for a more detailed
  74. // explanation of the optional parameters.
  75. //
  76. // Connection status constants for use by the connection handler
  77. // callback.
  78. //
  79. // Status.ERROR - An error has occurred (websockets specific)
  80. // Status.CONNECTING - The connection is currently being made
  81. // Status.CONNFAIL - The connection attempt failed
  82. // Status.AUTHENTICATING - The connection is authenticating
  83. // Status.AUTHFAIL - The authentication attempt failed
  84. // Status.CONNECTED - The connection has succeeded
  85. // Status.DISCONNECTED - The connection has been terminated
  86. // Status.DISCONNECTING - The connection is currently being terminated
  87. // Status.ATTACHED - The connection has been attached
  88. var anonymousConnectionFailed = false;
  89. var connectionFailed = false;
  90. var lastErrorMsg;
  91. this.connection.connect(jid, password, function (status, msg) {
  92. console.log('Strophe status changed to',
  93. Strophe.getStatusString(status), msg);
  94. if (status === Strophe.Status.CONNECTED) {
  95. if (self.options.useStunTurn) {
  96. self.connection.jingle.getStunAndTurnCredentials();
  97. }
  98. console.info("My Jabber ID: " + self.connection.jid);
  99. if (password)
  100. authenticatedUser = true;
  101. if (self.connection && self.connection.connected &&
  102. Strophe.getResourceFromJid(self.connection.jid)) {
  103. // .connected is true while connecting?
  104. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  105. Strophe.getResourceFromJid(self.connection.jid));
  106. }
  107. } else if (status === Strophe.Status.CONNFAIL) {
  108. if (msg === 'x-strophe-bad-non-anon-jid') {
  109. anonymousConnectionFailed = true;
  110. }
  111. else
  112. {
  113. connectionFailed = true;
  114. }
  115. lastErrorMsg = msg;
  116. } else if (status === Strophe.Status.DISCONNECTED) {
  117. if (anonymousConnectionFailed) {
  118. // prompt user for username and password
  119. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  120. JitsiConnectionErrors.PASSWORD_REQUIRED);
  121. } else if(connectionFailed) {
  122. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  123. JitsiConnectionErrors.OTHER_ERROR,
  124. msg ? msg : lastErrorMsg);
  125. } else {
  126. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  127. msg ? msg : lastErrorMsg);
  128. }
  129. } else if (status === Strophe.Status.AUTHFAIL) {
  130. // wrong password or username, prompt user
  131. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  132. JitsiConnectionErrors.PASSWORD_REQUIRED);
  133. }
  134. });
  135. }
  136. XMPP.prototype.connect = function (jid, password) {
  137. if(!jid) {
  138. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  139. // Force authenticated domain if room is appended with '?login=true'
  140. if (this.options.hosts.anonymousdomain &&
  141. window.location.search.indexOf("login=true") !== -1) {
  142. configDomain = this.options.hosts.domain;
  143. }
  144. jid = configDomain || window.location.hostname;
  145. }
  146. return this._connect(jid, password);
  147. };
  148. XMPP.prototype.joinRoom = function(roomName, useNicks, nick) {
  149. var roomjid = roomName;
  150. if (useNicks) {
  151. if (nick) {
  152. roomjid += '/' + nick;
  153. } else {
  154. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  155. }
  156. } else {
  157. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  158. if(!authenticatedUser)
  159. tmpJid = tmpJid.substr(0, 8);
  160. roomjid += '/' + tmpJid;
  161. }
  162. this.connection.emuc.doJoin(roomjid);
  163. };
  164. XMPP.prototype.myJid = function () {
  165. if(!this.connection)
  166. return null;
  167. return this.connection.emuc.myroomjid;
  168. }
  169. XMPP.prototype.myResource = function () {
  170. if(!this.connection || ! this.connection.emuc.myroomjid)
  171. return null;
  172. return Strophe.getResourceFromJid(this.connection.emuc.myroomjid);
  173. }
  174. XMPP.prototype.disposeConference = function (onUnload) {
  175. var handler = this.connection.jingle.activecall;
  176. if (handler && handler.peerconnection) {
  177. // FIXME: probably removing streams is not required and close() should
  178. // be enough
  179. if (RTC.localAudio) {
  180. handler.peerconnection.removeStream(
  181. RTC.localAudio.getOriginalStream(), onUnload);
  182. }
  183. if (RTC.localVideo) {
  184. handler.peerconnection.removeStream(
  185. RTC.localVideo.getOriginalStream(), onUnload);
  186. }
  187. handler.peerconnection.close();
  188. }
  189. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  190. this.connection.jingle.activecall = null;
  191. if (!onUnload) {
  192. this.sessionTerminated = true;
  193. this.connection.emuc.doLeave();
  194. }
  195. };
  196. XMPP.prototype.addListener = function(type, listener) {
  197. this.eventEmitter.on(type, listener);
  198. };
  199. XMPP.prototype.removeListener = function (type, listener) {
  200. this.eventEmitter.removeListener(type, listener);
  201. };
  202. XMPP.prototype.leaveRoom = function () {
  203. this.connection.emuc.doLeave();
  204. };
  205. XMPP.prototype.allocateConferenceFocus = function(roomName, callback) {
  206. Moderator.allocateConferenceFocus(roomName, callback);
  207. };
  208. XMPP.prototype.getLoginUrl = function (roomName, callback) {
  209. Moderator.getLoginUrl(roomName, callback);
  210. }
  211. XMPP.prototype.getPopupLoginUrl = function (roomName, callback) {
  212. Moderator.getPopupLoginUrl(roomName, callback);
  213. };
  214. XMPP.prototype.isModerator = function () {
  215. return Moderator.isModerator();
  216. };
  217. XMPP.prototype.isSipGatewayEnabled = function () {
  218. return Moderator.isSipGatewayEnabled();
  219. }
  220. XMPP.prototype.isExternalAuthEnabled = function () {
  221. return Moderator.isExternalAuthEnabled();
  222. };
  223. XMPP.prototype.isConferenceInProgress = function () {
  224. return this.connection && this.connection.jingle.activecall &&
  225. this.connection.jingle.activecall.peerconnection;
  226. };
  227. XMPP.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  228. if (this.isConferenceInProgress()) {
  229. // FIXME: will block switchInProgress on true value in case of exception
  230. this.connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  231. } else {
  232. // We are done immediately
  233. console.warn("No conference handler or conference not started yet");
  234. callback();
  235. }
  236. };
  237. XMPP.prototype.sendVideoInfoPresence = function (mute) {
  238. if(!this.connection)
  239. return;
  240. this.connection.emuc.addVideoInfoToPresence(mute);
  241. this.connection.emuc.sendPresence();
  242. };
  243. XMPP.prototype.setVideoMute = function (mute, callback, options) {
  244. if(!this.connection)
  245. return;
  246. var self = this;
  247. var localCallback = function (mute) {
  248. self.sendVideoInfoPresence(mute);
  249. return callback(mute);
  250. };
  251. if(this.connection.jingle.activecall)
  252. {
  253. this.connection.jingle.activecall.setVideoMute(
  254. mute, localCallback, options);
  255. }
  256. else {
  257. localCallback(mute);
  258. }
  259. };
  260. XMPP.prototype.setAudioMute = function (mute, callback) {
  261. if (!(this.connection && RTC.localAudio)) {
  262. return false;
  263. }
  264. if (this.forceMuted && !mute) {
  265. console.info("Asking focus for unmute");
  266. this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  267. // FIXME: wait for result before resetting muted status
  268. this.forceMuted = false;
  269. }
  270. if (mute == RTC.localAudio.isMuted()) {
  271. // Nothing to do
  272. return true;
  273. }
  274. RTC.localAudio.setMute(mute);
  275. this.sendAudioInfoPresence(mute, callback);
  276. return true;
  277. };
  278. XMPP.prototype.sendAudioInfoPresence = function(mute, callback) {
  279. if(this.connection) {
  280. this.connection.emuc.addAudioInfoToPresence(mute);
  281. this.connection.emuc.sendPresence();
  282. }
  283. callback();
  284. return true;
  285. };
  286. XMPP.prototype.addToPresence = function (name, value, dontSend) {
  287. switch (name) {
  288. case "displayName":
  289. this.connection.emuc.addDisplayNameToPresence(value);
  290. break;
  291. case "prezi":
  292. this.connection.emuc.addPreziToPresence(value, 0);
  293. break;
  294. case "preziSlide":
  295. this.connection.emuc.addCurrentSlideToPresence(value);
  296. break;
  297. case "connectionQuality":
  298. this.connection.emuc.addConnectionInfoToPresence(value);
  299. break;
  300. case "email":
  301. this.connection.emuc.addEmailToPresence(value);
  302. break;
  303. case "devices":
  304. this.connection.emuc.addDevicesToPresence(value);
  305. break;
  306. case "videoType":
  307. this.connection.emuc.addVideoTypeToPresence(value);
  308. break;
  309. case "startMuted":
  310. if(!Moderator.isModerator())
  311. return;
  312. this.connection.emuc.addStartMutedToPresence(value[0],
  313. value[1]);
  314. break;
  315. default :
  316. console.log("Unknown tag for presence: " + name);
  317. return;
  318. }
  319. if (!dontSend)
  320. this.connection.emuc.sendPresence();
  321. };
  322. /**
  323. * Sends 'data' as a log message to the focus. Returns true iff a message
  324. * was sent.
  325. * @param data
  326. * @returns {boolean} true iff a message was sent.
  327. */
  328. XMPP.prototype.sendLogs = function (data) {
  329. if(!this.connection.emuc.focusMucJid)
  330. return false;
  331. var deflate = true;
  332. var content = JSON.stringify(data);
  333. if (deflate) {
  334. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  335. }
  336. content = Base64.encode(content);
  337. // XEP-0337-ish
  338. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  339. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  340. id: 'PeerConnectionStats'});
  341. message.c('message').t(content).up();
  342. if (deflate) {
  343. message.c('tag', {name: "deflated", value: "true"}).up();
  344. }
  345. message.up();
  346. this.connection.send(message);
  347. return true;
  348. };
  349. // Gets the logs from strophe.jingle.
  350. XMPP.prototype.getJingleLog = function () {
  351. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  352. };
  353. // Gets the logs from strophe.
  354. XMPP.prototype.getXmppLog = function () {
  355. return this.connection.logger ? this.connection.logger.log : null;
  356. };
  357. XMPP.prototype.sendChatMessage = function (message, nickname) {
  358. this.connection.emuc.sendMessage(message, nickname);
  359. };
  360. XMPP.prototype.setSubject = function (topic) {
  361. this.connection.emuc.setSubject(topic);
  362. };
  363. XMPP.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  364. this.connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  365. };
  366. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  367. this.connection.rayo.dial(to, from, roomName,roomPass);
  368. };
  369. XMPP.prototype.setMute = function (jid, mute) {
  370. this.connection.moderate.setMute(jid, mute);
  371. };
  372. XMPP.prototype.eject = function (jid) {
  373. this.connection.moderate.eject(jid);
  374. };
  375. XMPP.prototype.logout = function (callback) {
  376. Moderator.logout(callback);
  377. };
  378. XMPP.prototype.findJidFromResource = function (resource) {
  379. return this.connection.emuc.findJidFromResource(resource);
  380. };
  381. XMPP.prototype.getMembers = function () {
  382. return this.connection.emuc.members;
  383. };
  384. XMPP.prototype.getJidFromSSRC = function (ssrc) {
  385. if (!this.isConferenceInProgress())
  386. return null;
  387. return this.connection.jingle.activecall.getSsrcOwner(ssrc);
  388. };
  389. // Returns true iff we have joined the MUC.
  390. XMPP.prototype.isMUCJoined = function () {
  391. return this.connection.emuc.joined;
  392. };
  393. XMPP.prototype.getSessions = function () {
  394. return this.connection.jingle.sessions;
  395. };
  396. XMPP.prototype.removeStream = function (stream) {
  397. if (!this.isConferenceInProgress())
  398. return;
  399. this.connection.jingle.activecall.peerconnection.removeStream(stream);
  400. };
  401. XMPP.prototype.disconnect = function (callback) {
  402. if (disconnectInProgress || !this.connection || !this.connection.connected)
  403. {
  404. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  405. return;
  406. }
  407. disconnectInProgress = true;
  408. this.connection.disconnect();
  409. };
  410. module.exports = XMPP;