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

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