Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

xmpp.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /* global $, APP, config, Strophe */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var EventEmitter = require("events");
  4. var Pako = require("pako");
  5. var RTCEvents = require("../../service/RTC/RTCEvents");
  6. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  8. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  9. var RTC = require("../RTC/RTC");
  10. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11. var authenticatedUser = false;
  12. function createConnection(bosh, token) {
  13. bosh = bosh || '/http-bind';
  14. // Append token as URL param
  15. if (token) {
  16. bosh += (bosh.indexOf('?') == -1 ? '?' : '&') + 'token=' + token;
  17. }
  18. return new Strophe.Connection(bosh);
  19. };
  20. //!!!!!!!!!! FIXME: ...
  21. function initStrophePlugins(XMPP) {
  22. require("./strophe.emuc")(XMPP);
  23. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  24. // require("./strophe.moderate")(XMPP, eventEmitter);
  25. require("./strophe.util")();
  26. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  27. require("./strophe.rayo")();
  28. require("./strophe.logger")();
  29. }
  30. function XMPP(options, token) {
  31. this.eventEmitter = new EventEmitter();
  32. this.connection = null;
  33. this.disconnectInProgress = false;
  34. this.connectionTimes = {};
  35. this.forceMuted = false;
  36. this.options = options;
  37. initStrophePlugins(this);
  38. this.connection = createConnection(options.bosh, token);
  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. XMPP.prototype.initFeaturesList = function () {
  52. var disco = this.connection.disco;
  53. if (disco) {
  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 (this.options.enableLipSync && RTCBrowserType.isChrome()) {
  75. logger.info("Lip-sync enabled !");
  76. this.connection.disco.addFeature('http://jitsi.org/meet/lipsync');
  77. }
  78. }
  79. };
  80. XMPP.prototype.getConnection = function () { 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. XMPP.prototype.connectionHandler = function (password, status, msg) {
  88. var now = window.performance.now();
  89. this.connectionTimes[Strophe.getStatusString(status).toLowerCase()] = now;
  90. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  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. 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. this.disconnectInProgress = false;
  129. if (this.anonymousConnectionFailed) {
  130. // prompt user for username and password
  131. this.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  132. JitsiConnectionErrors.PASSWORD_REQUIRED);
  133. } else if(this.connectionFailed) {
  134. this.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  135. JitsiConnectionErrors.OTHER_ERROR,
  136. msg ? msg : this.lastErrorMsg);
  137. } else {
  138. this.eventEmitter.emit(
  139. JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  140. msg ? msg : this.lastErrorMsg);
  141. }
  142. } else if (status === Strophe.Status.AUTHFAIL) {
  143. // wrong password or username, prompt user
  144. this.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  145. JitsiConnectionErrors.PASSWORD_REQUIRED);
  146. }
  147. }
  148. XMPP.prototype._connect = function (jid, password) {
  149. // connection.connect() starts the connection process.
  150. //
  151. // As the connection process proceeds, the user supplied callback will
  152. // be triggered multiple times with status updates. The callback should
  153. // take two arguments - the status code and the error condition.
  154. //
  155. // The status code will be one of the values in the Strophe.Status
  156. // constants. The error condition will be one of the conditions defined
  157. // in RFC 3920 or the condition ‘strophe-parsererror’.
  158. //
  159. // The Parameters wait, hold and route are optional and only relevant
  160. // for BOSH connections. Please see XEP 124 for a more detailed
  161. // explanation of the optional parameters.
  162. //
  163. // Connection status constants for use by the connection handler
  164. // callback.
  165. //
  166. // Status.ERROR - An error has occurred (websockets specific)
  167. // Status.CONNECTING - The connection is currently being made
  168. // Status.CONNFAIL - The connection attempt failed
  169. // Status.AUTHENTICATING - The connection is authenticating
  170. // Status.AUTHFAIL - The authentication attempt failed
  171. // Status.CONNECTED - The connection has succeeded
  172. // Status.DISCONNECTED - The connection has been terminated
  173. // Status.DISCONNECTING - The connection is currently being terminated
  174. // Status.ATTACHED - The connection has been attached
  175. this.anonymousConnectionFailed = false;
  176. this.connectionFailed = false;
  177. this.lastErrorMsg = undefined;
  178. this.connection.connect(jid, password,
  179. this.connectionHandler.bind(this, password));
  180. }
  181. /**
  182. * Attach to existing connection. Can be used for optimizations. For example:
  183. * if the connection is created on the server we can attach to it and start
  184. * using it.
  185. *
  186. * @param options {object} connecting options - rid, sid, jid and password.
  187. */
  188. XMPP.prototype.attach = function (options) {
  189. var now = this.connectionTimes["attaching"] = window.performance.now();
  190. logger.log("(TIME) Strophe Attaching\t:" + now);
  191. this.connection.attach(options.jid, options.sid, parseInt(options.rid,10)+1,
  192. this.connectionHandler.bind(this, options.password));
  193. }
  194. XMPP.prototype.connect = function (jid, password) {
  195. if (!jid) {
  196. var configDomain
  197. = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  198. // Force authenticated domain if room is appended with '?login=true'
  199. // or if we're joining with the token
  200. if (this.options.hosts.anonymousdomain
  201. && (window.location.search.indexOf("login=true") !== -1
  202. || this.options.token)) {
  203. configDomain = this.options.hosts.domain;
  204. }
  205. jid = configDomain || window.location.hostname;
  206. }
  207. return this._connect(jid, password);
  208. };
  209. XMPP.prototype.createRoom = function (roomName, options, settings) {
  210. var roomjid = roomName + '@' + this.options.hosts.muc;
  211. if (options.useNicks) {
  212. if (options.nick) {
  213. roomjid += '/' + options.nick;
  214. } else {
  215. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  216. }
  217. } else {
  218. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  219. if (!authenticatedUser)
  220. tmpJid = tmpJid.substr(0, 8);
  221. roomjid += '/' + tmpJid;
  222. }
  223. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  224. }
  225. XMPP.prototype.addListener = function(type, listener) {
  226. this.eventEmitter.on(type, listener);
  227. };
  228. XMPP.prototype.removeListener = function (type, listener) {
  229. this.eventEmitter.removeListener(type, listener);
  230. };
  231. /**
  232. * Sends 'data' as a log message to the focus. Returns true iff a message
  233. * was sent.
  234. * @param data
  235. * @returns {boolean} true iff a message was sent.
  236. */
  237. XMPP.prototype.sendLogs = function (data) {
  238. if (!this.connection.emuc.focusMucJid)
  239. return false;
  240. var deflate = true;
  241. var content = JSON.stringify(data);
  242. if (deflate) {
  243. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  244. }
  245. content = Base64.encode(content);
  246. // XEP-0337-ish
  247. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  248. message.c('log', {xmlns: 'urn:xmpp:eventlog', id: 'PeerConnectionStats'});
  249. message.c('message').t(content).up();
  250. if (deflate) {
  251. message.c('tag', {name: "deflated", value: "true"}).up();
  252. }
  253. message.up();
  254. this.connection.send(message);
  255. return true;
  256. };
  257. // Gets the logs from strophe.jingle.
  258. XMPP.prototype.getJingleLog = function () {
  259. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  260. };
  261. // Gets the logs from strophe.
  262. XMPP.prototype.getXmppLog = function () {
  263. return this.connection.logger ? this.connection.logger.log : null;
  264. };
  265. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  266. this.connection.rayo.dial(to, from, roomName,roomPass);
  267. };
  268. XMPP.prototype.setMute = function (jid, mute) {
  269. this.connection.moderate.setMute(jid, mute);
  270. };
  271. XMPP.prototype.eject = function (jid) {
  272. this.connection.moderate.eject(jid);
  273. };
  274. XMPP.prototype.getSessions = function () {
  275. return this.connection.jingle.sessions;
  276. };
  277. /**
  278. * Disconnects this from the XMPP server (if this is connected).
  279. *
  280. * @param ev optionally, the event which triggered the necessity to disconnect
  281. * from the XMPP server (e.g. beforeunload, unload)
  282. */
  283. XMPP.prototype.disconnect = function (ev) {
  284. if (this.disconnectInProgress
  285. || !this.connection
  286. || !this.connection.connected) {
  287. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  288. return;
  289. }
  290. this.disconnectInProgress = true;
  291. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  292. // means that there may not be enough time to send an unavailable presence
  293. // or disconnect at all. Switching Strophe to synchronous sending is not
  294. // much of an option because it may lead to a noticeable delay in navigating
  295. // away from the current location. As a compromise, we will try to increase
  296. // the chances of sending an unavailable presence and/or disconecting within
  297. // the short time span that we have upon unloading by invoking flush() on
  298. // the connection. We flush() once before disconnect() in order to attemtp
  299. // to have its unavailable presence at the top of the send queue. We flush()
  300. // once more after disconnect() in order to attempt to have its unavailable
  301. // presence sent as soon as possible.
  302. this.connection.flush();
  303. if (ev !== null && typeof ev !== 'undefined') {
  304. var evType = ev.type;
  305. if (evType == 'beforeunload' || evType == 'unload') {
  306. // XXX Whatever we said above, synchronous sending is the best
  307. // (known) way to properly disconnect from the XMPP server.
  308. // Consequently, it may be fine to have the source code and comment
  309. // it in or out depending on whether we want to run with it for some
  310. // time.
  311. this.connection.options.sync = true;
  312. }
  313. }
  314. this.connection.disconnect();
  315. if (this.connection.options.sync !== true) {
  316. this.connection.flush();
  317. }
  318. };
  319. module.exports = XMPP;