Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 authenticatedUser = false;
  11. function createConnection(bosh) {
  12. bosh = bosh || '/http-bind';
  13. // Append token as URL param
  14. if (this.token) {
  15. bosh += (bosh.indexOf('?') == -1 ? '?' : '&') + 'token=' + this.token;
  16. }
  17. return new Strophe.Connection(bosh);
  18. };
  19. //!!!!!!!!!! FIXME: ...
  20. function initStrophePlugins(XMPP) {
  21. require("./strophe.emuc")(XMPP);
  22. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  23. // require("./strophe.moderate")(XMPP, eventEmitter);
  24. require("./strophe.util")();
  25. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  26. require("./strophe.rayo")();
  27. require("./strophe.logger")();
  28. }
  29. function XMPP(options) {
  30. this.eventEmitter = new EventEmitter();
  31. this.connection = null;
  32. this.disconnectInProgress = false;
  33. this.forceMuted = false;
  34. this.options = options;
  35. initStrophePlugins(this);
  36. this.connection = createConnection(options.bosh);
  37. // Setup a disconnect on unload as a way to facilitate API consumers. It
  38. // sounds like they would want that. A problem for them though may be if
  39. // they wanted to utilize the connected connection in an unload handler of
  40. // their own. However, it should be fairly easy for them to do that by
  41. // registering their unload handler before us.
  42. $(window).on('beforeunload unload', this.disconnect.bind(this));
  43. }
  44. XMPP.prototype.getConnection = function () { return this.connection; };
  45. XMPP.prototype._connect = function (jid, password) {
  46. var self = this;
  47. // connection.connect() starts the connection process.
  48. //
  49. // As the connection process proceeds, the user supplied callback will
  50. // be triggered multiple times with status updates. The callback should
  51. // take two arguments - the status code and the error condition.
  52. //
  53. // The status code will be one of the values in the Strophe.Status
  54. // constants. The error condition will be one of the conditions defined
  55. // in RFC 3920 or the condition ‘strophe-parsererror’.
  56. //
  57. // The Parameters wait, hold and route are optional and only relevant
  58. // for BOSH connections. Please see XEP 124 for a more detailed
  59. // explanation of the optional parameters.
  60. //
  61. // Connection status constants for use by the connection handler
  62. // callback.
  63. //
  64. // Status.ERROR - An error has occurred (websockets specific)
  65. // Status.CONNECTING - The connection is currently being made
  66. // Status.CONNFAIL - The connection attempt failed
  67. // Status.AUTHENTICATING - The connection is authenticating
  68. // Status.AUTHFAIL - The authentication attempt failed
  69. // Status.CONNECTED - The connection has succeeded
  70. // Status.DISCONNECTED - The connection has been terminated
  71. // Status.DISCONNECTING - The connection is currently being terminated
  72. // Status.ATTACHED - The connection has been attached
  73. var anonymousConnectionFailed = false;
  74. var connectionFailed = false;
  75. var lastErrorMsg;
  76. this.connection.connect(jid, password, function (status, msg) {
  77. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  78. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  79. if (status === Strophe.Status.CONNECTED) {
  80. if (self.options.useStunTurn) {
  81. self.connection.jingle.getStunAndTurnCredentials();
  82. }
  83. logger.info("My Jabber ID: " + self.connection.jid);
  84. // Schedule ping ?
  85. var pingJid = self.connection.domain;
  86. self.connection.ping.hasPingSupport(
  87. pingJid,
  88. function (hasPing) {
  89. if (hasPing)
  90. self.connection.ping.startInterval(pingJid);
  91. else
  92. logger.warn("Ping NOT supported by " + pingJid);
  93. }
  94. );
  95. if (password)
  96. authenticatedUser = true;
  97. if (self.connection && self.connection.connected &&
  98. Strophe.getResourceFromJid(self.connection.jid)) {
  99. // .connected is true while connecting?
  100. // self.connection.send($pres());
  101. self.eventEmitter.emit(
  102. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  103. Strophe.getResourceFromJid(self.connection.jid));
  104. }
  105. } else if (status === Strophe.Status.CONNFAIL) {
  106. if (msg === 'x-strophe-bad-non-anon-jid') {
  107. anonymousConnectionFailed = true;
  108. } else {
  109. connectionFailed = true;
  110. }
  111. lastErrorMsg = msg;
  112. } else if (status === Strophe.Status.DISCONNECTED) {
  113. // Stop ping interval
  114. self.connection.ping.stopInterval();
  115. self.disconnectInProgress = false;
  116. if (anonymousConnectionFailed) {
  117. // prompt user for username and password
  118. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  119. JitsiConnectionErrors.PASSWORD_REQUIRED);
  120. } else if(connectionFailed) {
  121. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  122. JitsiConnectionErrors.OTHER_ERROR,
  123. msg ? msg : lastErrorMsg);
  124. } else {
  125. self.eventEmitter.emit(
  126. JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  127. msg ? msg : lastErrorMsg);
  128. }
  129. } else if (status === Strophe.Status.AUTHFAIL) {
  130. // wrong password or username, prompt user
  131. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  132. JitsiConnectionErrors.PASSWORD_REQUIRED);
  133. }
  134. });
  135. }
  136. XMPP.prototype.connect = function (jid, password) {
  137. if (!jid) {
  138. var configDomain
  139. = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  140. // Force authenticated domain if room is appended with '?login=true'
  141. if (this.options.hosts.anonymousdomain
  142. && window.location.search.indexOf("login=true") !== -1) {
  143. configDomain = this.options.hosts.domain;
  144. }
  145. jid = configDomain || window.location.hostname;
  146. }
  147. return this._connect(jid, password);
  148. };
  149. XMPP.prototype.createRoom = function (roomName, options, settings) {
  150. var roomjid = roomName + '@' + this.options.hosts.muc;
  151. if (options.useNicks) {
  152. if (options.nick) {
  153. roomjid += '/' + options.nick;
  154. } else {
  155. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  156. }
  157. } else {
  158. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  159. if (!authenticatedUser)
  160. tmpJid = tmpJid.substr(0, 8);
  161. roomjid += '/' + tmpJid;
  162. }
  163. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  164. }
  165. XMPP.prototype.addListener = function(type, listener) {
  166. this.eventEmitter.on(type, listener);
  167. };
  168. XMPP.prototype.removeListener = function (type, listener) {
  169. this.eventEmitter.removeListener(type, listener);
  170. };
  171. //FIXME: this should work with the room
  172. XMPP.prototype.leaveRoom = function (jid) {
  173. var handler = this.connection.jingle.jid2session[jid];
  174. if (handler && handler.peerconnection) {
  175. // FIXME: probably removing streams is not required and close() should
  176. // be enough
  177. if (RTC.localAudio) {
  178. handler.peerconnection.removeStream(
  179. RTC.localAudio.getOriginalStream(), true);
  180. }
  181. if (RTC.localVideo) {
  182. handler.peerconnection.removeStream(
  183. RTC.localVideo.getOriginalStream(), true);
  184. }
  185. handler.peerconnection.close();
  186. }
  187. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  188. this.connection.emuc.doLeave(jid);
  189. };
  190. /**
  191. * Sends 'data' as a log message to the focus. Returns true iff a message
  192. * was sent.
  193. * @param data
  194. * @returns {boolean} true iff a message was sent.
  195. */
  196. XMPP.prototype.sendLogs = function (data) {
  197. if (!this.connection.emuc.focusMucJid)
  198. return false;
  199. var deflate = true;
  200. var content = JSON.stringify(data);
  201. if (deflate) {
  202. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  203. }
  204. content = Base64.encode(content);
  205. // XEP-0337-ish
  206. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  207. message.c('log', {xmlns: 'urn:xmpp:eventlog', id: 'PeerConnectionStats'});
  208. message.c('message').t(content).up();
  209. if (deflate) {
  210. message.c('tag', {name: "deflated", value: "true"}).up();
  211. }
  212. message.up();
  213. this.connection.send(message);
  214. return true;
  215. };
  216. // Gets the logs from strophe.jingle.
  217. XMPP.prototype.getJingleLog = function () {
  218. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  219. };
  220. // Gets the logs from strophe.
  221. XMPP.prototype.getXmppLog = function () {
  222. return this.connection.logger ? this.connection.logger.log : null;
  223. };
  224. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  225. this.connection.rayo.dial(to, from, roomName,roomPass);
  226. };
  227. XMPP.prototype.setMute = function (jid, mute) {
  228. this.connection.moderate.setMute(jid, mute);
  229. };
  230. XMPP.prototype.eject = function (jid) {
  231. this.connection.moderate.eject(jid);
  232. };
  233. XMPP.prototype.getSessions = function () {
  234. return this.connection.jingle.sessions;
  235. };
  236. /**
  237. * Disconnects this from the XMPP server (if this is connected).
  238. *
  239. * @param ev optionally, the event which triggered the necessity to disconnect
  240. * from the XMPP server (e.g. beforeunload, unload)
  241. */
  242. XMPP.prototype.disconnect = function (ev) {
  243. if (this.disconnectInProgress
  244. || !this.connection
  245. || !this.connection.connected) {
  246. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  247. return;
  248. }
  249. this.disconnectInProgress = true;
  250. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  251. // means that there may not be enough time to send an unavailable presence
  252. // or disconnect at all. Switching Strophe to synchronous sending is not
  253. // much of an option because it may lead to a noticeable delay in navigating
  254. // away from the current location. As a compromise, we will try to increase
  255. // the chances of sending an unavailable presence and/or disconecting within
  256. // the short time span that we have upon unloading by invoking flush() on
  257. // the connection. We flush() once before disconnect() in order to attemtp
  258. // to have its unavailable presence at the top of the send queue. We flush()
  259. // once more after disconnect() in order to attempt to have its unavailable
  260. // presence sent as soon as possible.
  261. this.connection.flush();
  262. if (ev !== null && typeof ev !== 'undefined') {
  263. var evType = ev.type;
  264. if (evType == 'beforeunload' || evType == 'unload') {
  265. // XXX Whatever we said above, synchronous sending is the best
  266. // (known) way to properly disconnect from the XMPP server.
  267. // Consequently, it may be fine to have the source code and comment
  268. // it in or out depending on whether we want to run with it for some
  269. // time.
  270. this.connection.options.sync = true;
  271. }
  272. }
  273. this.connection.disconnect();
  274. if (this.connection.options.sync !== true) {
  275. this.connection.flush();
  276. }
  277. };
  278. module.exports = XMPP;