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

xmpp.js 16KB

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