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

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