From 7765e9afa9085b5e1d74d6513887438300d0b719 Mon Sep 17 00:00:00 2001 From: Stevil Knevil Date: Thu, 6 May 2021 17:33:55 +0100 Subject: [PATCH 01/12] Implemented ignored commands --- docs/configuration/config_yaml.rst | 5 +++++ src/octoprint/server/api/settings.py | 5 +++++ src/octoprint/settings.py | 1 + .../static/js/app/viewmodels/settings.js | 7 +++++++ .../dialogs/settings/serialconnection.jinja2 | 7 +++++++ src/octoprint/util/comm.py | 16 ++++++++++++++++ 6 files changed, 41 insertions(+) diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index a945a6c2a..992e9af39 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -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 diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 39d7db81a..19e030b5d 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -202,6 +202,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"]), @@ -766,6 +767,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) ): diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 2a7c9fe39..963987934 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -135,6 +135,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"], diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 1e0cc0fdf..f6cc79a93 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -206,6 +206,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); @@ -1057,6 +1058,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); }, @@ -1259,6 +1263,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(", ")); }, diff --git a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 index 52b391fa6..e712742d6 100644 --- a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 +++ b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 @@ -401,6 +401,13 @@ {{ _('Use this to specify commands that should never be sent to the printer. Just the G or M code, comma separated. Defaults to M0 and M1 since most firmware will block until a button on the controller has been pressed if it receives either of those two commands.') }} +
+ +
+ + {{ _('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.') }} +
+
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index a5dcd8895..fe0fb80c2 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -645,6 +645,7 @@ class MachineCom(object): ["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"]) @@ -5297,6 +5298,21 @@ class MachineCom(object): }, ) 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 From 98454a2827d31d78d0606e88b6053f8892b4a693 Mon Sep 17 00:00:00 2001 From: Stevil Knevil Date: Thu, 6 May 2021 17:45:41 +0100 Subject: [PATCH 02/12] Updated Authors.md --- AUTHORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS.md b/AUTHORS.md index 705d6bb33..cbdfc50f8 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -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 From e403e8cc750e1124a3316549b64c229a768a110a Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Sun, 9 May 2021 16:58:39 +0100 Subject: [PATCH 03/12] :zap: Don't re-render the plugin repository if notmodified Closes #4131 --- .../plugins/pluginmanager/static/js/pluginmanager.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 7d7eba04b..6248965f2 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -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); From 7234b26d2a1980b4c1baa8415ac49b927c9dcc60 Mon Sep 17 00:00:00 2001 From: Eyal <109809+eyal0@users.noreply.github.com> Date: Tue, 11 May 2021 09:34:16 -0600 Subject: [PATCH 04/12] bedZ should be a float --- src/octoprint/server/api/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index c3e6cea10..d718707c3 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -643,7 +643,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"]: From 2c03ecdfff8f111fd2f9d9db1bdb6a8d01fdfe84 Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Wed, 12 May 2021 00:08:32 +0100 Subject: [PATCH 05/12] :bug: Fix SameSite=None cookie When passing Python's NoneType down to Werkzeug, it uses this logic: ```python if samesite is not None: samesite = samesite.title() if samesite not in {"Strict", "Lax", "None"}: raise ValueError("SameSite must be 'Strict', 'Lax', or 'None'.") ``` This means that when OctoPrint converted any strings 'None' into NoneType, they would not show up in the Set-Cookie header. Investigation: https://community.octoprint.org/t/unable-to-log-into-octoprint-through-an-iframe-on-home-assistant/33977/20?u=charlie_powell Link to werkzeug source: https://github.com/pallets/werkzeug/blob/1dde4b1790f9c46b7122bb8225e6b48a5b22a615/src/werkzeug/http.py#L1213-L1217 Docs, while not explicitly clear, here: https://werkzeug.palletsprojects.com/en/1.0.x/http/?highlight=dump_cookie#werkzeug.http.dump_cookie --- src/octoprint/server/util/flask.py | 6 ++++-- tests/server/util/test_flask.py | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 4afa58051..cf7434f0b 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -567,8 +567,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 diff --git a/tests/server/util/test_flask.py b/tests/server/util/test_flask.py index 6596e232c..397eeccf7 100644 --- a/tests/server/util/test_flask.py +++ b/tests/server/util/test_flask.py @@ -503,7 +503,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], From d83d4b15280bd716274f8012c78653c6578e5625 Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Wed, 12 May 2021 16:45:27 +0100 Subject: [PATCH 06/12] :pencil: Adjust/clarify docs --- docs/configuration/config_yaml.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index a945a6c2a..c8d461e15 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -904,9 +904,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 From d153bad51b5371368c2537399096188c9b4ca75e Mon Sep 17 00:00:00 2001 From: Harald Wagener Date: Thu, 13 May 2021 11:25:06 +0200 Subject: [PATCH 07/12] Update messages.po tiny grammar fix. --- src/octoprint/translations/de/LC_MESSAGES/messages.po | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/translations/de/LC_MESSAGES/messages.po b/src/octoprint/translations/de/LC_MESSAGES/messages.po index 34c282e10..dca455d93 100644 --- a/src/octoprint/translations/de/LC_MESSAGES/messages.po +++ b/src/octoprint/translations/de/LC_MESSAGES/messages.po @@ -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" From 884ccee5f8ff8b5f040cb265ba40bb9f55bd7a89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 18 May 2021 12:38:45 +0200 Subject: [PATCH 08/12] =?UTF-8?q?=F0=9F=93=9D=20Fix=20some=20doc=20bugs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #4084 --- docs/api/datamodel.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index bbca4519f..703c19c4e 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -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 From 5d326e9c57656401c8f6fe8718f373b99429cd46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 18 May 2021 14:42:24 +0200 Subject: [PATCH 09/12] =?UTF-8?q?=F0=9F=A5=85=20Ensure=20int=20for=20print?= =?UTF-8?q?TimeLeft=20from=20plugins?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See #4084 --- src/octoprint/printer/standard.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index a2084db7e..0aaa197a6 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -1184,13 +1184,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( "Error while estimating print time via {}".format(estimator) From ecf56b6658ddc5ac567a5181541d3651d821d74b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 19 May 2021 17:56:08 +0200 Subject: [PATCH 10/12] =?UTF-8?q?=F0=9F=94=A5=20Remove=20deprecated=20octo?= =?UTF-8?q?print.util.get=5Ffree=5Fbytes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/util/__init__.py | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 25add714f..6504baa13 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -480,17 +480,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 `_.", - 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 ): From f912adcd3320ac6a3c3b5b3161d907bce188eab7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 20 May 2021 10:36:01 +0200 Subject: [PATCH 11/12] =?UTF-8?q?=E2=9C=A8=20Support=20unicode=20file=20na?= =?UTF-8?q?mes=20on=20Py3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If we are on py3 and thus can rely on pathvalidate, we'll now no longer slugify uploaded files names, but try to keep them as close to the original name as possible, including unicode and emoji and whatnot. This requires the underlying file system to support this, so just in case the old behaviour can be enforced by setting the config flag feature.enforceReallyUniversalFilenames to true. Closes #4078 --- THIRDPARTYLICENSES.md | 1 + setup.py | 1 + src/octoprint/filemanager/storage.py | 34 ++- src/octoprint/server/__init__.py | 5 +- src/octoprint/settings.py | 1 + src/octoprint/util/__init__.py | 203 +----------------- src/octoprint/util/files.py | 277 +++++++++++++++++++++++++ src/octoprint/util/text.py | 9 +- tests/filemanager/test_localstorage.py | 109 ++++++---- tests/util/test_files.py | 69 ++++++ 10 files changed, 444 insertions(+), 265 deletions(-) create mode 100644 src/octoprint/util/files.py create mode 100644 tests/util/test_files.py diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index 2708c1520..e54f45971 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -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 diff --git a/setup.py b/setup.py index bc25b849f..b03544e42 100644 --- a/setup.py +++ b/setup.py @@ -84,6 +84,7 @@ INSTALL_REQUIRES_PYTHON3 = [ "feedparser>=6.0.2,<7", "zeroconf>=0.24,<0.25", "immutabledict>=1.2.0,<2", + "pathvalidate>=2.4.1,<3", ] # OSX specific requirements diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 954d18807..da20673aa 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -24,7 +24,7 @@ from past.builtins import basestring 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(object): @@ -468,13 +468,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__) @@ -487,6 +488,8 @@ class LocalFileStorage(StorageInterface): code=StorageError.INVALID_DIRECTORY, ) + self._really_universal = really_universal + import threading self._metadata_lock_mutex = threading.RLock() @@ -1165,22 +1168,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): """ @@ -1199,7 +1190,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( diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 93cafa498..0d5e1cdd7 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -410,7 +410,10 @@ class Server(object): 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( diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 6032bf36b..b81ab1cad 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -288,6 +288,7 @@ default_settings = { "uploadOverwriteConfirmation": True, "autoUppercaseBlacklist": ["M117", "M118"], "g90InfluencesExtruder": False, + "enforceReallyUniversalFilenames": False, }, "folder": { "uploads": None, diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 6504baa13..ba3e25af3 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -50,6 +50,11 @@ from past.builtins import basestring, unicode 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, @@ -480,204 +485,6 @@ def get_exception_string(fmt="{type}: '{message}' @ {file}:{function}:{line}"): return fmt.format(**exception) -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 "." 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 "." - 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 := "." - 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``, ..., - ``~.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 ``~99.`` 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, basestring): raise ValueError( diff --git a/src/octoprint/util/files.py b/src/octoprint/util/files.py new file mode 100644 index 000000000..49a6efb28 --- /dev/null +++ b/src/octoprint/util/files.py @@ -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 "." 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 "." + 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 := "." + 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``, ..., + ``~.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 ``~99.`` 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 diff --git a/src/octoprint/util/text.py b/src/octoprint/util/text.py index 50b7c151b..41026a18c 100644 --- a/src/octoprint/util/text.py +++ b/src/octoprint/util/text.py @@ -15,6 +15,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. @@ -47,8 +53,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) diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py index d4d3dc708..73fa296de 100644 --- a/tests/filemanager/test_localstorage.py +++ b/tests/filemanager/test_localstorage.py @@ -11,10 +11,25 @@ import os.path import unittest import 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(object): def __init__(self, filename): @@ -238,28 +253,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") @@ -322,9 +323,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" ) @@ -441,25 +440,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") @@ -744,6 +732,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"), ( @@ -753,7 +742,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) @@ -787,17 +790,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)) @@ -814,6 +807,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 ): diff --git a/tests/util/test_files.py b/tests/util/test_files.py new file mode 100644 index 000000000..dcbb7527e --- /dev/null +++ b/tests/util/test_files.py @@ -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) From 3c9fa3eff2916b2cbf7ba32844aa014a94d7a112 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 20 May 2021 12:11:00 +0200 Subject: [PATCH 12/12] =?UTF-8?q?=F0=9F=93=9D=20Update=20dev=20env=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We need to update the links to the py2 windows files. Also make py2 environment instructions optional across the board, they really should only be relevant for maintenance going forward. --- docs/development/environment.rst | 154 ++++++++++++++++++++----------- 1 file changed, 101 insertions(+), 53 deletions(-) diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 9f3e05d6b..c30a29667 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -15,7 +15,6 @@ below. * Prerequisites: * `Python 3.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` - * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` * `Git `_ * Checkout the OctoPrint sources from their Git repository: @@ -23,24 +22,17 @@ 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: - - * PY3: ``virtualenv --python=python3 venv3`` - * PY2: ``virtualenv --python=python2 venv2`` + issues for the dependencies with system wide installed instances: ``virtualenv --python=python3 venv3`` .. note:: - This assumes that `python2` and `python3` are binaries available directly on your ``PATH``. If your Python 2 and 3 - binaries cannot be found on your ``PATH`` like this you'll need to specify the full paths to them here, - e.g. ``virtualenv --python=/path/to/python2/bin/python venv2`` + This assumes that the ``python3`` binary is available directly on your ``PATH``. If + it cannot be found on your ``PATH`` like this you'll need to specify the full path here, + e.g. ``virtualenv --python=/path/to/python3/bin/python venv3`` - * Activate one of the virtual environments (the Python 3 venv should be considered the - primary one at this point): - - * PY3: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below) - * PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below) + * Activate the virtual environment: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below) * Update ``pip`` in the virtual environment: @@ -49,7 +41,7 @@ below. * Install OctoPrint in `"editable" mode `_, including its regular *and* development and plugin development dependencies: - * ``pip install -e '.[develop,plugins]'`` + * ``pip install -e '.[develop,plugins,docs]'`` * Set up the pre-commit hooks that make sure any changes you do adhere to the styling rules: @@ -65,22 +57,34 @@ 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`` + * 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`` -To switch the activated virtual environment, simply activate the new environment as described above. +If a Python 2 environment is also desired (e.g. for maintenance reasons), also do the following extra steps: -To deactivate the virtual environment and return to the system's default Python: ``deactivate``. + * Prerequisites: -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: + * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` - * ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below) - * ``pip install -e '.[develop,plugins,docs]'`` + * Create a virtual environment in the checked out source folder for Python 2: ``virtualenv --python=python2 venv2`` -Go to the directory `docs` and you can then build the documentation: + .. note:: - * ``sphinx-build -b html . _build`` + This assumes that the ``python2`` binary is available directly on your ``PATH``. If + it cannot be found on your ``PATH`` like this you'll need to specify the full path here, + e.g. ``virtualenv --python=/path/to/python2/bin/python venv2`` -The documentation will be available in the newly created ``_build`` directory. You can simply browse it locally by opening ``index.html`` + * Activate the virtual environment: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below) + + * Update ``pip`` in the virtual environment: + + * ``pip install --upgrade pip`` + + * Install OctoPrint in `"editable" mode `_, + including its regular *and* development and plugin development dependencies: + + * ``pip install -e '.[develop,plugins]'`` .. _sec-development-environment-source-linux: @@ -99,12 +103,6 @@ installed: sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv python3 python3-virtualenv python3-dev git libyaml-dev build-essential -.. todo:: - - Using a Linux distribution that doesn't use ``apt``? Please send a - `Pull Request `_ to get the necessary - steps into this guide! - Then: .. code-block:: none @@ -112,19 +110,43 @@ Then: cd ~/devel git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint - virtualenv --python=python2 venv2 virtualenv --python=python3 venv3 - source ./venv2/bin/activate - pip install --upgrade pip - pip install -e '.[develop,plugins]' source ./venv3/bin/activate pip install --upgrade pip pip install -e '.[develop,plugins,docs]' pre-commit install git config blame.ignoreRevsFile .git-blame-ignore-revs +.. _sec-development-environment-linux-python2: + +Optional Python 2 environment +............................. + +If a Python 2 environment is also desired: + + * On apt based distributions (e.g. Debian, Ubuntu, ...): + + .. code-block:: none + + sudo apt-get install python2 python2-dev python-pip python-setuptools python-virtualenv + +Then: + +.. code-block:: none + + virtualenv --python=python2 venv2 + source ./venv2/bin/activate + pip install --upgrade pip + pip install -e '.[develop,plugins]' + You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments. +.. todo:: + + Using a Linux distribution that doesn't use ``apt``? Please send a + `Pull Request `_ to get the necessary + steps into this guide! + .. _sec-development-environment-windows: Windows @@ -136,19 +158,23 @@ location, please substitute accordingly. First download & install: * `Git for Windows `_ - * `Latest *stable* Python 2.7 and Python 3.8 releases from python.org `_ - (at the time of writing those are ``2.7.18`` and ``3.8.7``) - * 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 - different install locations please substitute accordingly - * it's also recommended to have both versions get installed for all users + * Python 3 & dependencies: - * `Microsoft Visual C++ Compiler for Python 2.7 `_ - * `Build Tools For Visual Studio 2019 `_ + * `Latest *stable* Python 3 release from python.org `_ + + * make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too + * it's recommended to install Python 3 into ``C:\Python3`` - if you select + different install locations please substitute accordingly + * it's also recommended to install for all users + + * `Build Tools For Visual Studio 2019 `_ + + * install "C++ build tools" and ensure the latest versions of "MSVCv142 - VS 2019 C++ x64/x86 build tools" and + "Windows 10 SDK" are checked under individual components. + + * (optional) Python 2 & dependencies: - * install "C++ build tools" and ensure the latest versions of "MSVCv142 - VS 2019 C++ x64/x86 build tools" and - "Windows 10 SDK" are checked under individual components. Open the Git Bash you just installed and in that: @@ -158,17 +184,38 @@ Open the Git Bash you just installed and in that: cd /c/Devel git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint - virtualenv --python=C:\Python27\python.exe venv2 - virtualenv --python=C:\Python38\python.exe venv3 - source ./venv2/Scripts/activate - python -m pip install --upgrade pip - pip install -e '.[develop,plugins]' + virtualenv --python=C:\Python3\python.exe venv3 source ./venv3/Scripts/activate pip install --upgrade pip python -m pip install -e '.[develop,plugins,docs]' pre-commit install git config blame.ignoreRevsFile .git-blame-ignore-revs +.. _sec-development-environment-windows-python2: + +Optional Python 2 environment +............................. + +If a Python 2 environment is also desired, then also download and install + + * `Python 2.7.18 MSI installer `_ (mirrored on octoprint.org) + + * it's recommended to install Python 2.7 into ``C:\Python27`` - if you select + different install locations please substitute accordingly + * it's also recommended to install for all users + + * `Microsoft Visual C++ Compiler for Python 2.7 `_ (mirrored on octoprint.org) + +Then: + +.. code-block:: none + + cd /c/Devel/OctoPrint + virtualenv --python=C:\Python27\python.exe venv2 + source ./venv2/Scripts/activate + python -m pip install --upgrade pip + pip install -e '.[develop,plugins]' + .. _sec-development-environment-windows-optional: Optional but recommended tools @@ -177,6 +224,7 @@ Optional but recommended tools These are some tools that are recommended but not required to have on hand: * `Visual Studio Code `_ + * `Windows Terminal `_ Add the following profile to ``profiles.list`` in the settings, that will allow you to @@ -265,11 +313,11 @@ PyCharm - Register virtual environments: - **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", - select OctoPrint ``venv2`` folder (e.g. ``~/devel/OctoPrint/venv2`` or ``C:\Devel\OctoPrint\venv2``). + select OctoPrint ``venv3`` folder (e.g. ``~/devel/OctoPrint/venv3`` or ``C:\Devel\OctoPrint\venv3``). - **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." > - "Virtualenv Environment > "Existing Environment", select OctoPrint ``venv2`` folder (e.g. ``~/devel/OctoPrint/venv2``). + "Virtualenv Environment > "Existing Environment", select OctoPrint ``venv3`` folder (e.g. ``~/devel/OctoPrint/venv3``). - Repeat for the ``venv3`` folder. + If desired, repeat for the ``venv2`` folder, or any other additional Python venvs. - Right click "src" in project tree, mark as source folder - Add Run/Debug Configuration, select "Python": @@ -334,7 +382,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. Python 3 and 2), 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.