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 14KB

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