You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xmpp.js 12KB

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