Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

xmpp.js 15KB

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