Merge branch 'maintenance' into devel

This commit is contained in:
GitHub Nightly Merge Action committed 2022-08-16 00:15:27 +00:00
commit 2712412c66
17 files changed
+314 -44

No files matched your search

+1
View File
@@ -171,6 +171,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
+6
View File
@@ -118,6 +118,12 @@ There many configuration options via ``config.yaml`` for the virtual printer tha
# False: <filename>
size: true
# Whether M20 responses will include timestamp or not (only if size = true as well)
#
# True: <filename> <filesize in bytes> <timestamp as hex>
# False: <filename> <filesize in bytes>
timestamp: false
# Whether M20 responses will include longname or not (only if size = true as well)
#
# True: <filename> <filesize in bytes> <longname>
+1
View File
@@ -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
@@ -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):
+1 -1
View File
@@ -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(),
)
)
+10
View File
@@ -70,6 +70,7 @@ app = Flask("octoprint")
assets = None
babel = None
limiter = None
debug = False
safe_mode = False
@@ -1342,6 +1343,8 @@ class Server:
timer.start()
def _setup_app(self, app):
global limiter
from octoprint.server.util.flask import (
OctoPrintFlaskRequest,
OctoPrintFlaskResponse,
@@ -1437,6 +1440,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
+5
View File
@@ -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:
+2
View File
@@ -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
+1 -1
View File
@@ -1 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,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}
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}
+10 -4
View File
@@ -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;
+2 -1
View File
@@ -31,7 +31,8 @@ body {
}
}
#login-error,
#login-error-credentials,
#login-error-rate,
#login-offline {
display: none;
+1
View File
@@ -880,6 +880,7 @@ ul.dropdown-menu li a {
text-overflow: ellipsis;
word-break: break-all;
margin-right: 30px;
white-space: pre-wrap;
}
.toggleAdditionalData {
+2 -1
View File
@@ -65,7 +65,8 @@
<form class="form-signin">
<h2 class="form-signin-heading" data-test-id="login-title">{{ _('Please log in') }}</h2>
<div id="login-error" class="alert alert-error" data-test-id="login-error">{{ _('Incorrect username or password. Hint: Both are case sensitive!') }}</div>
<div id="login-error-credentials" class="alert alert-error" data-test-id="login-error">{{ _('Incorrect username or password. Hint: Both are case sensitive!') }}</div>
<div id="login-error-rate" class="alert alert-error" data-test-id="login-error-rate">{{ _('You have made too many failed login attempts. Please try again later.') }}</div>
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
{% if user_id %}<p>
+65 -28
View File
@@ -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:
@@ -1966,7 +1967,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):
@@ -2004,7 +2005,7 @@ class MachineCom:
tags = set()
if self._capability_supported(self.CAPABILITY_EXTENDED_M20):
command = "M20 L"
command = "M20 L T"
else:
command = "M20"
@@ -2440,28 +2441,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):
@@ -2484,11 +2464,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
@@ -6272,6 +6249,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.
+63
View File
@@ -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())
+101
View File
@@ -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
+24
View File
@@ -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