Merge branch 'maintenance' into devel

This commit is contained in:
Gina Häußge committed 2021-05-20 12:23:26 +02:00
commit 49621a65b0
23 files changed
+520 -317

No files matched your search

+1
View File
@@ -144,6 +144,7 @@ date of first contribution):
* [Yvan Rodrigues](https://github.com/TwoRedCells)
* [Elton Law](https://github.com/eltonlaw)
* ["sparxooo"](https://github.com/sparxooo)
* ["Stevil Knevil"](https://github.com/StevilKnevil)
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
+1
View File
@@ -55,6 +55,7 @@
* [monotonic](https://github.com/atdt/monotonic): Apache License 2.0
* [netaddr](https://github.com/drkjam/netaddr/): BSD
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
* [pathvalidate](https://pathvalidate.readthedocs.io/en/latest/index.html): MIT
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
* [psutil](https://github.com/giampaolo/psutil): BSD
* [pylru](https://github.com/jlhutch/pylru): GPLv2
+5 -5
View File
@@ -195,11 +195,11 @@ Job information
- The file that is the target of the current print job
* - ``estimatedPrintTime``
- 0..1
- Integer
- Float
- The estimated print time for the file, in seconds.
* - ``lastPrintTime``
- 0..1
- Integer
- Float
- The print time of the last print of the file, in seconds.
* - ``filament``
- 0..1
@@ -207,7 +207,7 @@ Job information
- Information regarding the estimated filament usage of the print job
* - ``filament.length``
- 0..1
- Integer
- Float
- Length of filament used, in mm
* - ``filament.volume``
- 0..1
@@ -419,7 +419,7 @@ GCODE analysis information
- Description
* - ``estimatedPrintTime``
- 0..1
- Integer
- Float
- The estimated print time of the file, in seconds
* - ``filament``
- 0..1
@@ -427,7 +427,7 @@ GCODE analysis information
- The estimated usage of filament
* - ``filament.tool{n}.length``
- 0..1
- Integer
- Float
- The length of filament used, in mm
* - ``filament.tool{n}.volume``
- 0..1
+8 -3
View File
@@ -708,6 +708,11 @@ Use the following settings to configure the serial connection to the printer:
- M0
- M1
# Commands which should not be sent to the printer and just silently ignored.
# An example of when you may wish to use this could be useful if you wish to manually change a filament on M600,
# by using that as a Pausing command (below)
ignoredCommands:
# Commands which should cause OctoPrint to pause any ongoing prints.
pausingCommands:
- M0
@@ -904,9 +909,9 @@ Use the following settings to configure the server:
# Settings for further configuration of the cookies that OctoPrint sets (login, remember me, ...)
cookies:
# SameSite setting to use on the cookies. Possible values are None, Lax and Strict. Defaults to None but
# be advised that browsers will soon force this to Lax unless also being set as Secure and served over
# https, which will cause issues with embedding OctoPrint in frames.
# SameSite setting to use on the cookies. Possible values are None, Lax and Strict. Defaults to not set but
# be advised that many browsers now default to Lax unless set as Secure, explicitly setting the cookie type
# here and served over https, which causes issues with embedding OctoPrint in frames.
#
# See also https://www.chromestatus.com/feature/5088147346030592,
# https://www.chromestatus.com/feature/5633521622188032 and issue #3482
+11 -25
View File
@@ -22,7 +22,7 @@ below.
* ``git clone https://github.com/OctoPrint/OctoPrint.git``
* Enter the checked out source folder: ``cd OctoPrint``
* Create virtual environments in the checked out source folder for both Python 2 and Python 3 to use for
* Create a virtual environment in the checked out source folder to use for
installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning
issues for the dependencies with system wide installed instances:
@@ -34,10 +34,7 @@ below.
binary cannot be found on your ``PATH`` like this you'll need to specify the full path to it here,
e.g. ``virtualenv --python=/path/to/python3/bin/python venv``
* Activate one of the virtual environments (the Python 3 venv should be considered the
primary one at this point):
* ``source venv/bin/activate`` (Linux, macOS) or ``source venv/Scripts/activate`` (Git Bash under Windows, see below)
* Activate the virtual environment: ``source venv/bin/activate`` (Linux, macOS) or ``source venv/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
@@ -62,22 +59,9 @@ When the virtual environment is activated you can then:
* run the test suite from the checked out source folder via ``pytest``
* trigger the pre-commit check suite manually from the checked out source folder via
``pre-commit run --hook-stage manual --all-files``
To switch the activated virtual environment, simply activate the new environment as described above.
To deactivate the virtual environment and return to the system's default Python: ``deactivate``.
If you also want to be able to build the documentation that resides in the ``docs`` subfolder, you need to activate
the *Python 3* environment and install the docs dependencies as well:
* ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* ``pip install -e '.[develop,plugins,docs]'``
Go to the directory `docs` and you can then build the documentation:
* ``sphinx-build -b html . _build``
The documentation will be available in the newly created ``_build`` directory. You can simply browse it locally by opening ``index.html``
* build the documentation running ``sphinx-build -b html . _build`` in the ``docs``
folder -- the documentation will be available in the newly created ``_build``
directory. You can simply browse it locally by opening ``index.html``
.. _sec-development-environment-source-linux:
@@ -94,7 +78,7 @@ installed:
.. code-block:: none
sudo apt-get install python3 python3-pip python3-dev python3-setuptools python3-virtualenv python3 python3-virtualenv python3-dev git libyaml-dev build-essential
sudo apt-get install python3 python3-pip python3-dev python3-setuptools python3-virtualenv git libyaml-dev build-essential
.. todo::
@@ -131,9 +115,9 @@ First download & install:
* `The current Python 3.8 Windows x86 executable installer <https://www.python.org/downloads/windows/>`_
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
* it's recommended to install Python 2.7 into ``C:\Python27`` and Python 3 into ``C:\Python38`` - if you select
* it's recommended to install Python 3 into ``C:\Python3`` - if you select
different install locations please substitute accordingly
* it's also recommended to have both versions get installed for all users
* it's also recommended to install for all users
* `Build Tools for Visual Studio 2019 <https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019>`_
@@ -257,6 +241,8 @@ PyCharm
- **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." >
"Virtualenv Environment > "Existing Environment", select OctoPrint ``venv`` folder (e.g. ``~/devel/OctoPrint/venv``).
If desired, repeat for any other additional Python venvs (e.g. different versions).
- Right click "src" in project tree, mark as source folder
- Add Run/Debug Configuration, select "Python":
@@ -320,7 +306,7 @@ PyCharm
* disable "Auto-save edited files to trigger the watched"
* enable "Trigger the watched on external changes"
To switch between Python 2 and 3, all you need to do now is change the Project Default Interpreter and restart
To switch between virtual environments (e.g. various Python 3 versions), all you need to do now is change the Project Default Interpreter and restart
OctoPrint. On current PyCharm versions you can do that right from a small selection field in the footer of the IDE.
Otherwise go through Settings.
+1
View File
@@ -63,6 +63,7 @@ INSTALL_REQUIRES = [
"filetype>=1.0.7,<2",
"zeroconf>=0.24,<0.25",
"zipstream-new>=1.1.8,<1.2",
"pathvalidate>=2.4.1,<3",
# vendor bundled dependencies
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
"blinker>=1.4,<2", # dependency of flask_principal
+14 -20
View File
@@ -13,7 +13,7 @@ import pylru
import octoprint.filemanager
from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode
from octoprint.util.text import sanitize
from octoprint.util.files import sanitize_filename
class StorageInterface:
@@ -457,13 +457,14 @@ class LocalFileStorage(StorageInterface):
This storage type implements :func:`path_on_disk`.
"""
def __init__(self, basefolder, create=False):
def __init__(self, basefolder, create=False, really_universal=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
if necessary and ``create`` is set to ``True``.
:param string basefolder: the path to the folder under which to create the storage
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
:param string basefolder: the path to the folder under which to create the storage
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
:param bool really_universal: ``True`` if the file names should be forced to really universal, ``False`` otherwise
"""
self._logger = logging.getLogger(__name__)
@@ -476,6 +477,8 @@ class LocalFileStorage(StorageInterface):
code=StorageError.INVALID_DIRECTORY,
)
self._really_universal = really_universal
import threading
self._metadata_lock_mutex = threading.RLock()
@@ -1151,22 +1154,10 @@ class LocalFileStorage(StorageInterface):
def sanitize_name(self, name):
"""
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
``(``, and ``)`` as is.
sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also
strips leading ``.``s.
"""
name = to_unicode(name)
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_")
if result and result != "." and result != ".." and result[0] == ".":
# hidden files under *nix
result = result[1:]
return result
return sanitize_filename(name, really_universal=self._really_universal)
def sanitize_path(self, path):
"""
@@ -1185,7 +1176,10 @@ class LocalFileStorage(StorageInterface):
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
if path_element == ".." or path_element == ".":
joined_path = os.path.join(joined_path, path_element)
else:
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(
@@ -693,11 +693,15 @@ $(function () {
}
OctoPrint.plugins.pluginmanager
.getRepository(!!options.refresh)
.getRepository(!!options.refresh, {ifModified: true})
.fail(function () {
deferred.reject();
})
.done(function (data) {
.done(function (data, status, xhr) {
// Don't update if cached - requires ifModified: true to pass through
// the 304 status, otherwise it fakes it and produces 200 all the time.
if (xhr.status === 304) return;
self.fromRepositoryResponse(data.repository);
self.online(data.online !== undefined ? data.online : true);
deferred.resolveWith(data);
+2 -1
View File
@@ -1159,13 +1159,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
)
try:
printTimeLeft, printTimeLeftOrigin = estimator.estimate(
ptl, printTimeLeftOrigin = estimator.estimate(
progress,
printTime,
cleanedPrintTime,
statisticalTotalPrintTime,
statisticalTotalPrintTimeType,
)
printTimeLeft = int(ptl)
except Exception:
self._logger.exception(
f"Error while estimating print time via {estimator}"
+4 -1
View File
@@ -407,7 +407,10 @@ class Server:
storage_managers[
octoprint.filemanager.FileDestinations.LOCAL
] = octoprint.filemanager.storage.LocalFileStorage(
self._settings.getBaseFolder("uploads")
self._settings.getBaseFolder("uploads"),
really_universal=self._settings.getBoolean(
["feature", "enforceReallyUniversalFilenames"]
),
)
fileManager = octoprint.filemanager.FileManager(
+6 -1
View File
@@ -198,6 +198,7 @@ def getSettings():
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
"blockedCommands": s.get(["serial", "blockedCommands"]),
"ignoredCommands": s.get(["serial", "ignoredCommands"]),
"pausingCommands": s.get(["serial", "pausingCommands"]),
"emergencyCommands": s.get(["serial", "emergencyCommands"]),
"helloCommand": s.get(["serial", "helloCommand"]),
@@ -626,7 +627,7 @@ def _saveSettings(data):
if "runAt" in data["gcodeAnalysis"]:
s.set(["gcodeAnalysis", "runAt"], data["gcodeAnalysis"]["runAt"])
if "bedZ" in data["gcodeAnalysis"]:
s.setBoolean(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"])
s.setFloat(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"])
if "serial" in data:
if "autoconnect" in data["serial"]:
@@ -748,6 +749,10 @@ def _saveSettings(data):
data["serial"]["blockedCommands"], (list, tuple)
):
s.set(["serial", "blockedCommands"], data["serial"]["blockedCommands"])
if "ignoredCommands" in data["serial"] and isinstance(
data["serial"]["ignoredCommands"], (list, tuple)
):
s.set(["serial", "ignoredCommands"], data["serial"]["ignoredCommands"])
if "pausingCommands" in data["serial"] and isinstance(
data["serial"]["pausingCommands"], (list, tuple)
):
+4 -2
View File
@@ -556,8 +556,10 @@ class OctoPrintFlaskResponse(flask.Response):
if samesite is not None:
samesite = samesite.lower()
if samesite == "none":
samesite = None
if samesite not in (None, "strict", "lax"):
# Must be string "None"
samesite = "None"
if samesite not in ("None", "strict", "lax"):
# If NoneType, the cookie is not set
samesite = None
kwargs["samesite"] = samesite
+2
View File
@@ -110,6 +110,7 @@ default_settings = {
"blacklistedBaudrates": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"],
"blockedCommands": ["M0", "M1"],
"ignoredCommands": [],
"pausingCommands": ["M0", "M1", "M25"],
"emergencyCommands": ["M112", "M108", "M410"],
"checksumRequiringCommands": ["M110"],
@@ -261,6 +262,7 @@ default_settings = {
"uploadOverwriteConfirmation": True,
"autoUppercaseBlacklist": ["M117", "M118"],
"g90InfluencesExtruder": False,
"enforceReallyUniversalFilenames": False,
},
"folder": {
"uploads": None,
@@ -207,6 +207,7 @@ $(function () {
self.serial_longRunningCommands = ko.observable(undefined);
self.serial_checksumRequiringCommands = ko.observable(undefined);
self.serial_blockedCommands = ko.observable(undefined);
self.serial_ignoredCommands = ko.observable(undefined);
self.serial_pausingCommands = ko.observable(undefined);
self.serial_emergencyCommands = ko.observable(undefined);
self.serial_helloCommand = ko.observable(undefined);
@@ -1058,6 +1059,9 @@ $(function () {
blockedCommands: function () {
return splitTextToArray(self.serial_blockedCommands(), ",", true);
},
ignoredCommands: function () {
return splitTextToArray(self.serial_ignoredCommands(), ",", true);
},
pausingCommands: function () {
return splitTextToArray(self.serial_pausingCommands(), ",", true);
},
@@ -1260,6 +1264,9 @@ $(function () {
blockedCommands: function (value) {
self.serial_blockedCommands(value.join(", "));
},
ignoredCommands: function (value) {
self.serial_ignoredCommands(value.join(", "));
},
pausingCommands: function (value) {
self.serial_pausingCommands(value.join(", "));
},
@@ -408,6 +408,13 @@
<span class="help-inline">{{ _('Use this to specify commands that should never be sent to the printer. Just the G or M code, comma separated. Defaults to <code>M0</code> and <code>M1</code> since most firmware will block until a button on the controller has been pressed if it receives either of those two commands.') }}</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialIgnoredCommands">{{ _('Ignored commands') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialIgnoredCommands" data-bind="value: serial_ignoredCommands">
<span class="help-inline">{{ _('Use this to specify commands that should be silently ignored and never be sent to the printer. Just the G or M code, comma separated. Unlike blocked commands above, there will be no warning popup when these commands are encountered.') }}</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialPausingCommands">{{ _('Pausing commands') }}</label>
<div class="controls">
@@ -5852,7 +5852,7 @@ msgid "\n"
" web interface now by clicking the button below.\n"
" "
msgstr "\n"
" Die Serverversion hat sich geändert, ein Neuladen des Webinterfaces ist notwendig. Das wird evtl. laufenden Printjobs nicht unterbrechen. Bitte lade das Webinterface jetzt neu, indem du auf den Button unten klickst."
" Die Serverversion hat sich geändert, ein Neuladen des Webinterfaces ist notwendig. Das wird evtl. laufende Printjobs nicht unterbrechen. Bitte lade das Webinterface jetzt neu, indem du auf den Button unten klickst."
#: src/octoprint/templates/sidebar/connection.jinja2:8
msgid "Save connection settings"
+5 -209
View File
@@ -29,6 +29,11 @@ from immutabledict import immutabledict
from octoprint import UMASK
from octoprint.util.connectivity import ConnectivityChecker # noqa: F401
from octoprint.util.files import ( # noqa: F401
find_collision_free_name,
get_dos_filename,
silent_remove,
)
from octoprint.util.net import ( # noqa: F401
address_for_client,
interface_addresses,
@@ -462,215 +467,6 @@ def get_exception_string(fmt="{type}: '{message}' @ {file}:{function}:{line}"):
return fmt.format(**exception)
@deprecated(
"get_free_bytes has been deprecated and will be removed in the future",
includedoc="Replaced by `psutil.disk_usage <http://pythonhosted.org/psutil/#psutil.disk_usage>`_.",
since="1.2.5",
)
def get_free_bytes(path):
import psutil
return psutil.disk_usage(path).free
def get_dos_filename(
input, existing_filenames=None, extension=None, whitelisted_extensions=None, **kwargs
):
"""
Converts the provided input filename to a 8.3 DOS compatible filename. If ``existing_filenames`` is provided, the
conversion result will be guaranteed not to collide with any of the filenames provided thus.
Uses :func:`find_collision_free_name` internally.
Arguments:
input (string): The original filename incl. extension to convert to the 8.3 format.
existing_filenames (list): A list of existing filenames with which the generated 8.3 name must not collide.
Optional.
extension (string): The .3 file extension to use for the generated filename. If not provided, the extension of
the provided ``filename`` will simply be truncated to 3 characters.
whitelisted_extensions (list): A list of extensions on ``input`` that will be left as-is instead of
exchanging for ``extension``.
kwargs (dict): Additional keyword arguments to provide to :func:`find_collision_free_name`.
Returns:
string: A 8.3 compatible translation of the original filename, not colliding with the optionally provided
``existing_filenames`` and with the provided ``extension`` or the original extension shortened to
a maximum of 3 characters.
Raises:
ValueError: No 8.3 compatible name could be found that doesn't collide with the provided ``existing_filenames``.
Examples:
>>> get_dos_filename("test1234.gco") # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> get_dos_filename("test1234.gcode") # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> get_dos_filename("test12345.gco") # doctest: +ALLOW_UNICODE
'test12~1.gco'
>>> get_dos_filename("test1234.fnord", extension="gco") # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> get_dos_filename("auto0.g", extension="gco") # doctest: +ALLOW_UNICODE
'auto0.gco'
>>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"]) # doctest: +ALLOW_UNICODE
'auto0.g'
>>> get_dos_filename(None)
>>> get_dos_filename("foo") # doctest: +ALLOW_UNICODE
'foo'
"""
if input is None:
return None
if existing_filenames is None:
existing_filenames = []
if extension is not None:
extension = extension.lower()
if whitelisted_extensions is None:
whitelisted_extensions = []
filename, ext = os.path.splitext(input)
ext = ext.lower()
ext = ext[1:] if ext.startswith(".") else ext
if ext in whitelisted_extensions or extension is None:
extension = ext
return find_collision_free_name(filename, extension, existing_filenames, **kwargs)
def find_collision_free_name(filename, extension, existing_filenames, max_power=2):
"""
Tries to find a collision free translation of "<filename>.<extension>" to the 8.3 DOS compatible format,
preventing collisions with any of the ``existing_filenames``.
First strips all of ``."/\\[]:;=,`` from the filename and extensions, converts them to lower case and truncates
the ``extension`` to a maximum length of 3 characters.
If the filename is already equal or less than 8 characters in length after that procedure and "<filename>.<extension>"
are not contained in the ``existing_files``, that concatenation will be returned as the result.
If not, the following algorithm will be applied to try to find a collision free name::
set counter := power := 1
while counter < 10^max_power:
set truncated := substr(filename, 0, 6 - power + 1) + "~" + counter
set result := "<truncated>.<extension>"
if result is collision free:
return result
counter++
if counter >= 10 ** power:
power++
raise ValueError
This will basically -- for a given original filename of ``some_filename`` and an extension of ``gco`` -- iterate
through names of the format ``some_f~1.gco``, ``some_f~2.gco``, ..., ``some_~10.gco``, ``some_~11.gco``, ...,
``<prefix>~<n>.gco`` for ``n`` less than 10 ^ ``max_power``, returning as soon as one is found that is not colliding.
Arguments:
filename (string): The filename without the extension to convert to 8.3.
extension (string): The extension to convert to 8.3 -- will be truncated to 3 characters if it's longer than
that.
existing_filenames (list): A list of existing filenames to prevent name collisions with.
max_power (int): Limits the possible attempts of generating a collision free name to 10 ^ ``max_power``
variations. Defaults to 2, so the name generation will maximally reach ``<name>~99.<ext>`` before
aborting and raising an exception.
Returns:
string: A 8.3 representation of the provided original filename, ensured to not collide with the provided
``existing_filenames``
Raises:
ValueError: No collision free name could be found.
Examples:
>>> find_collision_free_name("test1234", "gco", []) # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> find_collision_free_name("test1234", "gcode", []) # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> find_collision_free_name("test12345", "gco", []) # doctest: +ALLOW_UNICODE
'test12~1.gco'
>>> find_collision_free_name("test 123", "gco", []) # doctest: +ALLOW_UNICODE
'test_123.gco'
>>> find_collision_free_name("test1234", "g o", []) # doctest: +ALLOW_UNICODE
'test1234.g_o'
>>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) # doctest: +ALLOW_UNICODE
'test12~2.gco'
>>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]]
>>> find_collision_free_name("test12345", "gco", many_files) # doctest: +ALLOW_UNICODE
'test1~10.gco'
>>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)]
>>> find_collision_free_name("test12345", "gco", many_more_files) # doctest: +ALLOW_UNICODE
'test1~99.gco'
>>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"]
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) # doctest: +ALLOW_UNICODE
Traceback (most recent call last):
...
ValueError: Can't create a collision free filename
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3) # doctest: +ALLOW_UNICODE
'test~100.gco'
"""
filename = to_unicode(filename)
extension = to_unicode(extension)
if filename.startswith("/"):
filename = filename[1:]
existing_filenames = [
to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames
]
def make_valid(text):
return re.sub(
r"\s+", "_", text.translate({ord(i): None for i in r".\"/\[]:;=,"})
).lower()
filename = make_valid(filename)
extension = make_valid(extension)
extension = extension[:3] if len(extension) > 3 else extension
full_name_format = "{filename}.{extension}" if extension else "{filename}"
result = full_name_format.format(filename=filename, extension=extension)
if len(filename) <= 8 and result not in existing_filenames:
# early exit
return result
counter = 1
power = 1
prefix_format = "{segment}~{counter}"
while counter < (10 ** max_power):
prefix = prefix_format.format(
segment=filename[: (6 - power + 1)], counter=str(counter)
)
result = full_name_format.format(filename=prefix, extension=extension)
if result not in existing_filenames:
return result
counter += 1
if counter >= 10 ** power:
power += 1
raise ValueError("Can't create a collision free filename")
def silent_remove(file):
"""
Silently removes a file. Does not raise an error if the file doesn't exist.
Arguments:
file (string): The path of the file to be removed
"""
try:
os.remove(file)
except OSError:
pass
def sanitize_ascii(line):
if not isinstance(line, (str, bytes)):
raise ValueError(
+16
View File
@@ -630,6 +630,7 @@ class MachineCom:
["serial", "checksumRequiringCommands"]
)
self._blocked_commands = settings().get(["serial", "blockedCommands"])
self._ignored_commands = settings().get(["serial", "ignoredCommands"])
self._pausing_commands = settings().get(["serial", "pausingCommands"])
self._emergency_commands = settings().get(["serial", "emergencyCommands"])
self._sanity_check_tools = settings().getBoolean(["serial", "sanityCheckTools"])
@@ -5286,6 +5287,21 @@ class MachineCom:
},
)
return (None,)
if gcode in self._ignored_commands:
message = "Not sending {} to printer, it's configured as an ignored command".format(
gcode
)
self._log("Info: " + message)
self._logger.info(message)
eventManager().fire(
Events.COMMAND_SUPPRESSED,
{
"command": cmd,
"message": message,
"severity": "info",
},
)
return (None,)
def _command_phase_sending(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
+277
View File
@@ -0,0 +1,277 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
import itertools
import os.path
import re
def _sfn_really_universal(name):
from octoprint.util.text import sanitize
### taken from pathvalidate library
_WINDOWS_RESERVED_FILE_NAMES = ("CON", "PRN", "AUX", "CLOCK$", "NUL") + tuple(
"{:s}{:d}".format(name, num)
for name, num in itertools.product(("COM", "LPT"), range(1, 10))
)
_MACOS_RESERVED_FILE_NAMES = (":",)
result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_")
root, ext = os.path.splitext(result)
if root.upper() in (_WINDOWS_RESERVED_FILE_NAMES + _MACOS_RESERVED_FILE_NAMES):
root += "_"
return root + ext
def sanitize_filename(name, really_universal=False):
"""
Sanitizes the provided filename. Implementation differs between Python versions.
On Python 2, the name will be ASCII-fied, using ``octoprint.util.text.sanitize`` with
safe chars ``-_.()[] `` and all spaces replaced by ``_``.
On Python 3, ``pathvalidate.sanitize_filename`` will be used instead, leaving the
name as intact as possible while still being a legal file name under all operating
systems.
In all cases, a single leading ``.`` will be removed (as it denotes hidden files
on *nix).
Args:
name: The file name to sanitize. Only the name, no path elements.
really_universal: If ``True``, the Python 2 method of sanitization will always
be used. Defaults to ``False``.
Returns:
the sanitized file name
"""
from octoprint.util import to_unicode
name = to_unicode(name)
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
try:
from pathvalidate import sanitize_filename as sfn
except ImportError:
sfn = _sfn_really_universal
if really_universal:
result = _sfn_really_universal(name)
else:
result = sfn(name)
return result.lstrip(".")
def get_dos_filename(
input, existing_filenames=None, extension=None, whitelisted_extensions=None, **kwargs
):
"""
Converts the provided input filename to a 8.3 DOS compatible filename. If ``existing_filenames`` is provided, the
conversion result will be guaranteed not to collide with any of the filenames provided thus.
Uses :func:`find_collision_free_name` internally.
Arguments:
input (string): The original filename incl. extension to convert to the 8.3 format.
existing_filenames (list): A list of existing filenames with which the generated 8.3 name must not collide.
Optional.
extension (string): The .3 file extension to use for the generated filename. If not provided, the extension of
the provided ``filename`` will simply be truncated to 3 characters.
whitelisted_extensions (list): A list of extensions on ``input`` that will be left as-is instead of
exchanging for ``extension``.
kwargs (dict): Additional keyword arguments to provide to :func:`find_collision_free_name`.
Returns:
string: A 8.3 compatible translation of the original filename, not colliding with the optionally provided
``existing_filenames`` and with the provided ``extension`` or the original extension shortened to
a maximum of 3 characters.
Raises:
ValueError: No 8.3 compatible name could be found that doesn't collide with the provided ``existing_filenames``.
Examples:
>>> get_dos_filename("test1234.gco") # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> get_dos_filename("test1234.gcode") # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> get_dos_filename("test12345.gco") # doctest: +ALLOW_UNICODE
'test12~1.gco'
>>> get_dos_filename("Wölfe 🐺.gcode") # doctest: +ALLOW_UNICODE
'wolfe_~1.gco'
>>> get_dos_filename("💚.gcode") # doctest: +ALLOW_UNICODE
'green_~1.gco'
>>> get_dos_filename("test1234.fnord", extension="gco") # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> get_dos_filename("auto0.g", extension="gco") # doctest: +ALLOW_UNICODE
'auto0.gco'
>>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"]) # doctest: +ALLOW_UNICODE
'auto0.g'
>>> get_dos_filename(None)
>>> get_dos_filename("foo") # doctest: +ALLOW_UNICODE
'foo'
"""
if input is None:
return None
input = sanitize_filename(input, really_universal=True)
if existing_filenames is None:
existing_filenames = []
if extension is not None:
extension = extension.lower()
if whitelisted_extensions is None:
whitelisted_extensions = []
filename, ext = os.path.splitext(input)
ext = ext.lower()
ext = ext[1:] if ext.startswith(".") else ext
if ext in whitelisted_extensions or extension is None:
extension = ext
return find_collision_free_name(filename, extension, existing_filenames, **kwargs)
def find_collision_free_name(filename, extension, existing_filenames, max_power=2):
"""
Tries to find a collision free translation of "<filename>.<extension>" to the 8.3 DOS compatible format,
preventing collisions with any of the ``existing_filenames``.
First strips all of ``."/\\[]:;=,`` from the filename and extensions, converts them to lower case and truncates
the ``extension`` to a maximum length of 3 characters.
If the filename is already equal or less than 8 characters in length after that procedure and "<filename>.<extension>"
are not contained in the ``existing_files``, that concatenation will be returned as the result.
If not, the following algorithm will be applied to try to find a collision free name::
set counter := power := 1
while counter < 10^max_power:
set truncated := substr(filename, 0, 6 - power + 1) + "~" + counter
set result := "<truncated>.<extension>"
if result is collision free:
return result
counter++
if counter >= 10 ** power:
power++
raise ValueError
This will basically -- for a given original filename of ``some_filename`` and an extension of ``gco`` -- iterate
through names of the format ``some_f~1.gco``, ``some_f~2.gco``, ..., ``some_~10.gco``, ``some_~11.gco``, ...,
``<prefix>~<n>.gco`` for ``n`` less than 10 ^ ``max_power``, returning as soon as one is found that is not colliding.
Arguments:
filename (string): The filename without the extension to convert to 8.3.
extension (string): The extension to convert to 8.3 -- will be truncated to 3 characters if it's longer than
that.
existing_filenames (list): A list of existing filenames to prevent name collisions with.
max_power (int): Limits the possible attempts of generating a collision free name to 10 ^ ``max_power``
variations. Defaults to 2, so the name generation will maximally reach ``<name>~99.<ext>`` before
aborting and raising an exception.
Returns:
string: A 8.3 representation of the provided original filename, ensured to not collide with the provided
``existing_filenames``
Raises:
ValueError: No collision free name could be found.
Examples:
>>> find_collision_free_name("test1234", "gco", []) # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> find_collision_free_name("test1234", "gcode", []) # doctest: +ALLOW_UNICODE
'test1234.gco'
>>> find_collision_free_name("test12345", "gco", []) # doctest: +ALLOW_UNICODE
'test12~1.gco'
>>> find_collision_free_name("test 123", "gco", []) # doctest: +ALLOW_UNICODE
'test_123.gco'
>>> find_collision_free_name("test1234", "g o", []) # doctest: +ALLOW_UNICODE
'test1234.g_o'
>>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) # doctest: +ALLOW_UNICODE
'test12~2.gco'
>>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]]
>>> find_collision_free_name("test12345", "gco", many_files) # doctest: +ALLOW_UNICODE
'test1~10.gco'
>>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)]
>>> find_collision_free_name("test12345", "gco", many_more_files) # doctest: +ALLOW_UNICODE
'test1~99.gco'
>>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"]
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) # doctest: +ALLOW_UNICODE
Traceback (most recent call last):
...
ValueError: Can't create a collision free filename
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3) # doctest: +ALLOW_UNICODE
'test~100.gco'
"""
from octoprint.util import to_unicode
filename = to_unicode(filename)
extension = to_unicode(extension)
if filename.startswith("/"):
filename = filename[1:]
existing_filenames = [
to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames
]
def make_valid(text):
return re.sub(
r"\s+", "_", text.translate({ord(i): None for i in r".\"/\[]:;=,"})
).lower()
filename = make_valid(filename)
extension = make_valid(extension)
extension = extension[:3] if len(extension) > 3 else extension
full_name_format = "{filename}.{extension}" if extension else "{filename}"
result = full_name_format.format(filename=filename, extension=extension)
if len(filename) <= 8 and result not in existing_filenames:
# early exit
return result
counter = 1
power = 1
prefix_format = "{segment}~{counter}"
while counter < (10 ** max_power):
prefix = prefix_format.format(
segment=filename[: (6 - power + 1)], counter=str(counter)
)
result = full_name_format.format(filename=prefix, extension=extension)
if result not in existing_filenames:
return result
counter += 1
if counter >= 10 ** power:
power += 1
raise ValueError("Can't create a collision free filename")
def silent_remove(file):
"""
Silently removes a file. Does not raise an error if the file doesn't exist.
Arguments:
file (string): The path of the file to be removed
"""
try:
os.remove(file)
except OSError:
pass
+7 -2
View File
@@ -12,6 +12,12 @@ _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
_SLUGIFIES = {}
def demojify(text):
text = to_unicode(text)
text = remove_unicode_variations(text)
return demojize(text, delimiters=("", ""))
def sanitize(text, safe_chars="-_.", demoji=True):
"""
Sanitizes text by running it through slugify and optionally emoji translating.
@@ -44,8 +50,7 @@ def sanitize(text, safe_chars="-_.", demoji=True):
text = to_unicode(text)
if demoji:
text = remove_unicode_variations(text)
text = demojize(text, delimiters=("", ""))
text = demojify(text)
return slugify(text)
+65 -44
View File
@@ -7,10 +7,25 @@ import os.path
import unittest
import unittest.mock as mock
import pytest
from ddt import data, ddt, unpack
from octoprint.filemanager.storage import LocalFileStorage, StorageError
try:
import pathvalidate # noqa: F401
HAS_PATHVALIDATE = True
except ImportError:
HAS_PATHVALIDATE = False
pathvalidate_unavailable_only = pytest.mark.skipif(
HAS_PATHVALIDATE, reason="pathvalidate available"
)
pathvalidate_available_only = pytest.mark.skipif(
not HAS_PATHVALIDATE, reason="pathvalidate unavailable"
)
class FileWrapper:
def __init__(self, filename):
@@ -234,28 +249,14 @@ class LocalStorageTest(unittest.TestCase):
self.assertIsNotNone(copied_metadata)
self.assertDictEqual(before_stl_metadata, copied_metadata)
def test_copy_file_new_display(self):
def test_copy_file_same_name(self):
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
try:
self.storage.copy_file("bp_case.stl", "bp_cäse.stl")
self.storage.copy_file("bp_case.stl", "bp_case.stl")
self.fail("Expected an exception")
except StorageError as e:
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
def test_move_file_new_display(self):
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
before_metadata = self.storage.get_metadata("bp_case.stl")
self.storage.move_file("bp_case.stl", "bp_cäse.stl")
after_metadata = self.storage.get_metadata("bp_case.stl")
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "bp_case.stl")))
self.assertIsNotNone(before_metadata)
self.assertIsNotNone(after_metadata)
self.assertIn("display", after_metadata)
self.assertEqual("bp_cäse.stl", after_metadata["display"])
@data("copy_file", "move_file")
def test_copy_move_file_different_display(self, operation):
self._add_file("bp_case.stl", FILE_BP_CASE_STL, display="bp_cäse.stl")
@@ -318,9 +319,7 @@ class LocalStorageTest(unittest.TestCase):
self.assertEqual("täst", metadata["display"])
def test_add_subfolder(self):
folder_name = self._add_and_verify_folder(
"folder with some spaces", "folder_with_some_spaces"
)
folder_name = self._add_and_verify_folder("folder", "folder")
subfolder_name = self._add_and_verify_folder(
(folder_name, "subfolder"), folder_name + "/subfolder"
)
@@ -437,25 +436,14 @@ class LocalStorageTest(unittest.TestCase):
self.assertIsNotNone(copied_metadata)
self.assertDictEqual(before_source_metadata, copied_metadata)
def test_copy_folder_new_display(self):
def test_copy_folder_same_name(self):
self._add_folder("folder")
try:
self.storage.copy_folder("folder", "földer")
self.storage.copy_folder("folder", "folder")
self.fail("Expected an exception")
except StorageError as e:
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
def test_move_folder_new_display(self):
self._add_folder("folder")
before_metadata = self.storage.get_metadata("folder")
self.storage.move_folder("folder", "földer")
after_metadata = self.storage.get_metadata("folder")
self.assertIsNone(before_metadata)
self.assertIsNotNone(after_metadata)
self.assertDictEqual(after_metadata, {"display": "földer"})
@data("copy_folder", "move_folder")
def test_copy_move_folder_different_display(self, operation):
self._add_folder("folder", display="földer")
@@ -740,6 +728,7 @@ class LocalStorageTest(unittest.TestCase):
self.assertEqual(0, len(gcode_metadata["links"]))
self.assertEqual(1, len(stl_metadata["links"]))
@pathvalidate_unavailable_only
@data(
("some_file.gco", "some_file.gco"),
(
@@ -749,7 +738,21 @@ class LocalStorageTest(unittest.TestCase):
("pengüino pequeño.stl", "penguino_pequeno.stl"),
)
@unpack
def test_sanitize_name(self, input, expected):
def test_sanitize_name_pvu(self, input, expected):
actual = self.storage.sanitize_name(input)
self.assertEqual(expected, actual)
@pathvalidate_available_only
@data(
("some_file.gco", "some_file.gco"),
(
"some_file with (parentheses) and ümläuts and digits 123.gco",
"some_file with (parentheses) and ümläuts and digits 123.gco",
),
("pengüino pequeño.stl", "pengüino pequeño.stl"),
)
@unpack
def test_sanitize_name_pva(self, input, expected):
actual = self.storage.sanitize_name(input)
self.assertEqual(expected, actual)
@@ -783,17 +786,7 @@ class LocalStorageTest(unittest.TestCase):
except ValueError as e:
self.assertTrue(e.args[0].startswith("path not contained in base folder: "))
@data(
("some/folder/and/some file.gco", "/some/folder/and", "some_file.gco"),
(("some", "folder", "and", "some file.gco"), "/some/folder/and", "some_file.gco"),
("some file.gco", "/", "some_file.gco"),
(("some file.gco",), "/", "some_file.gco"),
("", "/", ""),
("some/folder/with/trailing/slash/", "/some/folder/with/trailing/slash", ""),
(("some", "folder", ""), "/some/folder", ""),
)
@unpack
def test_sanitize(self, input, expected_path, expected_name):
def _test_sanitize(self, input, expected_path, expected_name):
actual = self.storage.sanitize(input)
self.assertTrue(isinstance(actual, tuple))
self.assertEqual(2, len(actual))
@@ -810,6 +803,34 @@ class LocalStorageTest(unittest.TestCase):
self.assertEqual(expected_path, actual_path)
self.assertEqual(expected_name, actual_name)
@pathvalidate_unavailable_only
@data(
("some/folder/and/some file.gco", "/some/folder/and", "some_file.gco"),
(("some", "folder", "and", "some file.gco"), "/some/folder/and", "some_file.gco"),
("some file.gco", "/", "some_file.gco"),
(("some file.gco",), "/", "some_file.gco"),
("", "/", ""),
("some/folder/with/trailing/slash/", "/some/folder/with/trailing/slash", ""),
(("some", "folder", ""), "/some/folder", ""),
)
@unpack
def test_sanitize_pvu(self, input, expected_path, expected_name):
self._test_sanitize(input, expected_path, expected_name)
@pathvalidate_available_only
@data(
("some/folder/and/some file.gco", "/some/folder/and", "some file.gco"),
(("some", "folder", "and", "some file.gco"), "/some/folder/and", "some file.gco"),
("some file.gco", "/", "some file.gco"),
(("some file.gco",), "/", "some file.gco"),
("", "/", ""),
("some/folder/with/trailing/slash/", "/some/folder/with/trailing/slash", ""),
(("some", "folder", ""), "/some/folder", ""),
)
@unpack
def test_sanitize_pva(self, input, expected_path, expected_name):
self._test_sanitize(input, expected_path, expected_name)
def _add_and_verify_file(
self, path, expected_path, file_object, links=None, overwrite=False, display=None
):
+1 -1
View File
@@ -500,7 +500,7 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
@data(
[None, None, False, None, None],
[None, None, False, "none", None],
[None, None, False, "none", "None"],
[None, None, False, "lax", "lax"],
[None, None, False, "StRiCt", "strict"],
[None, None, False, "INVALID", None],
+69
View File
@@ -0,0 +1,69 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import pytest
from ddt import data, ddt, unpack
from octoprint.util.files import sanitize_filename
try:
import pathvalidate # noqa: F401
HAS_PATHVALIDATE = True
except ImportError:
HAS_PATHVALIDATE = False
pathvalidate_unavailable_only = pytest.mark.skipif(
HAS_PATHVALIDATE, reason="pathvalidate available"
)
pathvalidate_available_only = pytest.mark.skipif(
not HAS_PATHVALIDATE, reason="pathvalidate unavailable"
)
@ddt
class FilesUtilTest(unittest.TestCase):
@data(
("some_file.gcode", "some_file.gcode"),
("NUL.gcode", "NUL_.gcode"),
("LPT1", "LPT1_"),
(".test.gcode", "test.gcode"),
("..text.gcode", "test.gcode"),
)
@unpack
def test_sanitize_filename(self, filename, expected):
actual = sanitize_filename(filename)
self.assertEqual(actual, expected)
@data("file/with/slash.gcode", "file\\with\\backslash.gcode")
def test_sanitize_filename_invalid(self, filename):
try:
sanitize_filename(filename)
self.fail("expected ValueError")
except ValueError as ex:
self.assertEqual(str(ex), "name must not contain / or \\")
@pathvalidate_unavailable_only
@data(
("file with space.gcode", "file_with_space.gcode"),
("Wölfe 🐺.gcode", "Wolfe_wolf_face.gcode"),
)
@unpack
def test_sanitize_filename_pvu(self, filename, expected):
actual = sanitize_filename(filename)
self.assertEqual(actual, expected)
@pathvalidate_available_only
@data(
("file with space.gcode", "file with space.gcode"),
("Wölfe 🐺.gcode", "Wölfe 🐺.gcode"),
)
@unpack
def test_sanitize_filename_pva(self, filename, expected):
actual = sanitize_filename(filename)
self.assertEqual(actual, expected)