您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

xmpp.js 15KB

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