Merge branch 'maintenance' into devel

# Conflicts:
#	src/octoprint/filemanager/storage.py
#	src/octoprint/plugins/announcements/__init__.py
This commit is contained in:
Gina Häußge committed 2020-11-25 13:19:01 +01:00
commit 8ef57e2ab7
16 files changed
+165 -80

No files matched your search

+7 -2
View File
@@ -249,5 +249,10 @@ Job information response
* - ``state``
- 1
- String
- A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused",
"Cancelling", "Error" or "Offline".
- A textual representation of the current state of the job or connection, e.g. "Operational", "Printing", "Pausing", "Paused",
"Cancelling", "Error", "Offline", "Offline after error", "Opening serial connection", ... -- please note
that this list is not exhaustive!
* - ``error``
- 0..1
- String
- Any error message for the job or connection, only set if there has been an error.
+2 -20
View File
@@ -6,17 +6,15 @@ import copy
import io
import logging
import os
import re
import shutil
from contextlib import contextmanager
from os import scandir, walk
import pylru
from emoji import demojize
import octoprint.filemanager
from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode
from octoprint.vendor.awesome_slugify import Slugify
from octoprint.util.text import sanitize
class StorageInterface:
@@ -456,22 +454,6 @@ class LocalFileStorage(StorageInterface):
This storage type implements :func:`path_on_disk`.
"""
_UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
@classmethod
def _no_unicode_variations(cls, text):
return cls._UNICODE_VARIATIONS.sub("", text)
_SLUGIFY = Slugify()
_SLUGIFY.safe_chars = "-_.()[] "
@classmethod
def _slugify(cls, text):
text = to_unicode(text)
text = cls._no_unicode_variations(text)
text = demojize(text, delimiters=("", ""))
return cls._SLUGIFY(text)
def __init__(self, basefolder, create=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
@@ -1166,7 +1148,7 @@ class LocalFileStorage(StorageInterface):
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
result = self._slugify(name).replace(" ", "_")
result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_")
if result and result != "." and result != ".." and result[0] == ".":
# hidden files under *nix
result = result[1:]
@@ -26,6 +26,7 @@ from octoprint.server.util.flask import (
with_revalidation_checking,
)
from octoprint.util import count, utmify
from octoprint.util.text import sanitize
PY2 = sys.version_info[0] < 3
@@ -44,11 +45,6 @@ class AnnouncementPlugin(
self._cached_channel_configs = None
self._cached_channel_configs_mutex = threading.RLock()
from octoprint.vendor.awesome_slugify import Slugify
self._slugify = Slugify()
self._slugify.safe_chars = "-_."
# Additional permissions hook
def get_additional_permissions(self):
@@ -363,14 +359,14 @@ class AnnouncementPlugin(
if config is None or "url" not in config or "name" not in config:
# strip invalid entries
continue
result[self._slugify(key)] = config
result[sanitize(key)] = config
self._cached_channel_configs = result
return self._cached_channel_configs
def _get_channel_config(self, key, force=False):
"""Retrieve specific channel config for channel."""
safe_key = self._slugify(key)
safe_key = sanitize(key)
return self._get_channel_configs(force=force).get(safe_key)
def _fetch_all_channels_async(self, force=False):
@@ -521,7 +517,7 @@ class AnnouncementPlugin(
def _get_channel_cache_path(self, key):
"""Retrieve cache path for channel key."""
safe_key = self._slugify(key)
safe_key = sanitize(key)
return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key))
+14 -8
View File
@@ -45,18 +45,13 @@ import sarge
from flask_babel import gettext
from octoprint.settings import valid_boolean_trues
from octoprint.util.text import sanitize
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
BACKUP_FILE_PREFIX = "octoprint-backup"
BACKUP_DATE_TIME_FMT = "%Y%m%d-%H%M%S"
def build_backup_filename():
return "{}-{}.zip".format(BACKUP_FILE_PREFIX, time.strftime(BACKUP_DATE_TIME_FMT))
class BackupPlugin(
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
@@ -168,7 +163,7 @@ class BackupPlugin(
@no_firstrun_access
@Permissions.PLUGIN_BACKUP_ACCESS.require(403)
def create_backup(self):
backup_file = build_backup_filename()
backup_file = self._build_backup_filename(settings=self._settings)
data = flask.request.json
exclude = data.get("exclude", [])
@@ -484,7 +479,7 @@ class BackupPlugin(
if path is not None:
datafolder, backup_file = os.path.split(os.path.abspath(path))
else:
backup_file = build_backup_filename()
backup_file = self._build_backup_filename(settings=settings)
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
@@ -1284,6 +1279,17 @@ class BackupPlugin(
return True
@classmethod
def _build_backup_filename(cls, settings):
if settings.global_get(["appearance", "name"]) == "":
backup_prefix = "octoprint"
else:
backup_prefix = settings.global_get(["appearance", "name"])
backup_prefix = sanitize(backup_prefix)
return "{}-backup-{}.zip".format(
backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT)
)
@classmethod
def _restore_supported(cls, settings):
return (
@@ -1077,7 +1077,7 @@ class VirtualPrinter:
config = self._virtual_eeprom.eeprom["material"]
lines = []
for material in ["0", "1"]:
line = "echo: " + config["command"] + "S" + material
line = "echo: " + config["command"] + " S" + material
for param, saved_value in config["params"][material].items():
line = line + " " + param + str(saved_value)
lines.append(line)
+48 -10
View File
@@ -143,7 +143,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
on_get_resends=self._updateResendDataCallback,
)
self._stateMonitor.reset(
state=self._dict(text=self.get_state_string(), flags=self._getStateFlags()),
state=self._dict(
text=self.get_state_string(),
flags=self._getStateFlags(),
error=self.get_error(),
),
job_data=self._dict(
file=self._dict(name=None, path=None, size=None, origin=None, date=None),
estimatedPrintTime=None,
@@ -786,6 +790,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
else:
return self._comm.getStateId(state=state)
def get_error(self):
if self._comm is None:
return ""
else:
return self._comm.getErrorString()
def get_current_data(self, *args, **kwargs):
return util.thaw_frozendict(self._stateMonitor.get_current_data())
@@ -1039,13 +1049,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._currentZ = currentZ
self._stateMonitor.set_current_z(self._currentZ)
def _setState(self, state, state_string=None):
def _setState(self, state, state_string=None, error_string=None):
if state_string is None:
state_string = self.get_state_string()
if error_string is None:
error_string = self.get_error()
self._state = state
self._stateMonitor.set_state(
self._dict(text=state_string, flags=self._getStateFlags())
self._dict(text=state_string, flags=self._getStateFlags(), error=error_string)
)
payload = {
@@ -1415,8 +1427,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
oldState = self._state
state_string = None
error_string = None
if self._comm is not None:
state_string = self._comm.getStateString()
error_string = self._comm.getErrorString()
if oldState in (comm.MachineCom.STATE_PRINTING,):
# if we were still printing and went into an error state, mark the print as failed
@@ -1477,7 +1491,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printerProfileManager.deselect()
eventManager().fire(Events.DISCONNECTED)
self._setState(state, state_string=state_string)
self._setState(state, state_string=state_string, error_string=error_string)
def on_comm_message(self, message):
"""
@@ -1508,7 +1522,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
def on_comm_sd_state_change(self, sdReady):
self._stateMonitor.set_state(
self._dict(text=self.get_state_string(), flags=self._getStateFlags())
self._dict(
text=self.get_state_string(),
flags=self._getStateFlags(),
error=self.get_error(),
)
)
def on_comm_sd_files(self, files):
@@ -1540,7 +1558,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setJobData(full_path, size, sd, user=user)
self._stateMonitor.set_state(
self._dict(text=self.get_state_string(), flags=self._getStateFlags())
self._dict(
text=self.get_state_string(),
flags=self._getStateFlags(),
error=self.get_error(),
)
)
self._create_estimator()
@@ -1587,7 +1609,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printTimeLeft=0,
)
self._stateMonitor.set_state(
self._dict(text=self.get_state_string(), flags=self._getStateFlags())
self._dict(
text=self.get_state_string(),
flags=self._getStateFlags(),
error=self.get_error(),
)
)
eventManager().fire(Events.PRINT_DONE, payload)
@@ -1624,7 +1650,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
else:
self._updateProgressData()
self._stateMonitor.set_state(
self._dict(text=self.get_state_string(), flags=self._getStateFlags())
self._dict(
text=self.get_state_string(),
flags=self._getStateFlags(),
error=self.get_error(),
)
)
def on_comm_print_job_cancelling(self, firmware_error=None, user=None):
@@ -1740,7 +1770,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setJobData(remote_filename, filesize, True, user=user)
self._updateProgressData(completion=0.0, filepos=0, printTime=0)
self._stateMonitor.set_state(
self._dict(text=self.get_state_string(), flags=self._getStateFlags())
self._dict(
text=self.get_state_string(),
flags=self._getStateFlags(),
error=self.get_error(),
)
)
def on_comm_file_transfer_done(
@@ -1767,7 +1801,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setJobData(None, None, None)
self._updateProgressData()
self._stateMonitor.set_state(
self._dict(text=self.get_state_string(), flags=self._getStateFlags())
self._dict(
text=self.get_state_string(),
flags=self._getStateFlags(),
error=self.get_error(),
)
)
def on_comm_file_transfer_failed(self, local_filename, remote_filename, elapsed):
+9 -7
View File
@@ -76,10 +76,12 @@ def controlJob():
@Permissions.STATUS.require(403)
def jobState():
currentData = printer.get_current_data()
return jsonify(
{
"job": currentData["job"],
"progress": currentData["progress"],
"state": currentData["state"]["text"],
}
)
response = {
"job": currentData["job"],
"progress": currentData["progress"],
"state": currentData["state"]["text"],
}
if currentData["state"]["error"]:
response["error"] = currentData["state"]["error"]
return jsonify(**response)
+3
View File
@@ -228,12 +228,15 @@ $(function () {
[
// printer states
gettext("Offline"),
gettext("Offline after error"),
gettext("Error"),
gettext("Opening serial connection"),
gettext("Detecting serial connection"),
gettext("Connecting"),
gettext("Operational"),
gettext("Starting"),
gettext("Starting print from SD"),
gettext("Starting to send file to SD"),
gettext("Printing from SD"),
gettext("Sending file to SD"),
gettext("Printing"),
@@ -7,6 +7,10 @@ $(function () {
self.access = parameters[2];
self.stateString = ko.observable(undefined);
self.errorString = ko.observable(undefined);
self.hasErrorString = ko.pureComputed(function () {
return !!self.errorString();
});
self.resendCount = ko.observable(0);
self.resendTotalTransmitted = ko.observable(0);
@@ -291,6 +295,7 @@ $(function () {
var prevPaused = self.isPaused();
self.stateString(gettext(data.text));
self.errorString(data.error);
self.isErrorOrClosed(data.flags.closedOrError);
self.isOperational(data.flags.operational);
self.isPaused(data.flags.paused);
@@ -13,8 +13,9 @@
<legend>{{ _('Global API Key') }}</legend>
<div class="alert">
<p>{% trans %}
The global API key should best not be used anymore. It's one single key that gives full admin access to
your whole OctoPrint instance. Instead of using it you should create individual Application Keys for
It is recommended to no longer use the global API key as it's one single key that gives full admin access
to your whole OctoPrint instance. <strong>It will be removed in OctoPrint 2.0</strong>.
Instead of using the global key you should create individual Application Keys for
your third party clients. That way they get permissions matching the user account used for key
creation and you can also revoke access to one app without having to change the keys for all other apps.
It's also recommended to create a user account without admin access and use that for third
@@ -1,4 +1,5 @@
<span title="{{ _('Current printer state')|edq }}">{{ _('State') }}</span>: <strong data-test-id="state-string" data-bind="text: stateString"></strong><br>
<span data-bind="visible: hasErrorString" class="text-error"><span data-test-id="error-string" data-bind="text: errorString"></span><br></span>
<span data-bind="visible: isOperational"><span title="{{ _('Count of resend requests, transmitted lines and resend ratio')|edq }}">{{ _('Resend ratio') }}</span>: <strong data-bind="css: {'text-error': resendRatioCritical}"><span title="{{ _('resend requests') | edq }}" data-bind="text: formatHuman(resendCount())"></span> / <span title="{{ _('transmitted lines') | edq }}" data-bind="text: formatHuman(resendTotalTransmitted())"></span> (<span title="{{ _('resend ratio') }}" data-bind="text: resendRatio"></span>%) <a href="https://faq.octoprint.org/communication-errors" target="_blank" class="text-error" data-bind="visible: resendRatioCritical"><i class="fas fa-question-circle"></i></a></strong><br></span>
<hr>
<span title="{{ _('Name of file currently selected for printing')|edq }}">{{ _('File') }}</span>: <strong data-bind="text: filedisplay, attr: {title: filepath}"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
+10 -9
View File
@@ -442,7 +442,7 @@ def get_fully_qualified_classname(o):
return module + "." + o.__class__.__name__
def get_exception_string():
def get_exception_string(fmt="{type}: '{message}' @ {file}:{function}:{line}"):
"""
Retrieves the exception info of the last raised exception and returns it as a string formatted as
``<exception type>: <exception message> @ <source file>:<function name>:<line number>``.
@@ -451,14 +451,15 @@ def get_exception_string():
string: The formatted exception information.
"""
locationInfo = traceback.extract_tb(sys.exc_info()[2])[0]
return "%s: '%s' @ %s:%s:%d" % (
str(sys.exc_info()[0].__name__),
str(sys.exc_info()[1]),
os.path.basename(locationInfo[0]),
locationInfo[2],
locationInfo[1],
)
location_info = traceback.extract_tb(sys.exc_info()[2])[0]
exception = {
"type": str(sys.exc_info()[0].__name__),
"message": str(sys.exc_info()[1]),
"file": os.path.basename(location_info[0]),
"function": location_info[2],
"line": location_info[1],
}
return fmt.format(**exception)
@deprecated(
+5 -5
View File
@@ -937,9 +937,9 @@ class MachineCom:
elif state == self.STATE_CLOSED:
return "Offline"
elif state == self.STATE_ERROR:
return "Error: {}".format(self.getErrorString())
return "Error"
elif state == self.STATE_CLOSED_WITH_ERROR:
return "Offline (Error: {})".format(self.getErrorString())
return "Offline after error"
elif state == self.STATE_TRANSFERING_FILE:
return "Transferring file to SD"
return "Unknown State ({})".format(self._state)
@@ -3826,7 +3826,7 @@ class MachineCom:
"Please see https://faq.octoprint.org/serialerror for possible reasons of this.",
level=logging.ERROR,
)
self._errorValue = get_exception_string()
self._errorValue = get_exception_string(fmt="{type}: {message}")
self.close(is_error=True)
return None
@@ -4697,7 +4697,7 @@ class MachineCom:
"Please see https://faq.octoprint.org/serialerror for possible reasons of this.",
level=logging.INFO,
)
self._errorValue = get_exception_string()
self._errorValue = get_exception_string(fmt="{type}: {message}")
self.close(is_error=True)
break
except Exception as ex:
@@ -4714,7 +4714,7 @@ class MachineCom:
"Please see https://faq.octoprint.org/serialerror for possible reasons of this.",
level=logging.INFO,
)
self._errorValue = get_exception_string()
self._errorValue = get_exception_string(fmt="{type}: {message}")
self.close(is_error=True)
break
+53
View File
@@ -0,0 +1,53 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
from emoji import demojize
from octoprint.util import to_unicode
from octoprint.vendor.awesome_slugify import Slugify
_UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
_SLUGIFIES = {}
def sanitize(text, safe_chars="-_.", demoji=True):
"""
Sanitizes text by running it through slugify and optionally emoji translating.
Examples:
>>> sanitize("Hello World!") # doctest: +ALLOW_UNICODE
'Hello-World'
>>> sanitize("Hello World!", safe_chars="-_. ") # doctest: +ALLOW_UNICODE
'Hello World'
>>> sanitize("\u2764") # doctest: +ALLOW_UNICODE
'red_heart'
>>> sanitize("\u2764\ufe00") # doctest: +ALLOW_UNICODE
'red_heart'
>>> sanitize("\u2764", demoji=False) # doctest: +ALLOW_UNICODE
''
Args:
text: the text to sanitize
safe_chars: characters to consider safe and to keep after sanitization
emoji: whether to also convert emoji to text
Returns: the sanitized text
"""
slugify = _SLUGIFIES.get(safe_chars)
if slugify is None:
slugify = Slugify()
slugify.safe_chars = safe_chars
_SLUGIFIES[safe_chars] = slugify
text = to_unicode(text)
if demoji:
text = remove_unicode_variations(text)
text = demojize(text, delimiters=("", ""))
return slugify(text)
def remove_unicode_variations(text):
return _UNICODE_VARIATIONS.sub("", text)
-6
View File
@@ -811,12 +811,6 @@ class LocalStorageTest(unittest.TestCase):
self.assertEqual(expected_path, actual_path)
self.assertEqual(expected_name, actual_name)
@data(("test", "test"), ("\u2764", "red_heart"), ("\u2764\ufe00", "red_heart"))
@unpack
def test_slugify(self, input, expected):
output = LocalFileStorage._slugify(input)
self.assertEqual(output, expected)
def _add_and_verify_file(
self, path, expected_path, file_object, links=None, overwrite=False, display=None
):
-2
View File
@@ -1,5 +1,3 @@
from __future__ import absolute_import, division, print_function, unicode_literals
import octoprint.plugin