Merge branch 'maintenance' into devel

This commit is contained in:
Gina Häußge committed 2022-02-15 14:54:44 +01:00
commit 30161e98b5
109 files changed
+1498 -850

No files matched your search

+3
View File
@@ -1,5 +1,8 @@
# refs to ignore during git blame, use with --ignore-revs-file
# pre-commit version updates
b4f265d9f67508677e1697e74e248b895da7f43c
# Switch to black formatting
1f93b2355a2816918e11a55e61b42010d15a6720
5f2a95d154650366078b0d387e5b01427c4340c0
+15 -4
View File
@@ -1,9 +1,23 @@
name: 🐛 Report a bug
description: Create a bug report to help improve OctoPrint
description: Help improve OctoPrint by reporting observed bugs. Got a question or need support? See "Have questions or need support?" instead!
body:
- type: markdown
attributes:
value: >
### ✋ **This is bug tracker, not a support forum**
If something isn't working right, you have questions or need help, [**get in touch on the forums**](https://community.octoprint.org/c/support/).
Only proceed here if you are 100% sure the issue you are seeing is actually a bug in OctoPrint that *also happens in safe mode*. If in doubt, check
in on the forums first, we can always file a bug from a support request later.
---
**Thank you for wanting to report a bug in OctoPrint!**
@@ -19,9 +33,6 @@ body:
OctoPi, [read this FAQ entry](https://faq.octoprint.org/octoprint-vs-octopi).
Do also not seek support here ("I need help with ...", "I have a
question ...", "Can someone walk me through ..."), that belongs into the
[community forum at community.octoprint.org](https://community.octoprint.org) or on the [Discord server](https://discord.octoprint.org).
And finally, make sure any bug you want to report is still present with the **current**
+1
View File
@@ -1,3 +1,4 @@
blank_issues_enabled: false
contact_links:
- name: 🤔 Have questions or need support?
url: https://community.octoprint.org
+3
View File
@@ -13,3 +13,6 @@ labels:
additional_allowed_targets: ["master"]
ci/cd:
additional_allowed_targets: ["master"]
check_can_modify: true
create_review: true
+8 -8
View File
@@ -23,11 +23,11 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
#- name: 🔀 Merge maintenance into devel
# uses: robotology/gh-action-nightly-merge@v1.3.2
# with:
# stable_branch: "maintenance"
# development_branch: "devel"
# allow_ff: false
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: 🔀 Merge maintenance into devel
uses: robotology/gh-action-nightly-merge@v1.3.2
with:
stable_branch: "maintenance"
development_branch: "devel"
allow_ff: false
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+14 -38
View File
@@ -1,7 +1,7 @@
exclude: ^(src/octoprint/vendor/|src/octoprint/static/js/lib|src/octoprint/static/vendor|tests/static/js/lib|tests/util/_files|docs/|scripts/|translations/|versioneer.py|.*\.css|.*\.svg)
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
rev: v4.1.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
@@ -14,21 +14,21 @@ repos:
args: ["--remove"]
exclude: "setup.py|versioneer.py|src/octoprint_setuptools/__init__.py"
- repo: https://github.com/asottile/pyupgrade
rev: v2.10.0
rev: v2.31.0
hooks:
- id: pyupgrade
args: ["--py37-plus"]
exclude: "setup.py|versioneer.py|src/octoprint_setuptools/__init__.py"
- repo: https://github.com/OctoPrint/codemods
rev: devel
rev: "0.6.2"
hooks:
- id: codemod_detect_past_builtins_imports
args: ["--ignore", "src/octoprint/vendor"]
- id: codemod_not_in
args: ["--ignore", "src/octoprint/vendor"]
- id: codemod_detect_past_builtins_imports
- id: codemod_batch
args:
[
"--check",
"not_in",
"--check",
"detect_past_builtins_imports",
"--ignore",
"src/octoprint/vendor",
"--ignore",
@@ -36,53 +36,29 @@ repos:
"--ignore",
"versioneer.py",
"--ignore",
"src/octoprint_setuptools/__init__.py",
]
- id: codemod_remove_float_conversion
args:
[
"--ignore",
"src/octoprint/vendor",
"--ignore",
"setup.py",
"--ignore",
"versioneer.py",
"--ignore",
"src/octoprint_setuptools/__init__.py",
]
- id: codemod_remove_future_imports
args:
[
"--ignore",
"src/octoprint/vendor",
"--ignore",
"setup.py",
"--ignore",
"versioneer.py",
"--ignore",
"src/octoprint_setuptools/__init__.py",
"src/octoprint_setuptools/__init__.py"
]
- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.5.4
rev: v5.10.1
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 20.8b1
rev: 22.1.0
hooks:
- id: black
args: ["--config", "black.toml"]
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.4
rev: 3.9.2
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.1.2
rev: v2.5.1
hooks:
- id: prettier
- repo: https://github.com/pre-commit/mirrors-eslint
rev: v7.19.0
rev: v8.8.0
hooks:
- id: eslint
additional_dependencies:
+3
View File
@@ -161,7 +161,10 @@ date of first contribution):
* [Carey Metcalfe](https://github.com/pR0Ps)
* [Didi Kohen](https://github.com/kohend)
* [Taylor Talkington](https://github.com/The-EG)
* [Carey Metcalfe](https://github.com/pR0Ps)
* [Shell M. Shrader](https://github.com/synman)
* [Johan Verrept](https://github.com/JoveToo)
* [Nicu Surdu](https://github.com/surdu)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+6
View File
@@ -626,6 +626,12 @@ Profile
- 0..1
- ``float``
- The diameter of the printer's nozzle(s) in mm.
* - ``extruder.sharedNozzle``
- ``boolean``
- Whether there's only one nozzle shared among all extruders (true) or one nozzle per extruder (false).
* - ``extruder.defaultExtrusionLength``
- ``int``
- Default extrusion length used in Control tab on initial page load in mm.
* - ``extruder.count``
- 0..1
- ``int``
-2
View File
@@ -355,8 +355,6 @@ mapped, with the following exceptions:
- Maps to ``folder.timelapse_tmp`` in ``config.yaml``
* - ``plugins``
- Plugin settings as available from ``config.yaml`` and :class:`~octoprint.plugin.SettingsPlugin` implementations
* - ``printer.defaultExtrusionLength``
- Maps to ``printerParameters.defaultExtrusionLength`` in ``config.yaml``
* - ``scripts.gcode``
- Whole subtree of configured :ref:`GCODE scripts <sec-features-gcode_scripts>`
* - ``serial.port``
+4
View File
@@ -814,6 +814,10 @@ Use the following settings to configure the serial connection to the printer:
# other values can be used: https://docs.python.org/3/library/codecs.html#standard-encodings
encoding: ascii
# Whether to enable support for the shutdown action command, allowing the printer to
# shut down OctoPrint and the system it's running on
enableShutdownActionCommand: false
# Whether to "manually" trigger an ok for M29 (a lot of versions of this command are buggy and
# the response skips on the ok)
triggerOkForM29: true
+36
View File
@@ -265,6 +265,26 @@ FileRemoved
.. versionadded:: 1.3.3
FileMoved
A file has been moved from one location to an other location.
Payload:
* ``storage``: the storage's identifier
* ``source_path``: the source file's path within its storage location
* ``source_name``: the source file's name
* ``source_type``: the source file's type, a list of the path within the type hierarchy, e.g. ``["machinecode", "gcode"]`` or
``["model", "stl"]``
* ``destination_path``: the source file's path within its storage location
* ``destination_name``: the source file's name
* ``destination_type``: the source file's type, a list of the path within the type hierarchy, e.g. ``["machinecode", "gcode"]`` or
``["model", "stl"]``
.. note::
A moved file still triggers first a ``FileRemoved`` for its original path and then ``FileAdded`` event for the new one. After that a ```UpdatedFiles``` event is also fired.
.. versionadded:: 1.8.0
FolderAdded
A folder has been added to a storage.
@@ -294,6 +314,22 @@ FolderRemoved
.. versionadded:: 1.3.3
FolderMoved
A folder has been moved from one location to an other location.
Payload:
* ``storage``: the storage's identifier
* ``source_path``: the source folder's path within its storage location
* ``source_name``: the source folder's name
* ``destination_path``: the source folder's path within its storage location
* ``destination_name``: the source folder's name
.. note::
A moved folder still triggers first a ``FolderRemoved`` for its original path and then ``FolderAdded`` event for the new one. After that a ```UpdatedFiles``` event is also fired.
.. versionadded:: 1.8.0
UpdatedFiles
A file list was modified.
+11 -1
View File
@@ -75,8 +75,18 @@ sd_updated
.. versionadded:: 1.6.0
shutdown
When this command is received from the printer, **support for it is enabled in its settings**
and a working system shutdown command is configured, OctoPrint will immediately shutdown the system.
This command is not enabled by default due to the high risk of seeing it abused by malicious
firmware or manipulated GCODE, but can be enabled in the OctoPrint settings via Serial Connection >
Firmware & Protocol > Action Commands if so desired by the user.
.. versionadded:: 1.8.0
If the bundled :ref:`Action Command Prompt Support Plugin <sec-bundledplugins-action_command_prompt>` is enabled (which
should be the case by default), OctoPrint will also interactive dialog creation through its :ref:`supported commands <sec-bundledplugins-action_command_prompt-action_commands>`.
should be the case by default), OctoPrint will also support interactive dialog creation
through its :ref:`supported commands <sec-bundledplugins-action_command_prompt-action_commands>`.
Support for additional commands may be added by plugins by implementing a handler for the
:ref:`octoprint.comm.protocol.action <sec-plugins-hook-comm-protocol-action>` hook.
+3 -1
View File
@@ -227,7 +227,7 @@ octoprint.access.permissions
suffice.
* ``dangerous``: Whether this permission should be considered dangerous (``True``) or not (``False``)
* ``default_groups``: A list of standard groups this permission should be apply to by default. Standard groups
are ``admins``, ``users``, ``readonly`` and ``guests``
are ``octoprint.access.ADMIN_GROUP``, ``octoprint.access.USER_GROUP``, ``octoprint.access.READONLY_GROUP`` and ``octoprint.access.GUEST_GROUP``
The following example is based on some actual code included in the bundled Application Keys plugin and defines
one additional permission called ``ADMIN`` with a role ``admin`` which is marked as dangerous (since it gives
@@ -236,6 +236,8 @@ octoprint.access.permissions
.. code-block:: python
from octoprint.access import ADMIN_GROUP
def get_additional_permissions(*args, **kwargs):
return [
dict(key="ADMIN",
+1 -1
View File
@@ -36,7 +36,7 @@ bundled_plugins = [
core_deps = [
"cachelib>=0.2,<0.3",
"Click>=8.0.3,<9",
"colorlog>=5.0.1,<6",
"colorlog>=6,<7",
"emoji>=1.4.2,<2",
"feedparser>=6.0.8,<7",
"filetype>=1.0.7,<2",
+7 -5
View File
@@ -48,7 +48,7 @@ class FatalStartupError(Exception):
def __str__(self):
result = Exception.__str__(self)
if self.cause:
return "{}: {}".format(result, str(self.cause))
return f"{result}: {str(self.cause)}"
else:
return result
@@ -67,6 +67,7 @@ def init_platform(
verbosity=0,
uncaught_logger=None,
uncaught_handler=None,
disable_color=True,
safe_mode=False,
ignore_blacklist=False,
after_preinit_logging=None,
@@ -108,6 +109,7 @@ def init_platform(
verbosity=verbosity,
uncaught_logger=uncaught_logger,
uncaught_handler=uncaught_handler,
disable_color=disable_color,
)
except Exception as ex:
raise FatalStartupError("Could not initialize logging", cause=ex)
@@ -251,6 +253,7 @@ def init_logging(
verbosity=0,
uncaught_logger=None,
uncaught_handler=None,
disable_color=True,
):
"""Sets up logging."""
@@ -271,7 +274,6 @@ def init_logging(
"reset": True,
"log_colors": {
"DEBUG": "cyan",
"INFO": "white",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "bold_red",
@@ -285,7 +287,7 @@ def init_logging(
"console": {
"class": "octoprint.logging.handlers.OctoPrintStreamHandler",
"level": "DEBUG",
"formatter": "colored",
"formatter": "simple" if disable_color else "colored",
"stream": "ext://sys.stdout",
},
"file": {
@@ -667,7 +669,7 @@ def init_pluginsystem(
from octoprint.util import sv
sorted_disabled_from_overlays = sorted(
[(key, value[0], value[1]) for key, value in disabled_from_overlays.items()],
((key, value[0], value[1]) for key, value in disabled_from_overlays.items()),
key=lambda x: (x[2] is None, sv(x[2]), sv(x[0])),
)
@@ -723,7 +725,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
def format_blacklist(entries):
format_entry = (
lambda x: "{} ({})".format(x[0], x[1])
lambda x: f"{x[0]} ({x[1]})"
if isinstance(x, (list, tuple)) and len(x) == 2
else f"{x} (any)"
)
+10
View File
@@ -62,6 +62,7 @@ def init_platform_for_cli(ctx):
get_ctx_obj_option(ctx, "configfile", None),
overlays=get_ctx_obj_option(ctx, "overlays", None),
safe_mode=True,
disable_color=get_ctx_obj_option(ctx, "no_color", False),
)
(
@@ -236,6 +237,15 @@ def standard_options(hidden=False):
expose_value=False,
help="Enable safe mode; disables all third party plugins.",
),
factory(
"--no-color",
"no_color",
is_flag=True,
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Disable colored console output. Alternatively set the NO_COLOR environment variable to a value of 1.",
),
]
return bulk_options(options)
+1 -1
View File
@@ -131,7 +131,7 @@ def gcode_command(
bed_z=bedz,
)
click.echo("DONE:{}s".format(time.monotonic() - start_time))
click.echo(f"DONE:{time.monotonic() - start_time}s")
result = interpreter.get_result()
if empty_result(result):
+2 -4
View File
@@ -280,15 +280,13 @@ def listen(ctx):
click.echo(f"!!! Error: {error}")
def on_sent(ws, data):
click.echo(">>> {}".format(json.dumps(data)))
click.echo(f">>> {json.dumps(data)}")
def on_heartbeat(ws):
click.echo("<3")
def on_message(ws, message_type, message_payload):
click.echo(
"<<< {}, Payload: {}".format(message_type, json.dumps(message_payload))
)
click.echo(f"<<< {message_type}, Payload: {json.dumps(message_payload)}")
socket = ctx.obj.client.create_socket(
on_connect=on_connect,
+118 -3
View File
@@ -2,6 +2,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import sys
import click
@@ -16,7 +17,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
"""
sep = ":"
groups = ("plugin",)
groups = ("plugin", "css")
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
@@ -214,7 +215,6 @@ class OctoPrintDevelCommands(click.MultiCommand):
"""
import os
import sys
if not path:
path = os.getcwd()
@@ -235,7 +235,6 @@ class OctoPrintDevelCommands(click.MultiCommand):
@click.argument("name")
def command(name):
"""Uninstalls the plugin with the given name."""
import sys
lower_name = name.lower()
if not lower_name.startswith("octoprint_") and not lower_name.startswith(
@@ -249,6 +248,122 @@ class OctoPrintDevelCommands(click.MultiCommand):
return command
def css_build(self):
@click.command("build")
@click.option(
"--file",
"-f",
"files",
multiple=True,
help="Specify files to build, for a list of options use --list",
)
@click.option("--all", "all_files", is_flag=True, help="Build all less files")
@click.option(
"--list", "list_files", is_flag=True, help="List all available files and exit"
)
def command(files, all_files, list_files):
import os.path
import shutil
available_files = {
"core": {
"source": "static/less/octoprint.less",
"output": "static/css/octoprint.css",
},
"login": {
"source": "static/less/login.less",
"output": "static/css/login.css",
},
"recovery": {
"source": "static/less/recovery.less",
"output": "static/css/recovery.css",
},
"plugin_announcements": {
"source": "plugins/announcements/static/less/announcements.less",
"output": "plugins/announcements/static/css/announcements.css",
},
"plugin_appkeys_core": {
"source": "plugins/appkeys/static/less/appkeys.less",
"output": "plugins/appkeys/static/css/appkeys.css",
},
"plugin_appkeys_authdialog": {
"source": "plugins/appkeys/static/less/authdialog.less",
"output": "plugins/appkeys/static/css/authdialog.css",
},
"plugin_backup": {
"source": "plugins/backup/static/less/backup.less",
"output": "plugins/backup/static/css/backup.css",
},
"plugin_gcodeviewer": {
"source": "plugins/gcodeviewer/static/less/gcodeviewer.less",
"output": "plugins/gcodeviewer/static/css/gcodeviewer.css",
},
"plugin_logging": {
"source": "plugins/logging/static/less/logging.less",
"output": "plugins/logging/static/css/logging.css",
},
"plugin_pluginmanager": {
"source": "plugins/pluginmanager/static/less/pluginmanager.less",
"output": "plugins/pluginmanager/static/css/pluginmanager.css",
},
"plugin_softwareupdate": {
"source": "plugins/softwareupdate/static/less/softwareupdate.less",
"output": "plugins/softwareupdate/static/css/softwareupdate.css",
},
}
if list_files:
click.echo("Available files to build:")
for name in available_files.keys():
click.echo(f"- {name}")
sys.exit(0)
if all_files:
files = available_files.keys()
if not files:
click.echo(
"No files specified. Use `--file <file>` to specify individual files, or `--all` to build all."
)
sys.exit(1)
# Check that lessc is installed
less = shutil.which("lessc")
if not less:
click.echo(
"lessc is not installed/not available, please install it first"
)
click.echo(
"Try `npm i -g less` to install it (NOT lessc in this command!)"
)
sys.exit(1)
# Find the folder of the `octoprint` package
# Two folders up from this file
octoprint = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
for file in files:
if file not in available_files.keys():
click.echo(f"Unknown file {file}")
sys.exit(1)
source_path = os.path.join(octoprint, available_files[file]["source"])
output_path = os.path.join(octoprint, available_files[file]["output"])
# Check the target file exists
if not os.path.exists(source_path):
click.echo(f"Target file {source_path} does not exist")
continue
# Build command line, with necessary options
# TODO -x is deprecated, find replacement?
less_command = [less, "-x", source_path, output_path]
self.command_caller.call(less_command)
return command
@click.group(cls=OctoPrintDevelCommands)
def cli():
+4
View File
@@ -31,6 +31,7 @@ def run_server(
ignore_blacklist,
octoprint_daemon=None,
overlays=None,
disable_color=False,
):
"""Initializes the environment and starts up the server."""
@@ -120,6 +121,7 @@ def run_server(
ignore_blacklist=ignore_blacklist,
after_safe_mode=log_startup,
after_environment_detector=log_register_rollover,
disable_color=disable_color,
)
(
settings,
@@ -307,6 +309,7 @@ def serve_command(ctx, **kwargs):
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
overlays = get_value("overlays")
no_color = get_value("no_color")
if v4 and not host:
host = "0.0.0.0"
@@ -324,6 +327,7 @@ def serve_command(ctx, **kwargs):
safe_mode,
ignore_blacklist,
overlays=overlays,
disable_color=no_color,
)
+2 -2
View File
@@ -84,7 +84,7 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None
# add systeminfo
systeminfotxt = []
for k in sorted(systeminfo.keys()):
systeminfotxt.append("{}: {}".format(k, systeminfo[k]))
systeminfotxt.append(f"{k}: {systeminfo[k]}")
z.add(to_bytes("\n".join(systeminfotxt)), arcname="systeminfo.txt")
@@ -194,5 +194,5 @@ def systeminfo_command(ctx, path, **kwargs):
else:
# output systeminfo to console
for k in sorted(systeminfo.keys()):
click.echo("{}: {}".format(k, systeminfo[k]))
click.echo(f"{k}: {systeminfo[k]}")
ctx.exit(0)
+5 -5
View File
@@ -123,7 +123,7 @@ def add_user_command(ctx, username, password, groups, permissions, is_admin):
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
click.echo(f"\t{_user_to_line(user.as_dict())}")
except UserAlreadyExists:
click.echo(f"A user with the name {username} does already exist!", err=True)
@@ -170,7 +170,7 @@ def activate_command(ctx, username):
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
click.echo(f"\t{_user_to_line(user.asDict())}")
except UnknownUser:
click.echo(f"User {username} does not exist!", err=True)
@@ -187,17 +187,17 @@ def deactivate_command(ctx, username):
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
click.echo(f"\t{_user_to_line(user.asDict())}")
except UnknownUser:
click.echo(f"User {username} does not exist!", err=True)
def _print_list(users):
click.echo("{} users registered in the system:".format(len(users)))
click.echo(f"{len(users)} users registered in the system:")
for user in sorted(
map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))
):
click.echo("\t{}".format(_user_to_line(user)))
click.echo(f"\t{_user_to_line(user)}")
def _user_to_line(user):
+2 -2
View File
@@ -40,7 +40,7 @@ class Daemon:
# exit first parent
sys.exit(0)
except OSError as err:
self.error("First fork failed: {}".format(str(err)))
self.error(f"First fork failed: {str(err)}")
sys.exit(1)
# decouple from parent environment
@@ -55,7 +55,7 @@ class Daemon:
# exit from second parent
sys.exit(0)
except OSError as err:
self.error("Second fork failed: {}".format(str(err)))
self.error(f"Second fork failed: {str(err)}")
sys.exit(1)
def _redirect_io(self):
+1 -1
View File
@@ -70,7 +70,7 @@ class EnvironmentDetector:
return {
"id": get_os(),
"platform": sys.platform,
"bits": 64 if sys.maxsize > 2 ** 32 else 32,
"bits": 64 if sys.maxsize > 2**32 else 32,
}
def _detect_python(self):
+2
View File
@@ -62,8 +62,10 @@ class Events:
FILE_ADDED = "FileAdded"
FILE_REMOVED = "FileRemoved"
FILE_MOVED = "FileMoved"
FOLDER_ADDED = "FolderAdded"
FOLDER_REMOVED = "FolderRemoved"
FOLDER_MOVED = "FolderMoved"
# SD Upload
TRANSFER_STARTED = "TransferStarted"
+31 -15
View File
@@ -270,9 +270,7 @@ class FileManager:
def worker():
self._logger.info(
"Adding backlog items from all storage types to analysis queue...".format(
**locals()
)
"Adding backlog items from all storage types to analysis queue..."
)
for storage_type, storage_manager in self._storage_managers.items():
self._determine_analysis_backlog(storage_type, storage_manager)
@@ -329,15 +327,11 @@ class FileManager:
if root:
self._logger.info(
'Added {counter} items from storage type "{storage_type}" and root "{root}" to analysis queue'.format(
**locals()
)
f'Added {counter} items from storage type "{storage_type}" and root "{root}" to analysis queue'
)
else:
self._logger.info(
'Added {counter} items from storage type "{storage_type}" to analysis queue'.format(
**locals()
)
f'Added {counter} items from storage type "{storage_type}" to analysis queue'
)
def add_storage(self, storage_type, storage_manager):
@@ -451,9 +445,9 @@ class FileManager:
file_obj = StreamWrapper(
os.path.basename(dest_path),
io.BytesIO(
";Generated from {stl_name} (hash: {hash})\n".format(
**locals()
).encode("ascii", "replace")
f";Generated from {stl_name} (hash: {hash})\n".encode(
"ascii", "replace"
)
),
io.FileIO(tmp_path, "rb"),
)
@@ -828,6 +822,19 @@ class FileManager:
"type": get_file_type(dst_name),
},
)
eventManager().fire(
Events.FILE_MOVED,
{
"storage": destination,
"source_path": source_path_in_storage,
"source_name": source_name,
"source_type": get_file_type(source_name),
"destination_path": dst_path_in_storage,
"destination_name": dst_name,
"destination_type": get_file_type(dst_name),
},
)
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
def add_folder(self, destination, path, ignore_existing=True, display=None):
@@ -889,6 +896,17 @@ class FileManager:
Events.FOLDER_ADDED,
{"storage": destination, "path": dst_path_in_storage, "name": dst_name},
)
eventManager().fire(
Events.FOLDER_MOVED,
{
"storage": destination,
"source_path": source_path_in_storage,
"source_name": source_name,
"destination_path": dst_path_in_storage,
"destination_name": dst_name,
},
)
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
def has_analysis(self, destination, path):
@@ -1023,9 +1041,7 @@ class FileManager:
def _storage(self, destination):
if destination not in self._storage_managers:
raise NoSuchStorage(
"No storage configured for destination {destination}".format(**locals())
)
raise NoSuchStorage(f"No storage configured for destination {destination}")
return self._storage_managers[destination]
def _add_analysis_result(self, destination, path, result):
+15 -35
View File
@@ -480,7 +480,7 @@ class LocalFileStorage(StorageInterface):
os.makedirs(self.basefolder)
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
raise StorageError(
"{basefolder} is not a valid directory".format(**locals()),
f"{basefolder} is not a valid directory",
code=StorageError.INVALID_DIRECTORY,
)
@@ -671,7 +671,7 @@ class LocalFileStorage(StorageInterface):
if os.path.exists(folder_path):
if not ignore_existing:
raise StorageError(
"{name} does already exist in {path}".format(**locals()),
f"{name} does already exist in {path}",
code=StorageError.ALREADY_EXISTS,
)
else:
@@ -700,7 +700,7 @@ class LocalFileStorage(StorageInterface):
if not empty and not recursive:
raise StorageError(
"{name} in {path} is not empty".format(**locals()),
f"{name} in {path} is not empty",
code=StorageError.NOT_EMPTY,
)
@@ -870,23 +870,19 @@ class LocalFileStorage(StorageInterface):
if not octoprint.filemanager.valid_file_type(name):
raise StorageError(
"{name} is an unrecognized file type".format(**locals()),
f"{name} is an unrecognized file type",
code=StorageError.INVALID_FILE,
)
file_path = os.path.join(path, name)
if os.path.exists(file_path) and not os.path.isfile(file_path):
raise StorageError(
"{name} does already exist in {path} and is not a file".format(
**locals()
),
f"{name} does already exist in {path} and is not a file",
code=StorageError.ALREADY_EXISTS,
)
if os.path.exists(file_path) and not allow_overwrite:
raise StorageError(
"{name} does already exist in {path} and overwriting is prohibited".format(
**locals()
),
f"{name} does already exist in {path} and overwriting is prohibited",
code=StorageError.ALREADY_EXISTS,
)
@@ -942,16 +938,14 @@ class LocalFileStorage(StorageInterface):
return
if not os.path.isfile(file_path):
raise StorageError(
"{name} in {path} is not a file".format(**locals()),
f"{name} in {path} is not a file",
code=StorageError.INVALID_FILE,
)
try:
os.remove(file_path)
except Exception as e:
raise StorageError(
"Could not delete {name} in {path}".format(**locals()), cause=e
)
raise StorageError(f"Could not delete {name} in {path}", cause=e)
self._remove_metadata_entry(path, name)
@@ -1186,9 +1180,7 @@ class LocalFileStorage(StorageInterface):
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
path = os.path.realpath(joined_path)
if not path.startswith(self.basefolder):
raise ValueError(
"path not contained in base folder: {path}".format(**locals())
)
raise ValueError(f"path not contained in base folder: {path}")
return path
def _sanitize_entry(self, entry, path, entry_path):
@@ -1811,9 +1803,7 @@ class LocalFileStorage(StorageInterface):
metadata = json.load(f)
except Exception:
self._logger.exception(
"Error while reading .metadata.json from {path}".format(
**locals()
)
f"Error while reading .metadata.json from {path}"
)
def valid_json(value):
@@ -1858,9 +1848,7 @@ class LocalFileStorage(StorageInterface):
to_bytes(json.dumps(metadata, indent=2, separators=(",", ": ")))
)
except Exception:
self._logger.exception(
"Error while writing .metadata.json to {path}".format(**locals())
)
self._logger.exception(f"Error while writing .metadata.json to {path}")
def _delete_metadata(self, path):
with self._get_metadata_lock(path):
@@ -1876,9 +1864,7 @@ class LocalFileStorage(StorageInterface):
os.remove(metadata_path)
except Exception:
self._logger.exception(
"Error while deleting {metadata_file} from {path}".format(
**locals()
)
f"Error while deleting {metadata_file} from {path}"
)
@staticmethod
@@ -1905,18 +1891,14 @@ class LocalFileStorage(StorageInterface):
os.remove(metadata_path_yaml)
except Exception:
self._logger.exception(
"Error while removing .metadata.yaml from {path}".format(
**locals()
)
f"Error while removing .metadata.yaml from {path}"
)
return
try:
metadata = yaml.load_from_file(path=metadata_path_yaml)
except Exception:
self._logger.exception(
"Error while reading .metadata.yaml from {path}".format(**locals())
)
self._logger.exception(f"Error while reading .metadata.yaml from {path}")
return
if not isinstance(metadata, dict):
@@ -1929,9 +1911,7 @@ class LocalFileStorage(StorageInterface):
try:
os.remove(metadata_path_yaml)
except Exception:
self._logger.exception(
"Error while removing .metadata.yaml from {path}".format(**locals())
)
self._logger.exception(f"Error while removing .metadata.yaml from {path}")
@contextmanager
def _get_metadata_lock(self, path):
+15 -39
View File
@@ -1447,9 +1447,7 @@ class PluginManager:
**flags (dict): dictionary of flag names and values
"""
if name not in self.plugins:
self.logger.debug(
"Trying to mark an unknown plugin {name}".format(**locals())
)
self.logger.debug(f"Trying to mark an unknown plugin {name}")
for key, value in flags.items():
if value is None:
@@ -1480,9 +1478,7 @@ class PluginManager:
self, name, plugin=None, startup=False, initialize_implementation=True
):
if name not in self.plugins:
self.logger.warning(
"Trying to load an unknown plugin {name}".format(**locals())
)
self.logger.warning(f"Trying to load an unknown plugin {name}")
return
if plugin is None:
@@ -1499,7 +1495,7 @@ class PluginManager:
self.on_plugin_loaded(name, plugin)
plugin.loaded = True
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
self.logger.debug(f"Loaded plugin {name}: {plugin}")
except PluginLifecycleException as e:
raise e
except Exception:
@@ -1507,9 +1503,7 @@ class PluginManager:
def unload_plugin(self, name):
if name not in self.plugins:
self.logger.warning(
"Trying to unload unknown plugin {name}".format(**locals())
)
self.logger.warning(f"Trying to unload unknown plugin {name}")
return
plugin = self.plugins[name]
@@ -1529,13 +1523,11 @@ class PluginManager:
plugin.loaded = False
self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals()))
self.logger.debug(f"Unloaded plugin {name}: {plugin}")
except PluginLifecycleException as e:
raise e
except Exception:
self.logger.exception(
"There was an error unloading plugin {name}".format(**locals())
)
self.logger.exception(f"There was an error unloading plugin {name}")
# make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins
if name in self.enabled_plugins:
@@ -1549,9 +1541,7 @@ class PluginManager:
"""Enables a plugin"""
if name not in self.disabled_plugins:
self.logger.warning(
"Tried to enable plugin {name}, however it is not disabled".format(
**locals()
)
f"Tried to enable plugin {name}, however it is not disabled"
)
return
@@ -1578,9 +1568,7 @@ class PluginManager:
except PluginLifecycleException as e:
raise e
except Exception:
self.logger.exception(
"There was an error while enabling plugin {name}".format(**locals())
)
self.logger.exception(f"There was an error while enabling plugin {name}")
return False
else:
if name in self.disabled_plugins:
@@ -1595,7 +1583,7 @@ class PluginManager:
plugin.implementation.on_plugin_enabled()
self.on_plugin_enabled(name, plugin)
self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals()))
self.logger.debug(f"Enabled plugin {name}: {plugin}")
return True
@@ -1603,9 +1591,7 @@ class PluginManager:
"""Disables a plugin"""
if name not in self.enabled_plugins:
self.logger.warning(
"Tried to disable plugin {name}, however it is not enabled".format(
**locals()
)
f"Tried to disable plugin {name}, however it is not enabled"
)
return
@@ -1621,9 +1607,7 @@ class PluginManager:
except PluginLifecycleException as e:
raise e
except Exception:
self.logger.exception(
"There was an error while disabling plugin {name}".format(**locals())
)
self.logger.exception(f"There was an error while disabling plugin {name}")
return False
else:
if name in self.enabled_plugins:
@@ -1635,7 +1619,7 @@ class PluginManager:
plugin.implementation.on_plugin_disabled()
self.on_plugin_disabled(name, plugin)
self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals()))
self.logger.debug(f"Disabled plugin {name}: {plugin}")
return True
@@ -1973,17 +1957,13 @@ class PluginManager:
raise e
else:
self.logger.exception(
"Exception while initializing plugin {name}, disabling it".format(
**locals()
)
f"Exception while initializing plugin {name}, disabling it"
)
return False
else:
self.on_plugin_implementations_initialized(name, plugin)
self.logger.debug(
"Initialized plugin mixin implementation for plugin {name}".format(**locals())
)
self.logger.debug(f"Initialized plugin mixin implementation for plugin {name}")
return True
def log_all_plugins(
@@ -2426,11 +2406,7 @@ class PluginNeedsRestart(Exception):
def __init__(self, name):
Exception.__init__(self)
self.name = name
self.message = (
"Plugin {name} cannot be enabled or disabled after system startup".format(
**locals()
)
)
self.message = f"Plugin {name} cannot be enabled or disabled after system startup"
class PluginLifecycleException(Exception):
@@ -51,9 +51,12 @@ $(function () {
self.requestData();
};
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
self.onStartup =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.requestData();
};
self.onDataUpdaterPluginMessage = function (plugin, data) {
if (
@@ -243,7 +243,8 @@ $(function () {
)
return;
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
var displayLimit =
self.settings.settings.plugins.announcements.display_limit();
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
var cutAfterNewline = function (text) {
@@ -399,17 +400,20 @@ $(function () {
self.settings.show("settings_plugin_announcements");
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
)
) {
self.hideAnnouncements();
} else {
self.retrieveData();
}
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
)
) {
self.hideAnnouncements();
} else {
self.retrieveData();
}
};
self.onStartup = function () {
self.announcementDialog = $("#plugin_announcements_dialog");
@@ -1 +1 @@
#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}#plugin_appkeys_keygenerated .control-text{display:inline-block}
#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a{color:black}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type="checkbox"],#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type="checkbox"]{margin-top:0}#plugin_appkeys_keygenerated .control-text{display:inline-block}
@@ -1 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}#auth-choice,#auth-done,#auth-error,#auth-offline{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05);text-align:center}.form-auth-heading{margin-bottom:10px}
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}#auth-choice,#auth-done,#auth-error,#auth-offline{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05);text-align:center}.form-auth-heading{margin-bottom:10px}
+5 -5
View File
@@ -512,7 +512,7 @@ class BackupPlugin(
datafolder=datafolder,
)
click.echo("Done.")
click.echo("Backup located at {}".format(os.path.join(datafolder, filename)))
click.echo(f"Backup located at {os.path.join(datafolder, filename)}")
@click.command("restore")
@click.argument("path")
@@ -685,7 +685,7 @@ class BackupPlugin(
pass
self._send_client_message(
"backup_error", payload={"name": name, "error": "{}".format(exc_info[1])}
"backup_error", payload={"name": name, "error": f"{exc_info[1]}"}
)
self._logger.error("Error while creating backup zip", exc_info=exc_info)
@@ -751,7 +751,7 @@ class BackupPlugin(
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
if os.path.exists(data_file):
try:
with open(data_file, mode="rt", encoding="utf-8") as f:
with open(data_file, encoding="utf-8") as f:
unknown_plugins = json.load(f)
assert isinstance(unknown_plugins, list)
@@ -956,8 +956,8 @@ class BackupPlugin(
)
except Exception:
logger.exception(
"Error while retrieving additional excludes "
"from plugin {name}".format(**locals()),
f"Error while retrieving additional excludes "
f"from plugin {name}",
extra={"plugin": plugin},
)
@@ -1 +1 @@
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009}
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:black}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type="checkbox"]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:bold}#settings_plugin_backup_restoredialog_output .error{font-weight:bold;color:#990000}#settings_plugin_backup_restoredialog_output .stdout{color:#333333}#settings_plugin_backup_restoredialog_output .stderr{color:#990000}#settings_plugin_backup_restoredialog_output .call{color:#000099}
@@ -316,7 +316,8 @@ $(function () {
);
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._forcedStdoutLine =
/You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function (line) {
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
@@ -13,7 +13,8 @@ $(function () {
if (self.settings.settings.plugins.errortracking.enabled()) return;
// RC release channel?
var releaseChannel = self.settings.settings.plugins.softwareupdate.octoprint_release_channel();
var releaseChannel =
self.settings.settings.plugins.softwareupdate.octoprint_release_channel();
if (releaseChannel === "rc/maintenance" || releaseChannel === "rc/devel") {
if (notification !== undefined) return;
@@ -101,21 +102,24 @@ $(function () {
};
var subbed = false;
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function () {
performCheck();
if (
self.settings &&
self.settings.settings &&
self.settings.settings.plugins &&
self.settings.settings.plugins.softwareupdate &&
!subbed
) {
subbed = true;
self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe(
performCheck
);
}
};
self.onStartup =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
performCheck();
if (
self.settings &&
self.settings.settings &&
self.settings.settings.plugins &&
self.settings.settings.plugins.softwareupdate &&
!subbed
) {
subbed = true;
self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe(
performCheck
);
}
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -437,8 +437,10 @@ GCODE.renderer = (function () {
canvas.addEventListener(
"mousedown",
function (event) {
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect =
"none";
document.body.style.mozUserSelect =
document.body.style.webkitUserSelect =
document.body.style.userSelect =
"none";
// remember starting point of dragging gesture
lastX = (event.offsetX || event.pageX - canvas.offsetLeft) * pixelRatio;
@@ -1 +1 @@
table td.settings_logs_checkbox,table th.settings_logs_checkbox{text-align:center;width:10px}table td.settings_logs_checkbox input[type=checkbox],table th.settings_logs_checkbox input[type=checkbox]{margin-top:0}table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
table th.settings_logs_checkbox,table td.settings_logs_checkbox{text-align:center;width:10px}table th.settings_logs_checkbox input[type="checkbox"],table td.settings_logs_checkbox input[type="checkbox"]{margin-top:0}table th.settings_logs_name,table td.settings_logs_name{text-overflow:ellipsis;text-align:left}table th.settings_logs_size,table td.settings_logs_size{text-align:right;width:70px}table th.settings_logs_date,table td.settings_logs_date{text-align:left;width:130px}table th.settings_logs_action,table td.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table th.settings_logs_action a,table td.settings_logs_action a{text-decoration:none;color:#000}table th.settings_logs_action a.disabled,table td.settings_logs_action a.disabled{color:#ccc;cursor:default}
@@ -294,16 +294,20 @@ $(function () {
return OctoPrint.plugins.logging.bulkDownloadUrl(files);
};
self.onServerReconnect = self.onUserLoggedIn = self.onEventSettingsUpdated = self.onSettingsShown = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_LOGGING_MANAGE
)
) {
return;
}
self.requestData();
};
self.onServerReconnect =
self.onUserLoggedIn =
self.onEventSettingsUpdated =
self.onSettingsShown =
function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_LOGGING_MANAGE
)
) {
return;
}
self.requestData();
};
self.onSettingsBeforeSave = function () {
if (
+11 -17
View File
@@ -911,7 +911,7 @@ class PluginManagerPlugin(
force = True
except Exception as e:
self._logger.exception(f"Could not install plugin from {source}")
self._logger.exception("Reason: {}".format(repr(e)))
self._logger.exception(f"Reason: {repr(e)}")
result = {
"result": False,
"source": source,
@@ -934,7 +934,7 @@ class PluginManagerPlugin(
_, stdout, stderr = self._call_pip(pip_args)
except Exception as e:
self._logger.exception(f"Could not install plugin from {source}")
self._logger.exception("Reason: {}".format(repr(e)))
self._logger.exception(f"Reason: {repr(e)}")
result = {
"result": False,
"source": source,
@@ -1231,9 +1231,7 @@ class PluginManagerPlugin(
if plugin.origin is None:
self._logger.warning(
"Trying to uninstall plugin {plugin} but origin is unknown".format(
**locals()
)
f"Trying to uninstall plugin {plugin} but origin is unknown"
)
abort(500, description="Could not uninstall plugin, its origin is unknown")
@@ -1276,16 +1274,14 @@ class PluginManagerPlugin(
os.remove(full_path)
if full_path.endswith(".py"):
pyc_file = "{full_path}c".format(**locals())
pyc_file = f"{full_path}c"
if os.path.isfile(pyc_file):
self._log_stdout(f"Deleting plugin from {pyc_file}")
os.remove(pyc_file)
else:
self._logger.warning(
"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(
**locals()
)
f"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})"
)
abort(500, description="Could not uninstall plugin, its origin is unknown")
@@ -1427,9 +1423,7 @@ class PluginManagerPlugin(
"cleaned_up": sorted(list(cleaned_up)),
}
self._send_result_notification("cleanup_all", result)
self._logger.info(
"Cleaned up all data, {} left overs removed".format(len(cleaned_up))
)
self._logger.info(f"Cleaned up all data, {len(cleaned_up)} left overs removed")
# cleaning orphan cache
self._orphans = None
@@ -1537,7 +1531,7 @@ class PluginManagerPlugin(
package_name = plugin.origin.package_name
package_version = plugin.origin.package_version
versioned_package = "{package_name}-{package_version}".format(**locals())
versioned_package = f"{package_name}-{package_version}"
if package_name in packages or versioned_package in packages:
# exact match, we are done here
@@ -1564,7 +1558,7 @@ class PluginManagerPlugin(
def _call_pip(self, args):
if self._pip_caller is None or not self._pip_caller.available:
raise RuntimeError("No pip available, can't operate".format(**locals()))
raise RuntimeError("No pip available, can't operate")
if "--process-dependency-links" in args:
self._log_message(
@@ -1620,7 +1614,7 @@ class PluginManagerPlugin(
},
)
for line in lines: # noqa: B007
self._console_logger.debug("{prefix} {line}".format(**locals()))
self._console_logger.debug(f"{prefix} {line}")
def _mark_plugin_enabled(self, plugin, needs_restart=False):
disabled_list = list(
@@ -1945,8 +1939,8 @@ class PluginManagerPlugin(
reconnect_hooks.extend(filter(lambda x: isinstance(x, str), result))
except Exception:
self._logger.exception(
"Error while retrieving additional hooks for which a "
"reconnect is required from plugin {name}".format(**locals()),
f"Error while retrieving additional hooks for which a "
f"reconnect is required from plugin {name}",
extra={"plugin": name},
)
@@ -1 +1 @@
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox{text-align:center;width:10px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox],#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdiLine truncated
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox{text-align:center;width:10px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox input[type="checkbox"],#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox input[type="checkbox"]{margin-top:0}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px !important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px;padding-right:10px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty{overflow:hidden;width:100%;height:400px;background-image:url("../img/repo_unavailable.png");text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:bold}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:bold;color:#990000}#settings_plugin_pluLine truncated
@@ -1914,17 +1914,20 @@ $(function () {
self.settings = self.settingsViewModel.settings;
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
if (
self.loginState.hasPermission(
self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE
)
) {
self.requestPluginData({eval_notices: true});
} else {
self._resetNotifications();
}
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
if (
self.loginState.hasPermission(
self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE
)
) {
self.requestPluginData({eval_notices: true});
} else {
self._resetNotifications();
}
};
self.onSettingsShown = function () {
if (
@@ -1943,7 +1946,10 @@ $(function () {
self._resetNotifications = function () {
self._closeAllNotifications();
self.logContents.action.restart = self.logContents.action.reload = self.logContents.action.reconnect = false;
self.logContents.action.restart =
self.logContents.action.reload =
self.logContents.action.reconnect =
false;
self.logContents.steps = [];
};
@@ -2006,7 +2012,8 @@ $(function () {
}
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._forcedStdoutLine =
/You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function (line) {
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
@@ -28,6 +28,7 @@ from octoprint.server.util.flask import (
with_revalidation_checking,
)
from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml
from octoprint.util.commandline import CommandlineError
from octoprint.util.pip import create_pip_caller
from octoprint.util.version import (
get_comparable_version,
@@ -246,8 +247,8 @@ class SoftwareUpdatePlugin(
hook_checks = hook()
except Exception:
self._logger.exception(
"Error while retrieving update information "
"from plugin {name}".format(**locals()),
f"Error while retrieving update information "
f"from plugin {name}",
extra={"plugin": name},
)
else:
@@ -627,8 +628,7 @@ class SoftwareUpdatePlugin(
return False
restart_type = self._get_restart_type(check)
restart_command = self._get_restart_command(restart_type)
return restart_command is not None
return self._has_restart_command(restart_type)
def _get_restart_type(self, check):
if check.get("restart") in self.VALID_RESTART_TYPES:
@@ -640,17 +640,13 @@ class SoftwareUpdatePlugin(
return target_restart_type
def _get_restart_command(self, restart_type):
def _has_restart_command(self, restart_type):
if restart_type == "octoprint":
return self._settings.global_get(
["server", "commands", "serverRestartCommand"]
)
return self._system_commands.has_server_restart_command()
elif restart_type == "environment":
return self._settings.global_get(
["server", "commands", "systemRestartCommand"]
)
return self._system_commands.has_system_restart_command()
else:
return None
return False
# ~~ SettingsPlugin API
@@ -1702,7 +1698,7 @@ class SoftwareUpdatePlugin(
for key in sorted(d.keys()):
value = d[key]
if isinstance(value, dict):
lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value)))
lines.append(f"{key!r}: {dict_to_sorted_repr(value)}")
else:
lines.append(f"{key!r}: {value!r}")
@@ -1946,14 +1942,13 @@ class SoftwareUpdatePlugin(
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
# we can actually perform that
restart_command = self._get_restart_command(restart_type)
if restart_command:
if self._has_restart_command(restart_type):
self._send_client_message(
"restarting",
{"restart_type": restart_type, "results": target_results},
)
try:
self._perform_restart(restart_command)
self._perform_restart(restart_type)
except exceptions.RestartFailed:
self._send_client_message(
"restart_failed",
@@ -2163,18 +2158,19 @@ class SoftwareUpdatePlugin(
check["current"] = current
def _perform_restart(self, restart_command):
def _perform_restart(self, restart_type):
"""
Performs a restart using the supplied restart_command.
Performs a restart using the supplied restart_type.
"""
self._logger.info("Restarting...")
try:
util.execute(restart_command, evaluate_returncode=False, do_async=True)
except exceptions.ScriptError as e:
self._logger.exception(
f"Error while restarting via command {restart_command}"
)
if restart_type == "octoprint":
return self._system_commands.perform_server_restart()
elif restart_type == "environment":
return self._system_commands.perform_system_restart()
except CommandlineError as e:
self._logger.exception(f"Error while restarting of type {restart_type}")
self._logger.warning(f"Restart stdout:\n{e.stdout}")
self._logger.warning(f"Restart stderr:\n{e.stderr}")
raise exceptions.RestartFailed()
+1 -1
View File
@@ -238,7 +238,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
checks = data["checks"]
click.echo("Update in progress, updating:")
for name in to_be_updated:
click.echo("\t{}".format(name if name not in checks else checks[name]))
click.echo(f"\t{name if name not in checks else checks[name]}")
socket.wait()
@@ -1 +1 @@
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#990000}#settings_plugin_softwareupdate_workingdialog_output .call{color:#000099}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#990000}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -163,21 +163,24 @@ $(function () {
);
});
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
if (
self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK
)
) {
self.performCheck();
} else {
self._closePopup();
}
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
if (
self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK
)
) {
self.performCheck();
} else {
self._closePopup();
}
if (self.loginState.hasPermission(self.access.permissions.ADMIN)) {
self.requestUpdatelog();
}
};
if (self.loginState.hasPermission(self.access.permissions.ADMIN)) {
self.requestUpdatelog();
}
};
self._showPopup = function (options, eventListeners, singleButtonNotify) {
singleButtonNotify = singleButtonNotify || false;
@@ -665,9 +668,8 @@ $(function () {
current = JSON.parse(currentString);
}
current[self.loginState.username()] = self._informationToRemoteVersions(data);
localStorage["plugin.softwareupdate.seen_information"] = JSON.stringify(
current
);
localStorage["plugin.softwareupdate.seen_information"] =
JSON.stringify(current);
};
self._hasNotificationBeenSeen = function (data) {
@@ -15,6 +15,6 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
now = time.monotonic()
end = now + duration
while now < end:
log_cb(["{}s left...".format(end - now)], prefix=">", stream="output")
log_cb([f"{end - now}s left..."], prefix=">", stream="output")
time.sleep(5)
now = time.monotonic()
@@ -74,7 +74,8 @@ $(function () {
var data = {
plugins: {
tracking: {
enabled: self.settingsViewModel.settings.plugins.tracking.enabled()
enabled:
self.settingsViewModel.settings.plugins.tracking.enabled()
}
}
};
@@ -10,7 +10,6 @@ import queue
import re
import threading
import time
from typing import Any
from serial import SerialTimeoutException
@@ -1342,24 +1341,20 @@ class VirtualPrinter:
interval = int(sleep_after_match.group(2))
self._sleepAfter[command] = interval
self._send(
"// going to sleep {interval} seconds after each {command}".format(
**locals()
)
f"// going to sleep {interval} seconds after each {command}"
)
elif sleep_after_next_match is not None:
command = sleep_after_next_match.group(1)
interval = int(sleep_after_next_match.group(2))
self._sleepAfterNext[command] = interval
self._send(
"// going to sleep {interval} seconds after next {command}".format(
**locals()
)
f"// going to sleep {interval} seconds after next {command}"
)
elif custom_action_match is not None:
action = custom_action_match.group(1)
params = custom_action_match.group(2)
params = params.strip() if params is not None else ""
self._send("// action:{action} {params}".format(**locals()).strip())
self._send(f"// action:{action} {params}".strip())
elif prepare_ok_match is not None:
ok = prepare_ok_match.group(1)
self._prepared_oks.append(ok)
@@ -1476,7 +1471,7 @@ class VirtualPrinter:
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(
[
"E{}:{}".format(num, self._lastE[self.currentExtruder])
f"E{num}:{self._lastE[self.currentExtruder]}"
for num in range(self.extruderCount)
]
)
@@ -2100,8 +2095,8 @@ class VirtualPrinter:
ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize()
)
def _error(self, error: str, *args: Any, **kwargs: Any) -> str:
return "Error: {}".format(self._errors.get(error).format(*args, **kwargs))
def _error(self, error: str, *args, **kwargs) -> str:
return f"Error: {self._errors.get(error).format(*args, **kwargs)}"
class VirtualEEPROM:
+10
View File
@@ -83,6 +83,9 @@ A printer profile is a ``dict`` of the following structure:
* - ``extruder.sharedNozzle``
- ``boolean``
- Whether there's only one nozzle shared among all extruders (true) or one nozzle per extruder (false).
* - ``extruder.defaultExtrusionLength``
- ``int``
- Default extrusion length used in Control tab on initial page load in mm.
* - ``axes``
- ``dict``
- Information about the printer axes
@@ -242,6 +245,7 @@ class PrinterProfileManager:
"offsets": [(0, 0)],
"nozzleDiameter": 0.4,
"sharedNozzle": False,
"defaultExtrusionLength": 5,
},
"axes": {
"x": {"speed": 6000, "inverted": False},
@@ -606,6 +610,12 @@ class PrinterProfileManager:
profile["extruder"]["offsets"] = [(0.0, 0.0)]
modified = True
if "extruder" in profile and "defaultExtrusionLength" not in profile["extruder"]:
profile["extruder"]["defaultExtrusionLength"] = self.default["extruder"][
"defaultExtrusionLength"
]
modified = True
if "heatedChamber" not in profile:
profile["heatedChamber"] = False
modified = True
+26 -5
View File
@@ -65,9 +65,13 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._targetBedTemp = None
self._targetChamberTemp = None
self._temps = TemperatureHistory(
self._temps = DataHistory(
cutoff=settings().getInt(["temperature", "cutoff"]) * 60
)
self._markings = DataHistory(
cutoff=settings().getInt(["temperature", "cutoff"]) * 60
)
self._messages = deque([], 300)
self._log = deque([], 300)
@@ -503,7 +507,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if speed is None:
printer_profile = self._printerProfileManager.get_current_or_default()
speed = min([printer_profile["axes"][axis]["speed"] for axis in axes])
speed = min(printer_profile["axes"][axis]["speed"] for axis in axes)
if speed and not isinstance(speed, bool):
command += f" F{speed}"
@@ -718,6 +722,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return self._comm.getFilePosition()
def add_marking(self, type):
self._markings.append(
{
"type": type,
"time": time.time(),
}
)
def get_markings(self):
return self._markings
def start_print(self, pos=None, user=None, *args, **kwargs):
"""
Starts the currently loaded print job.
@@ -1390,6 +1405,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
temps=list(self._temps),
logs=list(self._log),
messages=list(self._messages),
markings=list(self._markings),
)
plugin_data = self._get_additional_plugin_data(initial=False)
@@ -1602,6 +1618,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload = self._payload_for_print_job_event(print_job_user=user, action_user=user)
if payload:
eventManager().fire(Events.PRINT_STARTED, payload)
self.add_marking("print")
self._logger_job.info(
"Print job started - origin: {}, path: {}, owner: {}, user: {}".format(
payload.get("origin"),
@@ -1625,6 +1642,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload = self._payload_for_print_job_event()
if payload:
payload["time"] = self._comm.getPrintTime()
self.add_marking("done")
self._updateProgressData(
completion=1.0,
filepos=payload["size"],
@@ -1701,6 +1719,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload["time"] = self._comm.getPrintTime()
eventManager().fire(Events.PRINT_CANCELLED, payload)
self.add_marking("cancel")
self._logger_job.info(
"Print job cancelled - origin: {}, path: {}, owner: {}, user: {}".format(
payload.get("origin"),
@@ -1752,6 +1771,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload.get("user"),
)
)
self.add_marking("pause")
if not suppress_script:
self.script(
"afterPrintPaused",
@@ -1764,6 +1784,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload = self._payload_for_print_job_event(action_user=user)
if payload:
eventManager().fire(Events.PRINT_RESUMED, payload)
self.add_marking("resume")
self._logger_job.info(
"Print job resumed - origin: {}, path: {}, owner: {}, user: {}".format(
payload.get("origin"),
@@ -2067,11 +2088,11 @@ class StateMonitor:
}
class TemperatureHistory(InvariantContainer):
class DataHistory(InvariantContainer):
def __init__(self, cutoff=30 * 60):
def temperature_invariant(data):
def data_invariant(data):
data.sort(key=lambda x: x["time"])
now = int(time.time())
return [item for item in data if item["time"] >= now - cutoff]
InvariantContainer.__init__(self, guarantee_invariant=temperature_invariant)
InvariantContainer.__init__(self, guarantee_invariant=data_invariant)
+19 -48
View File
@@ -43,6 +43,7 @@ from werkzeug.exceptions import HTTPException
import octoprint.util
import octoprint.util.net
from octoprint.server import util
from octoprint.systemcommands import system_command_manager
from octoprint.util.json import JsonEncoding
from octoprint.vendor.flask_principal import ( # noqa: F401
AnonymousIdentity,
@@ -381,6 +382,7 @@ class Server:
###
### See also issues #2035 and #2090
systemCommandManager = system_command_manager()
printerProfileManager = PrinterProfileManager()
eventManager = self._event_manager
@@ -487,6 +489,7 @@ class Server:
"json_decoder": jsonDecoder,
"connectivity_checker": connectivityChecker,
"environment_detector": self._environment_detector,
"system_commands": systemCommandManager,
}
# ~~ setup access control
@@ -691,11 +694,6 @@ class Server:
),
extra={"plugin": plugin},
)
access_validator = {
"access_validation": util.tornado.validation_chain(
*access_validators_from_plugins
)
}
timelapse_validators = [
util.tornado.access_validation_factory(
@@ -942,8 +940,8 @@ class Server:
result = hook(list(server_routes))
except Exception:
self._logger.exception(
"There was an error while retrieving additional "
"server routes from plugin hook {name}".format(**locals()),
f"There was an error while retrieving additional "
f"server routes from plugin hook {name}",
extra={"plugin": name},
)
else:
@@ -963,9 +961,7 @@ class Server:
)
self._logger.debug(
"Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}".format(
**locals()
)
f"Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}"
)
server_routes.append((route, handler, kwargs))
@@ -1019,8 +1015,8 @@ class Server:
result = hook(list(max_body_sizes))
except Exception:
self._logger.exception(
"There was an error while retrieving additional "
"upload sizes from plugin hook {name}".format(**locals()),
f"There was an error while retrieving additional "
f"upload sizes from plugin hook {name}",
extra={"plugin": name},
)
else:
@@ -1043,9 +1039,7 @@ class Server:
)
self._logger.debug(
"Adding maximum body size of {size}B for {method} requests to {route})".format(
**locals()
)
f"Adding maximum body size of {size}B for {method} requests to {route})"
)
max_body_sizes.append((method, route, size))
@@ -1059,7 +1053,7 @@ class Server:
self._logger.warning(
"server.reverseProxy.trustedDownstream is not a list, skipping"
)
trusted_downstreams = []
trusted_downstream = []
server_kwargs = {
"max_body_sizes": max_body_sizes,
@@ -1710,9 +1704,7 @@ class Server:
builder = EnvironBuilder(**kwargs)
app(builder.get_environ(), lambda *a, **kw: None)
logger.info(
"... done in {:.2f}s".format(time.monotonic() - start)
)
logger.info(f"... done in {time.monotonic() - start:.2f}s")
except Exception:
logger.exception(
"Error while trying to preemptively cache {} for {!r}".format(
@@ -1986,24 +1978,23 @@ class Server:
# delete path if it exists
if os.path.exists(path):
try:
self._logger.debug("Deleting {path}...".format(**locals()))
self._logger.debug(f"Deleting {path}...")
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except Exception:
self._logger.exception(
"Error while trying to delete {path}, "
"leaving it alone".format(**locals())
f"Error while trying to delete {path}, " f"leaving it alone"
)
continue
# re-create path if necessary
if recreate:
self._logger.debug("Creating {path}...".format(**locals()))
self._logger.debug(f"Creating {path}...")
error_text = (
"Error while trying to re-create {path}, that might cause "
"errors with the webassets cache".format(**locals())
f"Error while trying to re-create {path}, that might cause "
f"errors with the webassets cache"
)
try:
os.makedirs(path)
@@ -2026,8 +2017,8 @@ class Server:
except Exception:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception(
"Ignored error while creating "
"directory {path}".format(**locals())
f"Ignored error while creating "
f"directory {path}"
)
pass
else:
@@ -2046,7 +2037,7 @@ class Server:
self._logger.exception(error_text)
continue
self._logger.info("Reset webasset folder {path}...".format(**locals()))
self._logger.info(f"Reset webasset folder {path}...")
AdjustedEnvironment = type(Environment)(
Environment.__name__,
@@ -2129,26 +2120,6 @@ class Server:
"js/lib/hls.js",
"js/lib/less.js",
]
js_client = [
"js/app/client/base.js",
"js/app/client/socket.js",
"js/app/client/browser.js",
"js/app/client/connection.js",
"js/app/client/control.js",
"js/app/client/files.js",
"js/app/client/job.js",
"js/app/client/languages.js",
"js/app/client/printer.js",
"js/app/client/printerprofiles.js",
"js/app/client/settings.js",
"js/app/client/slicing.js",
"js/app/client/system.js",
"js/app/client/timelapse.js",
"js/app/client/users.js",
"js/app/client/util.js",
"js/app/client/wizard.js",
"js/app/client/access.js",
]
css_libs = [
"css/bootstrap.min.css",
+1 -3
View File
@@ -191,9 +191,7 @@ def _unpack_uploaded_tarball(path, target):
def _validate_archive_name(name):
if name.startswith("/") or ".." in name:
raise InvalidLanguagePack(
"Provided language pack contains invalid name {name}".format(**locals())
)
raise InvalidLanguagePack(f"Provided language pack contains invalid name {name}")
class InvalidLanguagePack(Exception):
+12 -5
View File
@@ -113,11 +113,6 @@ def getSettings():
"closeModalsWithClick": s.getBoolean(["appearance", "closeModalsWithClick"]),
"showInternalFilename": s.getBoolean(["appearance", "showInternalFilename"]),
},
"printer": {
"defaultExtrusionLength": s.getInt(
["printerParameters", "defaultExtrusionLength"]
)
},
"webcam": {
"webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]),
"timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]),
@@ -205,6 +200,7 @@ def getSettings():
"blockedCommands": s.get(["serial", "blockedCommands"]),
"ignoredCommands": s.get(["serial", "ignoredCommands"]),
"pausingCommands": s.get(["serial", "pausingCommands"]),
"sdCancelCommand": s.get(["serial", "sdCancelCommand"]),
"emergencyCommands": s.get(["serial", "emergencyCommands"]),
"helloCommand": s.get(["serial", "helloCommand"]),
"ignoreErrorsFromFirmware": s.getBoolean(
@@ -261,6 +257,9 @@ def getSettings():
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
"encoding": s.get(["serial", "encoding"]),
"enableShutdownActionCommand": s.get(
["serial", "enableShutdownActionCommand"]
),
},
"folder": {
"uploads": s.getBaseFolder("uploads"),
@@ -792,6 +791,8 @@ def _saveSettings(data):
data["serial"]["pausingCommands"], (list, tuple)
):
s.set(["serial", "pausingCommands"], data["serial"]["pausingCommands"])
if "sdCancelCommand" in data["serial"]:
s.set(["serial", "sdCancelCommand"], data["serial"]["sdCancelCommand"])
if "emergencyCommands" in data["serial"] and isinstance(
data["serial"]["emergencyCommands"], (list, tuple)
):
@@ -951,6 +952,12 @@ def _saveSettings(data):
if "encoding" in data["serial"]:
s.set(["serial", "encoding"], data["serial"]["encoding"])
if "enableShutdownActionCommand" in data["serial"]:
s.setBoolean(
["serial", "enableShutdownActionCommand"],
data["serial"]["enableShutdownActionCommand"],
)
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"]:
s.setBoolean(["serial", "log"], data["serial"]["log"])
+12 -20
View File
@@ -7,7 +7,6 @@ import re
import threading
import psutil
import sarge
from flask import abort, jsonify, request, url_for
from flask_babel import gettext
@@ -18,7 +17,8 @@ from octoprint.server import NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import get_remote_address, no_firstrun_access
from octoprint.settings import settings as s
from octoprint.util.platform import CLOSE_FDS
from octoprint.systemcommands import system_command_manager
from octoprint.util.commandline import CommandlineCaller
@api.route("/system/usage", methods=["GET"])
@@ -165,22 +165,14 @@ def executeSystemCommand(source, command):
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
p = sarge.run(
command_spec["command"],
close_fds=CLOSE_FDS,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
shell=True,
return_code, stdout_lines, stderr_lines = CommandlineCaller().call(
command_spec["command"], shell=True
)
if not do_ignore and p.returncode != 0:
returncode = p.returncode
stdout_text = p.stdout.text
stderr_text = p.stderr.text
error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(
source, command, returncode, stdout_text, stderr_text
)
if not do_ignore and return_code != 0:
stdout = "\n".join(stdout_lines)
stderr = "\n".join(stderr_lines)
error = f"Command for {source}:{command} failed with return code {return_code}:\n\nSTDOUT:\n{stdout}\n\nSTDERR:\n{stderr}"
logger.warning(prefix_multilines(error, prefix="! "))
if not do_async:
raise CommandFailed(error)
@@ -241,28 +233,28 @@ def _get_core_command_specs():
commands = collections.OrderedDict(
shutdown={
"command": s().get(["server", "commands", "systemShutdownCommand"]),
"command": system_command_manager().get_system_shutdown_command(),
"name": gettext("Shutdown system"),
"confirm": gettext(
"<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
},
reboot={
"command": s().get(["server", "commands", "systemRestartCommand"]),
"command": system_command_manager().get_system_restart_command(),
"name": gettext("Reboot system"),
"confirm": gettext(
"<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
},
restart={
"command": s().get(["server", "commands", "serverRestartCommand"]),
"command": system_command_manager().get_server_restart_command(),
"name": gettext("Restart OctoPrint"),
"confirm": gettext(
"<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
},
restart_safe={
"command": s().get(["server", "commands", "serverRestartCommand"]),
"command": system_command_manager().get_server_restart_command(),
"name": gettext("Restart OctoPrint in safe mode"),
"confirm": gettext(
"<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
+53 -32
View File
@@ -9,6 +9,8 @@ import logging
import os
import threading
import time
from datetime import datetime
from typing import Union
import flask
import flask.json
@@ -33,6 +35,7 @@ from octoprint.settings import settings
from octoprint.util import DefaultOrderedDict, deprecated, yaml
from octoprint.util.json import JsonEncoding
from octoprint.util.net import is_lan_address
from octoprint.util.tz import UTC_TZ, is_timezone_aware
# ~~ monkey patching
@@ -101,15 +104,12 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
# plugin translations
plugins = octoprint.plugin.plugin_manager().enabled_plugins
for name, plugin in plugins.items():
dirs = (
list(
map(
lambda x: os.path.join(x, "_plugins", name),
additional_folders,
)
dirs = list(
map(
lambda x: os.path.join(x, "_plugins", name),
additional_folders,
)
+ [os.path.join(plugin.location, "translations")]
)
) + [os.path.join(plugin.location, "translations")]
for dirname in dirs:
if not os.path.isdir(dirname):
continue
@@ -120,21 +120,20 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
)
except Exception:
logger.exception(
"Error while trying to load translations "
"for plugin {name}".format(**locals())
f"Error while trying to load translations "
f"for plugin {name}"
)
else:
if isinstance(plugin_translations, support.Translations):
translations = translations.merge(plugin_translations)
logger.debug(
"Using translation plugin folder {dirname} from "
"plugin {name} for locale {locale}".format(**locals())
f"Using translation plugin folder {dirname} from "
f"plugin {name} for locale {locale}"
)
break
else:
logger.debug(
"No translations for locale {locale} "
"from plugin {name}".format(**locals())
f"No translations for locale {locale} " f"from plugin {name}"
)
# core translations
@@ -145,8 +144,8 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
core_translations = support.Translations.load(dirname, [locale])
if isinstance(core_translations, support.Translations):
logger.debug(
"Using translation core folder {dirname} "
"for locale {locale}".format(**locals())
f"Using translation core folder {dirname} "
f"for locale {locale}"
)
break
else:
@@ -1278,21 +1277,40 @@ def check_etag(etag):
)
def check_lastmodified(lastmodified):
def check_lastmodified(lastmodified: Union[int, float, datetime]) -> bool:
"""Compares the provided lastmodified value with the value of the If-Modified-Since header.
If ``lastmodified`` is an int or float, it's assumed to be a Unix timestamp and converted
to a timezone aware datetime instance in UTC.
If ``lastmodified`` is a datetime instance, it needs to be timezone aware or the
result will always be ``False``.
Args:
lastmodified (Union[int, float, datetime]): The last modified value to compare against
Raises:
ValueError: If anything but an int, float or datetime instance is passed
Returns:
bool: true if the values indicate that the document is still up to date
"""
if lastmodified is None:
return False
from datetime import datetime
if isinstance(lastmodified, (int, float)):
# max(86400, lastmodified) is workaround for https://bugs.python.org/issue29097,
# present in CPython 3.6.x up to 3.7.1.
#
# I think it's fair to say that we'll never encounter lastmodified values older than
# 1970-01-02 so this is a safe workaround.
lastmodified = datetime.fromtimestamp(max(86400, lastmodified)).replace(
microsecond=0
)
#
# Timestamps are defined as seconds since epoch aka 1970/01/01 00:00:00Z, so we
# use UTC as timezone here.
lastmodified = datetime.fromtimestamp(
max(86400, lastmodified), tz=UTC_TZ
).replace(microsecond=0)
if not isinstance(lastmodified, datetime):
raise ValueError(
@@ -1301,6 +1319,15 @@ def check_lastmodified(lastmodified):
)
)
if not is_timezone_aware(lastmodified):
# datetime object is not timezone aware, we can't check lastmodified with that
logger = logging.getLogger(__name__)
logger.warning(
"lastmodified is not timezone aware, cannot check against If-Modified-Since. In the future this will become an error!",
stack_info=logger.isEnabledFor(logging.DEBUG),
)
return False
return (
flask.request.method in ("GET", "HEAD")
and flask.request.if_modified_since is not None
@@ -1752,24 +1779,20 @@ def collect_plugin_assets(preferred_stylesheet="css"):
for asset in all_assets["js"]:
if not asset_exists("js", asset):
continue
assets[asset_key]["js"][name].append(
"plugin/{name}/{asset}".format(**locals())
)
assets[asset_key]["js"][name].append(f"plugin/{name}/{asset}")
if "clientjs" in all_assets:
for asset in all_assets["clientjs"]:
if not asset_exists("clientjs", asset):
continue
assets[asset_key]["clientjs"][name].append(
"plugin/{name}/{asset}".format(**locals())
)
assets[asset_key]["clientjs"][name].append(f"plugin/{name}/{asset}")
if preferred_stylesheet in all_assets:
for asset in all_assets[preferred_stylesheet]:
if not asset_exists(preferred_stylesheet, asset):
continue
assets[asset_key][preferred_stylesheet][name].append(
"plugin/{name}/{asset}".format(**locals())
f"plugin/{name}/{asset}"
)
else:
for stylesheet in supported_stylesheets:
@@ -1779,9 +1802,7 @@ def collect_plugin_assets(preferred_stylesheet="css"):
for asset in all_assets[stylesheet]:
if not asset_exists(stylesheet, asset):
continue
assets[asset_key][stylesheet][name].append(
"plugin/{name}/{asset}".format(**locals())
)
assets[asset_key][stylesheet][name].append(f"plugin/{name}/{asset}")
break
return assets
+1
View File
@@ -445,6 +445,7 @@ class PrinterStateConnection(
"logs": self._filter_logs(logs),
"messages": messages,
"busyFiles": busy_files,
"markings": list(self._printer.get_markings()),
}
)
self._emit("current", payload=data)
-2
View File
@@ -1428,7 +1428,6 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
def get_attachment_name(self):
return self._attachment_name
# noinspection PyCompatibility
def normalize_files(self, files):
result = []
for f in files:
@@ -1456,7 +1455,6 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
pass
for f in self.normalize_files(files):
# noinspection PyCompatibility
name = f.get("name")
path = f.get("path")
data = f.get("iter") or f.get("content")
+2 -2
View File
@@ -64,7 +64,7 @@ class LessImportRewrite(UrlRewriter):
def import_rewrite(self, m):
import_with_options = m.group(1)
import_url = self.replace_url(m.group(3))
return '{import_with_options}"{import_url}";'.format(**locals())
return f'{import_with_options}"{import_url}";'
class SourceMapRewrite(UrlRewriter):
@@ -75,7 +75,7 @@ class SourceMapRewrite(UrlRewriter):
def url_rewrite(self, m):
mapping = m.group(1)
source_url = self.replace_url(m.group(2))
return "{mapping}{source_url}".format(**locals())
return f"{mapping}{source_url}"
class SourceMapRemove(PatternRewriter):
+18 -18
View File
@@ -374,12 +374,8 @@ def index():
connectivityChecker.online,
wizard_active(_templates.get(locale)),
] + sorted(
[
"{}:{}".format(
to_unicode(k, errors="replace"), to_unicode(v, errors="replace")
)
for k, v in _plugin_vars.items()
]
"{}:{}".format(to_unicode(k, errors="replace"), to_unicode(v, errors="replace"))
for k, v in _plugin_vars.items()
)
def get_preemptively_cached_view(
@@ -794,13 +790,13 @@ def fetch_template_data(refresh=False):
# Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and
# that require to access APIs to function will run into errors since those APIs won't work before ACL
# has been configured. See also #2140
return "0:{}".format(to_unicode(d[0]))
return f"0:{to_unicode(d[0])}"
elif d[1].get("mandatory", False):
# Other mandatory steps come before the optional ones
return "1:{}".format(to_unicode(d[0]))
return f"1:{to_unicode(d[0])}"
else:
# Finally everything else
return "2:{}".format(to_unicode(d[0]))
return f"2:{to_unicode(d[0])}"
template_sorting = {
"navbar": {"add": "prepend", "key": None},
@@ -826,8 +822,8 @@ def fetch_template_data(refresh=False):
result = hook(dict(template_sorting), dict(template_rules))
except Exception:
_logger.exception(
"Error while retrieving custom template type "
"definitions from plugin {name}".format(**locals()),
f"Error while retrieving custom template type "
f"definitions from plugin {name}",
extra={"plugin": name},
)
else:
@@ -849,11 +845,11 @@ def fetch_template_data(refresh=False):
# rule defaults
if "div" not in rule:
# default div name: <hook plugin>_<template_key>_plugin_<plugin>
div = "{name}_{key}_plugin_".format(**locals())
div = f"{name}_{key}_plugin_"
rule["div"] = lambda x: div + x
if "template" not in rule:
# default template name: <plugin>_plugin_<hook plugin>_<template key>.jinja2
template = "_plugin_{name}_{key}.jinja2".format(**locals())
template = f"_plugin_{name}_{key}.jinja2"
rule["template"] = lambda x: x + template
if "to_entry" not in rule:
# default to_entry assumes existing "name" property to be used as label for 2-tuple entry data structure (<name>, <properties>)
@@ -1607,6 +1603,8 @@ def _compute_date(files):
import stat
from datetime import datetime
from octoprint.util.tz import UTC_TZ
max_timestamp = 0
for path in files:
try:
@@ -1621,7 +1619,11 @@ def _compute_date(files):
if max_timestamp:
# we set the micros to 0 since microseconds are not speced for HTTP
max_timestamp = datetime.fromtimestamp(max_timestamp).replace(microsecond=0)
max_timestamp = (
datetime.fromtimestamp(max_timestamp)
.replace(microsecond=0)
.replace(tzinfo=UTC_TZ)
)
return max_timestamp
@@ -1655,9 +1657,7 @@ def _get_all_translationfiles(locale, domain):
from flask import _request_ctx_stack
def get_po_path(basedir, locale, domain):
return os.path.join(
basedir, locale, "LC_MESSAGES", "{domain}.po".format(**locals())
)
return os.path.join(basedir, locale, "LC_MESSAGES", f"{domain}.po")
po_files = []
@@ -1697,7 +1697,7 @@ def _get_translations(locale, domain):
def messages_from_po(path, locale, domain):
messages = {}
with open(path, mode="rt", encoding="utf-8") as f:
with open(path, encoding="utf-8") as f:
catalog = read_po(f, locale=locale, domain=domain)
for message in catalog:
+225 -126
View File
@@ -29,7 +29,6 @@ import time
from collections import ChainMap
from collections.abc import KeysView
# noinspection PyCompatibilitys
from yaml import YAMLError
from octoprint.util import (
@@ -139,6 +138,7 @@ default_settings = {
"sdRelativePath": False,
"sdAlwaysAvailable": False,
"sdLowerCase": False,
"sdCancelCommand": "M25",
"maxNotSdPrinting": 2,
"swallowOkAfterResend": True,
"repetierTargetTemp": False,
@@ -168,6 +168,7 @@ default_settings = {
"resendRatioStart": 100,
"ignoreEmptyPorts": False,
"encoding": "ascii",
"enableShutdownActionCommand": False,
# command specific flags
"triggerOkForM29": True,
},
@@ -303,7 +304,7 @@ default_settings = {
"sendAutomaticallyAfter": 1,
},
"printerProfiles": {"default": None},
"printerParameters": {"pauseTriggers": [], "defaultExtrusionLength": 5},
"printerParameters": {"pauseTriggers": []},
"appearance": {
"name": "",
"color": "default",
@@ -528,101 +529,232 @@ class DuplicateFolderPaths(InvalidSettings):
)
class HierarchicalChainMap(ChainMap):
def deep_dict(self):
def deep_dict_inner(root):
return {
key: deep_dict_inner(self.__class__._get_next(key, root))
if isinstance(value, dict)
else value
for key, value in root.items()
}
_CHAINMAP_SEP = "\x1f"
return deep_dict_inner(self)
class HierarchicalChainMap:
"""
Stores a bunch of nested dictionaries in chain map, allowing queries of nested values
work on lower directories. For example:
Example:
>>> example_dict = {"a": "a", "b": {"c": "c"}}
>>> hcm = HierarchicalChainMap({"b": {"d": "d"}}, example_dict)
>>> cm = ChainMap({"b": {"d": "d"}}, example_dict)
>>> cm["b"]["d"]
'd'
>>> cm["b"]["c"]
Traceback (most recent call last):
...
KeyError: 'c'
>>> hcm.get_by_path(["b", "d"])
'd'
>>> hcm.get_by_path(["b", "c"])
'c'
"""
@staticmethod
def _unflatten(kv_pairs, prefix=""):
"""
:type kv_pairs: Iterable[Tuple[str, any]]
"""
result = dict()
for key, value in kv_pairs:
if not key.startswith(prefix):
continue
subkeys = key[len(prefix) :].split(_CHAINMAP_SEP)
current = result
for subkey in subkeys[:-1]:
if subkey not in current:
current[subkey] = {}
current = current[subkey]
current[subkeys[-1]] = value
return result
def __init__(self, *maps):
self._chainmap = ChainMap(*map(self._flatten, maps))
@staticmethod
def from_layers(*layers):
result = HierarchicalChainMap()
result._chainmap.maps = layers
return result
@staticmethod
def _flatten(d, parent_key=""):
if d is None:
return {}
items = []
for k, v in d.items():
new_key = parent_key + _CHAINMAP_SEP + k if parent_key else k
if v and isinstance(v, dict):
items.extend(HierarchicalChainMap._flatten(v, new_key).items())
else:
items.append((new_key, v))
return dict(items)
def deep_dict(self):
return self._unflatten(self._chainmap.items())
@staticmethod
def _path_to_key(path):
"""
:type path: List[str]
"""
return _CHAINMAP_SEP.join(path)
def has_path(self, path, only_local=False, only_defaults=False):
if only_defaults:
current = self.parents
current = self._chainmap.parents
elif only_local:
current = self.__class__(self.maps[0])
current = self._chainmap.maps[0]
else:
current = self
current = self._chainmap
try:
for key in path[:-1]:
value = current[key]
if isinstance(value, dict):
current = self.__class__._get_next(
key, current, only_local=only_local
)
else:
return False
return path[-1] in current
except KeyError:
return False
return self._path_to_key(path) in current
def get_by_path(self, path, only_local=False, only_defaults=False, merged=False):
if only_defaults:
current = self.parents
current = self._chainmap.parents
elif only_local:
current = self.__class__(self.maps[0])
current = self._chainmap.maps[0]
else:
current = self
current = self._chainmap
for key in path[:-1]:
value = current[key]
if isinstance(value, dict):
current = self.__class__._get_next(key, current, only_local=only_local)
else:
raise KeyError(key)
key = self._path_to_key(path)
if merged:
current = current.deep_dict()
return current[path[-1]]
# we do something a bit odd here: if merged is not true, we don't include the
# full contents of the key. Instead, we only include the contents of the key on
# the first level where we find the value.
if not merged and not only_local:
for layer in current.maps:
for k in layer:
if k.startswith(key):
current = layer
break
else:
continue
break
if key not in current:
# we might be trying to grab a dict, look for children
key = key + _CHAINMAP_SEP
result = self._unflatten(
((k, v) for k, v in current.items() if k.startswith(key)), prefix=key
)
if not result:
raise KeyError("Could not find entry for " + str(path))
return result
return current[key]
def set_by_path(self, path, value):
current = self
current = self._chainmap
key = self._path_to_key(path)
for key in path[:-1]:
if key not in current.maps[0]:
current.maps[0][key] = {}
if not isinstance(current[key], dict):
raise KeyError(key)
current = self.__class__._hierarchy_for_key(key, current)
# delete any subkeys
subkeys_start = key + _CHAINMAP_SEP
for k in current.keys():
if k.startswith(subkeys_start):
del current[key]
current[path[-1]] = value
if isinstance(value, dict):
current.update(self._flatten(value, key))
else:
# when assigning to a existing, empty dict, delete the dict
#
# a/b = {} <- delete this
# a/b/c = "a"
up_one_path = self._path_to_key(path[:-1])
if up_one_path in current and current[up_one_path] == {}:
del current[up_one_path]
current[self._path_to_key(path)] = value
def del_by_path(self, path):
if not path:
raise ValueError("Invalid path")
current = self
current = self._chainmap
for key in path[:-1]:
if not isinstance(current[key], dict):
raise KeyError(key)
current = self.__class__._hierarchy_for_key(key, current)
# used to check if we've deleted anything
deleted_any = False
del current[path[-1]]
# we delete recursively: the path that we got, and any subpaths
delete_key = self._path_to_key(path)
for key in self._chainmap.keys():
if key.startswith(delete_key):
del current[key]
deleted_any = True
@classmethod
def _hierarchy_for_key(cls, key, chain):
wrapped_mappings = list()
for mapping in chain.maps:
if key in mapping and mapping[key] is not None:
wrapped_mappings.append(mapping[key])
else:
wrapped_mappings.append({})
return HierarchicalChainMap(*wrapped_mappings)
if not deleted_any:
raise KeyError("Could not find entry for " + str(path))
@classmethod
def _get_next(cls, key, node, only_local=False):
if isinstance(node, dict):
return node[key]
elif only_local and key not in node.maps[0]:
raise KeyError(key)
# create a placeholder object above if needed
#
# a/b = {}
# a/b/c = "a" # deleted
up_one_path = self._path_to_key(path[:-1])
if sum(1 for k in current.keys() if k.startswith(up_one_path)) == 0:
current[up_one_path] = {}
def with_config_defaults(self, config=None, defaults=None):
"""
Builds a new map with the following layers: provided config + any intermediary
parents + provided defaults + regular defaults
:param config:
:param defaults:
:return:
"""
if config is None and defaults is None:
return self
if config is not None:
config = self._flatten(config)
else:
return cls._hierarchy_for_key(key, node)
config = self.top_map
if defaults is not None:
defaults = [self._flatten(defaults)]
else:
defaults = []
layers = [config] + self._middle_layers() + defaults + [self._chainmap.maps[-1]]
return HierarchicalChainMap.from_layers(*layers)
@property
def top_map(self):
"""This is the layer that is written to"""
return self._unflatten(self._chainmap.maps[0].items())
@top_map.setter
def top_map(self, value):
self._chainmap.maps[0] = self._flatten(value)
@property
def bottom_map(self):
"""The very bottom layer is the default layer"""
return self._unflatten(self._chainmap.maps[-1])
def insert_map(self, pos, d):
self._chainmap.maps.insert(pos, self._flatten(d))
def delete_map(self, pos):
del self._chainmap.maps[pos]
@property
def all_layers(self):
"""A list of all layers in this map. read-only"""
return self._chainmap.maps
def _middle_layers(self):
if len(self._chainmap.maps) > 2:
return self._chainmap.maps[1:-1]
else:
return []
class Settings:
@@ -881,9 +1013,7 @@ class Settings:
return None
except Exception:
self._logger.exception(
"Exception while trying to resolve template {template_name}".format(
**locals()
)
f"Exception while trying to resolve template {template_name}"
)
return None
@@ -969,22 +1099,22 @@ class Settings:
@property
def _config(self):
return self._map.maps[0]
return self._map.top_map
@_config.setter
def _config(self, value):
self._map.maps[0] = value
self._map.top_map = value
@property
def _overlay_maps(self):
if len(self._map.maps) > 2:
return self._map.maps[1:-1]
def _overlay_layers(self):
if len(self._map.all_layers) > 2:
return self._map.all_layers[1:-1]
else:
return []
@property
def _default_map(self):
return self._map.maps[-1]
return self._map.bottom_map
@property
def last_modified(self):
@@ -1102,21 +1232,20 @@ class Settings:
overlay[self.OVERLAY_KEY] = key
if at_end:
pos = len(self._map.maps) - 1
self._map.maps.insert(pos, overlay)
self._map.insert_map(-1, overlay)
else:
self._map.maps.insert(1, overlay)
self._map.insert_map(1, overlay)
return key
def remove_overlay(self, key):
index = -1
for i, overlay in enumerate(self._overlay_maps):
for i, overlay in enumerate(self._overlay_layers):
if key == overlay.get(self.OVERLAY_KEY):
index = i
if index > -1:
del self._map.maps[index + 1]
self._map.delete_map(index + 1)
return True
return False
@@ -1604,7 +1733,7 @@ class Settings:
config["serial"]["blockedCommands"] = sorted(blockedCommands)
else:
config["serial"]["blockedCommands"] = sorted(
[v for v in blockedCommands if v not in ("M0", "M1")]
v for v in blockedCommands if v not in ("M0", "M1")
)
del config["serial"]["blockM0M1"]
return True
@@ -1705,18 +1834,7 @@ class Settings:
if not path:
raise NoSuchSettingsPath()
if config is not None or defaults is not None:
if config is None:
config = self._config
if defaults is None:
defaults = dict(self._map.parents)
# mappings: provided config + any intermediary parents + provided defaults + regular defaults
mappings = [config] + self._overlay_maps + [defaults, self._default_map]
chain = HierarchicalChainMap(*mappings)
else:
chain = self._map
chain = self._map.with_config_defaults(config=config, defaults=defaults)
if preprocessors is None:
preprocessors = self._get_preprocessors
@@ -1951,9 +2069,7 @@ class Settings:
script = template.render(**context)
except Exception:
self._logger.exception(
"Exception while trying to render script {script_type}:{name}".format(
**locals()
)
f"Exception while trying to render script {script_type}:{name}"
)
return None
@@ -1967,16 +2083,7 @@ class Settings:
raise NoSuchSettingsPath()
return
if config is not None or defaults is not None:
if config is None:
config = self._config
if defaults is None:
defaults = dict(self._map.parents)
chain = HierarchicalChainMap(config, defaults)
else:
chain = self._map
chain = self._map.with_config_defaults(config=config, defaults=defaults)
try:
chain.del_by_path(path)
@@ -2008,16 +2115,7 @@ class Settings:
if self._mtime is not None and self.last_modified != self._mtime:
self.load()
if config is not None or defaults is not None:
if config is None:
config = self._config
if defaults is None:
defaults = dict(self._map.parents)
chain = HierarchicalChainMap(config, defaults)
else:
chain = self._map
chain = self._map.with_config_defaults(config=config, defaults=defaults)
if preprocessors is None:
preprocessors = self._set_preprocessors
@@ -2059,12 +2157,15 @@ class Settings:
or (not in_local and in_defaults and default_value != value)
or (in_local and current != value)
):
if value is None and in_local:
chain.del_by_path(path)
else:
chain.set_by_path(path, value)
chain.set_by_path(path, value)
self._mark_dirty()
# we've changed the interface to no longer mutate the passed in config, so we
# must manually do that here
if config is not None:
config.clear()
config.update(chain.top_map)
def setInt(self, path, value, **kwargs):
if value is None:
self.set(path, None, **kwargs)
@@ -2151,9 +2252,7 @@ class Settings:
if not filename.startswith(os.path.realpath(script_folder)):
# oops, jail break, that shouldn't happen
raise ValueError(
"Invalid script path to save to: {filename} (from {script_type}:{name})".format(
**locals()
)
f"Invalid script path to save to: {filename} (from {script_type}:{name})"
)
path, _ = os.path.split(filename)
+3 -7
View File
@@ -306,10 +306,10 @@ class SlicingManager:
if slicer_name not in self.configured_slicers:
if slicer_name not in self.registered_slicers:
error = "No such slicer: {slicer_name}".format(**locals())
error = f"No such slicer: {slicer_name}"
exc = UnknownSlicer(slicer_name)
else:
error = "Slicer not configured: {slicer_name}".format(**locals())
error = f"Slicer not configured: {slicer_name}"
exc = SlicerNotConfigured(slicer_name)
callback_kwargs.update({"_error": error, "_exc": exc})
callback(*callback_args, **callback_kwargs)
@@ -726,11 +726,7 @@ class SlicingManager:
path = os.path.join(self.get_slicer_profile_path(slicer), f"{name}.profile")
if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)):
raise OSError(
"Path to profile {name} tried to break out of allows sub path".format(
**locals()
)
)
raise OSError(f"Path to profile {name} tried to break out of allows sub path")
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
raise UnknownProfile(slicer, name)
return path
+1 -1
View File
@@ -1 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .checkbox,.form-signin .form-signin-heading{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#fff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center}
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type="text"],.form-signin input[type="password"]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:white}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#ffffff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center}
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #fff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #fff, #e6e6e6);background-image:-o-linear-gradient(top, #fff, #e6e6e6);background-image:linear-gradient(to bottom, #fff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:65 / 100;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #08c, #04c);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#04c));background-image:-webkit-linear-gradient(top, #08c, #04c);background-image:-o-linear-gradient(top, #08c, #04c);background-image:linear-gradient(to bottom, #08c, #04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)Line truncated
+1 -1
View File
@@ -1 +1 @@
#workdialog .pre-output span{display:block}#workdialog .pre-output .message{font-weight:700}#workdialog .pre-output .error{font-weight:700;color:#900}#workdialog .pre-output .stdout{color:#333}#workdialog .pre-output .stderr{color:#900}#workdialog .pre-output .call{color:#009}
#workdialog .pre-output span{display:block}#workdialog .pre-output .message{font-weight:bold}#workdialog .pre-output .error{font-weight:bold;color:#990000}#workdialog .pre-output .stdout{color:#333333}#workdialog .pre-output .stderr{color:#990000}#workdialog .pre-output .call{color:#000099}
@@ -52,16 +52,18 @@ ko.bindingHandlers.slimScrolledForeach = {
},
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var prepped = ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(
valueAccessor
);
var prepped =
ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(
valueAccessor
);
ko.bindingHandlers["slimScrolledForeach"].slimscroll(element, prepped.slimscroll);
return ko.bindingHandlers["template"]["init"](element, prepped.accessor);
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var prepped = ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(
valueAccessor
);
var prepped =
ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(
valueAccessor
);
var options = $.extend(prepped.slimscroll, {scrollBy: 0});
ko.bindingHandlers["slimScrolledForeach"].slimscroll(element, options);
return ko.bindingHandlers["template"]["update"](
+2 -3
View File
@@ -368,9 +368,8 @@
return constructor;
};
OctoPrintClient.InvalidArgumentError = OctoPrintClient.createCustomException(
"InvalidArgumentError"
);
OctoPrintClient.InvalidArgumentError =
OctoPrintClient.createCustomException("InvalidArgumentError");
OctoPrintClient.deprecated = function (deprecatedFct, newFct, fn) {
return function () {
+21 -17
View File
@@ -17,25 +17,29 @@
this.base = base;
};
OctoPrintUserClient.prototype.list = deprecatedUserClient("list", "list", function (
opts
) {
return this.base.access.users.list(opts);
});
OctoPrintUserClient.prototype.list = deprecatedUserClient(
"list",
"list",
function (opts) {
return this.base.access.users.list(opts);
}
);
OctoPrintUserClient.prototype.add = deprecatedUserClient("add", "add", function (
user,
opts
) {
return this.base.access.users.add(user, opts);
});
OctoPrintUserClient.prototype.add = deprecatedUserClient(
"add",
"add",
function (user, opts) {
return this.base.access.users.add(user, opts);
}
);
OctoPrintUserClient.prototype.get = deprecatedUserClient("get", "get", function (
name,
opts
) {
return this.base.access.users.get(name, opts);
});
OctoPrintUserClient.prototype.get = deprecatedUserClient(
"get",
"get",
function (name, opts) {
return this.base.access.users.get(name, opts);
}
);
OctoPrintUserClient.prototype.update = deprecatedUserClient(
"update",
+6 -4
View File
@@ -1584,18 +1584,20 @@ var saveToLocalStorage = function (key, data) {
localStorage[key] = JSON.stringify(data);
};
var loadFromLocalStorage = function (key) {
if (!Modernizr.localstorage) return {};
var loadFromLocalStorage = function (key, defaultValue) {
defaultValue = defaultValue === undefined ? {} : defaultValue;
if (!Modernizr.localstorage) return defaultValue;
var currentString = localStorage[key];
var current;
if (currentString === undefined) {
current = {};
current = defaultValue;
} else {
try {
current = JSON.parse(currentString);
} catch (ex) {
current = {};
current = defaultValue;
}
}
return current;
+13 -13
View File
@@ -404,9 +404,8 @@ $(function () {
if (!additionalBindings.hasOwnProperty(viewModelId)) {
additionalBindings[viewModelId] = viewModelBindTargets;
} else {
additionalBindings[viewModelId] = additionalBindings[viewModelId].concat(
viewModelBindTargets
);
additionalBindings[viewModelId] =
additionalBindings[viewModelId].concat(viewModelBindTargets);
}
});
@@ -461,17 +460,18 @@ $(function () {
viewModel.additionalNames = viewModel.additionalNames || [];
// make sure all value's are set and in an array
_.each(["dependencies", "elements", "optional", "additionalNames"], function (
key
) {
if (viewModel[key] === undefined) {
viewModel[key] = [];
} else {
viewModel[key] = _.isArray(viewModel[key])
? viewModel[key]
: [viewModel[key]];
_.each(
["dependencies", "elements", "optional", "additionalNames"],
function (key) {
if (viewModel[key] === undefined) {
viewModel[key] = [];
} else {
viewModel[key] = _.isArray(viewModel[key])
? viewModel[key]
: [viewModel[key]];
}
}
});
);
// make sure that we don't have two view models going by the same name
if (_.has(viewModelMap, viewModel.name)) {
@@ -843,15 +843,16 @@ $(function () {
access.permissions.initialize();
};
access.onUserPermissionsChanged = access.onUserLoggedIn = access.onUserLoggedOut = function (
user
) {
if (access.loginState.hasPermission(access.permissions.SETTINGS)) {
access.groups.requestData().done(function () {
access.users.requestData();
});
}
};
access.onUserPermissionsChanged =
access.onUserLoggedIn =
access.onUserLoggedOut =
function (user) {
if (access.loginState.hasPermission(access.permissions.SETTINGS)) {
access.groups.requestData().done(function () {
access.users.requestData();
});
}
};
}
OCTOPRINT_VIEWMODELS.push([AccessViewModel, ["loginStateViewModel"], []]);
@@ -230,9 +230,12 @@ $(function () {
self.openOrCloseOnStateChange(true);
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -22,6 +22,7 @@ $(function () {
self.isLoading = ko.observable(undefined);
self.extrusionAmount = ko.observable(undefined);
self.controls = ko.observableArray([]);
self.distances = ko.observableArray([0.1, 1, 10, 100]);
@@ -82,10 +83,18 @@ $(function () {
self.settings.printerProfiles.currentProfileData.subscribe(function () {
self._updateExtruderCount();
self._updateExtrusionAmount();
self.settings.printerProfiles
.currentProfileData()
.extruder.count.subscribe(self._updateExtruderCount);
});
self._updateExtrusionAmount = function () {
self.extrusionAmount(
self.settings.printerProfiles
.currentProfileData()
.extruder.defaultExtrusionLength()
);
};
self._updateExtruderCount = function () {
var tools = [];
@@ -519,9 +528,13 @@ $(function () {
return span + " " + offset;
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.syncWebcamElements();
self.requestData();
};
self._disableWebcam = function () {
// only disable webcam stream if tab is out of focus for more than 5s,
@@ -613,12 +626,20 @@ $(function () {
}
self._enableWebcam();
self.extrusionAmount(self.settings.printer_defaultExtrusionLength());
self.extrusionAmount(
self.settings.printerProfiles
.currentProfileData()
.extruder.defaultExtrusionLength()
);
};
self.syncWebcamElements = function () {
self.webcamElementHls = document.getElementById("webcam_hls");
self.webcamElementWebrtc = document.getElementById("webcam_webrtc");
};
self.onStartup = function () {
self.webcamElementHls = document.getElementById("webcam_hls");
self.webcamElementWebrtc = document.getElementById("webcam_webrtc");
self.syncWebcamElements();
};
self.onFocus = function (data, event) {
+15 -10
View File
@@ -687,11 +687,13 @@ $(function () {
};
if (p) {
callViewModels(self.allViewModels, "onBeforePrintStart", function (
method
) {
prevented = prevented || method(callback) === false;
});
callViewModels(
self.allViewModels,
"onBeforePrintStart",
function (method) {
prevented = prevented || method(callback) === false;
}
);
}
if (!prevented) {
@@ -1296,11 +1298,14 @@ $(function () {
}
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.updateButtons();
self.requestData();
self._fromLocalStorage();
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.updateButtons();
self.requestData();
self._fromLocalStorage();
};
self.onStartup = function () {
$(".accordion-toggle[data-target='#files']").click(function () {
@@ -127,8 +127,7 @@ $(function () {
"mistaken since you are in an isolated LAN, feel free to ignore it.</small></p>"
);
text = _.sprintf(text, {
url:
"https://octoprint.org/blog/2018/09/03/safe-remote-access/"
url: "https://octoprint.org/blog/2018/09/03/safe-remote-access/"
});
if (self.externalAddressNotification !== undefined) {
@@ -32,9 +32,12 @@ $(function () {
return classes;
});
self.onServerReconnect = self.onServerConnect = self.onEventConnectivityChanged = function () {
self.offline(!ONLINE);
};
self.onServerReconnect =
self.onServerConnect =
self.onEventConnectivityChanged =
function () {
self.offline(!ONLINE);
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -25,7 +25,8 @@ $(function () {
count: 1,
offsets: [[0, 0]],
nozzleDiameter: 0.4,
sharedNozzle: false
sharedNozzle: false,
defaultExtrusionLength: 5
}
};
};
@@ -72,6 +73,7 @@ $(function () {
self.extruders = ko.observable();
self.extruderOffsets = ko.observableArray();
self.sharedNozzle = ko.observable();
self.defaultExtrusionLength = ko.observable();
self.axisXSpeed = ko.observable();
self.axisYSpeed = ko.observable();
@@ -233,6 +235,7 @@ $(function () {
self.nozzleDiameter(data.extruder.nozzleDiameter);
self.sharedNozzle(data.extruder.sharedNozzle);
self.defaultExtrusionLength(data.extruder.defaultExtrusionLength);
self.extruders(data.extruder.count);
var offsets = [];
if (data.extruder.count > 1) {
@@ -298,7 +301,11 @@ $(function () {
self.nozzleDiameter(),
defaultProfile.extruder.nozzleDiameter
),
sharedNozzle: self.sharedNozzle()
sharedNozzle: self.sharedNozzle(),
defaultExtrusionLength: validInt(
self.defaultExtrusionLength(),
defaultProfile.extruder.defaultExtrusionLength
)
},
axes: {
x: {
@@ -696,9 +703,12 @@ $(function () {
self.onSettingsShown = self.requestData;
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -441,11 +441,13 @@ $(function () {
OctoPrint.job.start();
};
callViewModels(self.allViewModels, "onBeforePrintStart", function (
method
) {
prevented = prevented || method(callback) === false;
});
callViewModels(
self.allViewModels,
"onBeforePrintStart",
function (method) {
prevented = prevented || method(callback) === false;
}
);
if (!prevented) {
callback();
@@ -212,6 +212,7 @@ $(function () {
self.serial_blockedCommands = ko.observable(undefined);
self.serial_ignoredCommands = ko.observable(undefined);
self.serial_pausingCommands = ko.observable(undefined);
self.serial_sdCancelCommand = ko.observable(undefined);
self.serial_emergencyCommands = ko.observable(undefined);
self.serial_helloCommand = ko.observable(undefined);
self.serial_serialErrorBehaviour = ko.observable("cancel");
@@ -247,6 +248,7 @@ $(function () {
self.serial_ackMax = ko.observable(undefined);
self.serial_resendRatioThreshold = ko.observable(100);
self.serial_resendRatioStart = ko.observable(100);
self.serial_enableShutdownActionCommand = ko.observable(undefined);
self.folder_uploads = ko.observable(undefined);
self.folder_timelapse = ko.observable(undefined);
@@ -417,8 +419,7 @@ $(function () {
self.addTerminalFilter = function () {
self.terminalFilters.push({
name: "New",
regex:
"(Send:\\s+(N\\d+\\s+)?M105)|(Recv:\\s+(ok\\s+([PBN]\\d+\\s+)*)?.*([BCLPR]|T\\d*):-?\\d+)"
regex: "(Send:\\s+(N\\d+\\s+)?M105)|(Recv:\\s+(ok\\s+([PBN]\\d+\\s+)*)?.*([BCLPR]|T\\d*):-?\\d+)"
});
};
@@ -1542,11 +1543,14 @@ $(function () {
self.requestData();
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
// we might have other user rights now, refresh (but only if startup has fully completed)
if (!self._startupComplete) return;
self.requestData();
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
// we might have other user rights now, refresh (but only if startup has fully completed)
if (!self._startupComplete) return;
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -323,9 +323,12 @@ $(function () {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.requestData();
};
self.onEventSettingsUpdated = function (payload) {
self.requestData();
@@ -128,16 +128,17 @@ $(function () {
return deferred.promise();
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function (
user
) {
if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
self.requestData();
} else {
self.lastCommandResponse = undefined;
self.systemActions([]);
}
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function (user) {
if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
self.requestData();
} else {
self.lastCommandResponse = undefined;
self.systemActions([]);
}
};
self.onEventSettingsUpdated = function () {
if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
@@ -123,7 +123,8 @@ $(function () {
var color;
// tools
var currentProfileData = self.settingsViewModel.printerProfiles.currentProfileData();
var currentProfileData =
self.settingsViewModel.printerProfiles.currentProfileData();
var numExtruders = currentProfileData
? currentProfileData.extruder.count()
: 0;
@@ -200,6 +201,43 @@ $(function () {
.heatedChamber.subscribe(self._printerProfileUpdated);
});
self.markings = [];
self.marking_props = {
print: {
label: gettext("Start"),
color: "#218656"
},
pause: {
label: gettext("Pause"),
color: "#FDC02F"
},
resume: {
label: gettext("Resume"),
color: "#27CAEE"
},
cancel: {
label: gettext("Cancel"),
color: "#DA3749"
},
done: {
label: gettext("Done"),
color: "#1B72F9"
}
};
self.showStateMarks = ko.observable(
loadFromLocalStorage("temperatureGraph.showStateMarks", true)
);
self.showStateMarks.subscribe(function (newValue) {
saveToLocalStorage("temperatureGraph.showStateMarks", newValue);
self.updatePlot();
});
self.toggleStateMarks = function () {
self.showStateMarks(!self.showStateMarks());
};
self.temperatures = [];
self.plot = undefined;
@@ -207,6 +245,7 @@ $(function () {
self.plotLegendTimeout = undefined;
self.fromCurrentData = function (data) {
self.markings = data.markings;
self._processStateData(data.state);
if (!self._printerProfileInitialized) {
self._currentTemperatureDataBacklog.push(data);
@@ -217,6 +256,7 @@ $(function () {
};
self.fromHistoryData = function (data) {
self.markings = data.markings;
self._processStateData(data.state);
if (!self._printerProfileInitialized) {
self._historyTemperatureDataBacklog.push(data);
@@ -421,6 +461,74 @@ $(function () {
}
};
self._drawMarkings = function () {
var graph = $("#temperature-graph");
if (!self.plot) {
return [];
}
$(".temperature-mark-label").remove();
if (!self.showStateMarks()) {
return [];
}
var graphWidth = self.plot.width();
var yAxisLabelWidth = 40;
var markingsLabelMargin = 0;
var lineWidth = 2;
var marks = self.markings.map(function (mark) {
var time = parseInt(mark.time * 1000);
var o = self.plot.pointOffset({
x: time,
y: self.plot.getAxes().yaxis.max
});
if (o.left > yAxisLabelWidth) {
var label = $("<div></div>");
label.html(self.marking_props[mark.type].label);
var css = {
backgroundColor: self.marking_props[mark.type].color
};
label.css(css);
label.addClass("temperature-mark-label");
graph.append(label);
// draw markings label on the left if doesn't fit on the right
if (
o.left >
graphWidth +
yAxisLabelWidth -
label.outerHeight() -
markingsLabelMargin
) {
label.css(
"left",
o.left - label.outerHeight() - markingsLabelMargin + "px"
);
label.css("border-radius", "5px 0 0 0");
} else {
label.css("left", o.left + markingsLabelMargin + "px");
label.css("border-radius", "0 0 0 5px");
}
// set top position
label.css("top", o.top + label.outerWidth() + "px");
}
return {
color: self.marking_props[mark.type].color,
lineWidth: lineWidth,
xaxis: {from: time, to: time}
};
});
return marks;
};
self._initializePlot = function (force, plotInfo) {
var graph = $("#temperature-graph");
if (!graph.length) return; // no graph
@@ -474,7 +582,11 @@ $(function () {
if (!OctoPrint.coreui.browser.mobile) {
options["crosshair"] = {mode: "x"};
options["grid"] = {hoverable: true, autoHighlight: false};
options["grid"] = {
hoverable: true,
autoHighlight: false,
markings: self._drawMarkings
};
}
self.plot = $.plot(graph, plotInfo.data, options);
@@ -992,9 +1104,12 @@ $(function () {
self._printerProfileUpdated();
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.initOrUpdate();
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.initOrUpdate();
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -800,11 +800,14 @@ $(function () {
self.renderAnimation(false);
};
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.requestData();
self.renderProgressBar = $("#render_progress");
};
self.renderProgressBar = $("#render_progress");
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -144,49 +144,54 @@ $(function () {
// also trigger the onWizardTabChange event here which we misnamed and
// on which we misordered the parameters on during development but which might
// already be used somewhere - log a deprecation warning to console though
callViewModels(allViewModels, "onWizardTabChange", function (
method,
viewModel
) {
log.warn(
"View model",
viewModel,
'is using deprecated callback "onWizardTabChange", please change to "onBeforeWizardTabChange"'
);
callViewModels(
allViewModels,
"onWizardTabChange",
function (method, viewModel) {
log.warn(
"View model",
viewModel,
'is using deprecated callback "onWizardTabChange", please change to "onBeforeWizardTabChange"'
);
// we want to continue evaluating even if result becomes false
result = method(current, next) !== false && result;
});
// we want to continue evaluating even if result becomes false
result = method(current, next) !== false && result;
}
);
return result;
}
},
onFinish: function (tab, navigation, index) {
var closeDialog = true;
callViewModels(allViewModels, "onBeforeWizardFinish", function (
method
) {
// we don't need to call all methods here, one method saying that
// the dialog must not be closed yet is enough to stop
//
// we evaluate closeDialog first to make sure we don't call
// the method once it becomes false
closeDialog = closeDialog && method() !== false;
});
callViewModels(
allViewModels,
"onBeforeWizardFinish",
function (method) {
// we don't need to call all methods here, one method saying that
// the dialog must not be closed yet is enough to stop
//
// we evaluate closeDialog first to make sure we don't call
// the method once it becomes false
closeDialog = closeDialog && method() !== false;
}
);
if (closeDialog) {
var reload = false;
callViewModels(allViewModels, "onWizardFinish", function (
method
) {
// if any of our methods returns that it wants to reload
// we'll need to set reload to true
//
// order is important here - the method call needs to happen
// first, or it won't happen after the reload flag has been
// set once due to the || making further evaluation unnecessary
// then
reload = method() == "reload" || reload;
});
callViewModels(
allViewModels,
"onWizardFinish",
function (method) {
// if any of our methods returns that it wants to reload
// we'll need to set reload to true
//
// order is important here - the method call needs to happen
// first, or it won't happen after the reload flag has been
// set once due to the || making further evaluation unnecessary
// then
reload = method() == "reload" || reload;
}
);
self.finishWizard().done(function () {
self.closeDialog();
if (reload) {
+1 -1
View File
@@ -28,7 +28,7 @@
// Components: common
//@import "sprites.less";
@import "../font-awesome.less";
//@import "../font-awesome.less";
@import "dropdowns.less";
@import "wells.less";
@import "component-animations.less";
+1 -1
View File
@@ -191,7 +191,7 @@
.navbar-static-top .container,
.navbar-fixed-top .container,
.navbar-fixed-bottom .container {
#grid > .core > .span(@gridColumns);
width: (@gridColumnWidth * @gridColumns) + (@gridGutterWidth * (@gridColumns - 1));
}
// Fixed to top
+6 -6
View File
@@ -264,13 +264,13 @@
// Fluid grid
// -------------------------
@fluidGridColumnWidth: percentage(@gridColumnWidth / @gridRowWidth);
@fluidGridGutterWidth: percentage(@gridGutterWidth / @gridRowWidth);
@fluidGridColumnWidth: percentage((@gridColumnWidth / @gridRowWidth));
@fluidGridGutterWidth: percentage((@gridGutterWidth / @gridRowWidth));
// 1200px min
@fluidGridColumnWidth1200: percentage(@gridColumnWidth1200 / @gridRowWidth1200);
@fluidGridGutterWidth1200: percentage(@gridGutterWidth1200 / @gridRowWidth1200);
@fluidGridColumnWidth1200: percentage((@gridColumnWidth1200 / @gridRowWidth1200));
@fluidGridGutterWidth1200: percentage((@gridGutterWidth1200 / @gridRowWidth1200));
// 768px-979px
@fluidGridColumnWidth768: percentage(@gridColumnWidth768 / @gridRowWidth768);
@fluidGridGutterWidth768: percentage(@gridGutterWidth768 / @gridRowWidth768);
@fluidGridColumnWidth768: percentage((@gridColumnWidth768 / @gridRowWidth768));
@fluidGridGutterWidth768: percentage((@gridGutterWidth768 / @gridRowWidth768));
+9
View File
@@ -564,6 +564,15 @@ table {
}
}
.temperature-mark-label {
position: absolute;
color: white;
padding: 0 5px;
font-size: 8px;
transform-origin: 0 0;
transform: rotate(-90deg);
}
/** Various */
.tab-content,
+91
View File
@@ -0,0 +1,91 @@
"""
This module represents OctoPrint's system and server commands.
"""
__author__ = "Johan Verrept <johan@verrept.eu>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
from octoprint.settings import settings
from octoprint.util.commandline import CommandlineCaller, CommandlineError
# singleton
_instance = None
def system_command_manager():
global _instance
if _instance is None:
_instance = SystemCommandManager()
return _instance
class SystemCommandManager:
SERVER_RESTART_COMMAND = "serverRestartCommand"
SYSTEM_RESTART_COMMAND = "systemRestartCommand"
SYSTEM_SHUTDOWN_COMMAND = "systemShutdownCommand"
def __init__(self):
self._logger = logging.getLogger(__name__)
self._caller = CommandlineCaller()
def execute(self, command):
if not command:
return False
try:
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
p = self._caller.non_blocking_call(command, shell=True)
if p is None:
raise CommandlineError(None, "", "")
if p.returncode is not None:
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
stderr = p.stderr.text if p is not None and p.stderr is not None else ""
raise CommandlineError(p.returncode, stdout, stderr)
except CommandlineError:
raise
except Exception:
self._logger.exception(f"Error while executing command: {command}")
raise CommandlineError(None, "", "")
return True
def get_command(self, cmd):
return settings().get(["server", "commands", cmd])
def has_command(self, cmd):
return self.get_command(cmd) is not None
def get_server_restart_command(self):
return self.get_command(self.SERVER_RESTART_COMMAND)
def get_system_restart_command(self):
return self.get_command(self.SYSTEM_RESTART_COMMAND)
def get_system_shutdown_command(self):
return self.get_command(self.SYSTEM_SHUTDOWN_COMMAND)
def has_server_restart_command(self):
return self.get_server_restart_command() is not None
def has_system_restart_command(self):
return self.get_system_restart_command() is not None
def has_system_shutdown_command(self):
return self.get_system_shutdown_command() is not None
def perform_server_restart(self):
return self.execute(self.get_server_restart_command())
def perform_system_restart(self):
return self.execute(self.get_system_restart_command())
def perform_system_shutdown(self):
return self.execute(self.get_system_shutdown_command())
@@ -446,6 +446,13 @@
<span class="help-inline">{{ _('Use this to specify commands on which OctoPrint should pause the print job. Just the G or M code, comma separated. Defaults to <code>M0</code>, <code>M1</code> and <code>M25</code>.') }}</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialSdCancelCommand">{{ _('SD Cancel Command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialSdCancelCommand" data-bind="value: serial_sdCancelCommand">
<span class="help-inline">{{ _('The command to send to printer when cancelling a SD card print. Defaults to <code>M25</code>.') }}</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialEmergencyCommands">{{ _('Emergency commands') }}</label>
<div class="controls">
@@ -486,6 +493,15 @@
</div>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Action commands') }}</legend>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_enableShutdownActionCommand" id="settings-serialEnableShutdownActionCommand"> {{ _('Enable the <code>shutdown</code> action command') }}
<span class="help-block">{{ _('If enabled and the system shutdown command is configured, your printer\'s firmware will be able to shutdown your OctoPrint server via an action command on the serial connection. This could get abused, so only enable this if you trust your firmware and your GCODE files!') }}</span>
</label>
</div>
</fieldset>
</div>
<div id="settings_serial_behaviour" class="tab-pane">
<fieldset>
@@ -51,7 +51,15 @@
<!-- /ko -->
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-defaultExtrusionLength">{{ _('Default extrusion length') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini text-right" min="1" data-bind="value: defaultExtrusionLength" id="settings-defaultExtrusionLength">
<span class="add-on">mm</span>
</div>
</div>
</div>
<p>
<small>{{ _('This information is used for the graph and controls available in the "Temperature" tab, the GCODE viewer, when slicing from within OctoPrint and for deciding which toolchange commands are safe to send to the printer.') }}</small>
</p>
@@ -1,4 +1,16 @@
{% if enableTemperatureGraph %}
<div class="row-fluid">
<div class="dropdown pull-right">
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
<i class="fas fa-wrench"></i>
</button>
<ul class="dropdown-menu pull-right">
<li><a href="javascript:void(0)" data-bind="click: toggleStateMarks"><i class="fas fa-check" data-bind="style: {visibility: showStateMarks() ? 'visible' : 'hidden'}"></i> {{ _('Show state marks') }}</a></li>
</ul>
</div>
</div>
</div>
<div class="row-fluid">
<div id="temperature-graph" style="width: 100%"></div>
</div>
+9 -12
View File
@@ -204,10 +204,10 @@ def get_unrendered_timelapses():
return job
return sorted(
[
(
util.dict_merge({"name": key}, finalize_fields(key, value))
for key, value in jobs.items()
],
),
key=lambda x: sv(x["name"]),
)
@@ -215,7 +215,7 @@ def get_unrendered_timelapses():
def delete_unrendered_timelapse(name):
global _cleanup_lock
pattern = "{}*.jpg".format(glob.escape(name))
pattern = f"{glob.escape(name)}*.jpg"
basedir = settings().getBaseFolder("timelapse_tmp")
with _cleanup_lock:
@@ -604,7 +604,8 @@ class Timelapse:
self._in_timelapse = True
self._gcode_file = os.path.basename(gcode_file)
self._file_prefix = "{}_{}".format(
os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")
os.path.splitext(self._gcode_file)[0].replace("%", "%%"),
time.strftime("%Y%m%d%H%M%S"),
)
def stop_timelapse(self, do_create_movie=True, success=True):
@@ -741,13 +742,11 @@ class Timelapse:
def _perform_capture(self, filename, onerror=None):
# pre-capture hook
for hook in self._pre_capture_hooks.values():
for name, hook in self._pre_capture_hooks.items():
try:
hook(filename)
except Exception:
self._logger.exception(
"Error while processing hook {name}.".format(**locals())
)
self._logger.exception(f"Error while processing hook {name}.")
eventManager().fire(Events.CAPTURE_START, {"file": filename})
try:
@@ -778,13 +777,11 @@ class Timelapse:
err = None
# post-capture hook
for hook in self._post_capture_hooks.values():
for name, hook in self._post_capture_hooks.items():
try:
hook(filename, err is None)
except Exception:
self._logger.exception(
"Error while processing hook {name}.".format(**locals())
)
self._logger.exception(f"Error while processing hook {name}.")
# handle events and onerror call
if err is None:
@@ -2755,7 +2755,7 @@ msgstr "Nur kompatible Plugins anzeigen"
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:239
msgid "Only show unabandoned plugins"
msgstr "Nur ungepflegte Plugins anzeigen"
msgstr "Nur gepflegte Plugins anzeigen"
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:241
msgid "Refresh list from repository"
+2 -2
View File
@@ -947,7 +947,7 @@ def parse_mime_type(mime):
import cgi
if not mime or not isinstance(mime, (str, bytes)):
raise ValueError("mime must be a non empty str or bytes")
raise ValueError("mime must be a non empty str")
mime, params = cgi.parse_header(mime)
@@ -1685,7 +1685,7 @@ def time_this(
data.update(
func_args=",".join(map(repr, args)),
func_kwargs=",".join(
map(lambda x: "{}={!r}".format(x[0], x[1]), kwargs.items())
map(lambda x: f"{x[0]}={x[1]!r}", kwargs.items())
),
)
if log_enter:
+66 -27
View File
@@ -27,6 +27,7 @@ from octoprint.events import Events, eventManager
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings
from octoprint.systemcommands import system_command_manager
from octoprint.util import (
CountedEvent,
PrependableQueue,
@@ -159,7 +160,7 @@ Groups will be as follows:
* ``es``: multiple E coordinates if present, to be parsed further with regex_e_positions
"""
regex_e_positions = re.compile(fr"E(?P<id>\d+):\s*(?P<value>{regex_float_pattern})")
regex_e_positions = re.compile(rf"E(?P<id>\d+):\s*(?P<value>{regex_float_pattern})")
"""Regex for matching multiple E coordinates in a position report.
Groups will be as follows:
@@ -555,6 +556,7 @@ class MachineCom:
self._sdAlwaysAvailable = settings().getBoolean(["serial", "sdAlwaysAvailable"])
self._sdRelativePath = settings().getBoolean(["serial", "sdRelativePath"])
self._sdLowerCase = settings().getBoolean(["serial", "sdLowerCase"])
self._sdCancelCommand = settings().get(["serial", "sdCancelCommand"])
self._blockWhileDwelling = settings().getBoolean(["serial", "blockWhileDwelling"])
self._send_m112_on_error = settings().getBoolean(["serial", "sendM112OnError"])
self._disable_sd_printing_detection = settings().getBoolean(
@@ -770,6 +772,11 @@ class MachineCom:
# serial encoding
self._serial_encoding = settings().get(["serial", "encoding"])
# action commands
self._enable_shutdown_action_command = settings().getBoolean(
["serial", "enableShutdownActionCommand"]
)
# print job
self._currentFile = None
self._job_on_hold = CountedEvent()
@@ -1303,7 +1310,7 @@ class MachineCom:
retval = hook(self, "gcode", scriptName)
except Exception:
self._logger.exception(
"Error while processing hook {name}.".format(**locals()),
f"Error while processing hook {name}.",
extra={"plugin": name},
)
else:
@@ -1413,9 +1420,7 @@ class MachineCom:
if "source:plugin" in tags:
for tag in tags:
if tag.startswith("plugin:"):
self._logger.info(
"Starting job on behalf of plugin {}".format(tag[7:])
)
self._logger.info(f"Starting job on behalf of plugin {tag[7:]}")
elif "source:api" in tags:
self._logger.info(f"Starting job on behalf of user {user}")
@@ -1674,9 +1679,7 @@ class MachineCom:
if "source:plugin" in tags:
for tag in tags:
if tag.startswith("plugin:"):
self._logger.info(
"Cancelling job on behalf of plugin {}".format(tag[7:])
)
self._logger.info(f"Cancelling job on behalf of plugin {tag[7:]}")
elif "source:api" in tags:
self._logger.info(f"Cancelling job on behalf of user {user}")
@@ -1732,7 +1735,7 @@ class MachineCom:
if self.isSdFileSelected():
if not external_sd:
self.sendCommand(
"M25",
self._sdCancelCommand,
part_of_job=True,
tags=tags | cancel_tags,
) # pause print
@@ -1825,7 +1828,7 @@ class MachineCom:
for tag in tags:
if tag.startswith("plugin:"):
self._logger.info(
"Pausing/resuming job on behalf of plugin {}".format(tag[7:])
f"Pausing/resuming job on behalf of plugin {tag[7:]}"
)
elif user:
self._logger.info(f"Pausing/resuming job on behalf of user {user}")
@@ -2279,25 +2282,32 @@ class MachineCom:
if action_name == "start":
if self._currentFile is not None:
self._log(
"(Re)Starting current job on request of the printer..."
self._dual_log(
"(Re)Starting current job on request of the printer...",
level=logging.INFO,
)
self.startPrint(
tags={"trigger:serial.action_command.start"}
)
elif action_name == "cancel":
self._log("Cancelling on request of the printer...")
self._dual_log(
"Cancelling on request of the printer...",
level=logging.INFO,
)
self.cancelPrint(
tags={"trigger:serial.action_command.cancel"}
)
elif action_name == "pause":
self._log("Pausing on request of the printer...")
self._dual_log(
"Pausing on request of the printer...", level=logging.INFO
)
self.setPause(
True, tags={"trigger:serial.action_command.pause"}
)
elif action_name == "paused":
self._log(
"Printer signalled that it paused, switching state..."
self._dual_log(
"Printer signalled that it paused, switching state...",
level=logging.INFO,
)
self.setPause(
True,
@@ -2305,13 +2315,17 @@ class MachineCom:
tags={"trigger:serial.action_command.paused"},
)
elif action_name == "resume":
self._log("Resuming on request of the printer...")
self._dual_log(
"Resuming on request of the printer...",
level=logging.INFO,
)
self.setPause(
False, tags={"trigger:serial.action_command.resume"}
)
elif action_name == "resumed":
self._log(
"Printer signalled that it resumed, switching state..."
self._dual_log(
"Printer signalled that it resumed, switching state...",
level=logging.INFO,
)
self.setPause(
False,
@@ -2319,20 +2333,45 @@ class MachineCom:
tags={"trigger:serial.action_command.resumed"},
)
elif action_name == "disconnect":
self._log("Disconnecting on request of the printer...")
self._dual_log(
"Disconnecting on request of the printer...",
level=logging.INFO,
)
self._callback.on_comm_force_disconnect()
elif action_name == "shutdown":
if self._enable_shutdown_action_command:
self._dual_log(
"Shutting down system on request of printer...",
level=logging.WARNING,
)
try:
system_command_manager().perform_system_shutdown()
except Exception as ex:
self._log(f"Error executing system shutdown: {ex}")
else:
self._dual_log(
"Received a shutdown command from the printer, but processing of this command is disabled",
level=logging.WARNING,
)
elif self._sdEnabled and action_name == "sd_inserted":
self._log("Printer reported SD card as inserted")
self._dual_log(
"Printer reported SD card as inserted", level=logging.INFO
)
self._sdAvailable = True
self.refreshSdFiles()
self._callback.on_comm_sd_state_change(self._sdAvailable)
elif self._sdEnabled and action_name == "sd_ejected":
self._log("Printer reported SD card as ejected")
self._dual_log(
"Printer reported SD card as ejected", level=logging.INFO
)
self._sdAvailable = False
self._sdFiles = []
self._callback.on_comm_sd_state_change(self._sdAvailable)
elif self._sdEnabled and action_name == "sd_updated":
self._log("Printer reported a change on the SD card")
self._dual_log(
"Printer reported a change on the SD card",
level=logging.INFO,
)
self.refreshSdFiles()
else:
for name, hook in self._printer_action_hooks.items():
@@ -3246,7 +3285,7 @@ class MachineCom:
len(self._detection_candidates),
", ".join(
map(
lambda x: "{}@{}".format(x[0], x[1]),
lambda x: f"{x[0]}@{x[1]}",
self._detection_candidates,
)
),
@@ -3874,7 +3913,7 @@ class MachineCom:
ret = hook(self, stripped_error)
except Exception:
self._logger.exception(
"Error while processing hook {name}:".format(**locals()),
f"Error while processing hook {name}:",
extra={"plugin": name},
)
else:
@@ -3955,7 +3994,7 @@ class MachineCom:
if ret != "":
try:
self._log("Recv: {}".format(sanitize_ascii(ret)))
self._log(f"Recv: {sanitize_ascii(ret)}")
except ValueError as e:
self._log(f"WARN: While reading last line: {e}")
self._log(f"Recv: {ret!r}")
@@ -3975,7 +4014,7 @@ class MachineCom:
ret = hook(self, ret)
except Exception:
self._logger.exception(
"Error while processing hook {name}:".format(**locals()),
f"Error while processing hook {name}:",
extra={"plugin": name},
)
else:
+52 -45
View File
@@ -8,7 +8,7 @@ import queue
import re
import time
import warnings
from typing import Dict, List, Tuple, Union
from typing import List, Optional, Tuple, Union
import sarge
@@ -157,8 +157,12 @@ class CommandlineCaller:
return returncode, stdout, stderr
def call(
self, command: Union[str, List[str], Tuple[str]], **kwargs: Dict[str, str]
) -> Tuple[int, List[str], List[str]]:
self,
command: Union[str, List[str], Tuple[str]],
delimiter: bytes = b"\n",
buffer_size: int = -1,
**kwargs,
) -> Tuple[Optional[int], List[str], List[str]]:
"""
Calls a command
@@ -171,49 +175,10 @@ class CommandlineCaller:
(tuple) a 3-tuple of return code, full stdout and full stderr output
"""
if isinstance(command, (list, tuple)):
joined_command = " ".join(command)
else:
joined_command = command
self._logger.debug(f"Calling: {joined_command}")
self.on_log_call(joined_command)
delimiter = kwargs.get("delimiter", b"\n")
try:
kwargs.pop("delimiter")
except KeyError:
pass
buffer_size = kwargs.get("buffer_size", -1)
try:
kwargs.pop("buffer_size")
except KeyError:
pass
kwargs.update(
{
"close_fds": CLOSE_FDS,
"async_": True,
"stdout": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
"stderr": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
}
p = self.non_blocking_call(
command, delimiter=delimiter, buffer_size=buffer_size, **kwargs
)
p = sarge.run(command, **kwargs)
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
if not p.commands[0].process:
# the process might have been set to None in case of any exception
self._logger.error(f"Error while trying to run command {joined_command}")
if p is None:
return None, [], []
all_stdout = []
@@ -248,6 +213,48 @@ class CommandlineCaller:
return p.returncode, all_stdout, all_stderr
def non_blocking_call(
self,
command: Union[str, List, Tuple],
delimiter: bytes = b"\n",
buffer_size: int = -1,
**kwargs,
) -> Optional[sarge.Pipeline]:
if isinstance(command, (list, tuple)):
joined_command = " ".join(command)
else:
joined_command = command
self._logger.debug(f"Calling: {joined_command}")
self.on_log_call(joined_command)
kwargs.update(
{
"close_fds": CLOSE_FDS,
"async_": True,
"stdout": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
"stderr": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
}
)
p = sarge.run(command, **kwargs)
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
if not p.commands[0].process:
# the process might have been set to None in case of any exception
self._logger.error(f"Error while trying to run command {joined_command}")
return None
return p
def _log_stdout(self, *lines):
self.on_log_stdout(*lines)
+1 -1
View File
@@ -58,7 +58,7 @@ def log_duration(log=None, with_args=False):
args_str = ", ".join(map(lambda x: repr(x), args))
kwargs_str = ", ".join(
map(
lambda item: "{}={}".format(item[0], repr(item[1])),
lambda item: f"{item[0]}={repr(item[1])}",
kwargs.items(),
)
)
+2 -2
View File
@@ -244,7 +244,7 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power=
counter = 1
power = 1
prefix_format = "{segment}~{counter}"
while counter < (10 ** max_power):
while counter < (10**max_power):
prefix = prefix_format.format(
segment=filename[: (6 - power + 1)], counter=str(counter)
)
@@ -252,7 +252,7 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power=
if result not in existing_filenames:
return result
counter += 1
if counter >= 10 ** power:
if counter >= 10**power:
power += 1
raise ValueError("Can't create a collision free filename")
+2 -6
View File
@@ -255,9 +255,7 @@ class ExceptionHandlerExtension(Extension):
return caller()
except Exception as e:
self._logger.exception(
"Caught exception while compiling template {filename} at line {lineno}".format(
**locals()
)
f"Caught exception while compiling template {filename} at line {lineno}"
)
error_string = self._format_error(error, e, filename, lineno)
return error_string if error_string else ""
@@ -273,9 +271,7 @@ class ExceptionHandlerExtension(Extension):
return error.format(exception=exception, filename=filename, lineno=lineno)
except Exception:
self._logger.exception(
"Error while compiling exception output for template {filename} at line {lineno}".format(
**locals()
)
f"Error while compiling exception output for template {filename} at line {lineno}"
)
return "Unknown error"
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more