From 7ab4d125481b4f9ead137999efaa508da2689699 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 29 Jun 2017 15:07:17 +0200 Subject: [PATCH 1/7] Better error resilience against wrong user manager Also improved get_class by using importlib instead of complicated climbing through the whole module tree. --- src/octoprint/server/__init__.py | 2 +- src/octoprint/util/__init__.py | 18 +++++++++--------- tests/util/test_misc.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 10 deletions(-) create mode 100644 tests/util/test_misc.py diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index bf922010c..0b0b9f5b0 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -210,7 +210,7 @@ class Server(object): try: clazz = octoprint.util.get_class(userManagerName) userManager = clazz() - except AttributeError as e: + except: self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName)) userManager = octoprint.users.FilebasedUserManager() finally: diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 84dd955f4..d43733ce2 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -174,8 +174,6 @@ def get_class(name): """ Retrieves the class object for a given fully qualified class name. - Taken from http://stackoverflow.com/a/452981/2028598. - Arguments: name (string): The fully qualified class name, including all modules separated by ``.`` @@ -183,15 +181,17 @@ def get_class(name): type: The class if it could be found. Raises: - AttributeError: The class could not be found. + ImportError """ - parts = name.split(".") - module = ".".join(parts[:-1]) - m = __import__(module) - for comp in parts[1:]: - m = getattr(m, comp) - return m + import importlib + + mod_name, cls_name = name.rsplit(".", 1) + m = importlib.import_module(mod_name) + try: + return getattr(m, cls_name) + except AttributeError: + raise ImportError("No module named " + name) def get_exception_string(): diff --git a/tests/util/test_misc.py b/tests/util/test_misc.py new file mode 100644 index 000000000..644654b76 --- /dev/null +++ b/tests/util/test_misc.py @@ -0,0 +1,31 @@ +# coding=utf-8 +from __future__ import absolute_import + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import unittest + +import octoprint.util + +class MiscTestCase(unittest.TestCase): + + def test_get_class(self): + octoprint.util.get_class("octoprint.users.FilebasedUserManager") + + def test_get_class_wrongmodule(self): + try: + octoprint.util.get_class("octoprint2.users.FilebasedUserManager") + self.fail("This should have thrown an ImportError") + except ImportError: + # success + pass + + def test_get_class_wrongclass(self): + try: + octoprint.util.get_class("octoprint.users.FilebasedUserManagerBzzztWrong") + self.fail("This should have thrown an ImportError") + except ImportError: + # success + pass From b205e84d4bb04b6de7751ab88daff63fd825c547 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 29 Jun 2017 15:42:19 +0200 Subject: [PATCH 2/7] Refactored web startup to minimise risks of race conditions Under specific circumstances it could happen that the passive login response was overtaken by a response from an earlier still unauthenticated request which would then effectively overwrite the session cookie immediately and hence cause the browser to use its login session against the server, but without displaying that to the user. See #1881 for what is probably an issue caused by exactly this kind of scenario. Additionally a couple of requests needed to be done a second time after login, just moments after having done them for an anonymous user. See #1572 for a request to change this behaviour. This patch changes the startup order of the web interface like this: 1. connect to the websocket, postpone any events triggered by this (e.g. "fromHistoryData") until 3 2. perform a passive login, postpone any events triggered by this (e.g. "onUserLoggedIn", "onUserLoggedOut") until 4 3. trigger postponed events from 1 4. trigger "onStartup" (triggers postponed events from 2) 5. fetch settings 6. bind view models etc A connection close of the websocket will disable event processing on the socket until it is marked as initialized again by the passive login processing, which will also be triggered immediately on server connect. That way under normal circumstances nothing should ever get triggered in the registered view models that might generated requests to the server API until a passive login has been done, a server session initialized and if necessary a user properly authenticated. --- src/octoprint/static/js/app/client/socket.js | 5 + src/octoprint/static/js/app/dataupdater.js | 249 +++++++++++------- src/octoprint/static/js/app/main.js | 79 ++++-- .../static/js/app/viewmodels/gcode.js | 2 +- .../static/js/app/viewmodels/loginstate.js | 43 +-- .../static/js/app/viewmodels/settings.js | 7 + .../static/js/app/viewmodels/timelapse.js | 4 - 7 files changed, 244 insertions(+), 145 deletions(-) diff --git a/src/octoprint/static/js/app/client/socket.js b/src/octoprint/static/js/app/client/socket.js index c12030a11..b1d70b7a4 100644 --- a/src/octoprint/static/js/app/client/socket.js +++ b/src/octoprint/static/js/app/client/socket.js @@ -106,6 +106,7 @@ var onOpen = function() { self.reconnecting = false; self.reconnectTrial = 0; + self.onConnected(); }; var onClose = function(e) { @@ -117,6 +118,8 @@ return; } + self.onDisconnected(e.code); + if (self.reconnectTrial < self.options.timeouts.length) { var timeout = self.options.timeouts[self.reconnectTrial]; setTimeout(function() { self.reconnect() }, timeout * 1000); @@ -160,6 +163,8 @@ OctoPrintSocketClient.prototype.onReconnectAttempt = function(trial) {}; OctoPrintSocketClient.prototype.onReconnectFailed = function() {}; + OctoPrintSocketClient.prototype.onConnected = function() {}; + OctoPrintSocketClient.prototype.onDisconnected = function(code) {}; OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) { this.increaseRate(); diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index 3c9dfbf44..108313032 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -1,13 +1,17 @@ -function DataUpdater(allViewModels) { +function DataUpdater(allViewModels, connectCallback, disconnectCallback) { var self = this; self.allViewModels = allViewModels; + self.connectCallback = connectCallback; + self.disconnectCallback = disconnectCallback; self._pluginHash = undefined; self._configHash = undefined; self._connectedDeferred = undefined; + self._initializedDeferred = undefined; + self._throttleFactor = 1; self._baseProcessingLimit = 500.0; self._lastProcessingTimes = []; @@ -57,6 +61,13 @@ function DataUpdater(allViewModels) { return self._connectedDeferred.promise(); }; + self.initialized = function() { + if (self._initializedDeferred) { + self._initializedDeferred.resolve(); + self._initializedDeferred = undefined; + } + }; + self._onReconnectAttempt = function(trial) { if (trial <= 0) { // Only consider it a real disconnect if the trial number has exceeded our threshold. @@ -99,7 +110,27 @@ function DataUpdater(allViewModels) { $("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.")); }; - self._onConnected = function(event) { + self._onDisconnected = function(code) { + if (self._initializedDeferred) { + self._initializedDeferred.reject(); + } + self._initializedDeferred = undefined; + + if (self.disconnectCallback) { + self.disconnectCallback(); + } + }; + + self._onConnectMessage = function(event) { + if (self._initializedDeferred) { + self._initializedDeferred.reject(); + } + self._initializedDeferred = $.Deferred(); + + if (self.connectCallback) { + self.connectCallback(); + } + var data = event.data; // update version information @@ -117,37 +148,40 @@ function DataUpdater(allViewModels) { var oldConfigHash = self._configHash; self._configHash = data["config_hash"]; - // process safe mode - if (self._safeModePopup) self._safeModePopup.remove(); - if (data["safe_mode"]) { - // safe mode is active, let's inform the user - log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled."); + self._ifInitialized(function() { + // process safe mode + if (self._safeModePopup) self._safeModePopup.remove(); + if (data["safe_mode"]) { + // safe mode is active, let's inform the user + log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled."); - self._safeModePopup = new PNotify({ - title: gettext("Safe mode is active"), - text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."), - hide: false - }); - } + self._safeModePopup = new PNotify({ + title: gettext("Safe mode is active"), + text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."), + hide: false + }); + } - // if the offline overlay is still showing, now's a good time to - // hide it, plus reload the camera feed if it's currently displayed - if ($("#offline_overlay").is(":visible")) { - hideOfflineOverlay(); - callViewModels(self.allViewModels, "onServerReconnect"); - callViewModels(self.allViewModels, "onDataUpdaterReconnect"); - } else { - callViewModels(self.allViewModels, "onServerConnect"); - } + // if the offline overlay is still showing, now's a good time to + // hide it, plus reload the camera feed if it's currently displayed + if ($("#offline_overlay").is(":visible")) { + hideOfflineOverlay(); + callViewModels(self.allViewModels, "onServerReconnect"); + callViewModels(self.allViewModels, "onDataUpdaterReconnect"); + } else { + callViewModels(self.allViewModels, "onServerConnect"); + } - // if the version, the plugin hash or the config hash changed, we - // want the user to reload the UI since it might be stale now - var versionChanged = oldVersion != VERSION; - var pluginsChanged = oldPluginHash != undefined && oldPluginHash != self._pluginHash; - var configChanged = oldConfigHash != undefined && oldConfigHash != self._configHash; - if (versionChanged || pluginsChanged || configChanged) { - showReloadOverlay(); - } + // if the version, the plugin hash or the config hash changed, we + // want the user to reload the UI since it might be stale now + var versionChanged = oldVersion !== VERSION; + var pluginsChanged = oldPluginHash !== undefined && oldPluginHash !== self._pluginHash; + var configChanged = oldConfigHash !== undefined && oldConfigHash !== self._configHash; + if (versionChanged || pluginsChanged || configChanged) { + showReloadOverlay(); + } + + }); log.info("Connected to the server"); @@ -159,81 +193,89 @@ function DataUpdater(allViewModels) { }; self._onHistoryData = function(event) { - callViewModels(self.allViewModels, "fromHistoryData", [event.data]); - }; - - self._onCurrentData = function(event) { - callViewModels(self.allViewModels, "fromCurrentData", [event.data]); - }; - - self._onSlicingProgress = function(event) { - $("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])})); - - var data = event.data; - callViewModels(self.allViewModels, "onSlicingProgress", [ - data["slicer"], - data["model_path"], - data["machinecode_path"], - data["progress"] - ]); - }; - - self._onEvent = function(event) { - var gcodeUploadProgress = $("#gcode_upload_progress"); - var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress); - - var type = event.data["type"]; - var payload = event.data["payload"]; - var html = ""; - - log.debug("Got event " + type + " with payload: " + JSON.stringify(payload)); - - if (type == "PrintCancelled") { - if (payload.firmwareError) { - new PNotify({ - title: gettext("Unhandled communication error"), - text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload), - type: "error", - hide: false - }); - } - } else if (type == "Error") { - if (payload.error && payload.error.indexOf("autodetect") == -1) { // ignore "failed to autodetect" - new PNotify({ - title: gettext("Unhandled communication error"), - text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload), - type: "error", - hide: false - }); - } - } - - var legacyEventHandlers = { - "UpdatedFiles": "onUpdatedFiles", - "MetadataStatisticsUpdated": "onMetadataStatisticsUpdated", - "MetadataAnalysisFinished": "onMetadataAnalysisFinished", - "SlicingDone": "onSlicingDone", - "SlicingCancelled": "onSlicingCancelled", - "SlicingFailed": "onSlicingFailed" - }; - _.each(self.allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onEvent" + type)) { - viewModel["onEvent" + type](payload); - } else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) { - // there might still be code that uses the old callbacks, make sure those still get called - // but log a warning - log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]); - viewModel[legacyEventHandlers[type]](payload); - } + self._ifInitialized(function() { + callViewModels(self.allViewModels, "fromHistoryData", [event.data]); }); }; + self._onCurrentData = function(event) { + self._ifInitialized(function() { + callViewModels(self.allViewModels, "fromCurrentData", [event.data]); + }); + }; + + self._onSlicingProgress = function(event) { + self._ifInitialized(function() { + $("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])})); + + var data = event.data; + callViewModels(self.allViewModels, "onSlicingProgress", [ + data["slicer"], + data["model_path"], + data["machinecode_path"], + data["progress"] + ]); + }); + }; + + self._onEvent = function(event) { + self._ifInitialized(function() { + var type = event.data["type"]; + var payload = event.data["payload"]; + + log.debug("Got event " + type + " with payload: " + JSON.stringify(payload)); + + if (type == "PrintCancelled") { + if (payload.firmwareError) { + new PNotify({ + title: gettext("Unhandled communication error"), + text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload), + type: "error", + hide: false + }); + } + } else if (type == "Error") { + if (payload.error && payload.error.indexOf("autodetect") == -1) { // ignore "failed to autodetect" + new PNotify({ + title: gettext("Unhandled communication error"), + text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload), + type: "error", + hide: false + }); + } + } + + var legacyEventHandlers = { + "UpdatedFiles": "onUpdatedFiles", + "MetadataStatisticsUpdated": "onMetadataStatisticsUpdated", + "MetadataAnalysisFinished": "onMetadataAnalysisFinished", + "SlicingDone": "onSlicingDone", + "SlicingCancelled": "onSlicingCancelled", + "SlicingFailed": "onSlicingFailed" + }; + _.each(self.allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onEvent" + type)) { + viewModel["onEvent" + type](payload); + } else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) { + // there might still be code that uses the old callbacks, make sure those still get called + // but log a warning + log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]); + viewModel[legacyEventHandlers[type]](payload); + } + }); + }) + }; + self._onTimelapse = function(event) { - callViewModels(self.allViewModels, "fromTimelapseData", [event.data]); + self._ifInitialized(function() { + callViewModels(self.allViewModels, "fromTimelapseData", [event.data]); + }) }; self._onPluginMessage = function(event) { - callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]); + self._ifInitialized(function() { + callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]); + }) }; self._onIncreaseRate = function(measurement, minimum) { @@ -246,12 +288,21 @@ function DataUpdater(allViewModels) { OctoPrint.socket.decreaseRate(); }; + self._ifInitialized = function(callback) { + if (self._initializedDeferred) { + self._initializedDeferred.done(callback); + } else { + callback(); + } + }; + + OctoPrint.socket.onDisconnected = self._onDisconnected; OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt; OctoPrint.socket.onReconnectFailed = self._onReconnectFailed; OctoPrint.socket.onRateTooHigh = self._onDecreaseRate; OctoPrint.socket.onRateTooLow = self._onIncreaseRate; OctoPrint.socket - .onMessage("connected", self._onConnected) + .onMessage("connected", self._onConnectMessage) .onMessage("history", self._onHistoryData) .onMessage("current", self._onCurrentData) .onMessage("slicingProgress", self._onSlicingProgress) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index abd664ed2..d3e580b6c 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -552,7 +552,15 @@ $(function() { // reload overlay $("#reloadui_overlay_reload").click(function() { location.reload(); }); - //~~ view model binding + //~~ final initialization - passive login, settings fetch, view model binding + + if (!_.has(viewModelMap, "settingsViewModel")) { + throw new Error("settingsViewModel is missing, can't run UI"); + } + + if (!_.has(viewModelMap, "loginStateViewModel")) { + throw new Error("loginStateViewModel is missing, can't run UI"); + } var bindViewModels = function() { log.info("Going to bind " + allViewModelData.length + " view models..."); @@ -643,34 +651,55 @@ $(function() { log.info("Application startup complete"); }; - if (!_.has(viewModelMap, "settingsViewModel")) { - throw new Error("settingsViewModel is missing, can't run UI") - } + var fetchSettings = function() { + log.info("Finalizing application startup"); + + //~~ Starting up the app + callViewModels(allViewModels, "onStartup"); + + viewModelMap["settingsViewModel"].requestData() + .done(function() { + // There appears to be an odd race condition either in JQuery's AJAX implementation or + // the browser's implementation of XHR, causing a second GET request from inside the + // completion handler of the very same request to never get its completion handler called + // if ETag headers are present on the response (the status code of the request does NOT + // seem to matter here, only that the ETag header is present). + // + // Minimal example with which I was able to reproduce this behaviour can be found + // at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f + // + // Decoupling all consecutive calls from this done event handler hence is an easy way + // to avoid this problem. A zero timeout should do the trick nicely. + window.setTimeout(bindViewModels, 0); + }); + }; log.info("Initial application setup done, connecting to server..."); - var dataUpdater = new DataUpdater(allViewModels); + + var onServerConnect = function() { + // Always perform a passive login on server (re)connect. No need for + // onServerConnect/onServerReconnect with this in place. + viewModelMap["loginStateViewModel"].requestData() + .done(function() { + // Only mark our data updater as initialized once we've done our initial + // passive login request. + // + // This is to ensure that we have no concurrent requests overriding each other's + // session during app intialization, and has the additional benefit of reducing the + // number of required requests since we don't have re-request data that might have + // changed if we turn out to be logged in. + dataUpdater.initialized(); + }); + }; + + var dataUpdater = new DataUpdater(allViewModels, onServerConnect); dataUpdater.connect() .done(function() { - log.info("Finalizing application startup"); - - //~~ Starting up the app - callViewModels(allViewModels, "onStartup"); - - viewModelMap["settingsViewModel"].requestData() - .done(function() { - // There appears to be an odd race condition either in JQuery's AJAX implementation or - // the browser's implementation of XHR, causing a second GET request from inside the - // completion handler of the very same request to never get its completion handler called - // if ETag headers are present on the response (the status code of the request does NOT - // seem to matter here, only that the ETag header is present). - // - // Minimal example with which I was able to reproduce this behaviour can be found - // at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f - // - // Decoupling all consecutive calls from this done event handler hence is an easy way - // to avoid this problem. A zero timeout should do the trick nicely. - window.setTimeout(bindViewModels, 0); - }); + // onServerConnect will have been called just before this. + // + // Decoupled settings fetch, for the reasons see above's lengthy description + // on a weird JQuery AJAX issue with ETag headers and promise handling. + window.setTimeout(fetchSettings, 0); }); } ); diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index f96ac908b..75bd3439f 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -257,7 +257,7 @@ $(function() { self._configureLayerSlider(layerSliderElement); self._configureLayerCommandSlider(commandSliderElement); - self.settings.requestData() + self.settings.firstRequest .done(function() { var initResult = GCODE.ui.init({ container: "#gcode_canvas", diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js index ab3423c1a..e9c3b0510 100644 --- a/src/octoprint/static/js/app/viewmodels/loginstate.js +++ b/src/octoprint/static/js/app/viewmodels/loginstate.js @@ -12,6 +12,7 @@ $(function() { self.isUser = ko.observable(false); self.allViewModels = undefined; + self.startupDeferred = $.Deferred(); self.currentUser = ko.observable(undefined); @@ -36,28 +37,40 @@ $(function() { }); self.reloadUser = function() { - if (self.currentUser() == undefined) { + if (self.currentUser() === undefined) { return; } - OctoPrint.users.get(self.currentUser().name) + return OctoPrint.users.get(self.currentUser().name) .done(self.updateCurrentUserData); }; self.requestData = function() { - OctoPrint.browser.passiveLogin() + return OctoPrint.browser.passiveLogin() .done(self.fromResponse); }; self.fromResponse = function(response) { - if (response && response.name) { - self.loggedIn(true); - self.updateCurrentUserData(response); - callViewModels(self.allViewModels, "onUserLoggedIn", [response]); + var process = function() { + if (response && response.name) { + self.loggedIn(true); + self.updateCurrentUserData(response); + callViewModels(self.allViewModels, "onUserLoggedIn", [response]); + log.info("User " + response.name + " logged in") + } else { + self.loggedIn(false); + self.resetCurrentUserData(); + callViewModels(self.allViewModels, "onUserLoggedOut"); + log.info("User logged out"); + } + }; + + if (self.startupDeferred !== undefined) { + // Make sure we only fire our "onUserLogged(In|Out)" message when the application + // has started up. + self.startupDeferred.done(process); } else { - self.loggedIn(false); - self.resetCurrentUserData(); - callViewModels(self.allViewModels, "onUserLoggedOut"); + process(); } }; @@ -101,7 +114,7 @@ $(function() { }; self.logout = function() { - OctoPrint.browser.logout() + return OctoPrint.browser.logout() .done(function(response) { new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"}); self.fromResponse(response); @@ -124,12 +137,10 @@ $(function() { self.allViewModels = allViewModels; }; - self.onStartupComplete = self.onServerConnect = self.onServerReconnect = function() { - if (self.allViewModels == undefined) return; - self.requestData(); - }; - self.onStartup = function() { + self.startupDeferred.resolve(); + self.startupDeferred = undefined; + self.elementUsernameInput = $("#login_user"); self.elementPasswordInput = $("#login_pass"); self.elementLoginButton = $("#login_button"); diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 9f73fab26..38818533f 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -7,6 +7,11 @@ $(function() { self.printerProfiles = parameters[2]; self.about = parameters[3]; + // use this promise to do certain things once the SettingsViewModel has processed + // its first request + var firstRequest = $.Deferred(); + self.firstRequest = firstRequest.promise(); + self.allViewModels = []; self.receiving = ko.observable(false); @@ -763,6 +768,8 @@ $(function() { }; mapToObservables(serverChangedData, specialMappings, clientChangedData); + + firstRequest.resolve(); }; self.saveData = function (data, successCallback, setAsSending) { diff --git a/src/octoprint/static/js/app/viewmodels/timelapse.js b/src/octoprint/static/js/app/viewmodels/timelapse.js index 88c19a03a..e0b6417cd 100644 --- a/src/octoprint/static/js/app/viewmodels/timelapse.js +++ b/src/octoprint/static/js/app/viewmodels/timelapse.js @@ -51,10 +51,6 @@ $(function() { return self.isDirty() && !self.isPrinting() && self.loginState.isUser(); }); - self.isOperational.subscribe(function() { - self.requestData(); - }); - self.timelapseType.subscribe(function() { self.isDirty(true); }); From 38a5da1c357b8fb27c71ca718da5e1c6b0415207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 29 Jun 2017 16:44:36 +0200 Subject: [PATCH 3/7] Fix connection accordion again Slightly different order of things caused #1001 to resurface. --- src/octoprint/static/js/app/main.js | 3 ++- .../static/js/app/viewmodels/connection.js | 16 ++++++---------- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index d3e580b6c..7df1640b3 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -629,7 +629,8 @@ $(function() { }); } - viewModel._unbound = viewModel._bindings != undefined && viewModel._bindings.length == 0; + viewModel._unbound = viewModel._bindings !== undefined && viewModel._bindings.length === 0; + viewModel._bound = viewModel._bindings.length > 0; if (viewModel.hasOwnProperty("onAfterBinding")) { viewModel.onAfterBinding(); diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index b5fb58b0c..b2ae598b0 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -81,6 +81,8 @@ $(function() { }; self.openOrCloseOnStateChange = function() { + if (self._bound !== true) return; + var connectionTab = $("#connection"); if (self.isOperational() && connectionTab.hasClass("in")) { connectionTab.collapse("hide"); @@ -100,7 +102,7 @@ $(function() { self.isReady(data.flags.ready); self.isLoading(data.flags.loading); - if (self.loginState.isUser() && self.previousIsOperational != self.isOperational()) { + if (self.loginState.isUser() && self.previousIsOperational !== self.isOperational()) { // only open or close if the panel is visible (for admins) and // the state just changed to avoid thwarting manual open/close self.openOrCloseOnStateChange(); @@ -132,16 +134,10 @@ $(function() { self.onStartup = function() { self.requestData(); + }; - // when isAdmin becomes true the first time, set the panel open or - // closed based on the connection state - var subscription = self.loginState.isAdmin.subscribe(function(newValue) { - if (newValue) { - // wait until after the isAdmin state has run through all subscriptions - setTimeout(self.openOrCloseOnStateChange, 0); - subscription.dispose(); - } - }); + self.onAfterBinding = function() { + self.openOrCloseOnStateChange(); }; } From ce4cf38547f825efae0ff29fa7e10ff4a5ec2281 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 29 Jun 2017 17:37:01 +0200 Subject: [PATCH 4/7] Removed log prefixing again It caused issues with our line number tracking in the browser developer tools and I don't see any way to avoid this considering that we can't adjust the arguments supplied to console.log without in fact wrapping it :/ --- src/octoprint/static/js/app/main.js | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 7df1640b3..f8d342c00 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -7,35 +7,6 @@ $(function() { //~~ Logging setup - var logFormats = { - trace: "color: grey", - debug: "color: blue", - warn: "color: red", - error: "color: red; font-weight: bold" - }; - - var origLogFactory = log.methodFactory; - log.methodFactory = function(methodName, logLevel, loggerName) { - var rawMethod = origLogFactory(methodName, logLevel, loggerName); - var format = logFormats[methodName]; - var level = _.padRight(methodName.toUpperCase(), 5, " "); - - return function() { - var newArgs; - if (format && (OctoPrint.coreui.browser.chrome || OctoPrint.coreui.browser.firefox)) { - newArgs = ["%c[" + level + "]", format]; - } else { - newArgs = ["[" + level + "]"]; - } - - for (var i = 0; i < arguments.length; i++) { - newArgs.push(arguments[i]); - } - - return rawMethod.apply(null, newArgs); - } - }; - log.setLevel(CONFIG_DEBUG ? log.levels.DEBUG : log.levels.INFO); //~~ OctoPrint client setup From 836fbef6d87d71d9a3f87234ccaad728be4fbfae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 30 Jun 2017 09:24:07 +0200 Subject: [PATCH 5/7] Fixed an error in the temp graph when not connected --- src/octoprint/static/js/app/helpers.js | 6 ++++-- src/octoprint/static/js/app/viewmodels/temperature.js | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 4845a3f63..01f3146d9 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -524,12 +524,14 @@ function formatFilament(filament) { } function cleanTemperature(temp) { - if (!temp || temp < 10) return gettext("off"); + if (temp === undefined || !_.isNumber(temp)) return "-"; + if (temp < 10) return gettext("off"); return temp; } function formatTemperature(temp, showF) { - if (!temp || temp < 10) return gettext("off"); + if (temp === undefined || !_.isNumber(temp)) return "-"; + if (temp < 10) return gettext("off"); if (showF) { return _.sprintf("%.1f°C (%.1f°F)", temp, temp * 9 / 5 + 32); } else { diff --git a/src/octoprint/static/js/app/viewmodels/temperature.js b/src/octoprint/static/js/app/viewmodels/temperature.js index 0afaada8c..4d9f5e3d1 100644 --- a/src/octoprint/static/js/app/viewmodels/temperature.js +++ b/src/octoprint/static/js/app/viewmodels/temperature.js @@ -363,9 +363,11 @@ $(function() { var p1 = series.data[i - 1]; var p2 = series.data[i]; - if (p1 == undefined) { + if (p1 === undefined && p2 === undefined) { + y = undefined; + } else if (p1 === undefined) { y = p2[1]; - } else if (p2 == undefined) { + } else if (p2 === undefined) { y = p1[1]; } else { y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]); From ac3f4d598c8f94b724f643997e09d956f906cf7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 30 Jun 2017 09:39:14 +0200 Subject: [PATCH 6/7] Fixed onUserLoggedIn/Out not firing correctly on startup anymore Introduced by b205e84d4bb04b6de7751ab88daff63fd825c547 --- src/octoprint/static/js/app/viewmodels/loginstate.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js index e9c3b0510..a356ef130 100644 --- a/src/octoprint/static/js/app/viewmodels/loginstate.js +++ b/src/octoprint/static/js/app/viewmodels/loginstate.js @@ -66,7 +66,7 @@ $(function() { }; if (self.startupDeferred !== undefined) { - // Make sure we only fire our "onUserLogged(In|Out)" message when the application + // Make sure we only fire our "onUserLogged(In|Out)" message after the application // has started up. self.startupDeferred.done(process); } else { @@ -135,12 +135,11 @@ $(function() { self.onAllBound = function(allViewModels) { self.allViewModels = allViewModels; + self.startupDeferred.resolve(); + self.startupDeferred = undefined; }; self.onStartup = function() { - self.startupDeferred.resolve(); - self.startupDeferred = undefined; - self.elementUsernameInput = $("#login_user"); self.elementPasswordInput = $("#login_pass"); self.elementLoginButton = $("#login_button"); From 697df4f3cebc5005f87ddb1dcf29fbfefc0a94f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 30 Jun 2017 09:43:58 +0200 Subject: [PATCH 7/7] And fixed connection accordion toggling again #1001 said hi once more after fixing the onUserLogged(In|Out) events not firing... --- src/octoprint/static/js/app/viewmodels/connection.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index b2ae598b0..2b383913a 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -81,8 +81,6 @@ $(function() { }; self.openOrCloseOnStateChange = function() { - if (self._bound !== true) return; - var connectionTab = $("#connection"); if (self.isOperational() && connectionTab.hasClass("in")) { connectionTab.collapse("hide"); @@ -136,7 +134,11 @@ $(function() { self.requestData(); }; - self.onAfterBinding = function() { + self.onUserLoggedIn = function() { + self.openOrCloseOnStateChange(); + }; + + self.onUserLoggedOut = function() { self.openOrCloseOnStateChange(); }; }