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.

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