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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. let authenticatedUser = true;
  20. function createConnection(token, bosh = '/http-bind') {
  21. // Append token as URL param
  22. if (token) {
  23. bosh += (bosh.indexOf('?') == -1 ? '?' : '&') + 'token=' + token;
  24. }
  25. return new Strophe.Connection(bosh);
  26. };
  27. export default class XMPP {
  28. constructor(options, token) {
  29. this.eventEmitter = new EventEmitter();
  30. this.connection = null;
  31. this.disconnectInProgress = false;
  32. this.connectionTimes = {};
  33. this.forceMuted = false;
  34. this.options = options;
  35. this.connectParams = {};
  36. this.token = token;
  37. this._initStrophePlugins(this);
  38. this.connection = createConnection(options.bosh, token);
  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. 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. let tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  221. let roomjid = roomName + "@" + this.options.hosts.muc + "/";
  222. roomjid += (options.useNicks)? options.nick || tmpJid :
  223. (authenticatedUser? "-" + RandomUtil.randomHexString(6):
  224. tmpJid.substr(0, 8));
  225. return this.connection.emuc.createRoom(roomjid, null, options,
  226. settings);
  227. }
  228. addListener (type, listener) {
  229. this.eventEmitter.on(type, listener);
  230. }
  231. removeListener (type, listener) {
  232. this.eventEmitter.removeListener(type, listener);
  233. };
  234. /**
  235. * Sends 'data' as a log message to the focus. Returns true iff a message
  236. * was sent.
  237. * @param data
  238. * @returns {boolean} true iff a message was sent.
  239. */
  240. sendLogs (data) {
  241. if (!this.connection.emuc.focusMucJid)
  242. return false;
  243. const content = Base64.encode(
  244. String.fromCharCode.apply(null,
  245. Pako.deflateRaw(JSON.stringify(data))));
  246. // XEP-0337-ish
  247. const message = $msg({
  248. to: this.connection.emuc.focusMucJid,
  249. type: "normal"
  250. });
  251. message.c("log", {
  252. xmlns: "urn:xmpp:eventlog",
  253. id: "PeerConnectionStats"
  254. });
  255. message.c("message").t(content).up();
  256. message.c("tag", {name: "deflated", value: "true"}).up();
  257. message.up();
  258. this.connection.send(message);
  259. return true;
  260. }
  261. /**
  262. * Returns the logs from strophe.jingle.
  263. * @returns {Object}
  264. */
  265. getJingleLog () {
  266. const jingle = this.connection.jingle;
  267. return jingle? jingle.getLog() : {};
  268. }
  269. /**
  270. * Returns the logs from strophe.
  271. */
  272. getXmppLog () {
  273. return (this.connection.logger || {}).log || null;
  274. }
  275. dial (to, from, roomName,roomPass) {
  276. this.connection.rayo.dial(to, from, roomName,roomPass);
  277. }
  278. setMute (jid, mute) {
  279. this.connection.moderate.setMute(jid, mute);
  280. }
  281. eject (jid) {
  282. this.connection.moderate.eject(jid);
  283. }
  284. getSessions () {
  285. return this.connection.jingle.sessions;
  286. }
  287. /**
  288. * Disconnects this from the XMPP server (if this is connected).
  289. *
  290. * @param ev optionally, the event which triggered the necessity to disconnect
  291. * from the XMPP server (e.g. beforeunload, unload)
  292. */
  293. disconnect (ev) {
  294. if (this.disconnectInProgress
  295. || !this.connection
  296. || !this.connection.connected) {
  297. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  298. return;
  299. }
  300. this.disconnectInProgress = true;
  301. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  302. // means that there may not be enough time to send an unavailable presence
  303. // or disconnect at all. Switching Strophe to synchronous sending is not
  304. // much of an option because it may lead to a noticeable delay in navigating
  305. // away from the current location. As a compromise, we will try to increase
  306. // the chances of sending an unavailable presence and/or disconecting within
  307. // the short time span that we have upon unloading by invoking flush() on
  308. // the connection. We flush() once before disconnect() in order to attemtp
  309. // to have its unavailable presence at the top of the send queue. We flush()
  310. // once more after disconnect() in order to attempt to have its unavailable
  311. // presence sent as soon as possible.
  312. this.connection.flush();
  313. if (ev !== null && typeof ev !== 'undefined') {
  314. const evType = ev.type;
  315. if (evType == 'beforeunload' || evType == 'unload') {
  316. // XXX Whatever we said above, synchronous sending is the best
  317. // (known) way to properly disconnect from the XMPP server.
  318. // Consequently, it may be fine to have the source code and comment
  319. // it in or out depending on whether we want to run with it for some
  320. // time.
  321. this.connection.options.sync = true;
  322. }
  323. }
  324. this.connection.disconnect();
  325. if (this.connection.options.sync !== true) {
  326. this.connection.flush();
  327. }
  328. }
  329. _initStrophePlugins() {
  330. initEmuc(this);
  331. initJingle(this, this.eventEmitter);
  332. initStropheUtil();
  333. initPing(this, this.eventEmitter);
  334. initRayo();
  335. initStropheLogger();
  336. }
  337. }