Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

xmpp.js 15KB

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