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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /* global $ */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { Strophe } from 'strophe.js';
  4. import 'strophejs-plugin-disco';
  5. import RandomUtil from '../util/RandomUtil';
  6. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  7. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  8. import RTCBrowserType from '../RTC/RTCBrowserType';
  9. import initEmuc from './strophe.emuc';
  10. import initJingle from './strophe.jingle';
  11. import initStropheUtil from './strophe.util';
  12. import initPing from './strophe.ping';
  13. import initRayo from './strophe.rayo';
  14. import initStropheLogger from './strophe.logger';
  15. import Listenable from '../util/Listenable';
  16. import Caps from './Caps';
  17. const logger = getLogger(__filename);
  18. /**
  19. *
  20. * @param token
  21. * @param bosh
  22. */
  23. function createConnection(token, bosh = '/http-bind') {
  24. // Append token as URL param
  25. if (token) {
  26. // eslint-disable-next-line no-param-reassign
  27. bosh += `${bosh.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  28. }
  29. return new Strophe.Connection(bosh);
  30. }
  31. /**
  32. *
  33. */
  34. export default class XMPP extends Listenable {
  35. /**
  36. * FIXME describe all options
  37. * @param {Object} options
  38. * @param {Array<Object>} options.p2pStunServers see
  39. * {@link JingleConnectionPlugin} for more details.
  40. * @param token
  41. */
  42. constructor(options, token) {
  43. super();
  44. this.connection = null;
  45. this.disconnectInProgress = false;
  46. this.connectionTimes = {};
  47. this.forceMuted = false;
  48. this.options = options;
  49. this.connectParams = {};
  50. this.token = token;
  51. this.authenticatedUser = false;
  52. this._initStrophePlugins(this);
  53. this.connection = createConnection(token, options.bosh);
  54. this.caps = new Caps(this.connection, this.options.clientNode);
  55. // Initialize features advertised in disco-info
  56. this.initFeaturesList();
  57. // Setup a disconnect on unload as a way to facilitate API consumers. It
  58. // sounds like they would want that. A problem for them though may be if
  59. // they wanted to utilize the connected connection in an unload handler
  60. // of their own. However, it should be fairly easy for them to do that
  61. // by registering their unload handler before us.
  62. $(window).on('beforeunload unload', this.disconnect.bind(this));
  63. }
  64. /**
  65. * Initializes the list of feature advertised through the disco-info
  66. * mechanism.
  67. */
  68. initFeaturesList() {
  69. // http://xmpp.org/extensions/xep-0167.html#support
  70. // http://xmpp.org/extensions/xep-0176.html#support
  71. this.caps.addFeature('urn:xmpp:jingle:1');
  72. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:1');
  73. this.caps.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  74. this.caps.addFeature('urn:xmpp:jingle:apps:dtls:0');
  75. this.caps.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  76. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  77. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:video');
  78. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  79. this.caps.addFeature('urn:ietf:rfc:4588');
  80. }
  81. // this is dealt with by SDP O/A so we don't need to announce this
  82. // XEP-0293
  83. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0');
  84. // XEP-0294
  85. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0');
  86. this.caps.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  87. this.caps.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  88. // this.caps.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  89. // Enable Lipsync ?
  90. if (RTCBrowserType.isChrome() && this.options.enableLipSync !== false) {
  91. logger.info('Lip-sync enabled !');
  92. this.caps.addFeature('http://jitsi.org/meet/lipsync');
  93. }
  94. if (this.connection.rayo) {
  95. this.caps.addFeature('urn:xmpp:rayo:client:1');
  96. }
  97. }
  98. /**
  99. *
  100. */
  101. getConnection() {
  102. return this.connection;
  103. }
  104. /**
  105. * Receive connection status changes and handles them.
  106. *
  107. * @param {Object} credentials
  108. * @param {string} credentials.jid - The user's XMPP ID passed to the
  109. * connect method. For example, 'user@xmpp.com'.
  110. * @param {string} credentials.password - The password passed to the connect
  111. * method.
  112. * @param {string} status - One of Strophe's connection status strings.
  113. * @param {string} [msg] - The connection error message provided by Strophe.
  114. */
  115. connectionHandler(credentials = {}, status, msg) {
  116. const now = window.performance.now();
  117. const statusStr = Strophe.getStatusString(status).toLowerCase();
  118. this.connectionTimes[statusStr] = now;
  119. logger.log(
  120. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  121. now);
  122. if (status === Strophe.Status.CONNECTED
  123. || status === Strophe.Status.ATTACHED) {
  124. if (this.options.useStunTurn
  125. || (this.options.p2p && this.options.p2p.useStunTurn)) {
  126. this.connection.jingle.getStunAndTurnCredentials();
  127. }
  128. logger.info(`My Jabber ID: ${this.connection.jid}`);
  129. // Schedule ping ?
  130. const pingJid = this.connection.domain;
  131. this.connection.ping.hasPingSupport(
  132. pingJid,
  133. hasPing => {
  134. if (hasPing) {
  135. this.connection.ping.startInterval(pingJid);
  136. } else {
  137. logger.warn(`Ping NOT supported by ${pingJid}`);
  138. }
  139. });
  140. if (credentials.password) {
  141. this.authenticatedUser = true;
  142. }
  143. if (this.connection && this.connection.connected
  144. && Strophe.getResourceFromJid(this.connection.jid)) {
  145. // .connected is true while connecting?
  146. // this.connection.send($pres());
  147. this.eventEmitter.emit(
  148. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  149. Strophe.getResourceFromJid(this.connection.jid));
  150. }
  151. } else if (status === Strophe.Status.CONNFAIL) {
  152. if (msg === 'x-strophe-bad-non-anon-jid') {
  153. this.anonymousConnectionFailed = true;
  154. } else {
  155. this.connectionFailed = true;
  156. }
  157. this.lastErrorMsg = msg;
  158. } else if (status === Strophe.Status.DISCONNECTED) {
  159. // Stop ping interval
  160. this.connection.ping.stopInterval();
  161. const wasIntentionalDisconnect = this.disconnectInProgress;
  162. const errMsg = msg || this.lastErrorMsg;
  163. this.disconnectInProgress = false;
  164. if (this.anonymousConnectionFailed) {
  165. // prompt user for username and password
  166. this.eventEmitter.emit(
  167. JitsiConnectionEvents.CONNECTION_FAILED,
  168. JitsiConnectionErrors.PASSWORD_REQUIRED);
  169. } else if (this.connectionFailed) {
  170. this.eventEmitter.emit(
  171. JitsiConnectionEvents.CONNECTION_FAILED,
  172. JitsiConnectionErrors.OTHER_ERROR, errMsg);
  173. } else if (wasIntentionalDisconnect) {
  174. this.eventEmitter.emit(
  175. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  176. } else {
  177. // XXX if Strophe drops the connection while not being asked to,
  178. // it means that most likely some serious error has occurred.
  179. // One currently known case is when a BOSH request fails for
  180. // more than 4 times. The connection is dropped without
  181. // supplying a reason(error message/event) through the API.
  182. logger.error('XMPP connection dropped!');
  183. // XXX if the last request error is within 5xx range it means it
  184. // was a server failure
  185. const lastErrorStatus = Strophe.getLastErrorStatus();
  186. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  187. this.eventEmitter.emit(
  188. JitsiConnectionEvents.CONNECTION_FAILED,
  189. JitsiConnectionErrors.SERVER_ERROR,
  190. errMsg || 'server-error');
  191. } else {
  192. this.eventEmitter.emit(
  193. JitsiConnectionEvents.CONNECTION_FAILED,
  194. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  195. errMsg || 'connection-dropped-error');
  196. }
  197. }
  198. } else if (status === Strophe.Status.AUTHFAIL) {
  199. // wrong password or username, prompt user
  200. this.eventEmitter.emit(
  201. JitsiConnectionEvents.CONNECTION_FAILED,
  202. JitsiConnectionErrors.PASSWORD_REQUIRED,
  203. msg,
  204. credentials);
  205. }
  206. }
  207. /**
  208. *
  209. * @param jid
  210. * @param password
  211. */
  212. _connect(jid, password) {
  213. // connection.connect() starts the connection process.
  214. //
  215. // As the connection process proceeds, the user supplied callback will
  216. // be triggered multiple times with status updates. The callback should
  217. // take two arguments - the status code and the error condition.
  218. //
  219. // The status code will be one of the values in the Strophe.Status
  220. // constants. The error condition will be one of the conditions defined
  221. // in RFC 3920 or the condition ‘strophe-parsererror’.
  222. //
  223. // The Parameters wait, hold and route are optional and only relevant
  224. // for BOSH connections. Please see XEP 124 for a more detailed
  225. // explanation of the optional parameters.
  226. //
  227. // Connection status constants for use by the connection handler
  228. // callback.
  229. //
  230. // Status.ERROR - An error has occurred (websockets specific)
  231. // Status.CONNECTING - The connection is currently being made
  232. // Status.CONNFAIL - The connection attempt failed
  233. // Status.AUTHENTICATING - The connection is authenticating
  234. // Status.AUTHFAIL - The authentication attempt failed
  235. // Status.CONNECTED - The connection has succeeded
  236. // Status.DISCONNECTED - The connection has been terminated
  237. // Status.DISCONNECTING - The connection is currently being terminated
  238. // Status.ATTACHED - The connection has been attached
  239. this.anonymousConnectionFailed = false;
  240. this.connectionFailed = false;
  241. this.lastErrorMsg = undefined;
  242. this.connection.connect(
  243. jid,
  244. password,
  245. this.connectionHandler.bind(this, {
  246. jid,
  247. password
  248. }));
  249. }
  250. /**
  251. * Attach to existing connection. Can be used for optimizations. For
  252. * example: if the connection is created on the server we can attach to it
  253. * and start using it.
  254. *
  255. * @param options {object} connecting options - rid, sid, jid and password.
  256. */
  257. attach(options) {
  258. const now = this.connectionTimes.attaching = window.performance.now();
  259. logger.log(`(TIME) Strophe Attaching\t:${now}`);
  260. this.connection.attach(options.jid, options.sid,
  261. parseInt(options.rid, 10) + 1,
  262. this.connectionHandler.bind(this, {
  263. jid: options.jid,
  264. password: options.password
  265. }));
  266. }
  267. /**
  268. *
  269. * @param jid
  270. * @param password
  271. */
  272. connect(jid, password) {
  273. this.connectParams = {
  274. jid,
  275. password
  276. };
  277. if (!jid) {
  278. const { anonymousdomain, domain } = this.options.hosts;
  279. let configDomain = anonymousdomain || domain;
  280. // Force authenticated domain if room is appended with '?login=true'
  281. // or if we're joining with the token
  282. // FIXME Do not rely on window.location because (1) React Native
  283. // does not have a window.location by default and (2) here we cannot
  284. // know for sure that query/search has not be stripped from
  285. // window.location by the time the following executes.
  286. const { location } = window;
  287. if (anonymousdomain) {
  288. const search = location && location.search;
  289. if ((search && search.indexOf('login=true') !== -1)
  290. || this.token) {
  291. configDomain = domain;
  292. }
  293. }
  294. // eslint-disable-next-line no-param-reassign
  295. jid = configDomain || (location && location.hostname);
  296. }
  297. return this._connect(jid, password);
  298. }
  299. /**
  300. *
  301. * @param roomName
  302. * @param options
  303. */
  304. createRoom(roomName, options) {
  305. // By default MUC nickname is the resource part of the JID
  306. let mucNickname = Strophe.getNodeFromJid(this.connection.jid);
  307. let roomjid = `${roomName}@${this.options.hosts.muc}/`;
  308. const cfgNickname
  309. = options.useNicks && options.nick ? options.nick : null;
  310. if (cfgNickname) {
  311. // Use nick if it's defined
  312. mucNickname = options.nick;
  313. } else if (!this.authenticatedUser) {
  314. // node of the anonymous JID is very long - here we trim it a bit
  315. mucNickname = mucNickname.substr(0, 8);
  316. }
  317. // Constant JIDs need some random part to be appended in order to be
  318. // able to join the MUC more than once.
  319. if (this.authenticatedUser || cfgNickname !== null) {
  320. mucNickname += `-${RandomUtil.randomHexString(6)}`;
  321. }
  322. roomjid += mucNickname;
  323. return this.connection.emuc.createRoom(roomjid, null, options);
  324. }
  325. /**
  326. * Returns the logs from strophe.jingle.
  327. * @returns {Object}
  328. */
  329. getJingleLog() {
  330. const jingle = this.connection.jingle;
  331. return jingle ? jingle.getLog() : {};
  332. }
  333. /**
  334. * Returns the logs from strophe.
  335. */
  336. getXmppLog() {
  337. return (this.connection.logger || {}).log || null;
  338. }
  339. /**
  340. *
  341. */
  342. dial(...args) {
  343. this.connection.rayo.dial(...args);
  344. }
  345. /**
  346. *
  347. * @param jid
  348. * @param mute
  349. */
  350. setMute(jid, mute) {
  351. this.connection.moderate.setMute(jid, mute);
  352. }
  353. /**
  354. *
  355. * @param jid
  356. */
  357. eject(jid) {
  358. this.connection.moderate.eject(jid);
  359. }
  360. /**
  361. *
  362. */
  363. getSessions() {
  364. return this.connection.jingle.sessions;
  365. }
  366. /**
  367. * Disconnects this from the XMPP server (if this is connected).
  368. *
  369. * @param ev optionally, the event which triggered the necessity to
  370. * disconnect from the XMPP server (e.g. beforeunload, unload).
  371. */
  372. disconnect(ev) {
  373. if (this.disconnectInProgress
  374. || !this.connection
  375. || !this.connection.connected) {
  376. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  377. return;
  378. }
  379. this.disconnectInProgress = true;
  380. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  381. // means that there may not be enough time to send an unavailable
  382. // presence or disconnect at all. Switching Strophe to synchronous
  383. // sending is not much of an option because it may lead to a noticeable
  384. // delay in navigating away from the current location. As a compromise,
  385. // we will try to increase the chances of sending an unavailable
  386. // presence and/or disconecting within the short time span that we have
  387. // upon unloading by invoking flush() on the connection. We flush() once
  388. // before disconnect() in order to attemtp to have its unavailable
  389. // presence at the top of the send queue. We flush() once more after
  390. // disconnect() in order to attempt to have its unavailable presence
  391. // sent as soon as possible.
  392. this.connection.flush();
  393. if (ev !== null && typeof ev !== 'undefined') {
  394. const evType = ev.type;
  395. if (evType === 'beforeunload' || evType === 'unload') {
  396. // XXX Whatever we said above, synchronous sending is the best
  397. // (known) way to properly disconnect from the XMPP server.
  398. // Consequently, it may be fine to have the source code and
  399. // comment it in or out depending on whether we want to run with
  400. // it for some time.
  401. this.connection.options.sync = true;
  402. }
  403. }
  404. this.connection.disconnect();
  405. if (this.connection.options.sync !== true) {
  406. this.connection.flush();
  407. }
  408. }
  409. /**
  410. *
  411. */
  412. _initStrophePlugins() {
  413. // FIXME: remove once we have a default config template. -saghul
  414. const defaultStunServers = [
  415. { urls: 'stun:stun.l.google.com:19302' },
  416. { urls: 'stun:stun1.l.google.com:19302' },
  417. { urls: 'stun:stun2.l.google.com:19302' }
  418. ];
  419. const p2pStunServers = (this.options.p2p
  420. && this.options.p2p.stunServers) || defaultStunServers;
  421. initEmuc(this);
  422. initJingle(this, this.eventEmitter, p2pStunServers);
  423. initStropheUtil();
  424. initPing(this);
  425. initRayo();
  426. initStropheLogger();
  427. }
  428. }