Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

xmpp.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /* global $, APP, config, Strophe */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var EventEmitter = require("events");
  4. var Pako = require("pako");
  5. var RTCEvents = require("../../service/RTC/RTCEvents");
  6. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  8. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  9. var RTC = require("../RTC/RTC");
  10. var authenticatedUser = false;
  11. function createConnection(bosh, token) {
  12. bosh = bosh || '/http-bind';
  13. // Append token as URL param
  14. if (token) {
  15. bosh += (bosh.indexOf('?') == -1 ? '?' : '&') + 'token=' + token;
  16. }
  17. return new Strophe.Connection(bosh);
  18. };
  19. //!!!!!!!!!! FIXME: ...
  20. function initStrophePlugins(XMPP) {
  21. require("./strophe.emuc")(XMPP);
  22. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  23. // require("./strophe.moderate")(XMPP, eventEmitter);
  24. require("./strophe.util")();
  25. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  26. require("./strophe.rayo")();
  27. require("./strophe.logger")();
  28. }
  29. function XMPP(options, token) {
  30. this.eventEmitter = new EventEmitter();
  31. this.connection = null;
  32. this.disconnectInProgress = false;
  33. this.connectionTimes = {};
  34. this.forceMuted = false;
  35. this.options = options;
  36. initStrophePlugins(this);
  37. this.connection = createConnection(options.bosh, token);
  38. // Setup a disconnect on unload as a way to facilitate API consumers. It
  39. // sounds like they would want that. A problem for them though may be if
  40. // they wanted to utilize the connected connection in an unload handler of
  41. // their own. However, it should be fairly easy for them to do that by
  42. // registering their unload handler before us.
  43. $(window).on('beforeunload unload', this.disconnect.bind(this));
  44. }
  45. XMPP.prototype.getConnection = function () { return this.connection; };
  46. /**
  47. * Receive connection status changes and handles them.
  48. * @password {string} the password passed in connect method
  49. * @status the connection status
  50. * @msg message
  51. */
  52. XMPP.prototype.connectionHandler = function (password, status, msg) {
  53. var now = window.performance.now();
  54. this.connectionTimes[Strophe.getStatusString(status).toLowerCase()] = now;
  55. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  56. (msg ? "[" + msg + "]" : "") + ":\t", now);
  57. if (status === Strophe.Status.CONNECTED ||
  58. status === Strophe.Status.ATTACHED) {
  59. if (this.options.useStunTurn) {
  60. this.connection.jingle.getStunAndTurnCredentials();
  61. }
  62. logger.info("My Jabber ID: " + this.connection.jid);
  63. // Schedule ping ?
  64. var pingJid = this.connection.domain;
  65. this.connection.ping.hasPingSupport(
  66. pingJid,
  67. function (hasPing) {
  68. if (hasPing)
  69. this.connection.ping.startInterval(pingJid);
  70. else
  71. logger.warn("Ping NOT supported by " + pingJid);
  72. }.bind(this));
  73. if (password)
  74. authenticatedUser = true;
  75. if (this.connection && this.connection.connected &&
  76. Strophe.getResourceFromJid(this.connection.jid)) {
  77. // .connected is true while connecting?
  78. // this.connection.send($pres());
  79. this.eventEmitter.emit(
  80. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  81. Strophe.getResourceFromJid(this.connection.jid));
  82. }
  83. } else if (status === Strophe.Status.CONNFAIL) {
  84. if (msg === 'x-strophe-bad-non-anon-jid') {
  85. this.anonymousConnectionFailed = true;
  86. } else {
  87. this.connectionFailed = true;
  88. }
  89. this.lastErrorMsg = msg;
  90. } else if (status === Strophe.Status.DISCONNECTED) {
  91. // Stop ping interval
  92. this.connection.ping.stopInterval();
  93. this.disconnectInProgress = false;
  94. if (this.anonymousConnectionFailed) {
  95. // prompt user for username and password
  96. this.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  97. JitsiConnectionErrors.PASSWORD_REQUIRED);
  98. } else if(this.connectionFailed) {
  99. this.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  100. JitsiConnectionErrors.OTHER_ERROR,
  101. msg ? msg : this.lastErrorMsg);
  102. } else {
  103. this.eventEmitter.emit(
  104. JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  105. msg ? msg : this.lastErrorMsg);
  106. }
  107. } else if (status === Strophe.Status.AUTHFAIL) {
  108. // wrong password or username, prompt user
  109. this.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  110. JitsiConnectionErrors.PASSWORD_REQUIRED);
  111. }
  112. }
  113. XMPP.prototype._connect = function (jid, password) {
  114. // connection.connect() starts the connection process.
  115. //
  116. // As the connection process proceeds, the user supplied callback will
  117. // be triggered multiple times with status updates. The callback should
  118. // take two arguments - the status code and the error condition.
  119. //
  120. // The status code will be one of the values in the Strophe.Status
  121. // constants. The error condition will be one of the conditions defined
  122. // in RFC 3920 or the condition ‘strophe-parsererror’.
  123. //
  124. // The Parameters wait, hold and route are optional and only relevant
  125. // for BOSH connections. Please see XEP 124 for a more detailed
  126. // explanation of the optional parameters.
  127. //
  128. // Connection status constants for use by the connection handler
  129. // callback.
  130. //
  131. // Status.ERROR - An error has occurred (websockets specific)
  132. // Status.CONNECTING - The connection is currently being made
  133. // Status.CONNFAIL - The connection attempt failed
  134. // Status.AUTHENTICATING - The connection is authenticating
  135. // Status.AUTHFAIL - The authentication attempt failed
  136. // Status.CONNECTED - The connection has succeeded
  137. // Status.DISCONNECTED - The connection has been terminated
  138. // Status.DISCONNECTING - The connection is currently being terminated
  139. // Status.ATTACHED - The connection has been attached
  140. this.anonymousConnectionFailed = false;
  141. this.connectionFailed = false;
  142. this.lastErrorMsg;
  143. this.connection.connect(jid, password,
  144. this.connectionHandler.bind(this, password));
  145. }
  146. /**
  147. * Attach to existing connection. Can be used for optimizations. For example:
  148. * if the connection is created on the server we can attach to it and start
  149. * using it.
  150. *
  151. * @param options {object} connecting options - rid, sid, jid and password.
  152. */
  153. XMPP.prototype.attach = function (options) {
  154. var now = this.connectionTimes["attaching"] = window.performance.now();
  155. logger.log("(TIME) Strophe Attaching\t:" + now);
  156. this.connection.attach(options.jid, options.sid, parseInt(options.rid,10)+1,
  157. this.connectionHandler.bind(this, options.password));
  158. }
  159. XMPP.prototype.connect = function (jid, password) {
  160. if (!jid) {
  161. var configDomain
  162. = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  163. // Force authenticated domain if room is appended with '?login=true'
  164. if (this.options.hosts.anonymousdomain
  165. && window.location.search.indexOf("login=true") !== -1) {
  166. configDomain = this.options.hosts.domain;
  167. }
  168. jid = configDomain || window.location.hostname;
  169. }
  170. return this._connect(jid, password);
  171. };
  172. XMPP.prototype.createRoom = function (roomName, options, settings) {
  173. var roomjid = roomName + '@' + this.options.hosts.muc;
  174. if (options.useNicks) {
  175. if (options.nick) {
  176. roomjid += '/' + options.nick;
  177. } else {
  178. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  179. }
  180. } else {
  181. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  182. if (!authenticatedUser)
  183. tmpJid = tmpJid.substr(0, 8);
  184. roomjid += '/' + tmpJid;
  185. }
  186. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  187. }
  188. XMPP.prototype.addListener = function(type, listener) {
  189. this.eventEmitter.on(type, listener);
  190. };
  191. XMPP.prototype.removeListener = function (type, listener) {
  192. this.eventEmitter.removeListener(type, listener);
  193. };
  194. //FIXME: this should work with the room
  195. XMPP.prototype.leaveRoom = function (jid) {
  196. var handler = this.connection.jingle.jid2session[jid];
  197. if (handler && handler.peerconnection) {
  198. // FIXME: probably removing streams is not required and close() should
  199. // be enough
  200. if (RTC.localAudio) {
  201. handler.peerconnection.removeStream(
  202. RTC.localAudio.getOriginalStream(), true);
  203. }
  204. if (RTC.localVideo) {
  205. handler.peerconnection.removeStream(
  206. RTC.localVideo.getOriginalStream(), true);
  207. }
  208. handler.peerconnection.close();
  209. }
  210. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  211. this.connection.emuc.doLeave(jid);
  212. };
  213. /**
  214. * Sends 'data' as a log message to the focus. Returns true iff a message
  215. * was sent.
  216. * @param data
  217. * @returns {boolean} true iff a message was sent.
  218. */
  219. XMPP.prototype.sendLogs = function (data) {
  220. if (!this.connection.emuc.focusMucJid)
  221. return false;
  222. var deflate = true;
  223. var content = JSON.stringify(data);
  224. if (deflate) {
  225. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  226. }
  227. content = Base64.encode(content);
  228. // XEP-0337-ish
  229. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  230. message.c('log', {xmlns: 'urn:xmpp:eventlog', id: 'PeerConnectionStats'});
  231. message.c('message').t(content).up();
  232. if (deflate) {
  233. message.c('tag', {name: "deflated", value: "true"}).up();
  234. }
  235. message.up();
  236. this.connection.send(message);
  237. return true;
  238. };
  239. // Gets the logs from strophe.jingle.
  240. XMPP.prototype.getJingleLog = function () {
  241. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  242. };
  243. // Gets the logs from strophe.
  244. XMPP.prototype.getXmppLog = function () {
  245. return this.connection.logger ? this.connection.logger.log : null;
  246. };
  247. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  248. this.connection.rayo.dial(to, from, roomName,roomPass);
  249. };
  250. XMPP.prototype.setMute = function (jid, mute) {
  251. this.connection.moderate.setMute(jid, mute);
  252. };
  253. XMPP.prototype.eject = function (jid) {
  254. this.connection.moderate.eject(jid);
  255. };
  256. XMPP.prototype.getSessions = function () {
  257. return this.connection.jingle.sessions;
  258. };
  259. /**
  260. * Disconnects this from the XMPP server (if this is connected).
  261. *
  262. * @param ev optionally, the event which triggered the necessity to disconnect
  263. * from the XMPP server (e.g. beforeunload, unload)
  264. */
  265. XMPP.prototype.disconnect = function (ev) {
  266. if (this.disconnectInProgress
  267. || !this.connection
  268. || !this.connection.connected) {
  269. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  270. return;
  271. }
  272. this.disconnectInProgress = true;
  273. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  274. // means that there may not be enough time to send an unavailable presence
  275. // or disconnect at all. Switching Strophe to synchronous sending is not
  276. // much of an option because it may lead to a noticeable delay in navigating
  277. // away from the current location. As a compromise, we will try to increase
  278. // the chances of sending an unavailable presence and/or disconecting within
  279. // the short time span that we have upon unloading by invoking flush() on
  280. // the connection. We flush() once before disconnect() in order to attemtp
  281. // to have its unavailable presence at the top of the send queue. We flush()
  282. // once more after disconnect() in order to attempt to have its unavailable
  283. // presence sent as soon as possible.
  284. this.connection.flush();
  285. if (ev !== null && typeof ev !== 'undefined') {
  286. var evType = ev.type;
  287. if (evType == 'beforeunload' || evType == 'unload') {
  288. // XXX Whatever we said above, synchronous sending is the best
  289. // (known) way to properly disconnect from the XMPP server.
  290. // Consequently, it may be fine to have the source code and comment
  291. // it in or out depending on whether we want to run with it for some
  292. // time.
  293. this.connection.options.sync = true;
  294. }
  295. }
  296. this.connection.disconnect();
  297. if (this.connection.options.sync !== true) {
  298. this.connection.flush();
  299. }
  300. };
  301. module.exports = XMPP;