From 82c892ba40b3741d1b7711d949e56af64f5bc2de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 15 Aug 2022 11:21:59 +0200 Subject: [PATCH 1/3] =?UTF-8?q?=F0=9F=94=92=EF=B8=8F=20Rate=20limit=20fail?= =?UTF-8?q?ed=20login=20attempts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Should reduce likelihood of brute force attacks on unsecure networks if users decide to deploy/make OctoPrint accessible there against all advice to the contrary. --- setup.py | 1 + src/octoprint/server/__init__.py | 10 ++++++++++ src/octoprint/server/api/__init__.py | 5 +++++ src/octoprint/static/css/login.css | 2 +- src/octoprint/static/js/login/login.js | 14 ++++++++++---- src/octoprint/static/less/login.less | 3 ++- src/octoprint/templates/login.jinja2 | 3 ++- 7 files changed, 31 insertions(+), 7 deletions(-) diff --git a/setup.py b/setup.py index 2c0988b31..4aafc687a 100644 --- a/setup.py +++ b/setup.py @@ -43,6 +43,7 @@ core_deps = [ "Flask-Assets>=2.0,<3", "Flask-Babel>=2.0,<3", "Flask-Login>=0.6,<0.7", # breaking changes can happen on minor version increases + "Flask-Limiter>=2.6,<3", "flask>=2.2,<2.3", # breaking changes can happen on minor version increases (with deprecation warnings) "frozendict>=2.0,<3", "future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index eea4b319b..53b3d6b98 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -70,6 +70,7 @@ app = Flask("octoprint") assets = None babel = None +limiter = None debug = False safe_mode = False @@ -1338,6 +1339,8 @@ class Server: timer.start() def _setup_app(self, app): + global limiter + from octoprint.server.util.flask import ( OctoPrintFlaskRequest, OctoPrintFlaskResponse, @@ -1433,6 +1436,13 @@ class Server: MarkdownFilter(app) + from flask_limiter import Limiter + from flask_limiter.util import get_remote_address + + app.config["RATELIMIT_STRATEGY"] = "fixed-window-elastic-expiry" + + limiter = Limiter(app, key_func=get_remote_address) + def _setup_i18n(self, app): global babel global LOCALES diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 83b625e74..08d9ccdd0 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -281,6 +281,11 @@ def serverStatus(): @api.route("/login", methods=["POST"]) +@octoprint.server.limiter.limit( + "3/minute;5/10 minutes;10/hour", + deduct_when=lambda response: response.status_code == 403, + error_message="You have made too many failed login attempts. Please try again later.", +) def login(): data = request.get_json() if not data: diff --git a/src/octoprint/static/css/login.css b/src/octoprint/static/css/login.css index ad8d23828..ff21ac632 100644 --- a/src/octoprint/static/css/login.css +++ b/src/octoprint/static/css/login.css @@ -1 +1 @@ -body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type="text"],.form-signin input[type="password"]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:white}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#ffffff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center} \ No newline at end of file +body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type="text"],.form-signin input[type="password"]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error-credentials,#login-error-rate,#login-offline{display:none}#login-error-credentials.in,#login-error-rate.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:white}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#ffffff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center} \ No newline at end of file diff --git a/src/octoprint/static/js/login/login.js b/src/octoprint/static/js/login/login.js index c9107d2cf..325634497 100644 --- a/src/octoprint/static/js/login/login.js +++ b/src/octoprint/static/js/login/login.js @@ -11,7 +11,8 @@ $(function () { }; var overlayElement = $("#login-overlay"); - var errorElement = $("#login-error"); + var errorCredentialsElement = $("#login-error-credentials"); + var errorRateElement = $("#login-error-rate"); var offlineElement = $("#login-offline"); var buttonElement = $("#login-button"); var reconnectElement = $("#login-reconnect"); @@ -28,7 +29,8 @@ $(function () { var remember = rememberElement.prop("checked"); overlayElement.addClass("in"); - errorElement.removeClass("in"); + errorCredentialsElement.removeClass("in"); + errorRateElement.removeClass("in"); OctoPrint.browser .login(username, password, remember) @@ -36,7 +38,7 @@ $(function () { ignoreDisconnect = true; window.location.href = REDIRECT_URL; }) - .fail(() => { + .fail((xhr) => { usernameElement.val(USER_ID); passwordElement.val(""); @@ -47,7 +49,11 @@ $(function () { } overlayElement.removeClass("in"); - errorElement.addClass("in"); + if (xhr.status === 429) { + errorRateElement.addClass("in"); + } else { + errorCredentialsElement.addClass("in"); + } }); return false; diff --git a/src/octoprint/static/less/login.less b/src/octoprint/static/less/login.less index a54d692fc..8d4f0b8ae 100644 --- a/src/octoprint/static/less/login.less +++ b/src/octoprint/static/less/login.less @@ -31,7 +31,8 @@ body { } } -#login-error, +#login-error-credentials, +#login-error-rate, #login-offline { display: none; diff --git a/src/octoprint/templates/login.jinja2 b/src/octoprint/templates/login.jinja2 index 252e33dbd..816235634 100644 --- a/src/octoprint/templates/login.jinja2 +++ b/src/octoprint/templates/login.jinja2 @@ -65,7 +65,8 @@
-
{{ _('Incorrect username or password. Hint: Both are case sensitive!') }}
+
{{ _('Incorrect username or password. Hint: Both are case sensitive!') }}
+
{{ _('You have made too many failed login attempts. Please try again later.') }}
{{ _('Server is currently offline.') }} {{ _('Reconnect...') }}
{% if user_id %}

From 65e222da1ecad4c708d53ee572fd78c0e1abb592 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arkadiusz=20Mi=C5=9Bkiewicz?= Date: Mon, 15 Aug 2022 12:16:30 +0200 Subject: [PATCH 2/3] =?UTF-8?q?=E2=9C=A8=20M20=20T=20support=20(timestamps?= =?UTF-8?q?=20for=20files=20on=20sd=20card)=20(#4610)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Use "M20 L T" (if CAPABILITY_EXTENDED_M20 is available) which gives us long file names but also file timestamps. - Wire up that timestamp into "date" field which gives us "Uploaded: ... ago" for files on SD card. Sorting by upload date also works. - Implementing this also fixes parsing of response to (for example manually sent) "M20 T" command. Octoprint assumed that third entry in response is always long file name while with M20 T it is timestamp. - Add conversion routines between M20 T timestamp and unix timestamp. Wire up that conversion in virtual printer. See also https://reprap.org/wiki/G-code#M20:_List_SD_card --- AUTHORS.md | 1 + docs/development/virtual_printer.rst | 6 ++ .../plugins/virtual_printer/virtual.py | 27 +++-- src/octoprint/printer/standard.py | 2 +- src/octoprint/server/api/files.py | 2 + src/octoprint/util/comm.py | 93 +++++++++++----- src/octoprint/util/files.py | 63 +++++++++++ tests/util/test_comm.py | 101 ++++++++++++++++++ tests/util/test_files.py | 24 +++++ 9 files changed, 282 insertions(+), 37 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index df96946b0..81dc11118 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -170,6 +170,7 @@ date of first contribution): * [Kestin Goforth](https://github.com/kforth) * [Dawid Pieper](https://github.com/dawidpieper) * ["arrdem"](https://github.com/arrdem) + * [Arkadiusz Miƛkiewicz](https://github.com/arekm) 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 diff --git a/docs/development/virtual_printer.rst b/docs/development/virtual_printer.rst index a17f2a513..d7222b14c 100644 --- a/docs/development/virtual_printer.rst +++ b/docs/development/virtual_printer.rst @@ -118,6 +118,12 @@ There many configuration options via ``config.yaml`` for the virtual printer tha # False: size: true + # Whether M20 responses will include timestamp or not (only if size = true as well) + # + # True: + # False: + timestamp: false + # Whether M20 responses will include longname or not (only if size = true as well) # # True: diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 0c1325f44..09a1b3a66 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -15,6 +15,7 @@ from serial import SerialTimeoutException from octoprint.plugin import plugin_manager from octoprint.util import RepeatedTimer, get_dos_filename, to_bytes, to_unicode +from octoprint.util.files import unix_timestamp_to_m20_timestamp # noinspection PyBroadException @@ -126,6 +127,7 @@ class VirtualPrinter: self._writingToSd = False self._writingToSdHandle = None + self._writingToSdFile = None self._newSdFilePos = None self._heatingUp = False @@ -256,6 +258,7 @@ class VirtualPrinter: pass self._writingToSd = False self._writingToSdHandle = None + self._writingToSdFile = None self._newSdFilePos = None self._heatingUp = False @@ -592,7 +595,7 @@ class VirtualPrinter: # noinspection PyUnusedLocal def _gcode_M20(self, data: str) -> None: if self._sdCardReady: - self._listSd(incl_long="L" in data) + self._listSd(incl_long="L" in data, incl_timestamp="T" in data) # noinspection PyUnusedLocal def _gcode_M21(self, data: str) -> None: @@ -1379,17 +1382,17 @@ class VirtualPrinter: except Exception: self._logger.exception("While handling %r", data) - def _listSd(self, incl_long=False): + def _listSd(self, incl_long=False, incl_timestamp=False): + line = "{dosname}" if self._settings.get_boolean(["sdFiles", "size"]): + line += " {size}" + if self._settings.get_boolean(["sdFiles", "timestamp"]) or incl_timestamp: + line += " {timestamp}" if self._settings.get_boolean(["sdFiles", "longname"]) or incl_long: if self._settings.get_boolean(["sdFiles", "longname_quoted"]): - line = '{dosname} {size} "{name}"' + line += ' "{name}"' else: - line = "{dosname} {size} {name}" - else: - line = "{dosname} {size}" - else: - line = "{dosname}" + line += " {name}" files = self._mappedSdList() items = map(lambda x: line.format(**x), files.values()) @@ -1414,6 +1417,7 @@ class VirtualPrinter: "path": entry.path, "dosname": dosname, "size": entry.stat().st_size, + "timestamp": unix_timestamp_to_m20_timestamp(entry.stat().st_mtime), } return result @@ -1791,6 +1795,7 @@ class VirtualPrinter: except Exception: self._send("error writing to file") self._writingToSdHandle = handle + self._writingToSdFile = file self._writingToSd = True self._selectedSdFile = file self._send("Writing to file: %s" % filename) @@ -1804,6 +1809,12 @@ class VirtualPrinter: self._writingToSdHandle = None self._writingToSd = False self._selectedSdFile = None + # Most printers don't have RTC and set some ancient date + # by default. Emulate that using 2000-01-01 01:00:00 + # (taken from prusa firmware behaviour) + st = os.stat(self._writingToSdFile) + os.utime(self._writingToSdFile, (st.st_atime, 946684800)) + self._writingToSdFile = None self._send("Done saving file") def _sdPrintingWorker(self): diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 0872b5e77..361752645 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -910,7 +910,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): return list( map( - lambda x: {"name": x[0][1:], "size": x[1], "display": x[2]}, + lambda x: {"name": x[0][1:], "size": x[1], "display": x[2], "date": x[3]}, self._comm.getSdFiles(), ) ) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 511301424..ec112a0ce 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -331,6 +331,8 @@ def _getFileList( } if f["size"] is not None: file.update({"size": f["size"]}) + if f["date"] is not None: + file.update({"date": f["date"]}) files.append(file) else: filter_func = None diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index e14a112ce..58d9f269a 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -43,6 +43,7 @@ from octoprint.util import ( sanitize_ascii, to_unicode, ) +from octoprint.util.files import m20_timestamp_to_unix_timestamp from octoprint.util.platform import get_os, set_close_exec try: @@ -1969,7 +1970,7 @@ class MachineCom: def getSdFiles(self): return list( - map(lambda x: (x[0], x[1], self._sdFilesMap.get(x[0])), self._sdFiles) + map(lambda x: (x[0], x[1], self._sdFilesMap.get(x[0]), x[2]), self._sdFiles) ) def deleteSdFile(self, filename, tags=None): @@ -2007,7 +2008,7 @@ class MachineCom: tags = set() if self._capability_supported(self.CAPABILITY_EXTENDED_M20): - command = "M20 L" + command = "M20 L T" else: command = "M20" @@ -2443,28 +2444,7 @@ class MachineCom: ##~~ SD file list # if we are currently receiving an sd file list, each line is just a filename, so just read it and abort processing if self._sdEnabled and self._sdFileList and "End file list" not in line: - preprocessed_line = line - fileinfo = preprocessed_line.split(None, 2) - if len(fileinfo) == 3: - # name, size, long name - filename, size, longname = fileinfo - elif len(fileinfo) == 2: - # name, size - filename, size = fileinfo - longname = None - else: - # name - filename = preprocessed_line - size = None - longname = None - - if size is not None: - try: - size = int(size) - except ValueError: - # whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None - filename = preprocessed_line - size = None + (filename, size, timestamp, longname) = parse_file_list_line(line) if valid_file_type(filename, "machinecode"): if filter_non_ascii(filename): @@ -2487,11 +2467,8 @@ class MachineCom: filename = "/" + filename if self._sdLowerCase: filename = filename.lower() - self._sdFiles.append((filename, size)) + self._sdFiles.append((filename, size, timestamp)) if longname is not None: - if longname[0] == '"' and longname[-1] == '"': - # apparently some firmwares enclose the long name in quotes... - longname = longname[1:-1] self._sdFilesMap[filename] = longname continue @@ -6275,6 +6252,66 @@ def canonicalize_temperatures(parsed, current): return result +def _validate_m20_timestamp(timestamp): + try: + m20_timestamp_to_unix_timestamp(timestamp) + except ValueError: + return False + return True + + +def parse_file_list_line(line): + longname = None + size = None + timestamp = None + fileinfo = line.split(None, 3) + if len(fileinfo) == 4: + # name, size, timestamp, long name or name, size, long name with spaces + filename, size, timestamp, longname = fileinfo + if not _validate_m20_timestamp(timestamp): + # longname with spaces. Split line again with twice split limit to get longname right in case + # of multiple whitespace characters in it. + filename, size, longname = line.split(None, 2) + timestamp = None + elif len(fileinfo) == 3: + # name, size, long name or name, size, timestamp + filename, size, third = fileinfo + if _validate_m20_timestamp(third): + timestamp = third + else: + longname = third + elif len(fileinfo) == 2: + # name, size + filename, size = fileinfo + else: + # name + filename = line + + if size is not None: + try: + size = int(size) + except ValueError: + # whatever that was, it was not an integer, so we'll just use the whole line as filename and set size/timestamp/longname to None + filename = line + size = None + timestamp = None + longname = None + else: + if timestamp is not None: + # size was valid and we have timestamp, so try to use it + try: + timestamp = m20_timestamp_to_unix_timestamp(timestamp) + except ValueError: + timestamp = None + + if longname is not None: + if longname[0] == '"' and longname[-1] == '"': + # apparently some firmwares enclose the long name in quotes... + longname = longname[1:-1] + + return (filename, size, timestamp, longname) + + def parse_temperature_line(line, current): """ Parses the provided temperature line. diff --git a/src/octoprint/util/files.py b/src/octoprint/util/files.py index 62c5cb820..0ea870cd3 100644 --- a/src/octoprint/util/files.py +++ b/src/octoprint/util/files.py @@ -1,6 +1,7 @@ __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 datetime import itertools import logging import os.path @@ -315,3 +316,65 @@ def search_through_file_python(path, term, compiled): if term in line or compiled.match(term): return True return False + + +def unix_timestamp_to_m20_timestamp(unix_timestamp): + """ + Converts unix timestamp to "M20 T" format + which embeds date and time into 32bit int. + Upper 16 bit contain date, lower 16 bit contain time. + + https://reprap.org/wiki/G-code#M20:_List_SD_card + + Format derived from FAT filesystem timestamps: + https://wiki.osdev.org/FAT + + Arguments: + unix_timestamp (int): Unix timestamp in seconds + Returns: + string: M20 T timestamp as hex string + """ + + dt = datetime.datetime.fromtimestamp(unix_timestamp) + m20_date = dt.year - 1980 << 9 | dt.month << 5 | dt.day + m20_time = dt.hour << 11 | dt.minute << 5 + m20_time |= (dt.second - (dt.second % 2)) // 2 + return hex(m20_date << 16 | m20_time) + + +def m20_timestamp_to_unix_timestamp(timestamp): + """ + Converts "M20 T" timestamp to unix timestamp. + Upper 16 bit contain date, lower 16 bit contain time. + + https://reprap.org/wiki/G-code#M20:_List_SD_card + + Format derived from FAT filesystem timestamps: + https://wiki.osdev.org/FAT + + Arguments: + timestamp (string): M20 T timestamp as hex string + Returns: + int: Unix timestamp in seconds + """ + + # Only hex in 0xABC format is valid while int() accepts + # hex without 0x prefix, too. + if not timestamp.startswith("0x"): + raise ValueError("Invalid M20 T timestamp format") + + timestamp = int(timestamp, 16) + dt = timestamp >> 16 + day = dt & (1 << 5) - 1 + month = (dt >> 5) & ((1 << 4) - 1) + year = ((dt >> 9) & (1 << 7) - 1) + 1980 + d = datetime.date(year, month, day) + + tm = timestamp & (2**16 - 1) + second = (tm & (1 << 5) - 1) * 2 + minute = (tm >> 5) & ((1 << 6) - 1) + hour = (tm >> 11) & ((1 << 5) - 1) + t = datetime.time(hour, minute, second) + + combined_dt = datetime.datetime.combine(d, t) + return int(combined_dt.timestamp()) diff --git a/tests/util/test_comm.py b/tests/util/test_comm.py index 6cd3ecf1e..afbb3c190 100644 --- a/tests/util/test_comm.py +++ b/tests/util/test_comm.py @@ -2,8 +2,10 @@ import unittest from unittest import mock import ddt +import pytest import octoprint.util.comm +from octoprint.util.files import m20_timestamp_to_unix_timestamp @ddt.ddt @@ -286,3 +288,102 @@ class TestCommErrorHandling(unittest.TestCase): self.assert_not_disconnected() self.assert_not_print_cancelled() self.assert_not_cleared_to_send() + + +@pytest.mark.parametrize( + "val,expected", + [ + ("aaa", False), + ("1234", False), + ("0x21bf7d", True), + ("0xghijk", False), + ("0x28210800", True), + ], +) +def test__validate_m20_timestamp(val, expected): + assert octoprint.util.comm._validate_m20_timestamp(val) == expected + + +@pytest.mark.parametrize( + "val,expected", + [ + ( + "line that makes little sense", + ("line that makes little sense", None, None, None), + ), + ("name.gco", ("name.gco", None, None, None)), + ("name.gco invalid-size", ("name.gco invalid-size", None, None, None)), + ( + "name.gco 3424324", + ("name.gco", 3424324, None, None), + ), + ( + "name.gco 3424324 longname.gcode", + ("name.gco", 3424324, None, "longname.gcode"), + ), + ( + "name.gco 3424324 0x21bf7d", + ( + "name.gco", + 3424324, + m20_timestamp_to_unix_timestamp("0x21bf7d"), + None, + ), + ), + ( + "name.gco 3424324 0xinvalid_timestamp_as_longname", + ("name.gco", 3424324, None, "0xinvalid_timestamp_as_longname"), + ), + ( + "longname.gcode 3424324 0x21bf7d", + ( + "longname.gcode", + 3424324, + m20_timestamp_to_unix_timestamp("0x21bf7d"), + None, + ), + ), + ( + "longname.gcode 3424324 longname.gcode", + ("longname.gcode", 3424324, None, "longname.gcode"), + ), + ( + "name.gco 32424 0x21bf7d long name without quoting", + ( + "name.gco", + 32424, + m20_timestamp_to_unix_timestamp("0x21bf7d"), + "long name without quoting", + ), + ), + ( + "name.gco 32424 0x21bf7d long name without quoting", + ( + "name.gco", + 32424, + m20_timestamp_to_unix_timestamp("0x21bf7d"), + "long name without quoting", + ), + ), + ( + 'name.gco 32424 0x21bf7d "long name with quoting"', + ( + "name.gco", + 32424, + m20_timestamp_to_unix_timestamp("0x21bf7d"), + "long name with quoting", + ), + ), + ( + 'name.gco 32424 0x21bf7d "long name with quoting"', + ( + "name.gco", + 32424, + m20_timestamp_to_unix_timestamp("0x21bf7d"), + "long name with quoting", + ), + ), + ], +) +def test_parse_file_list_line(val, expected): + assert octoprint.util.comm.parse_file_list_line(val) == expected diff --git a/tests/util/test_files.py b/tests/util/test_files.py index 272f39972..136725f38 100644 --- a/tests/util/test_files.py +++ b/tests/util/test_files.py @@ -1,16 +1,20 @@ __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 datetime import os import re import unittest +import pytest from ddt import data, ddt, unpack from octoprint.util.files import ( + m20_timestamp_to_unix_timestamp, sanitize_filename, search_through_file, search_through_file_python, + unix_timestamp_to_m20_timestamp, ) @@ -66,3 +70,23 @@ class FilesUtilTest(unittest.TestCase): ) actual = search_through_file_python(path, term, compiled) self.assertEqual(actual, expected) + + +# based on https://github.com/nathanhi/pyfatfs/blob/master/tests/test_DosDateTime.py +m20_timestamp_tests = [ + ("0x210000", datetime.datetime(1980, 1, 1).timestamp()), + ("0xff9f0000", datetime.datetime(2107, 12, 31).timestamp()), + ("0x21bf7d", datetime.datetime(1980, 1, 1, 23, 59, 58).timestamp()), + ("0x549088aa", datetime.datetime(2022, 4, 16, 17, 5, 20).timestamp()), + ("0x28210800", datetime.datetime(2000, 1, 1, 1, 0).timestamp()), +] + + +@pytest.mark.parametrize("val,expected", m20_timestamp_tests) +def test_m20_timestamp_to_unix_timestamp(val, expected): + assert m20_timestamp_to_unix_timestamp(val) == expected + + +@pytest.mark.parametrize("expected,val", m20_timestamp_tests) +def test_unix_timestamp_to_m20_timestamp(expected, val): + assert unix_timestamp_to_m20_timestamp(val) == expected From b4ccbf525261781618a3609e6b577be728fc2023 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arkadiusz=20Mi=C5=9Bkiewicz?= Date: Mon, 15 Aug 2022 16:10:19 +0200 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=9A=B8=20Properly=20reflect=20all=20w?= =?UTF-8?q?hitespace=20in=20filenames=20(#4613)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Long filenames like 'more than one space.gcode' were shown in the UI as 'more than one space.gcode' --- src/octoprint/static/less/octoprint.less | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/static/less/octoprint.less b/src/octoprint/static/less/octoprint.less index 3bb305fb9..80acc34d0 100644 --- a/src/octoprint/static/less/octoprint.less +++ b/src/octoprint/static/less/octoprint.less @@ -880,6 +880,7 @@ ul.dropdown-menu li a { text-overflow: ellipsis; word-break: break-all; margin-right: 30px; + white-space: pre-wrap; } .toggleAdditionalData {