diff --git a/.versioneer-lookup b/.versioneer-lookup index 6f5e25bb4..b5f3dc330 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,21 +18,21 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.6.0 +# maintenance is currently the branch for preparation of maintenance release 1.7.0 # so are any fix/... and improve/... branches -maintenance 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev -fix/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev -improve/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev +maintenance 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev +fix/.* 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev +improve/.* 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev # staging/bugfix is the branch for preparation of the 1.5.3 hotfix release # so are any bug/... branches staging/bugfix 1.5.3 e46e8fa17a1553cd0c228a4fa4cfd93e2a9bce7b pep440-dev bug/.* 1.5.3 e46e8fa17a1553cd0c228a4fa4cfd93e2a9bce7b pep440-dev -# staging/maintenance is currently the branch for preparation of 1.5.0rc4 +# staging/maintenance is currently the branch for preparation of 1.6.0rc2 # so is regressionfix/... -staging/maintenance 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev -regressionfix/.* 1.5.0rc4 5e7ea35239908f9ed91895751d8a8202aa76ed4b pep440-dev +staging/maintenance 1.6.0rc2 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev +regressionfix/.* 1.6.0rc2 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev # staging/devel is currently inactive (but has the 1.4.1rc4 namespace) staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 46d0e9a1d..7a5f64a23 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -6,6 +6,7 @@ thanks to everyone who contributed! ## Patrons & Sponsors + * 3D-TECH * 3DPrinterOS * Andrew Moorby * Arnljot Arntsen @@ -17,11 +18,13 @@ thanks to everyone who contributed! * BuildBee * Christian Petropolis * Christian Wolf + * Christoph Sigrist * Creality3D * D Brian Kimmel * DeltaMaker 3D Printers * Dennis Breining * Diana C Rodriguez + * Douglas Floyd * Eric Betts * Ernesto Martinez * Franziska Kunsmann @@ -29,11 +32,10 @@ thanks to everyone who contributed! * Greg Holloway * Hog Duske * Hopewell Medical Acupuncture Center - * jean-claude migneault - * Jefferson Hunt * Jeremy Cole * Joe Pasqua * Joshua Wills + * Julian Melo * Justin Kaufman * Kaile Riser * Kale Stedman @@ -44,14 +46,16 @@ thanks to everyone who contributed! * Kyle Menigoz * LA 3D Printer Repair * Lee Dohm - * Loyal Moses * Makespace Madrid * Mark Walker * Michael Aumock * Michael Begala * Miles Flavel * Mosaic Manufacturing + * Nat Friedman * Neil R. Goldberg + * Norman Jaffe + * Ory Weaver * Patrick Glyré * Pete Barnwell * Prof Yuh Wen Chen @@ -69,6 +73,8 @@ thanks to everyone who contributed! * Stefan Krister * Steve Thompson * Sven Mueller + * TH3D + * The Spaghetti Detective * Ulrich Kempken -and 2225 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)! +and 2296 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)! diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index eb52fbec4..dcbb3b239 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -1253,6 +1253,26 @@ octoprint.printer.factory :return: The ``printer`` instance to use globally. :rtype: PrinterInterface subclass or None +.. _sec-plugins-hook-printer-handle_connect: + +octoprint.printer.handle_connect +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: handle_connect(*args, **kwargs): + + .. versionadded:: 1.6.0 + + Allows plugins to perform actions upon connecting to a printer. By returning ``True``, + plugins may also prevent further processing of the connect command. This hook is of + special interest if your plugin needs a connect from going through under certain + circumstances or if you need to do something before a connection to the printer is + established (e.g. switching on power to the printer). + + :param kwargs: All connection parameters supplied to the ``connect`` call. Currently + this also includes ``port``, ``baudrate`` and ``profile``. + :return: ``True`` if OctoPrint should not proceed with the connect + :rtype: boolean or None + .. _sec-plugins-hook-printer-estimation-factory: octoprint.printer.estimation.factory diff --git a/setup.py b/setup.py index 8fcd2a705..efae3aeea 100644 --- a/setup.py +++ b/setup.py @@ -22,8 +22,9 @@ SETUP_REQUIRES = [ # Requirements for our application INSTALL_REQUIRES = [ # additional OctoPrint plugins that are maintained on a different release cycle + "OctoPrint-FileCheck>=2021.2.23", "OctoPrint-FirmwareCheck>=2021.2.4", - "OctoPrint-FileCheck>=2020.08.07", + "OctoPrint-PiSupport>=2021.3.26", # the following dependencies are non trivial to update since later versions # introduce backwards incompatible changes that might affect plugins, or due to # other observed problems diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index 151de614d..ccb0af48e 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -10,10 +10,16 @@ click.disable_unicode_literals_warning = True # ~~ "octoprint util" commands -def validate_result(result): - dimensions = ("depth", "height", "width") - printing_area = ("maxX", "maxY", "maxZ", "minX", "minY", "minZ") +dimensions = ("depth", "height", "width") +printing_area = ("maxX", "maxY", "maxZ", "minX", "minY", "minZ") + +def empty_result(result): + dims = result.get("dimensions", {}) + return all(map(lambda x: dims.get(x) == 0.0, dimensions)) + + +def validate_result(result): def validate_list(data): return not any(map(invalid_float, data)) @@ -131,6 +137,10 @@ def gcode_command( click.echo("DONE:{}s".format(time.monotonic() - start_time)) result = interpreter.get_result() + if empty_result(result): + click.echo("EMPTY:There are no extrusions in the file, nothing to analyse") + sys.exit(0) + if not validate_result(result): click.echo( "ERROR:Invalid analysis result, please create a bug report in OctoPrint's " diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 555d9c358..eae8287e7 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -1036,6 +1036,8 @@ class FileManager: def _add_analysis_result(self, destination, path, result): if destination not in self._storage_managers: return + if not result: + return storage_manager = self._storage_managers[destination] storage_manager.set_additional_metadata(path, "analysis", result, overwrite=True) diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index 0391fd513..5309f5f67 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -470,27 +470,29 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): output = p.stdout.text self._logger.debug(f"Got output: {output!r}") + result = {} if "ERROR:" in output: _, error = output.split("ERROR:") raise RuntimeError(error.strip()) + elif "EMPTY:" in output: + self._logger.info("Result is empty, no extrusions found") elif "RESULTS:" not in output: raise RuntimeError("No analysis result found") + else: + _, output = output.split("RESULTS:") + analysis = yaml.safe_load(output) - _, output = output.split("RESULTS:") - analysis = yaml.safe_load(output) - - result = {} - result["printingArea"] = analysis["printing_area"] - result["dimensions"] = analysis["dimensions"] - if analysis["total_time"]: - result["estimatedPrintTime"] = analysis["total_time"] * 60 - if analysis["extrusion_length"]: - result["filament"] = {} - for i in range(len(analysis["extrusion_length"])): - result["filament"]["tool%d" % i] = { - "length": analysis["extrusion_length"][i], - "volume": analysis["extrusion_volume"][i], - } + result["printingArea"] = analysis["printing_area"] + result["dimensions"] = analysis["dimensions"] + if analysis["total_time"]: + result["estimatedPrintTime"] = analysis["total_time"] * 60 + if analysis["extrusion_length"]: + result["filament"] = {} + for i in range(len(analysis["extrusion_length"])): + result["filament"]["tool%d" % i] = { + "length": analysis["extrusion_length"][i], + "volume": analysis["extrusion_volume"][i], + } if self._current.analysis and isinstance(self._current.analysis, dict): return dict_merge(result, self._current.analysis) diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 7d12d1ff3..793601d88 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -107,7 +107,7 @@ def plugin_manager( plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] if plugin_considered_bundled is None: - plugin_considered_bundled = ["firmware_check", "file_check"] + plugin_considered_bundled = ["firmware_check", "file_check", "pi_support"] if plugin_validators is None: plugin_validators = [_validate_plugin] diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 index d5d2b360a..901b478b6 100644 --- a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 +++ b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 @@ -1,4 +1,4 @@ -{{ _('Registered application keys') }} +

{{ _('Registered application keys') }}

{{ _('There are no application keys registered yet.') }}

@@ -59,7 +59,7 @@
-{{ _('Manually generate an application key') }} +

{{ _('Manually generate an application key') }}

diff --git a/src/octoprint/plugins/errortracking/__init__.py b/src/octoprint/plugins/errortracking/__init__.py index bf015360e..3beebcfb3 100644 --- a/src/octoprint/plugins/errortracking/__init__.py +++ b/src/octoprint/plugins/errortracking/__init__.py @@ -18,10 +18,10 @@ from octoprint.util.version import ( ) SENTRY_URL_SERVER = ( - "https://c11d13d9e92046bca4691ad1658dc543@o118517.ingest.sentry.io/1373987" + "https://cd0da78d9d394b96bf910e74e9d366c3@o118517.ingest.sentry.io/1373987" ) SENTRY_URL_COREUI = ( - "https://a987a79a328e405a9545b8a036b420ee@o118517.ingest.sentry.io/1374096" + "https://9ed26aae61a4434194d9fbb17326b453@o118517.ingest.sentry.io/1374096" ) SETTINGS_DEFAULTS = { diff --git a/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 index 1ba49d79b..930fd8744 100644 --- a/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 +++ b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 @@ -1,3 +1,4 @@ +

{{ _("GCode Viewer") }}

diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py deleted file mode 100644 index 850d28ef2..000000000 --- a/src/octoprint/plugins/pi_support/__init__.py +++ /dev/null @@ -1,459 +0,0 @@ -__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 os - -import flask -import sarge -from flask_babel import gettext - -import octoprint.events -import octoprint.plugin -from octoprint.access.groups import USER_GROUP -from octoprint.access.permissions import Permissions -from octoprint.util import RepeatedTimer -from octoprint.util.platform import CLOSE_FDS - -_PROC_DT_MODEL_PATH = "/proc/device-tree/model" -_OCTOPI_VERSION_PATH = "/etc/octopi_version" -_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled" - -_CHECK_INTERVAL_OK = 300 -_CHECK_INTERVAL_THROTTLED = 30 - -__LOCAL_DEBUG = os.path.exists( - os.path.realpath(os.path.join(os.path.dirname(__file__), ".local_debug")) -) - -if __LOCAL_DEBUG: - ### mocks & settings for local debugging - import sys - - base = os.path.realpath( - os.path.join( - os.path.dirname(__file__), - "..", - "..", - "..", - "..", - "tests", - "plugins", - "pi_support", - "fakes", - ) - ) - _PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt") - _OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt") - _VCGENCMD_THROTTLE = "{} {}".format( - sys.executable, os.path.join(base, "fake_vcgencmd.py") - ) - import itertools - - _VCGENCMD_OUTPUT = itertools.chain( - iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005") - ) - - _CHECK_INTERVAL_OK = 10 - _CHECK_INTERVAL_THROTTLED = 5 - - -# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790 -_FLAG_UNDERVOLTAGE = 1 << 0 -_FLAG_FREQ_CAPPED = 1 << 1 -_FLAG_THROTTLED = 1 << 2 -_FLAG_PAST_UNDERVOLTAGE = 1 << 16 -_FLAG_PAST_FREQ_CAPPED = 1 << 17 -_FLAG_PAST_THROTTLED = 1 << 18 - - -class ThrottleState: - @classmethod - def from_value(cls, value=0): - if value == 0: - return ThrottleState(raw_value=value) - - kwargs = { - "undervoltage": _FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE, - "freq_capped": _FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED, - "throttled": _FLAG_THROTTLED & value == _FLAG_THROTTLED, - "past_undervoltage": _FLAG_PAST_UNDERVOLTAGE & value - == _FLAG_PAST_UNDERVOLTAGE, - "past_freq_capped": _FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED, - "past_throttled": _FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED, - "raw_value": value, - } - return ThrottleState(**kwargs) - - def __init__(self, **kwargs): - self._raw_value = kwargs.get("raw_value", -1) - self._undervoltage = False - self._freq_capped = False - self._throttled = False - self._past_undervoltage = False - self._past_freq_capped = False - self._past_throttled = False - - for key, value in kwargs.items(): - local_key = f"_{key}" - if hasattr(self, local_key) and isinstance(value, bool): - setattr(self, local_key, value) - - @property - def undervoltage(self): - return self.current_undervoltage or self.past_undervoltage - - @property - def current_undervoltage(self): - return self._undervoltage - - @property - def past_undervoltage(self): - return self._past_undervoltage - - @property - def overheat(self): - return self.current_overheat or self.past_overheat - - @property - def current_overheat(self): - return self._freq_capped - - @property - def past_overheat(self): - return self._past_freq_capped - - @property - def issue(self): - return self.current_issue or self.past_issue - - @property - def current_issue(self): - return self._undervoltage or self._freq_capped or self._throttled - - @property - def past_issue(self): - return self._past_undervoltage or self._past_freq_capped or self._past_throttled - - @property - def raw_value(self): - return self._raw_value - - @property - def raw_value_hex(self): - return f"0x{self._raw_value:X}" - - def __eq__(self, other): - if not isinstance(other, ThrottleState): - return False - - return ( - self._undervoltage == other._undervoltage - and self._freq_capped == other._freq_capped - and self._throttled == other._throttled - and self._past_undervoltage == other._past_undervoltage - and self._past_freq_capped == other._past_freq_capped - and self._past_throttled == other._past_throttled - and self._raw_value == other._raw_value - ) - - def as_dict(self): - return { - "raw_value": self._raw_value, - "current_undervoltage": self.current_undervoltage, - "past_undervoltage": self.past_undervoltage, - "current_overheat": self.current_overheat, - "past_overheat": self.past_overheat, - "current_issue": self.current_issue, - "past_issue": self.past_issue, - } - - -_proc_dt_model = None - - -def get_proc_dt_model(): - global _proc_dt_model - - if _proc_dt_model is None: - with open(_PROC_DT_MODEL_PATH, encoding="utf-8") as f: - _proc_dt_model = f.readline().strip(" \t\r\n\0") - - return _proc_dt_model - - -def get_vcgencmd_throttled_state(command): - if __LOCAL_DEBUG: - output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging - else: - output = sarge.get_stdout(command, close_fds=CLOSE_FDS) - - if "throttled=0x" not in output: - raise ValueError(f'cannot parse "{command}" output: {output}') - - value = output[len("throttled=") :].strip(" \t\r\n\0") - value = int(value, 0) - return ThrottleState.from_value(value) - - -def is_octopi(): - return os.path.exists(_OCTOPI_VERSION_PATH) - - -_octopi_version = None - - -def get_octopi_version(): - global _octopi_version - - if _octopi_version is None: - with open(_OCTOPI_VERSION_PATH, encoding="utf-8") as f: - _octopi_version = f.readline().strip(" \t\r\n\0") - - return _octopi_version - - -class PiSupportPlugin( - octoprint.plugin.EnvironmentDetectionPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.SettingsPlugin, -): - - # noinspection PyMissingConstructor - def __init__(self): - self._throttle_state = ThrottleState() - self._throttle_check = None - self._throttle_undervoltage = False - self._throttle_overheat = False - self._throttle_functional = True - - # Additional permissions hook - - def get_additional_permissions(self): - return [ - { - "key": "STATUS", - "name": "Status", - "description": gettext( - "Allows to check for the Pi's throttling status and environment info" - ), - "roles": ["check"], - "default_groups": [USER_GROUP], - } - ] - - # ~~ EnvironmentDetectionPlugin - - def get_additional_environment(self): - result = {"model": get_proc_dt_model()} - - self._check_throttled_state() - if self._throttle_functional: - result["throttle_state"] = self._throttle_state.raw_value_hex - - if is_octopi(): - result["octopi_version"] = get_octopi_version() - - return result - - # ~~ SimpleApiPlugin - - def on_api_get(self, request): - if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can(): - return flask.abort(403) - - environment = self.get_additional_environment() - - result = { - "throttle_state": self._throttle_state.as_dict(), - "model_unrecommended": "zero" in environment.get("model").lower(), - } - result.update(environment) - return flask.jsonify(**result) - - # ~~ AssetPlugin - - def get_assets(self): - return { - "js": ["js/pi_support.js"], - "clientjs": ["clientjs/pi_support.js"], - "css": ["css/pi_support.css"], - } - - # ~~ TemplatePlugin - - def get_template_configs(self): - configs = [ - { - "type": "settings", - "name": gettext("Pi Support"), - "template": "pi_support_settings.jinja2", - "custom_bindings": False, - } - ] - - if is_octopi(): - configs.append( - { - "type": "about", - "name": "About OctoPi", - "template": "pi_support_about_octopi.jinja2", - } - ) - - return configs - - def get_template_vars(self): - return self.get_additional_environment() - - # ~~ StartupPlugin - - def on_startup(self, *args, **kwargs): - if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]): - self._check_throttled_state() - self._throttle_check = RepeatedTimer( - self._check_throttled_state_interval, - self._check_throttled_state, - condition=self._check_throttled_state_condition, - ) - self._throttle_check.start() - - # ~~ SettingsPlugin - - def get_settings_defaults(self): - return { - "vcgencmd_throttle_check_enabled": True, - "vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE, - "ignore_unrecommended_model": False, - } - - def get_settings_restricted_paths(self): - return { - "admin": [ - ["vcgencmd_throttle_check_enabled"], - ["vcgencmd_throttle_check_command"], - ] - } - - # ~~ Helpers - - def _check_throttled_state_interval(self): - if self._throttle_state.current_issue: - return _CHECK_INTERVAL_THROTTLED - else: - return _CHECK_INTERVAL_OK - - def _check_throttled_state_condition(self): - return self._throttle_functional - - def get_throttle_state(self, run_now=False): - """Exposed as public helper.""" - if run_now: - self._check_throttled_state() - - if not self._throttle_functional: - return False - - return self._throttle_state.as_dict() - - def _check_throttled_state(self): - command = self._settings.get(["vcgencmd_throttle_check_command"]) - - self._logger.debug(f'Retrieving throttle state via "{command}"') - try: - state = get_vcgencmd_throttled_state(command) - except ValueError: - self._logger.warning( - 'Fetching the current throttle state via "{}" doesn\'t work'.format( - command - ) - ) - self._throttle_functional = False - return - - if self._throttle_state == state: - # no change - return - - self._throttle_state = state - - if (not self._throttle_undervoltage and self._throttle_state.undervoltage) or ( - not self._throttle_overheat and self._throttle_state.overheat - ): - message = ( - "This Raspberry Pi is reporting problems that might lead to bad performance or errors caused " - "by overheating or insufficient power." - ) - - if self._throttle_state.undervoltage: - self._throttle_undervoltage = True - message += ( - "\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are " - "capable of supplying enough voltage and current to your Pi." - ) - - if self._throttle_state.overheat: - self._throttle_overheat = True - message += ( - "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " - "CPU and GPU." - ) - - self._logger.warning(message) - - self._plugin_manager.send_plugin_message( - self._identifier, - {"type": "throttle_state", "state": self._throttle_state.as_dict()}, - ) - - # noinspection PyUnresolvedReferences - self._event_bus.fire( - octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, - self._throttle_state.as_dict(), - ) - - -def register_custom_events(*args, **kwargs): - return [ - "throttle_state", - ] - - -__plugin_name__ = "Pi Support Plugin" -__plugin_author__ = "Gina Häußge" -__plugin_description__ = "Provides additional information about your Pi in the UI." -__plugin_disabling_discouraged__ = gettext( - "Without this plugin OctoPrint will no longer be able to " - "provide additional information about your Pi, " - "which will make it more tricky to help you if you need support." -) -__plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" - - -def __plugin_check__(): - try: - proc_dt_model = get_proc_dt_model() - if proc_dt_model is None: - return False - except Exception: - return False - - return "raspberry pi" in proc_dt_model.lower() - - -def __plugin_load__(): - plugin = PiSupportPlugin() - global __plugin_implementation__ - __plugin_implementation__ = plugin - - global __plugin_hooks__ - __plugin_hooks__ = { - "octoprint.events.register_custom_events": register_custom_events, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, - } - - global __plugin_helpers__ - __plugin_helpers__ = {"get_throttled": plugin.get_throttle_state} diff --git a/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js b/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js deleted file mode 100644 index 232da6406..000000000 --- a/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js +++ /dev/null @@ -1,18 +0,0 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function (OctoPrintClient) { - var OctoPrintPiSupportClient = function (base) { - this.base = base; - }; - - OctoPrintPiSupportClient.prototype.get = function (opts) { - return this.base.get(this.base.getSimpleApiUrl("pi_support")); - }; - - OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient); - return OctoPrintPiSupportClient; -}); diff --git a/src/octoprint/plugins/pi_support/static/css/pi_support.css b/src/octoprint/plugins/pi_support/static/css/pi_support.css deleted file mode 100644 index c6065b7ed..000000000 --- a/src/octoprint/plugins/pi_support/static/css/pi_support.css +++ /dev/null @@ -1,8 +0,0 @@ -#octopi_support_footer { - white-space: nowrap; -} - -.pi_support_state_pulsate { - animation: pulsate 1s ease-out; - animation-iteration-count: infinite; -} diff --git a/src/octoprint/plugins/pi_support/static/js/pi_support.js b/src/octoprint/plugins/pi_support/static/js/pi_support.js deleted file mode 100644 index 95112fece..000000000 --- a/src/octoprint/plugins/pi_support/static/js/pi_support.js +++ /dev/null @@ -1,172 +0,0 @@ -$(function () { - function PiSupportViewModel(parameters) { - var self = this; - - self.loginState = parameters[0]; - self.access = parameters[1]; - self.settings = parameters[2]; - - self.model = ko.observable(); - - self.currentUndervoltage = ko.observable(false); - self.currentOverheat = ko.observable(false); - self.pastUndervoltage = ko.observable(false); - self.pastOverheat = ko.observable(false); - self.currentIssue = ko.observable(false); - self.pastIssue = ko.observable(false); - - self.requestData = function () { - if ( - !self.loginState.hasPermission( - self.access.permissions.PLUGIN_PI_SUPPORT_STATUS - ) - ) { - return; - } - - OctoPrint.plugins.pi_support.get().done(function (response) { - // Raspberry Pi model - self.model(response.model); - - // Unrecommended model - if ( - response.model_unrecommended && - !self.settings.settings.plugins.pi_support.ignore_unrecommended_model() - ) { - var warning = gettext( - "OctoPrint does not and never has supported the " + - "RPi Zero or Zero W. Use at least a Raspberry Pi 3, or " + - "risk bad performance and failed prints." - ); - var faq = gettext( - "" + - 'You can read more in the FAQ.' - ); - var remove = gettext( - "You can disable this message via Settings > " + - "Pi Support > Ignore warning on unsupported hardware" - ); - new PNotify({ - title: gettext("Unsupported hardware detected"), - text: - "

" + - warning + - "

" + - _.sprintf(faq, { - url: "https://faq.octoprint.org/recommended-hardware" - }) + - "

" + - "" + - remove + - "

", - type: "error", - hide: false - }); - } - - // Throttle state - self.fromThrottleState(response.throttle_state); - - // OctoPi version - $("#pi_support_footer").remove(); - if (!response.octopi_version) return; - - var octoPiVersion = $( - "" - ); - $("#footer_version").append(octoPiVersion); - }); - }; - - self.fromThrottleState = function (state) { - self.currentUndervoltage(state.current_undervoltage); - self.pastUndervoltage(state.past_undervoltage); - self.currentOverheat(state.current_overheat); - self.pastOverheat(state.past_overheat); - self.currentIssue(state.current_issue); - self.pastIssue(state.past_issue); - }; - - self.popoverContent = ko.pureComputed(function () { - var undervoltageParagraphClasses = "muted"; - var undervoltageSymbolClasses = ""; - - var overheatParagraphClasses = "muted"; - var overheatSymbolClasses = ""; - - if (self.currentUndervoltage()) { - undervoltageSymbolClasses = "text-error pi_support_state_pulsate"; - undervoltageParagraphClasses = ""; - } else if (self.pastUndervoltage()) { - undervoltageSymbolClasses = "text-error"; - undervoltageParagraphClasses = ""; - } - - if (self.currentOverheat()) { - overheatSymbolClasses = "text-error pi_support_state_pulsate"; - overheatParagraphClasses = ""; - } else if (self.pastOverheat()) { - overheatSymbolClasses = "text-error"; - overheatParagraphClasses = ""; - } - - return ( - "

- ' + - gettext( - "Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi." - ) + - "

" + - "

- ' + - gettext( - "Frequency capping due to overheating. Improve cooling of the CPU and GPU." - ) + - "

" + - "

" + - gettext( - "A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up." - ) + - "

" + - "

" + - gettext("Click the symbol in the navbar for more information.") + - "

" - ); - }); - - self.onStartup = self.onServerReconnect = self.onUserLoggedIn = self.onUserLoggedOut = function () { - self.requestData(); - }; - - self.onDataUpdaterPluginMessage = function (plugin, data) { - if (plugin !== "pi_support") return; - if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return; - if (data.type !== "throttle_state") return; - if ( - !self.loginState.hasPermission( - self.access.permissions.PLUGIN_PI_SUPPORT_STATUS - ) - ) - return; - - self.fromThrottleState(data.state); - }; - } - - OCTOPRINT_VIEWMODELS.push({ - construct: PiSupportViewModel, - elements: ["#navbar_plugin_pi_support"], - dependencies: ["loginStateViewModel", "accessViewModel", "settingsViewModel"] - }); -}); diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 deleted file mode 100644 index 5dcba4b65..000000000 --- a/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 +++ /dev/null @@ -1,31 +0,0 @@ -

{{ _('About OctoPi') }}

- -

The ready-to-go Raspberry Pi image with OctoPrint

- -

Version {{ plugin_pi_support_octopi_version }}, running on {{ plugin_pi_support_model }}

- - - -

- © 2013-{{ now.strftime("%Y") }} The OctoPi Authors -

- -

- OctoPi is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. -

-

- OctoPi is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. -

-

- For a copy of the GNU General Public License, see - www.gnu.org/licenses/gpl-3.0.en.html. -

diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 deleted file mode 100644 index 2811fcbb7..000000000 --- a/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 deleted file mode 100644 index 10972c0cc..000000000 --- a/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 +++ /dev/null @@ -1,38 +0,0 @@ -

{{ _('Pi Support') }}

- -

{{ _('Please restart OctoPrint after changing any of this plugin\'s settings.') }}

- - -
-
- - {{ _('If you check this, you will no longer get warned if you run OctoPrint on Raspberry Pi models that are not officially supported due to bad performance that can lead to failed prints. Do so at your own risk.') }} -
-
- -
-
- - {{ _('This will regularly check with the Pi if something is amiss either with power regulation or CPU/GPU temperature.') }} -
-
- -
-
{{ _('Advanced options') }}
-
- -
- -
- - {{ _('Defaults to /usr/bin/vcgencmd get_throttled. You usually shouldn\'t have to change this.') }} -
-
- -
-
- diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 6b79bb209..3649ed7cf 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -173,6 +173,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated ) + self._handle_connect_hooks = plugin_manager().get_hooks( + "octoprint.printer.handle_connect" + ) + def _create_estimator(self, job_type=None): if job_type is None: with self._selectedFileMutex: @@ -351,6 +355,19 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if self._comm is not None: return + for name, hook in self._handle_connect_hooks.items(): + try: + if hook( + self, port=port, baudrate=baudrate, profile=profile, *args, **kwargs + ): + self._logger.info(f"Connect signalled as handled by plugin {name}") + return + except Exception: + self._logger.exception( + f"Exception while handling connect in plugin {name}", + extra={"plugin": name}, + ) + eventManager().fire(Events.CONNECTING) self._printerProfileManager.select(profile) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index ee31a95ec..a494daa2d 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1270,7 +1270,7 @@ class Server: self._logger.exception("Stacktrace follows:") def _create_socket_connection(self, session): - global printer, fileManager, analysisQueue, userManager, eventManager + global printer, fileManager, analysisQueue, userManager, eventManager, connectivityChecker return util.sockjs.PrinterStateConnection( printer, fileManager, @@ -1279,6 +1279,7 @@ class Server: groupManager, eventManager, pluginManager, + connectivityChecker, session, ) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 37bce7181..5ccb1ffa3 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -160,6 +160,54 @@ def readGcodeFiles(): return jsonify(files=files, free=usage.free, total=usage.total) +@api.route("/files/test", methods=["POST"]) +@Permissions.FILES_LIST.require(403) +def runFilesTest(): + valid_commands = { + "sanitize": ["storage", "path", "filename"], + "exists": ["storage", "path", "filename"], + } + + command, data, response = get_json_command_from_request(request, valid_commands) + if response is not None: + return response + + def sanitize(storage, path, filename): + sanitized_path = fileManager.sanitize_path(storage, path) + sanitized_name = fileManager.sanitize_name(storage, filename) + joined = fileManager.join_path(storage, sanitized_path, sanitized_name) + return sanitized_path, sanitized_name, joined + + if command == "sanitize": + _, _, sanitized = sanitize(data["storage"], data["path"], data["filename"]) + return jsonify(sanitized=sanitized) + elif command == "exists": + storage = data["storage"] + path = data["path"] + filename = data["filename"] + + sanitized_path, _, sanitized = sanitize(storage, path, filename) + + exists = fileManager.file_exists(storage, sanitized) + if exists: + suggestion = filename + name, ext = os.path.splitext(filename) + counter = 0 + while fileManager.file_exists( + storage, + fileManager.join_path( + storage, + sanitized_path, + fileManager.sanitize_name(storage, suggestion), + ), + ): + counter += 1 + suggestion = name + f"_{counter}" + ext + return jsonify(exists=True, suggestion=suggestion) + else: + return jsonify(exists=False) + + @api.route("/files/", methods=["GET"]) @Permissions.FILES_LIST.require(403) @with_revalidation_checking( @@ -504,6 +552,11 @@ def uploadGcodeFile(target): canonPath, canonFilename = fileManager.canonicalize( FileDestinations.LOCAL, upload.filename ) + if request.values.get("path"): + canonPath = request.values.get("path") + if request.values.get("filename"): + canonFilename = request.values.get("filename") + futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath) futureFilename = fileManager.sanitize_name( FileDestinations.LOCAL, canonFilename @@ -516,12 +569,6 @@ def uploadGcodeFile(target): if futureFilename is None: abort(415, description="Can not upload file, wrong format?") - if "path" in request.values and request.values["path"]: - # we currently only support uploads to sdcard via local, so first target is local instead of "target" - futurePath = fileManager.sanitize_path( - FileDestinations.LOCAL, request.values["path"] - ) - # prohibit overwriting currently selected file while it's being printed futureFullPath = fileManager.join_path( FileDestinations.LOCAL, futurePath, futureFilename @@ -536,6 +583,12 @@ def uploadGcodeFile(target): description="Trying to overwrite file that is currently being printed", ) + if ( + fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage) + and request.values.get("noOverwrite") in valid_boolean_trues + ): + abort(409, description="File already exists and noOverwrite was set") + reselect = printer.is_current_file(futureFullPathInStorage, sd) user = current_user.get_name() diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 705f8f8ee..2aec771ab 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -126,6 +126,7 @@ def getSettings(): "snapshotTimeout": s.getInt(["webcam", "snapshotTimeout"]), "snapshotSslValidation": s.getBoolean(["webcam", "snapshotSslValidation"]), "ffmpegPath": s.get(["webcam", "ffmpeg"]), + "ffmpegCommandline": s.get(["webcam", "ffmpegCommandline"]), "bitrate": s.get(["webcam", "bitrate"]), "ffmpegThreads": s.get(["webcam", "ffmpegThreads"]), "ffmpegVideoCodec": s.get(["webcam", "ffmpegVideoCodec"]), @@ -144,6 +145,9 @@ def getSettings(): "printCancelConfirmation": s.getBoolean( ["feature", "printCancelConfirmation"] ), + "uploadOverwriteConfirmation": s.getBoolean( + ["feature", "uploadOverwriteConfirmation"] + ), "g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]), "autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]), }, @@ -524,6 +528,33 @@ def _saveSettings(data): ) if "ffmpegPath" in data["webcam"]: s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"]) + if "ffmpegCommandline" in data["webcam"]: + commandline = data["webcam"]["ffmpegCommandline"] + if not all( + map(lambda x: "{" + x + "}" in commandline, ("ffmpeg", "input", "output")) + ): + abort( + 400, + description="Invalid webcam.ffmpegCommandline setting, lacks mandatory {ffmpeg}, {input} or {output}", + ) + try: + commandline.format( + ffmpeg="ffmpeg", + fps="fps", + bitrate="bitrate", + threads="threads", + input="input", + output="output", + videocodec="videocodec", + containerformat="containerformat", + filters="filters", + ) + except Exception: + # some invalid data we'll refuse to set + logger.exception("Invalid webcam.ffmpegCommandline setting") + abort(400, description="Invalid webcam.ffmpegCommandline setting") + else: + s.set(["webcam", "ffmpegCommandline"], commandline) if "bitrate" in data["webcam"]: s.set(["webcam", "bitrate"], data["webcam"]["bitrate"]) if "ffmpegThreads" in data["webcam"]: @@ -568,6 +599,11 @@ def _saveSettings(data): ["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"], ) + if "uploadOverwriteConfirmation" in data["feature"]: + s.setBoolean( + ["feature", "uploadOverwriteConfirmation"], + data["feature"]["uploadOverwriteConfirmation"], + ) if "g90InfluencesExtruder" in data["feature"]: s.setBoolean( ["feature", "g90InfluencesExtruder"], diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index ac6b33b9a..818ec5a0e 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -116,6 +116,7 @@ class PrinterStateConnection( groupManager, eventManager, pluginManager, + connectivityChecker, session, ): if isinstance(session, octoprint.vendor.sockjs.tornado.session.Session): @@ -142,6 +143,7 @@ class PrinterStateConnection( self._groupManager = groupManager self._eventManager = eventManager self._pluginManager = pluginManager + self._connectivityChecker = connectivityChecker self._remoteAddress = None self._user = self._userManager.anonymous_user_factory() @@ -220,6 +222,7 @@ class PrinterStateConnection( "config_hash": config_hash, "debug": octoprint.server.debug, "safe_mode": octoprint.server.safe_mode, + "online": self._connectivityChecker.online, "permissions": [permission.as_dict() for permission in Permissions.all()], }, ) diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 04dcf1344..ec5dc80b8 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -312,7 +312,7 @@ def in_cache(): @app.route("/") def index(): - from octoprint.server import printer + from octoprint.server import connectivityChecker, printer global _templates, _plugin_names, _plugin_vars @@ -366,6 +366,7 @@ def index(): enable_webcam, enable_temperature_graph, sockjs_connect_timeout, + connectivityChecker.online, wizard_active(_templates.get(locale)), ] + sorted( [ @@ -588,6 +589,7 @@ def index(): "enableSdSupport": enable_sd_support, "sockJsConnectTimeout": sockjs_connect_timeout * 1000, "wizard": wizard, + "online": connectivityChecker.online, "now": now, } ) @@ -859,6 +861,11 @@ def fetch_template_data(refresh=False): # navbar templates["navbar"]["entries"] = { + "offlineindicator": { + "template": "navbar/offlineindicator.jinja2", + "_div": "navbar_offlineindicator", + "custom_bindings": False, + }, "settings": { "template": "navbar/settings.jinja2", "_div": "navbar_settings", diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 0eb8848f6..11542c192 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -230,6 +230,7 @@ default_settings = { "flipH": False, "flipV": False, "rotate90": False, + "ffmpegCommandline": '{ffmpeg} -r {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b {bitrate} -f {containerformat} -y {filters} "{output}"', "timelapse": { "type": "off", "options": {}, @@ -254,6 +255,7 @@ default_settings = { "modelSizeDetection": True, "printStartConfirmation": False, "printCancelConfirmation": True, + "uploadOverwriteConfirmation": True, "autoUppercaseBlacklist": ["M117", "M118"], "g90InfluencesExtruder": False, }, diff --git a/src/octoprint/static/js/app/client/files.js b/src/octoprint/static/js/app/client/files.js index f066f7112..517f57d1e 100644 --- a/src/octoprint/static/js/app/client/files.js +++ b/src/octoprint/static/js/app/client/files.js @@ -7,6 +7,7 @@ })(this, function (OctoPrintClient, $, _) { var url = "api/files"; var downloadUrl = "downloads/files"; + var testUrl = url + "/test"; var OctoPrintFilesClient = function (base) { this.base = base; @@ -198,20 +199,22 @@ return recursiveSearch(path.split("/"), root); }; - OctoPrintFilesClient.prototype.pathForElement = function (element) { - // TODO Remove in 1.4.x - log.warn( - "pathForElement has been renamed to pathForEntry, please use that instead" + OctoPrintFilesClient.prototype.sanitize = function (location, path, filename, opts) { + return this.base.issueCommand( + testUrl, + "sanitize", + {storage: location, path: path, filename: filename}, + opts ); - return this.pathForEntry(element); }; - OctoPrintFilesClient.prototype.elementByPath = function (location, startElement) { - // TODO Remove in 1.4.x - log.warn( - "elementByPath has been renamed to entryForPath, please use that instead" + OctoPrintFilesClient.prototype.exists = function (location, path, filename, opts) { + return this.base.issueCommand( + testUrl, + "exists", + {storage: location, path: path, filename: filename}, + opts ); - return this.entryForPath(location, startElement); }; OctoPrintClient.registerComponent("files", OctoPrintFilesClient); diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index a1f9ca672..75b6e062c 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -173,6 +173,9 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { BRANCH = data["branch"]; $("span.version").text(DISPLAY_VERSION); + // update connectivity state + ONLINE = data["online"]; + // update plugin hash var oldPluginHash = self._pluginHash; self._pluginHash = data["plugin_hash"]; @@ -413,6 +416,8 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { type: severity, hide: false }); + } else if (type === "ConnectivityChanged") { + ONLINE = payload.new; } var legacyEventHandlers = { diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 7349e49cb..5c3633155 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -97,6 +97,9 @@ $(function () { ); }); + self.uploadExistsDialog = undefined; + self.uploadFilename = ko.observable(undefined); + self.allItems = ko.observable(undefined); self.currentPath = ko.observable(""); self.uploadProgressText = ko.observable(); @@ -1221,6 +1224,8 @@ $(function () { } }); + self.uploadExistsDialog = $("#upload_exists_dialog"); + //~~ Gcode upload self.uploadButton = $("#gcode_upload"); @@ -1419,22 +1424,18 @@ $(function () { if (button === undefined) return; - button - .fileupload({ - url: url, - dataType: "json", - dropZone: enable ? drop : null, - drop: function (e, data) {}, - submit: self._handleUploadStart, - done: self._handleUploadDone, - fail: self._handleUploadFail, - always: self._handleUploadAlways, - progressall: self._handleUploadProgress - }) - .bind("fileuploadsubmit", function (e, data) { - if (self.currentPath() !== "") - data.formData = {path: self.currentPath()}; - }); + button.fileupload({ + url: url, + dataType: "json", + dropZone: enable ? drop : null, + drop: function (e, data) {}, + add: self._handleUploadAdd, + submit: self._handleUploadStart, + done: self._handleUploadDone, + fail: self._handleUploadFail, + always: self._handleUploadAlways, + progressall: self._handleUploadProgress + }); }; self._enableDragNDrop = function (enable) { @@ -1460,6 +1461,89 @@ $(function () { } }; + self._handleUploadAdd = function (e, data) { + var file = data.files[0]; + var path = self.currentPath(); + + var formData = {}; + if (path !== "") { + formData.path = path; + } + + if (self.settingsViewModel.feature_uploadOverwriteConfirmation()) { + OctoPrint.files + .exists("local", path, file.name) + .done(function (response) { + if (response.exists) { + $("h3", self.uploadExistsDialog).text( + _.sprintf(gettext("File already exists: %(name)s"), { + name: file.name + }) + ); + $("input", self.uploadExistsDialog) + .val("") + .prop("placeholder", response.suggestion); + $("a.upload-rename", self.uploadExistsDialog) + .prop("disabled", false) + .off("click") + .on("click", function () { + var newName = $( + "input", + self.uploadExistsDialog + ).val(); + if (newName === "") newName = response.suggestion; + + OctoPrint.files + .exists("local", path, newName) + .done(function (r) { + if (r.exists) { + $( + ".control-group", + self.uploadExistsDialog + ).addClass("error"); + $( + ".help-block", + self.uploadExistsDialog + ).show(); + } else { + $( + ".control-group", + self.uploadExistsDialog + ).removeClass("error"); + $( + ".help-block", + self.uploadExistsDialog + ).hide(); + + self.uploadExistsDialog.modal("hide"); + + formData.filename = newName; + formData.noOverwrite = true; + data.formData = formData; + + data.submit(); + } + }); + }); + $("a.upload-overwrite", self.uploadExistsDialog) + .off("click") + .on("click", function () { + self.uploadExistsDialog.modal("hide"); + data.formData = formData; + data.submit(); + }); + self.uploadExistsDialog.modal("show"); + } else { + data.formData = formData; + data.submit(); + } + }); + } else { + data.formData = formData; + data.submit(); + } + }; + self._handleUploadStart = function (e, data) { self.ignoreUpdatedFilesEvent = true; return true; @@ -1607,6 +1691,11 @@ $(function () { "printerProfilesViewModel", "accessViewModel" ], - elements: ["#files_wrapper", "#add_folder_dialog", "#move_file_or_folder_dialog"] + elements: [ + "#files_wrapper", + "#add_folder_dialog", + "#move_file_or_folder_dialog", + "#upload_exists_dialog" + ] }); }); diff --git a/src/octoprint/static/js/app/viewmodels/navigation.js b/src/octoprint/static/js/app/viewmodels/navigation.js index 96bf58cdd..1d343848a 100644 --- a/src/octoprint/static/js/app/viewmodels/navigation.js +++ b/src/octoprint/static/js/app/viewmodels/navigation.js @@ -9,6 +9,21 @@ $(function () { self.system = parameters[4]; self.access = parameters[5]; + self.offline = ko.observable(!ONLINE); + self.offlinePopoverContent = function () { + return ( + "

" + + gettext( + "OctoPrint cannot reach the internet. If this is not " + + "intentional, please check OctoPrint's network settings and " + + "the connectivity check configuration. Updates, plugin repository " + + "and anything else requiring access to the public internet will not " + + "work." + ) + + "

" + ); + }; + self.appearanceClasses = ko.pureComputed(function () { var classes = self.appearance.color(); if (self.appearance.colorTransparent()) { @@ -16,6 +31,10 @@ $(function () { } return classes; }); + + self.onServerReconnect = self.onServerConnect = self.onEventConnectivityChanged = function () { + self.offline(!ONLINE); + }; } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 1a123747c..1457d4a17 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -157,6 +157,7 @@ $(function () { self.webcam_snapshotTimeout = ko.observable(undefined); self.webcam_snapshotSslValidation = ko.observable(undefined); self.webcam_ffmpegPath = ko.observable(undefined); + self.webcam_ffmpegCommandline = ko.observable(undefined); self.webcam_bitrate = ko.observable(undefined); self.webcam_ffmpegThreads = ko.observable(undefined); self.webcam_ffmpegVideoCodec = ko.observable(undefined); @@ -172,6 +173,7 @@ $(function () { self.feature_modelSizeDetection = ko.observable(undefined); self.feature_printStartConfirmation = ko.observable(undefined); self.feature_printCancelConfirmation = ko.observable(undefined); + self.feature_uploadOverwriteConfirmation = ko.observable(undefined); self.feature_g90InfluencesExtruder = ko.observable(undefined); self.feature_autoUppercaseBlacklist = ko.observable(undefined); diff --git a/src/octoprint/templates/dialogs/files.jinja2 b/src/octoprint/templates/dialogs/files.jinja2 index b841abf1d..75cc5e71e 100644 --- a/src/octoprint/templates/dialogs/files.jinja2 +++ b/src/octoprint/templates/dialogs/files.jinja2 @@ -41,3 +41,27 @@ {{ _('Move') }}
+ + diff --git a/src/octoprint/templates/dialogs/settings/accesscontrol.jinja2 b/src/octoprint/templates/dialogs/settings/accesscontrol.jinja2 index 06f89eb73..2e8cc7b22 100644 --- a/src/octoprint/templates/dialogs/settings/accesscontrol.jinja2 +++ b/src/octoprint/templates/dialogs/settings/accesscontrol.jinja2 @@ -1,3 +1,4 @@ +

{{ _("Access Control") }}