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

xmpp.js 15KB

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