Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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