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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /* global $, Strophe */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. const logger = getLogger(__filename);
  4. import RandomUtil from '../util/RandomUtil';
  5. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  6. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  7. import RTCBrowserType from '../RTC/RTCBrowserType';
  8. import initEmuc from './strophe.emuc';
  9. import initJingle from './strophe.jingle';
  10. import initStropheUtil from './strophe.util';
  11. import initPing from './strophe.ping';
  12. import initRayo from './strophe.rayo';
  13. import initStropheLogger from './strophe.logger';
  14. import Listenable from '../util/Listenable';
  15. import Caps from './Caps';
  16. function createConnection(token, bosh = '/http-bind') {
  17. // Append token as URL param
  18. if (token) {
  19. // eslint-disable-next-line no-param-reassign
  20. bosh += `${bosh.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  21. }
  22. return new Strophe.Connection(bosh);
  23. }
  24. export default class XMPP extends Listenable {
  25. constructor(options, token) {
  26. super();
  27. this.connection = null;
  28. this.disconnectInProgress = false;
  29. this.connectionTimes = {};
  30. this.forceMuted = false;
  31. this.options = options;
  32. this.connectParams = {};
  33. this.token = token;
  34. this.authenticatedUser = false;
  35. this._initStrophePlugins(this);
  36. this.connection = createConnection(token, options.bosh);
  37. this.caps = new Caps(this.connection, this.options.clientNode);
  38. // Initialize features advertised in disco-info
  39. this.initFeaturesList();
  40. // Setup a disconnect on unload as a way to facilitate API consumers. It
  41. // sounds like they would want that. A problem for them though may be if
  42. // they wanted to utilize the connected connection in an unload handler
  43. // of their own. However, it should be fairly easy for them to do that
  44. // by registering their unload handler before us.
  45. $(window).on('beforeunload unload', this.disconnect.bind(this));
  46. }
  47. /**
  48. * Initializes the list of feature advertised through the disco-info
  49. * mechanism.
  50. */
  51. initFeaturesList() {
  52. // http://xmpp.org/extensions/xep-0167.html#support
  53. // http://xmpp.org/extensions/xep-0176.html#support
  54. this.caps.addFeature('urn:xmpp:jingle:1');
  55. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:1');
  56. this.caps.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  57. this.caps.addFeature('urn:xmpp:jingle:apps:dtls:0');
  58. this.caps.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  59. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  60. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:video');
  61. if (!this.options.disableRtx && !RTCBrowserType.isFirefox()) {
  62. this.caps.addFeature('urn:ietf:rfc:4588');
  63. }
  64. // this is dealt with by SDP O/A so we don't need to announce this
  65. // XEP-0293
  66. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0');
  67. // XEP-0294
  68. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0');
  69. this.caps.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  70. this.caps.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  71. // this.caps.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  72. // Enable Lipsync ?
  73. if (RTCBrowserType.isChrome() && this.options.enableLipSync !== false) {
  74. logger.info('Lip-sync enabled !');
  75. this.caps.addFeature('http://jitsi.org/meet/lipsync');
  76. }
  77. if (this.connection.rayo) {
  78. this.caps.addFeature('urn:xmpp:rayo:client:1');
  79. }
  80. }
  81. getConnection() {
  82. return this.connection;
  83. }
  84. /**
  85. * Receive connection status changes and handles them.
  86. * @password {string} the password passed in connect method
  87. * @status the connection status
  88. * @msg message
  89. */
  90. connectionHandler(password, status, msg) {
  91. const now = window.performance.now();
  92. const statusStr = Strophe.getStatusString(status).toLowerCase();
  93. this.connectionTimes[statusStr] = now;
  94. logger.log(
  95. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  96. now);
  97. if (status === Strophe.Status.CONNECTED
  98. || status === Strophe.Status.ATTACHED) {
  99. if (this.options.useStunTurn) {
  100. this.connection.jingle.getStunAndTurnCredentials();
  101. }
  102. logger.info(`My Jabber ID: ${this.connection.jid}`);
  103. // Schedule ping ?
  104. const pingJid = this.connection.domain;
  105. this.connection.ping.hasPingSupport(
  106. pingJid,
  107. hasPing => {
  108. if (hasPing) {
  109. this.connection.ping.startInterval(pingJid);
  110. } else {
  111. logger.warn(`Ping NOT supported by ${pingJid}`);
  112. }
  113. });
  114. if (password) {
  115. this.authenticatedUser = true;
  116. }
  117. if (this.connection && this.connection.connected
  118. && Strophe.getResourceFromJid(this.connection.jid)) {
  119. // .connected is true while connecting?
  120. // this.connection.send($pres());
  121. this.eventEmitter.emit(
  122. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  123. Strophe.getResourceFromJid(this.connection.jid));
  124. }
  125. } else if (status === Strophe.Status.CONNFAIL) {
  126. if (msg === 'x-strophe-bad-non-anon-jid') {
  127. this.anonymousConnectionFailed = true;
  128. } else {
  129. this.connectionFailed = true;
  130. }
  131. this.lastErrorMsg = msg;
  132. } else if (status === Strophe.Status.DISCONNECTED) {
  133. // Stop ping interval
  134. this.connection.ping.stopInterval();
  135. const wasIntentionalDisconnect = this.disconnectInProgress;
  136. const errMsg = msg ? msg : this.lastErrorMsg;
  137. this.disconnectInProgress = false;
  138. if (this.anonymousConnectionFailed) {
  139. // prompt user for username and password
  140. this.eventEmitter.emit(
  141. JitsiConnectionEvents.CONNECTION_FAILED,
  142. JitsiConnectionErrors.PASSWORD_REQUIRED);
  143. } else if (this.connectionFailed) {
  144. this.eventEmitter.emit(
  145. JitsiConnectionEvents.CONNECTION_FAILED,
  146. JitsiConnectionErrors.OTHER_ERROR, errMsg);
  147. } else if (wasIntentionalDisconnect) {
  148. this.eventEmitter.emit(
  149. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  150. } else {
  151. // XXX if Strophe drops the connection while not being asked to,
  152. // it means that most likely some serious error has occurred.
  153. // One currently known case is when a BOSH request fails for
  154. // more than 4 times. The connection is dropped without
  155. // supplying a reason(error message/event) through the API.
  156. logger.error('XMPP connection dropped!');
  157. // XXX if the last request error is within 5xx range it means it
  158. // was a server failure
  159. const lastErrorStatus = Strophe.getLastErrorStatus();
  160. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  161. this.eventEmitter.emit(
  162. JitsiConnectionEvents.CONNECTION_FAILED,
  163. JitsiConnectionErrors.SERVER_ERROR,
  164. errMsg ? errMsg : 'server-error');
  165. } else {
  166. this.eventEmitter.emit(
  167. JitsiConnectionEvents.CONNECTION_FAILED,
  168. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  169. errMsg ? errMsg : 'connection-dropped-error');
  170. }
  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. _connect(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
  213. * example: if the connection is created on the server we can attach to it
  214. * and start using it.
  215. *
  216. * @param options {object} connecting options - rid, sid, jid and password.
  217. */
  218. attach(options) {
  219. const now = this.connectionTimes.attaching = window.performance.now();
  220. logger.log(`(TIME) Strophe Attaching\t:${now}`);
  221. this.connection.attach(options.jid, options.sid,
  222. parseInt(options.rid, 10) + 1,
  223. this.connectionHandler.bind(this, options.password));
  224. }
  225. connect(jid, password) {
  226. this.connectParams = {
  227. jid,
  228. password
  229. };
  230. if (!jid) {
  231. let configDomain
  232. = this.options.hosts.anonymousdomain
  233. || this.options.hosts.domain;
  234. // Force authenticated domain if room is appended with '?login=true'
  235. // or if we're joining with the token
  236. if (this.options.hosts.anonymousdomain
  237. && (window.location.search.indexOf('login=true') !== -1
  238. || this.options.token)) {
  239. configDomain = this.options.hosts.domain;
  240. }
  241. // eslint-disable-next-line no-param-reassign
  242. jid = configDomain || window.location.hostname;
  243. }
  244. return this._connect(jid, password);
  245. }
  246. createRoom(roomName, options) {
  247. // By default MUC nickname is the resource part of the JID
  248. let mucNickname = Strophe.getNodeFromJid(this.connection.jid);
  249. let roomjid = `${roomName}@${this.options.hosts.muc}/`;
  250. const cfgNickname
  251. = options.useNicks && options.nick ? options.nick : null;
  252. if (cfgNickname) {
  253. // Use nick if it's defined
  254. mucNickname = options.nick;
  255. } else if (!this.authenticatedUser) {
  256. // node of the anonymous JID is very long - here we trim it a bit
  257. mucNickname = mucNickname.substr(0, 8);
  258. }
  259. // Constant JIDs need some random part to be appended in order to be
  260. // able to join the MUC more than once.
  261. if (this.authenticatedUser || cfgNickname !== null) {
  262. mucNickname += `-${RandomUtil.randomHexString(6)}`;
  263. }
  264. roomjid += mucNickname;
  265. return this.connection.emuc.createRoom(roomjid, null, options);
  266. }
  267. /**
  268. * Returns the logs from strophe.jingle.
  269. * @returns {Object}
  270. */
  271. getJingleLog() {
  272. const jingle = this.connection.jingle;
  273. return jingle ? jingle.getLog() : {};
  274. }
  275. /**
  276. * Returns the logs from strophe.
  277. */
  278. getXmppLog() {
  279. return (this.connection.logger || {}).log || null;
  280. }
  281. dial(to, from, roomName, roomPass) {
  282. this.connection.rayo.dial(to, from, roomName, roomPass);
  283. }
  284. setMute(jid, mute) {
  285. this.connection.moderate.setMute(jid, mute);
  286. }
  287. eject(jid) {
  288. this.connection.moderate.eject(jid);
  289. }
  290. getSessions() {
  291. return this.connection.jingle.sessions;
  292. }
  293. /**
  294. * Disconnects this from the XMPP server (if this is connected).
  295. *
  296. * @param ev optionally, the event which triggered the necessity to
  297. * disconnect from the XMPP server (e.g. beforeunload, unload).
  298. */
  299. disconnect(ev) {
  300. if (this.disconnectInProgress
  301. || !this.connection
  302. || !this.connection.connected) {
  303. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  304. return;
  305. }
  306. this.disconnectInProgress = true;
  307. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  308. // means that there may not be enough time to send an unavailable
  309. // presence or disconnect at all. Switching Strophe to synchronous
  310. // sending is not much of an option because it may lead to a noticeable
  311. // delay in navigating away from the current location. As a compromise,
  312. // we will try to increase the chances of sending an unavailable
  313. // presence and/or disconecting within the short time span that we have
  314. // upon unloading by invoking flush() on the connection. We flush() once
  315. // before disconnect() in order to attemtp to have its unavailable
  316. // presence at the top of the send queue. We flush() once more after
  317. // disconnect() in order to attempt to have its unavailable presence
  318. // sent as soon as possible.
  319. this.connection.flush();
  320. if (ev !== null && typeof ev !== 'undefined') {
  321. const evType = ev.type;
  322. if (evType === 'beforeunload' || evType === 'unload') {
  323. // XXX Whatever we said above, synchronous sending is the best
  324. // (known) way to properly disconnect from the XMPP server.
  325. // Consequently, it may be fine to have the source code and
  326. // comment it in or out depending on whether we want to run with
  327. // it for some time.
  328. this.connection.options.sync = true;
  329. }
  330. }
  331. this.connection.disconnect();
  332. if (this.connection.options.sync !== true) {
  333. this.connection.flush();
  334. }
  335. }
  336. _initStrophePlugins() {
  337. initEmuc(this);
  338. initJingle(this, this.eventEmitter);
  339. initStropheUtil();
  340. initPing(this);
  341. initRayo();
  342. initStropheLogger();
  343. }
  344. }