From f8dc5047732ad1e270760c090e4172e675507371 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?H=C3=A5kon=20L=C3=B8vdal?=
Date: Fri, 5 Apr 2019 00:47:42 +0200
Subject: [PATCH 001/105] Add example of using explicit python version
---
README.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index a77a96dbe..13e326d2e 100644
--- a/README.md
+++ b/README.md
@@ -65,7 +65,8 @@ you already have Python 2.7, pip and virtualenv set up on your system:
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
2. Change into the OctoPrint folder: `cd OctoPrint`
-3. Create a user-owned virtual environment therein: `virtualenv venv`
+3. Create a user-owned virtual environment therein: `virtualenv venv` if your system default python version is
+ python 2.7, otherwise you need to specify the version explicitly, e.g. `virtualenv --python=python2.7 venv`.
4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .`
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
From a3254466f73cdc835e36834b52958f1c91f5fca6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?H=C3=A5kon=20L=C3=B8vdal?=
Date: Fri, 5 Apr 2019 00:47:59 +0200
Subject: [PATCH 002/105] Whitespace fixes
---
README.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/README.md b/README.md
index 13e326d2e..c3144cd5b 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!**
You are currently looking at the source code repository of OctoPrint. If you already installed it
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
-might be of more interest for you. You might also want to subscribe to join
+might be of more interest for you. You might also want to subscribe to join
[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be
able to help you with any questions you might have.
@@ -39,7 +39,7 @@ able to help you with any questions you might have.
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help
-in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
+in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
[the community forum at community.octoprint.org](https://community.octoprint.org)
and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
@@ -73,7 +73,7 @@ You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octopri
for details.
After installation, please make sure you follow the first-run wizard and set up
-access control as necessary.
+access control as necessary.
## Dependencies
From 03e328fd1392161c44a7170dc086e6bcfca8b200 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 10 Apr 2019 17:04:01 +0200
Subject: [PATCH 003/105] =?UTF-8?q?=F0=9F=93=9D=20Fix=20a=20documentation?=
=?UTF-8?q?=20issue?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Fixes #3117
---
docs/configuration/config_yaml.rst | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst
index bb1236c38..88fa4545e 100644
--- a/docs/configuration/config_yaml.rst
+++ b/docs/configuration/config_yaml.rst
@@ -409,8 +409,7 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# Lines to send on simulated reset
resetLines:
- start
- - Marlin: Virtual Marlin!
- - "\x80"
+ - "Marlin: Virtual Marlin!"
- "SD card ok"
# Initial set of prepared oks to use instead of regular ok (e.g. to simulate
From 07423712a6d6731ac720a061ffdf34091092bea8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 15 May 2019 11:48:45 +0200
Subject: [PATCH 004/105] =?UTF-8?q?=F0=9F=90=9B=20Fix=20wrong=20variable?=
=?UTF-8?q?=20name=20in=20exception=20handler?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3153 & Sentry SERVER-11A
---
src/octoprint/server/__init__.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py
index 366f23c2a..c8213cd38 100644
--- a/src/octoprint/server/__init__.py
+++ b/src/octoprint/server/__init__.py
@@ -485,7 +485,7 @@ class Server(object):
except:
self._logger.exception("Error while trying to migrate settings for "
"plugin {}, ignoring it".format(implementation._identifier),
- extra=dict(plugin=plugin._identifier))
+ extra=dict(plugin=implementation._identifier))
pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup]
From b03d43156defe3b4159d5fd239b06f1c454bd12d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 15 May 2019 13:19:14 +0200
Subject: [PATCH 005/105] =?UTF-8?q?=F0=9F=90=9B=20Strip=20interface=20tags?=
=?UTF-8?q?=20from=20addresses=20on=20local=20check?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3143 and Sentry SERVER-11B
---
src/octoprint/util/net.py | 24 +++++++++++++++++-------
tests/util/test_net.py | 24 +++++++++++++++++++++++-
2 files changed, 40 insertions(+), 8 deletions(-)
diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py
index f8cb2c311..9feadb65b 100644
--- a/src/octoprint/util/net.py
+++ b/src/octoprint/util/net.py
@@ -46,9 +46,8 @@ else:
def is_lan_address(address, additional_private=None):
try:
- if address.lower().startswith("::ffff:") and "." in address:
- # ipv6 mapped ipv4 address, unmap
- address = address[len("::ffff:"):]
+ address = unmap_v4_as_v6(address)
+ address = strip_interface_tag(address)
ip = netaddr.IPAddress(address)
if ip.is_private() or ip.is_loopback():
@@ -71,10 +70,7 @@ def is_lan_address(address, additional_private=None):
# v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
_, prefix = prefix.split("/")
- addr = address["addr"]
- if "%" in addr:
- # interface comment in netifaces output, e.g. "fe80::457f:bbee:d579:1063%wlan0"
- addr = addr[:addr.find("%")]
+ addr = strip_interface_tag(address["addr"])
return netaddr.IPNetwork("{}/{}".format(addr, prefix))
for interface in netifaces.interfaces():
@@ -103,3 +99,17 @@ def is_lan_address(address, additional_private=None):
# we are extra careful here since an unhandled exception in this method will effectively nuke the whole UI
logging.getLogger(__name__).exception("Error while trying to determine whether {} is a local address".format(address))
return True
+
+
+def strip_interface_tag(address):
+ if "%" in address:
+ # interface comment, e.g. "fe80::457f:bbee:d579:1063%wlan0"
+ address = address[:address.find("%")]
+ return address
+
+
+def unmap_v4_as_v6(address):
+ if address.lower().startswith("::ffff:") and "." in address:
+ # ipv6 mapped ipv4 address, unmap
+ address = address[len("::ffff:"):]
+ return address
diff --git a/tests/util/test_net.py b/tests/util/test_net.py
index a1a33cec0..2f90bb2de 100644
--- a/tests/util/test_net.py
+++ b/tests/util/test_net.py
@@ -43,7 +43,8 @@ class UtilNetTest(unittest.TestCase):
("11.1.2.3", [], False),
("11.1.2.3", ["11/8"], True),
("12.1.1.123", [], True),
- ("2a01:4f8:1c0c:6958::1:23", [], True)
+ ("2a01:4f8:1c0c:6958::1:23", [], True),
+ ("fe80::89f3:31bb:ced0:2093%wlan0", [], True)
)
@ddt.unpack
@mock.patch("netifaces.interfaces", side_effect=patched_interfaces)
@@ -52,3 +53,24 @@ class UtilNetTest(unittest.TestCase):
def test_is_lan_address(self, input_address, input_additional, expected, nifa, nifs):
actual = octoprint.util.net.is_lan_address(input_address, additional_private=input_additional)
self.assertEqual(expected, actual)
+
+ @ddt.data(
+ ("fe80::89f3:31bb:ced0:2093%wlan0", "fe80::89f3:31bb:ced0:2093"),
+ ("2a01:4f8:1c0c:6958::1:23", "2a01:4f8:1c0c:6958::1:23"),
+ ("10.1.2.3", "10.1.2.3")
+ )
+ @ddt.unpack
+ def test_strip_interface_tag(self, address, expected):
+ actual = octoprint.util.net.strip_interface_tag(address)
+ self.assertEqual(expected, actual)
+
+ @ddt.data(
+ ("::ffff:192.168.1.1", "192.168.1.1"),
+ ("::ffff:2a01:4f8", "::ffff:2a01:4f8"),
+ ("2a01:4f8:1c0c:6958::1:23", "2a01:4f8:1c0c:6958::1:23"),
+ ("11.1.2.3", "11.1.2.3")
+ )
+ @ddt.unpack
+ def test_unmap_v4_in_v6(self, address, expected):
+ actual = octoprint.util.net.unmap_v4_as_v6(address)
+ self.assertEqual(expected, actual)
From 2387b4a7710884271987033343b0a6516a4d850c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 15 May 2019 15:15:25 +0200
Subject: [PATCH 006/105] =?UTF-8?q?=F0=9F=90=9B=20backup:=20make=20sure=20?=
=?UTF-8?q?exclude=20is=20always=20a=20list?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3155 and Sentry SERVER-119
---
src/octoprint/plugins/backup/__init__.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py
index 14cacaf08..5408e71ad 100644
--- a/src/octoprint/plugins/backup/__init__.py
+++ b/src/octoprint/plugins/backup/__init__.py
@@ -619,6 +619,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
try:
if exclude is None:
exclude = []
+ if not isinstance(exclude, list):
+ exclude = list(exclude)
if "timelapse" in exclude:
exclude.append("timelapse_tmp")
From d6516e4a4c1ad36f4b2cc22a98184f39ff53aeff Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 15 May 2019 15:19:57 +0200
Subject: [PATCH 007/105] =?UTF-8?q?=F0=9F=90=9B=20tracking:=20handle=20tim?=
=?UTF-8?q?e=3D=3DNone=20case?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3156 and Sentry SERVER-WR
---
src/octoprint/plugins/tracking/__init__.py | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py
index 1aa8d91c6..b7e3ca894 100644
--- a/src/octoprint/plugins/tracking/__init__.py
+++ b/src/octoprint/plugins/tracking/__init__.py
@@ -305,7 +305,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
elapsed = int(payload.get(b"time", 0))
if elapsed:
args[b"elapsed"] = elapsed
- except ValueError:
+ except (ValueError, TypeError):
pass
track_event = "print_done"
elif event == Events.PRINT_FAILED:
@@ -313,7 +313,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
elapsed = int(payload.get(b"time", 0))
if elapsed:
args[b"elapsed"] = elapsed
- except ValueError:
+ except (ValueError, TypeError):
pass
args[b"reason"] = payload.get(b"reason", "unknown")
@@ -326,7 +326,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
elapsed = int(payload.get(b"time", 0))
if elapsed:
args[b"elapsed"] = elapsed
- except ValueError:
+ except (ValueError, TypeError):
pass
track_event = "print_cancelled"
From 547db7c1f565b5025d96a34af755db3229424c37 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 15 May 2019 17:34:54 +0200
Subject: [PATCH 008/105] =?UTF-8?q?=E2=98=94=20pmgr:=20better=20handling?=
=?UTF-8?q?=20of=20unexpected=20repository=20format?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3157 and Sentry SERVER-116
---
src/octoprint/plugins/pluginmanager/__init__.py | 17 +++++++++++++++--
1 file changed, 15 insertions(+), 2 deletions(-)
diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py
index 5caa980b6..ea8d99cc4 100644
--- a/src/octoprint/plugins/pluginmanager/__init__.py
+++ b/src/octoprint/plugins/pluginmanager/__init__.py
@@ -37,6 +37,9 @@ _DATA_FORMAT_VERSION = "v2"
def map_repository_entry(entry):
+ if not isinstance(entry, dict):
+ return None
+
result = copy.deepcopy(entry)
if not "follow_dependency_links" in result:
@@ -797,7 +800,16 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
return None
- repo_data = r.json()
+ try:
+ repo_data = r.json()
+ except Exception as e:
+ self._logger.exception("Error while reading repository data")
+ return None
+
+ # validation
+ if not isinstance(repo_data, (list, tuple)):
+ self._logger.warn("Invalid repository data: expected a list, got {!r}".format(repo_data))
+ return None
try:
import json
@@ -814,7 +826,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if repo_data is None:
return False
- self._repository_plugins = map(map_repository_entry, repo_data)
+ self._repository_plugins = filter(lambda x: x is not None,
+ map(map_repository_entry, repo_data))
return True
def _fetch_notices_from_disk(self):
From e864d6b03efb589ea975b85ab55e67506846a954 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 15 May 2019 17:35:57 +0200
Subject: [PATCH 009/105] =?UTF-8?q?=F0=9F=9A=B8=20Ensure=20line=20breaks?=
=?UTF-8?q?=20on=20copy=20of=20terminal=20contents?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/octoprint/templates/tabs/terminal.jinja2 | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/templates/tabs/terminal.jinja2 b/src/octoprint/templates/tabs/terminal.jinja2
index ba6c20482..4ecded92b 100644
--- a/src/octoprint/templates/tabs/terminal.jinja2
+++ b/src/octoprint/templates/tabs/terminal.jinja2
@@ -1,5 +1,5 @@
-
+
From 3bd9d11fc3ab9a374f8f408934e533f09aaaf105 Mon Sep 17 00:00:00 2001
From: Kyle Evans
Date: Fri, 17 May 2019 22:43:13 -0500
Subject: [PATCH 010/105] comm: Don't open twice on FreeBSD
Originally introduced by PR #673 to fix reconnect issues on pyserial,
OctoPrint will first open the serial port with PARITY_ODD then close it
again and reopen with the desired PARITY_NONE. This works around issues
likely sitting somewhere in the linux tty layer, at least on some
distributions, that don't necessarily exist on other platforms.
Stop doing the workaround on FreeBSD to start with, as this is the only
platform I can effectively test. I suspect MacOS/Windows likely also don't
need to do this.
---
src/octoprint/util/comm.py | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index e83b9d703..97b3d360e 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -39,6 +39,7 @@ from octoprint.filemanager.destinations import FileDestinations
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \
to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks, ResettableTimer, \
monotonic_time
+from octoprint.util.platform import get_os
try:
import _winreg
@@ -2613,20 +2614,25 @@ class MachineCom(object):
self._log("Connecting to: %s" % port)
serial_port_args = {
- "port": str(port),
"baudrate": baudrateList()[0] if baudrate == 0 else baudrate,
"timeout": read_timeout,
"write_timeout": 0,
- "parity": serial.PARITY_ODD
}
if settings().getBoolean(["serial", "exclusive"]):
serial_port_args["exclusive"] = True
serial_obj = serial.Serial(**serial_port_args)
+ serial_obj.port = str(port)
- serial_obj.close()
- serial_obj.parity = serial.PARITY_NONE
+ # This may also not be applicable to other platforms, in which case
+ # this should probably get rewritten as a whitelist for the platforms
+ # that have issues here.
+ if get_os() != 'freebsd':
+ serial_obj.parity = serial.PARITY_ODD
+ serial_obj.open()
+ serial_obj.close()
+ serial_obj.parity = serial.PARITY_NONE
serial_obj.open()
return BufferedReadlineWrapper(serial_obj)
From 12be637f850ff2c4ece622f2bf9125c9139bacc8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 20 May 2019 16:46:45 +0200
Subject: [PATCH 011/105] =?UTF-8?q?=E2=9C=A8=20Add=20setting=20for=20parit?=
=?UTF-8?q?y=20double=20open=20workaround?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Can now be set to be applied if possibly needed (OS is a Debian Linux),
always or never.
Closes #3169, enhances #3167
---
src/octoprint/server/api/settings.py | 5 +++++
src/octoprint/settings.py | 1 +
.../static/js/app/viewmodels/settings.js | 1 +
.../dialogs/settings/serialconnection.jinja2 | 18 +++++++++++++++++-
src/octoprint/util/comm.py | 9 +++++----
5 files changed, 29 insertions(+), 5 deletions(-)
diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py
index cc7e0e574..3a61c97cd 100644
--- a/src/octoprint/server/api/settings.py
+++ b/src/octoprint/server/api/settings.py
@@ -172,6 +172,7 @@ def getSettings():
"ignoreIdenticalResends": s.getBoolean(["serial", "ignoreIdenticalResends"]),
"firmwareDetection": s.getBoolean(["serial", "firmwareDetection"]),
"blockWhileDwelling": s.getBoolean(["serial", "blockWhileDwelling"]),
+ "useParityWorkaround": s.get(["serial", "useParityWorkaround"]),
"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
"maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"]),
@@ -459,6 +460,10 @@ def _saveSettings(data):
if "ignoreIdenticalResends" in data["serial"]: s.setBoolean(["serial", "ignoreIdenticalResends"], data["serial"]["ignoreIdenticalResends"])
if "firmwareDetection" in data["serial"]: s.setBoolean(["serial", "firmwareDetection"], data["serial"]["firmwareDetection"])
if "blockWhileDwelling" in data["serial"]: s.setBoolean(["serial", "blockWhileDwelling"], data["serial"]["blockWhileDwelling"])
+ if "useParityWorkaround" in data["serial"]:
+ value = data["serial"]["useParityWorkaround"]
+ if value in ("always", "detect", "never"):
+ s.set(["serial", "useParityWorkaround"], value)
if "logPositionOnPause" in data["serial"]: s.setBoolean(["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"])
if "logPositionOnCancel" in data["serial"]: s.setBoolean(["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"])
if "abortHeatupOnCancel" in data["serial"]: s.setBoolean(["serial", "abortHeatupOnCancel"], data["serial"]["abortHeatupOnCancel"])
diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py
index 74dd986d6..5a29d99fa 100644
--- a/src/octoprint/settings.py
+++ b/src/octoprint/settings.py
@@ -144,6 +144,7 @@ default_settings = {
"supportFAsCommand": False,
"firmwareDetection": True,
"blockWhileDwelling": False,
+ "useParityWorkaround": "detect",
"capabilities": {
"autoreport_temp": True,
diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js
index cb4b3caaa..8a0c29455 100644
--- a/src/octoprint/static/js/app/viewmodels/settings.js
+++ b/src/octoprint/static/js/app/viewmodels/settings.js
@@ -185,6 +185,7 @@ $(function() {
self.serial_ignoreIdenticalResends = ko.observable(undefined);
self.serial_firmwareDetection = ko.observable(undefined);
self.serial_blockWhileDwelling = ko.observable(undefined);
+ self.serial_useParityWorkaround = ko.observable(undefined);
self.serial_supportResendsWithoutOk = ko.observable(undefined);
self.serial_logPositionOnPause = ko.observable(undefined);
self.serial_logPositionOnCancel = ko.observable(undefined);
diff --git a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2
index b180c8ddb..c3b6b019a 100644
--- a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2
+++ b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2
@@ -33,7 +33,7 @@
- {{ _('Use this to define additional glob patterns matching serial ports to list for connecting against, e.g. /dev/ttyAMA*. One entry per line.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}
+ {{ _('Use this to define additional glob patterns matching serial ports to list for connecting against, e.g. /dev/ttyAMA*. One entry per line. Please note that ports will only be offered to connect to if they get also detected by the operating system. Adding a port here will not make it magically appear in OctoPrint. If the operating system doesn\'t see your printer you need to solve this first.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}
@@ -51,6 +51,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
From fa2716c65cc7c44f655eac72833db724e2dec734 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Janne=20M=C3=A4ntyharju?=
Date: Sun, 26 May 2019 20:53:59 +0300
Subject: [PATCH 028/105] Calculate filament usage for all extruders is M605
duplicate/mirror command is used (Issue #3075)
---
AUTHORS.md | 1 +
src/octoprint/util/gcodeInterpreter.py | 19 ++++++++++++++++++-
2 files changed, 19 insertions(+), 1 deletion(-)
diff --git a/AUTHORS.md b/AUTHORS.md
index 2b018c0e6..e7f9e60d4 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -102,6 +102,7 @@ date of first contribution):
* [Jack Wilsdon](https://github.com/jackwilsdon)
* [Ryan Finnie](https://github.com/rfinnie)
* [Timur Duehr](https://github.com/tduehr)
+ * [Janne Mäntyharju](https://github.com/JanneMantyharju)
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/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py
index b953b1e22..8d7834c4b 100644
--- a/src/octoprint/util/gcodeInterpreter.py
+++ b/src/octoprint/util/gcodeInterpreter.py
@@ -218,6 +218,7 @@ class gcode(object):
totalMoveTimeMinute = 0.0
relativeE = False
relativeMode = False
+ duplicationMode = False
scale = 1.0
fwretractTime = 0
fwretractDist = 0
@@ -339,6 +340,14 @@ class gcode(object):
currentE[currentExtruder] += e
maxExtrusion[currentExtruder] = max(maxExtrusion[currentExtruder],
totalExtrusion[currentExtruder])
+
+ if currentExtruder == 0 and len(currentE) > 1 and duplicationMode:
+ # Copy first extruder length to other extruders
+ for i in range(1, len(currentE)):
+ totalExtrusion[i] += e
+ currentE[i] += e
+ maxExtrusion[i] = max(maxExtrusion[i],
+ totalExtrusion[i])
else:
e = 0.0
@@ -426,6 +435,14 @@ class gcode(object):
fwretractDist = s
else:
fwrecoverTime = (fwretractDist + s) / f
+ elif M == 605: #Duplication/Mirroring mode
+ s = getCodeInt(line, 'S')
+ if s in [2, 4, 5, 6]:
+ # Duplication / Mirroring mode selected. Printer firmware copies extrusion commands
+ # from first extruder to all other extruders
+ duplicationMode = True
+ else:
+ duplicationMode = False
elif T is not None:
if T > max_extruders:
@@ -474,7 +491,7 @@ class gcode(object):
printing_area=self.printing_area)
def getCodeInt(line, code):
- return getCode(line, code, float)
+ return getCode(line, code, int)
def getCodeFloat(line, code):
From 11040f272a0bf546373fbb7391fd67c73d03b100 Mon Sep 17 00:00:00 2001
From: Nicolai Nielsen
Date: Sat, 25 May 2019 09:07:00 -0500
Subject: [PATCH 029/105] Added confirmation dialog before uninstalling plugin
Added confirmation dialog before disabling plugin Added configuration options
to control the confirmation dialogs Defaults are not to confirm for disabling
but confirm for uninstalling
---
AUTHORS.md | 1 +
.../plugins/pluginmanager/__init__.py | 6 ++
.../pluginmanager/static/js/pluginmanager.js | 74 ++++++++++++++-----
.../templates/pluginmanager_settings.jinja2 | 19 +++++
4 files changed, 81 insertions(+), 19 deletions(-)
diff --git a/AUTHORS.md b/AUTHORS.md
index 2b018c0e6..f7d18be6f 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -102,6 +102,7 @@ date of first contribution):
* [Jack Wilsdon](https://github.com/jackwilsdon)
* [Ryan Finnie](https://github.com/rfinnie)
* [Timur Duehr](https://github.com/tduehr)
+ * [Nicolai Nielsen](https://github.com/dovecode)
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/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py
index ea8d99cc4..b4ce1c8a3 100644
--- a/src/octoprint/plugins/pluginmanager/__init__.py
+++ b/src/octoprint/plugins/pluginmanager/__init__.py
@@ -120,6 +120,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._notices_cache_path = os.path.join(self.get_plugin_data_folder(), "notices.json")
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
+ self._confirm_uninstall = self._settings.global_get_boolean(["confirm_uninstall"])
+ self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"])
self._pip_caller = LocalPipCaller(force_user=self._settings.get_boolean(["pip_force_user"]))
self._pip_caller.on_log_call = self._log_call
@@ -157,6 +159,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
notices_ttl=6*60,
pip_args=None,
pip_force_user=False,
+ confirm_uninstall=True,
+ confirm_disable=False,
dependency_links=False,
hidden=[]
)
@@ -167,6 +171,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"])
+ self._confirm_uninstall = self._settings.global_get_boolean(["confirm_uninstall"])
+ self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"])
##~~ AssetPlugin
diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js
index 8557c4a4b..e23043c0a 100644
--- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js
+++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js
@@ -13,6 +13,8 @@ $(function() {
self.config_noticesTtl = ko.observable();
self.config_pipAdditionalArgs = ko.observable();
self.config_pipForceUser = ko.observable();
+ self.config_confirmUninstall = ko.observable();
+ self.config_confirmDisable = ko.observable();
self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog");
@@ -394,12 +396,13 @@ $(function() {
.done(onSuccess)
.fail(onError);
} else {
- var perform = function() {
+ var performDisabling = function() {
OctoPrint.plugins.pluginmanager.disable(data.key)
.done(onSuccess)
.fail(onError);
};
+ // always warn if plugin is marked "disabling discouraged"
if (data.disabling_discouraged) {
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: data.name})
+ "
" + data.disabling_discouraged;
@@ -409,10 +412,21 @@ $(function() {
question: gettext("Do you still want to disable it?"),
cancel: gettext("Keep enabled"),
proceed: gettext("Disable anyway"),
- onproceed: perform
- })
+ onproceed: performDisabling
+ });
+ }
+ // warn if global "warn disabling" setting is set"
+ else if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()) {
+ showConfirmationDialog({
+ message: _.sprintf(gettext("You are about to disable \"%(name)s\""), {name: data.name}),
+ cancel: gettext("Keep enabled"),
+ proceed: gettext("Disable plugin"),
+ onproceed: performDisabling,
+ nofade: true
+ });
} else {
- perform();
+ // otherwise just go ahead and disable...
+ performDisabling();
}
}
};
@@ -511,23 +525,41 @@ $(function() {
if (data.bundled) return;
if (data.key == "pluginmanager") return;
- self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
+ // defining actual uninstall logic as functor in order to handle
+ // the confirm/no-confirm logic without duplication of logic
+ var performUninstall = function() {
+ self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
- OctoPrint.plugins.pluginmanager.uninstall(data.key)
- .done(function() {
- self.requestData();
- })
- .fail(function() {
- new PNotify({
- title: gettext("Something went wrong"),
- text: gettext("Please consult octoprint.log for details"),
- type: "error",
- hide: false
+ OctoPrint.plugins.pluginmanager.uninstall(data.key)
+ .done(function() {
+ self.requestData();
+ })
+ .fail(function() {
+ new PNotify({
+ title: gettext("Something went wrong"),
+ text: gettext("Please consult octoprint.log for details"),
+ type: "error",
+ hide: false
+ });
+ })
+ .always(function() {
+ self._markDone();
});
- })
- .always(function() {
- self._markDone();
+ };
+
+ if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_uninstall()) {
+ // confirmation needed. Show confirmation dialog and call performUninstall if user clicks Yes
+ showConfirmationDialog({
+ message: _.sprintf(gettext("You are about to uninstall the plugin \"%(name)s\""), {name: data.name}),
+ cancel: gettext("Keep installed"),
+ proceed: gettext("Uninstall"),
+ onproceed: performUninstall,
+ nofade: true
});
+ } else {
+ // no confirmation needed, just go ahead and uninstall
+ performUninstall();
+ }
};
self.refreshRepository = function() {
@@ -596,7 +628,9 @@ $(function() {
notices: notices,
notices_ttl: noticesTtl,
pip_args: pipArgs,
- pip_force_user: self.config_pipForceUser()
+ pip_force_user: self.config_pipForceUser(),
+ confirm_uninstall: self.config_confirmUninstall(),
+ confirm_disable: self.config_confirmDisable(),
}
}
};
@@ -614,6 +648,8 @@ $(function() {
self.config_noticesTtl(self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl());
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user());
+ self.config_confirmUninstall(self.settingsViewModel.settings.plugins.pluginmanager.confirm_uninstall());
+ self.config_confirmDisable(self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable());
};
self.installed = function(data) {
diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2
index 0e4eef7ee..9d0ee36ff 100644
--- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2
+++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2
@@ -234,6 +234,25 @@
+
+
+
{% endtrans %}
+
{% trans %}
+
+ OctoPrint is running on a throttled system, updates are disabled.
+
+
+ To reduce the likelihood of running into update problems on throttled and hence potentially unstable systems
+ as seen in the past, OctoPrint doesn't support updating under such conditions. Please fix the current issue
+ before trying to update. Take a look at the displayed warning in the navigation bar to learn about what is
+ wrong and to get hints on how to solve the problem.
+
+{% endtrans %}
+
{% trans %}
+
+ OctoPrint is currently printing, updates are disabled.
+
+
+ Running updates is not supported while printing in order to not risk any kind of disruption to the print job.
+ Please let the print finish before trying to update.
+
{% trans %}
+ The system OctoPrint is running on is currently throttled. Due to that it's not possible to install new
+ plugins in order to avoid possible issues caused by system instability.
+{% endtrans %}
{% trans %}
It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible
@@ -30,6 +37,7 @@
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
+{{ pluginmanager_throttled() }}
{{ _('... from the Plugin Repository', url='https://plugins.octoprint.org') }}
From 1c3e463ac6750b3ad1d9b3c3e8a3227911bd172b Mon Sep 17 00:00:00 2001
From: Kelly Anderson
Date: Sat, 22 Jun 2019 18:11:36 -0600
Subject: [PATCH 045/105] fix RuntimeError: dictionary changed size during
iteration
---
src/octoprint/server/api/printer.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py
index 2e15f35b1..685f748b4 100644
--- a/src/octoprint/server/api/printer.py
+++ b/src/octoprint/server/api/printer.py
@@ -525,7 +525,9 @@ def _delete_chamber(x):
def _delete_from_data(x, key_matcher):
data = dict(x)
- for k in data.keys():
+ # must make list of keys first to avoid
+ # RuntimeError: dictionary changed size during iteration
+ for k in list(data.keys()):
if key_matcher(k):
del data[k]
return data
From a924520dd6848bef5159733b48cfbe3c7f4ca39c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 26 Jun 2019 18:32:33 +0200
Subject: [PATCH 046/105] =?UTF-8?q?=E2=9C=A8=20tracking:=20track=20plugins?=
=?UTF-8?q?=20&=20versions=20on=20startup?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Requested feature by plugin developers, will also allow us to compile
stuff like top10 lists.
---
src/octoprint/plugins/tracking/__init__.py | 23 ++++++++++++++++------
1 file changed, 17 insertions(+), 6 deletions(-)
diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py
index b7e3ca894..4a89a98ba 100644
--- a/src/octoprint/plugins/tracking/__init__.py
+++ b/src/octoprint/plugins/tracking/__init__.py
@@ -207,7 +207,11 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
if b"octopi_version" in self._environment[b"plugins"][b"pi_support"]:
payload[b"octopi_version"] = self._environment[b"plugins"][b"pi_support"][b"octopi_version"]
- self._track("startup", **payload)
+ plugins = self._plugin_manager.enabled_plugins
+ plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled]
+ payload[b"plugins"] = ",".join(map(lambda x: "{}:{}".format(x.key.lower(), x.version.lower()), plugins_thirdparty))
+
+ self._track("startup", body=True, **payload)
def _track_shutdown(self):
if not self._settings.get_boolean([b"enabled"]):
@@ -369,7 +373,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._executor.submit(self._do_track, event, **kwargs)
- def _do_track(self, event, **kwargs):
+ def _do_track(self, event, body=False, **kwargs):
if not self._connectivity_checker.online:
return
@@ -389,10 +393,17 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
try:
params = urlencode(kwargs, doseq=True).replace("+", "%20")
- requests.get(url,
- params=params,
- timeout=3.1,
- headers=headers)
+ if body:
+ requests.post(url,
+ data=params,
+ timeout=3.1,
+ headers=headers)
+ else:
+ requests.get(url,
+ params=params,
+ timeout=3.1,
+ headers=headers)
+
self._logger.info("Sent tracking event {}, payload: {!r}".format(event, kwargs))
except:
if self._logger.isEnabledFor(logging.DEBUG):
From 7b4c148dd798c6d4051ffbb61c909723be61278c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 26 Jun 2019 19:27:57 +0200
Subject: [PATCH 047/105] =?UTF-8?q?=E2=9C=A8=20tracking:=20track=20slicing?=
=?UTF-8?q?=20events?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Gives us some numbers the next time someone complains about
slicer support.
---
docs/events/index.rst | 4 +++
src/octoprint/filemanager/__init__.py | 34 +++++++++++--------
src/octoprint/plugins/tracking/__init__.py | 13 ++++++-
.../templates/tracking_settings.jinja2 | 3 ++
4 files changed, 38 insertions(+), 16 deletions(-)
diff --git a/docs/events/index.rst b/docs/events/index.rst
index eeaac5869..2250d402f 100644
--- a/docs/events/index.rst
+++ b/docs/events/index.rst
@@ -588,6 +588,7 @@ SlicingStarted
Payload:
+ * ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -599,6 +600,7 @@ SlicingDone
Payload:
+ * ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -611,6 +613,7 @@ SlicingCancelled
Payload:
+ * ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -621,6 +624,7 @@ SlicingFailed
Payload:
+ * ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py
index 2c7ff6161..6551d7090 100644
--- a/src/octoprint/filemanager/__init__.py
+++ b/src/octoprint/filemanager/__init__.py
@@ -329,16 +329,18 @@ class FileManager(object):
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
try:
if _error:
- eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
- stl_location=source_location,
- gcode=dest_path,
- gcode_location=dest_location,
- reason=_error))
+ eventManager().fire(Events.SLICING_FAILED, dict(slicer=slicer_name,
+ stl=source_path,
+ stl_location=source_location,
+ gcode=dest_path,
+ gcode_location=dest_location,
+ reason=_error))
elif _cancelled:
- eventManager().fire(Events.SLICING_CANCELLED, dict(stl=source_path,
- stl_location=source_location,
- gcode=dest_path,
- gcode_location=dest_location))
+ eventManager().fire(Events.SLICING_CANCELLED, dict(slicer=slicer_name,
+ stl=source_path,
+ stl_location=source_location,
+ gcode=dest_path,
+ gcode_location=dest_location))
else:
source_meta = self.get_metadata(source_location, source_path)
hash = source_meta.get("hash", "n/a")
@@ -356,11 +358,12 @@ class FileManager(object):
printer_profile=printer_profile, analysis=_analysis)
end_time = octoprint.util.monotonic_time()
- eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
- stl_location=source_location,
- gcode=dest_path,
- gcode_location=dest_location,
- time=end_time - start_time))
+ eventManager().fire(Events.SLICING_DONE, dict(slicer=slicer_name,
+ stl=source_path,
+ stl_location=source_location,
+ gcode=dest_path,
+ gcode_location=dest_location,
+ time=end_time - start_time))
if callback is not None:
if callback_args is None:
@@ -381,7 +384,8 @@ class FileManager(object):
slicer = self._slicing_manager.get_slicer(slicer_name)
start_time = octoprint.util.monotonic_time()
- eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
+ eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name,
+ "stl": source_path,
"stl_location": source_location,
"gcode": dest_path,
"gcode_location": dest_location,
diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py
index 4a89a98ba..732ebefbe 100644
--- a/src/octoprint/plugins/tracking/__init__.py
+++ b/src/octoprint/plugins/tracking/__init__.py
@@ -67,7 +67,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
update=True,
printer=True,
printer_safety_check=True,
- throttled=True))
+ throttled=True,
+ slicing=True))
def get_settings_restricted_paths(self):
return dict(admin=[["enabled"], ["unique_id"], ["events"]],
@@ -121,6 +122,9 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._record_next_firmware_info = False
self._track_printer_event(event, payload)
+ elif event in (Events.SLICING_STARTED,):
+ self._track_slicing_event(event, payload)
+
elif hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN") and \
event in (Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN):
@@ -367,6 +371,13 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
printer_safety_warning_type=payload.get(b"warning_type", "unknown"),
printer_safety_check_name=payload.get(b"check_name", "unknown"))
+ def _track_slicing_event(self, event, payload):
+ if not self._settings.get_boolean(["events", "slicing"]):
+ return
+
+ self._track("slicing_started",
+ slicer=payload.get(b"slicer", "unknown"))
+
def _track(self, event, **kwargs):
if not self._settings.get_boolean([b"enabled"]):
return
diff --git a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2
index 570038309..9d1d572a9 100644
--- a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2
+++ b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2
@@ -46,6 +46,9 @@
+
From 2c6568acd1403ee9231dcdae152a9b2cce2aec99 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 1 Jul 2019 17:17:34 +0200
Subject: [PATCH 048/105] =?UTF-8?q?=E2=9C=A8=20Mimetype=20guessing=20for?=
=?UTF-8?q?=20the=20webcam=20test?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Related to #3207
---
setup.py | 3 ++-
src/octoprint/server/api/__init__.py | 10 ++++++++++
src/octoprint/static/js/app/viewmodels/settings.js | 7 ++++---
src/octoprint/util/__init__.py | 4 ++++
4 files changed, 20 insertions(+), 4 deletions(-)
diff --git a/setup.py b/setup.py
index 43d94e50d..27d031eb9 100644
--- a/setup.py
+++ b/setup.py
@@ -61,7 +61,8 @@ INSTALL_REQUIRES = [
"monotonic>=1.5,<1.6",
"frozendict>=1.2,<1.3",
"sentry-sdk==0.7.7",
- "typing>=3.6.6,<4"
+ "typing>=3.6.6,<4",
+ "filetype>=1.0.5,<2"
]
if sys.platform == "darwin":
diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py
index a330e1ecb..f9e64940e 100644
--- a/src/octoprint/server/api/__init__.py
+++ b/src/octoprint/server/api/__init__.py
@@ -464,7 +464,17 @@ def _test_url(data):
response_result = dict(headers=dict(response.headers),
content_type=content_type)
+ if not content_type and data.get("content_type_guess") in valid_boolean_trues:
+ content = response.content
+ content_type = util.guess_mime_type(bytearray(content))
+
+ if not content_type:
+ content_type = "application/octet-stream"
+
+ response_result = dict(assumed_content_type=content_type)
+
parsed_content_type = util.parse_mime_type(content_type)
+
in_whitelist = content_type_whitelist is None or any(
map(lambda x: util.mime_type_matches(parsed_content_type, x), content_type_whitelist))
in_blacklist = content_type_blacklist is not None and any(
diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js
index 0225b0019..5d3490743 100644
--- a/src/octoprint/static/js/app/viewmodels/settings.js
+++ b/src/octoprint/static/js/app/viewmodels/settings.js
@@ -361,7 +361,8 @@ $(function() {
response: "bytes",
timeout: self.webcam_snapshotTimeout(),
validSsl: self.webcam_snapshotSslValidation(),
- content_type_whitelist: ["image/*"]
+ content_type_whitelist: ["image/*"],
+ content_type_guess: true
})
.done(function(response) {
if (!response.result) {
@@ -385,7 +386,7 @@ $(function() {
}
var content = response.response.content;
- var contentType = response.response.content_type
+ var contentType = response.response.assumed_content_type;
var mimeType = "image/jpeg";
if (contentType) {
@@ -395,7 +396,7 @@ $(function() {
var text = gettext("If you see your webcam snapshot picture below, the entered snapshot URL is ok.");
showMessageDialog({
title: gettext("Snapshot test"),
- message: $('
' + text + '
'),
+ message: $('
' + text + '
'),
onclose: function() {
self.testWebcamSnapshotUrlBusy(false);
}
diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py
index 5c02e76af..99e1250a9 100644
--- a/src/octoprint/util/__init__.py
+++ b/src/octoprint/util/__init__.py
@@ -867,6 +867,10 @@ def server_reachable(host, port, timeout=3.05, proto="tcp", source=None):
except:
return False
+def guess_mime_type(data):
+ import filetype
+ return filetype.guess_mime(data)
+
def parse_mime_type(mime):
import cgi
From 72167d14d2796e8527f09d183107fad99c0ab2fa Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Tue, 2 Jul 2019 12:44:29 +0200
Subject: [PATCH 049/105] =?UTF-8?q?=F0=9F=90=9B=20Fix=20caching=20headers?=
=?UTF-8?q?=20on=20/=20in=20case=20of=20wizards?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Revalidation header from ceade46dd782c3685242788124639067ac91061e was
overwriting custom header in case of active wizards, causing the browser
to cache HTML code with enabled wizards.
This fixes this by checking if the headers in question actually need to
be set and aren't already there.
---
src/octoprint/server/util/flask.py | 9 ++++++++-
1 file changed, 8 insertions(+), 1 deletion(-)
diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py
index a5b5eace4..e8bf15133 100644
--- a/src/octoprint/server/util/flask.py
+++ b/src/octoprint/server/util/flask.py
@@ -1143,7 +1143,14 @@ def check_lastmodified(lastmodified):
def add_revalidation_response_headers(response):
- response.headers["Cache-Control"] = "no-cache, must-revalidate"
+ import werkzeug.http
+
+ cache_control = werkzeug.http.parse_dict_header(response.headers.get("Cache-Control", ""))
+ if "no-cache" not in cache_control:
+ cache_control["no-cache"] = None
+ if "must-revalidate" not in cache_control:
+ cache_control["must-revalidate"] = None
+ response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control)
return response
From 59ae7e39f229310dab11ebf15c8b2959decd3aab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Tue, 2 Jul 2019 13:43:57 +0200
Subject: [PATCH 050/105] =?UTF-8?q?=E2=98=94=20Only=20set=20relevant=20cac?=
=?UTF-8?q?he=20control=20headers?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
We don't want to accidentally overwrite anything again.
---
src/octoprint/server/util/flask.py | 27 +++++++++++++++++++++++++--
1 file changed, 25 insertions(+), 2 deletions(-)
diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py
index e8bf15133..f24e890ac 100644
--- a/src/octoprint/server/util/flask.py
+++ b/src/octoprint/server/util/flask.py
@@ -1151,18 +1151,41 @@ def add_revalidation_response_headers(response):
if "must-revalidate" not in cache_control:
cache_control["must-revalidate"] = None
response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control)
+
return response
def add_non_caching_response_headers(response):
- response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
+ import werkzeug.http
+
+ cache_control = werkzeug.http.parse_dict_header(response.headers.get("Cache-Control", ""))
+ if "no-store" not in cache_control:
+ cache_control["no-store"] = None
+ if "no-cache" not in cache_control:
+ cache_control["no-cache"] = None
+ if "must-revalidate" not in cache_control:
+ cache_control["must-revalidate"] = None
+ if "post-check" not in cache_control or cache_control["post-check"] != "0":
+ cache_control["post-check"] = "0"
+ if "pre-check" not in cache_control or cache_control["pre-check"] != "0":
+ cache_control["pre-check"] = "0"
+ if "max-age" not in cache_control or cache_control["max-age"] != "0":
+ cache_control["max-age"] = "0"
+ response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control)
+
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "-1"
return response
def add_no_max_age_response_headers(response):
- response.headers["Cache-Control"] = "max-age=0"
+ import werkzeug.http
+
+ cache_control = werkzeug.http.parse_dict_header(response.headers.get("Cache-Control", ""))
+ if "max-age" not in cache_control or cache_control["max-age"] != "0":
+ cache_control["max-age"] = "0"
+ response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control)
+
return response
From 530fca95e49000bead67bf677844f5f80a037b1f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Tue, 2 Jul 2019 13:48:28 +0200
Subject: [PATCH 051/105] =?UTF-8?q?=E2=98=94=20Include=20wizard=20flag=20i?=
=?UTF-8?q?n=20etag?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Additional protection against #3211 and #3166
---
src/octoprint/server/views.py | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py
index b220e77ae..8491e97de 100644
--- a/src/octoprint/server/views.py
+++ b/src/octoprint/server/views.py
@@ -200,9 +200,10 @@ def index():
default_additional_etag = [enable_accesscontrol,
enable_gcodeviewer,
- enable_timelapse] + sorted(["{}:{}".format(to_bytes(k, errors="replace"),
- to_bytes(v, errors="replace"))
- for k, v in _plugin_vars.items()])
+ enable_timelapse,
+ wizard_active(_templates.get(locale))] + sorted(["{}:{}".format(to_bytes(k, errors="replace"),
+ to_bytes(v, errors="replace"))
+ for k, v in _plugin_vars.items()])
def get_preemptively_cached_view(key, view, data=None, additional_request_data=None, additional_unless=None):
if (data is None and additional_request_data is None) or g.locale is None:
From 44af09580ac58d3616a68d04cf3db2c696e54dbc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Tue, 2 Jul 2019 13:56:19 +0200
Subject: [PATCH 052/105] =?UTF-8?q?=F0=9F=9A=B8=20Make=20clear=20when=20GC?=
=?UTF-8?q?ODE=20scripts=20are=20executed?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3198
---
.../templates/dialogs/settings/gcodescripts.jinja2 | 9 ++++++++-
1 file changed, 8 insertions(+), 1 deletion(-)
diff --git a/src/octoprint/templates/dialogs/settings/gcodescripts.jinja2 b/src/octoprint/templates/dialogs/settings/gcodescripts.jinja2
index 4ed9268da..04423948f 100644
--- a/src/octoprint/templates/dialogs/settings/gcodescripts.jinja2
+++ b/src/octoprint/templates/dialogs/settings/gcodescripts.jinja2
@@ -3,42 +3,49 @@
+ {{ _('Anything you put here will be executed before any lines in your files.') }}
+ {{ _('Anything you put here will be executed after any lines in your files.') }}
+ {{ _('Anything you put here will be executed after any lines in your files.') }}
+ {{ _('Anything you put here will be executed after any lines in your files.') }}
+ {{ _('Anything you put here will be executed before any lines in your files.') }}
+ {{ _('Anything you put here will be executed before any tool change commands Tn.') }}
+ {{ _('Anything you put here will be executed after any tool change commands Tn.') }}
@@ -51,7 +58,7 @@
- {{ _('This will only be executed when closing the connection actively. If the connection to the printer is suddenly lost nothing will be sent.') }}
+ {{ _('Anything you put here will only be executed when closing the connection actively. If the connection to the printer is suddenly lost nothing will be sent.') }}
From 85d212ba97f75aade3f8536e6bad303a0a4548b3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Tue, 2 Jul 2019 16:35:57 +0200
Subject: [PATCH 053/105] =?UTF-8?q?=E2=98=94=20More=20resilience=20against?=
=?UTF-8?q?=20garbage=20on=20the=20line=20on=20initial=20connect?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
We'll now send the hello command twice, and a third time if we run into
a timeout during initial connect.
Closes #3206
---
src/octoprint/util/comm.py | 14 ++++++++++++--
1 file changed, 12 insertions(+), 2 deletions(-)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index 9e2fa5436..c5b2ae8c4 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -441,6 +441,7 @@ class MachineCom(object):
self._max_write_passes = settings().getInt(["serial", "maxWritePasses"])
self._hello_command = settings().get(["serial", "helloCommand"])
+ self._hello_sent = 0
self._trigger_ok_for_m29 = settings().getBoolean(["serial", "triggerOkForM29"])
self._hello_command = settings().get(["serial", "helloCommand"])
@@ -1508,6 +1509,7 @@ class MachineCom(object):
self.sendCommand(self._hello_command, force=True, tags=tags | {"trigger:comm.say_hello",})
self._clear_to_send.set()
+ self._hello_sent += 1
def resetLineNumbers(self, number=0, part_of_job=False, tags=None):
if not self.isOperational():
@@ -1623,6 +1625,10 @@ class MachineCom(object):
if try_hello:
self.sayHello()
+ # we send a second one right away because sometimes there's garbage on the line on first connect
+ # that can kill oks
+ self.sayHello()
+
while self._monitoring_active:
try:
line = self._readline()
@@ -2150,8 +2156,12 @@ class MachineCom(object):
self._handle_ok()
self._onConnected()
elif monotonic_time() > self._timeout:
- self._log("There was a timeout while trying to connect to the printer")
- self.close(wait=False)
+ if try_hello and self._hello_sent < 3:
+ self._log("No answer from the printer within the connection timeout, trying another hello")
+ self.sayHello()
+ else:
+ self._log("There was a timeout while trying to connect to the printer")
+ self.close(wait=False)
### Operational (idle or busy)
elif self._state in (self.STATE_OPERATIONAL,
From 5483ef7cd4d5e2961645e001fcaa1b60a6cad67a Mon Sep 17 00:00:00 2001
From: Gaston Dombiak
Date: Thu, 4 Jul 2019 23:19:35 -0700
Subject: [PATCH 054/105] Fixed typo in chambers documentation
---
docs/api/printer.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/api/printer.rst b/docs/api/printer.rst
index 7ac2ec38b..3fe43aa18 100644
--- a/docs/api/printer.rst
+++ b/docs/api/printer.rst
@@ -770,7 +770,7 @@ Retrieve the current bed state
Issue a chamber command
=======================
-.. http:post:: /api/printer/bed
+.. http:post:: /api/printer/chamber
Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands
are:
@@ -790,7 +790,7 @@ Issue a chamber command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
- If no heated chambed is configured for the currently selected printer profile, the resource will return
+ If no heated chamber is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires user rights.
From d44747b39a3fad41e0810ecd7136413c1f3bbd2e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 8 Jul 2019 11:25:44 +0200
Subject: [PATCH 055/105] =?UTF-8?q?=F0=9F=90=9B=20Fix=20long=5Frunning=5Fc?=
=?UTF-8?q?ommand=20flag=20for=20M191?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3220
---
src/octoprint/util/comm.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index c5b2ae8c4..2605e64e4 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -3662,7 +3662,7 @@ class MachineCom(object):
def _gcode_M191_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
self._heatupWaitStartTime = monotonic_time()
- self._log_running_command = True
+ self._long_running_command = True
self._heating = True
self._gcode_M141_sent(cmd, cmd_type, wait=True, support_r=True)
From f140dd9d443340aa2b38e246ec6da2d51465fd4f Mon Sep 17 00:00:00 2001
From: Eyal
Date: Mon, 8 Jul 2019 21:20:08 -0400
Subject: [PATCH 056/105] Quote arguments in pip install
If the argument is not quoted, the shell will interpret the braces.
---
docs/development/environment.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/development/environment.rst b/docs/development/environment.rst
index 8308712b7..04f9af807 100644
--- a/docs/development/environment.rst
+++ b/docs/development/environment.rst
@@ -25,7 +25,7 @@ below.
``source venv/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]``
+ including its regular *and* development and plugin development dependencies: ``pip install -e '.[develop,plugins]'``
When the virtual environment is activated you can then:
From d25f664be3e125caba26cf7e81ab4dd100a672d0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Tue, 16 Jul 2019 10:47:42 +0200
Subject: [PATCH 057/105] =?UTF-8?q?=F0=9F=90=9B=20printer=20safety:=20Anyc?=
=?UTF-8?q?ubic=201.1.2=20is=20already=20safe?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Fix off by one error.
See also https://community.octoprint.org/t/octoprint-tells-me-that-my-printers-firmware-lacks-mandatory-safety-features-what-does-this-mean/350/61
---
.../plugins/printer_safety_check/checks/firmware_unsafe.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/plugins/printer_safety_check/checks/firmware_unsafe.py b/src/octoprint/plugins/printer_safety_check/checks/firmware_unsafe.py
index f0b0d24c3..03719772e 100644
--- a/src/octoprint/plugins/printer_safety_check/checks/firmware_unsafe.py
+++ b/src/octoprint/plugins/printer_safety_check/checks/firmware_unsafe.py
@@ -68,7 +68,7 @@ class AnycubicCheck(Check):
def _broken_version(self, line):
version_str = line[len(self.VERSION):]
version = get_comparable_version(version_str, base=True)
- if version is not None and version <= self.FIXED_VERSION:
+ if version is not None and version < self.FIXED_VERSION:
return True
else:
return False
From ee93e25ffdeeb58111a9182337e8761058669816 Mon Sep 17 00:00:00 2001
From: Piotr Usewicz
Date: Fri, 5 Jul 2019 12:05:01 +0200
Subject: [PATCH 058/105] Rename currentLine to current_line
---
AUTHORS.md | 1 +
.../plugins/virtual_printer/virtual.py | 10 ++++----
src/octoprint/util/comm.py | 24 +++++++++----------
3 files changed, 18 insertions(+), 17 deletions(-)
diff --git a/AUTHORS.md b/AUTHORS.md
index 8f703a897..b8ad940d9 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -105,6 +105,7 @@ date of first contribution):
* [Nicolai Nielsen](https://github.com/dovecode)
* [Janne Mäntyharju](https://github.com/JanneMantyharju)
* [Steven Spungin](https://github.com/flamenco)
+ * [Piotr Usewicz](https://github.com/pusewicz)
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/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py
index 65d8bc8e8..e3ae4332d 100644
--- a/src/octoprint/plugins/virtual_printer/virtual.py
+++ b/src/octoprint/plugins/virtual_printer/virtual.py
@@ -137,7 +137,7 @@ class VirtualPrinter(object):
self._temperature_reporter = None
self._sdstatus_reporter = None
- self.currentLine = 0
+ self.current_line = 0
self.lastN = 0
self._incoming_lock = threading.RLock()
@@ -205,7 +205,7 @@ class VirtualPrinter(object):
self._heatingUp = False
- self.currentLine = 0
+ self.current_line = 0
self.lastN = 0
self._debug_awol = False
@@ -312,10 +312,10 @@ class VirtualPrinter(object):
checksum = int(data[data.rfind("*") + 1:])
data = data[:data.rfind("*")]
if not checksum == self._calculate_checksum(data):
- self._triggerResend(expected=self.currentLine + 1)
+ self._triggerResend(expected=self.current_line + 1)
continue
- self.currentLine += 1
+ self.current_line += 1
elif settings().getBoolean(["devel", "virtualPrinter", "forceChecksum"]):
self._send(self._error("checksum_missing"))
continue
@@ -324,7 +324,7 @@ class VirtualPrinter(object):
if data.startswith("N") and "M110" in data:
linenumber = int(re.search("N([0-9]+)", data).group(1))
self.lastN = linenumber
- self.currentLine = linenumber
+ self.current_line = linenumber
self._triggerResendAt100 = True
self._triggerResendWithTimeoutAt105 = True
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index 2605e64e4..9ea5d26de 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -454,7 +454,7 @@ class MachineCom(object):
self._sdRelativePath = settings().getBoolean(["serial", "sdRelativePath"])
self._blockWhileDwelling = settings().getBoolean(["serial", "blockWhileDwelling"])
self._send_m112_on_error = settings().getBoolean(["serial", "sendM112OnError"])
- self._currentLine = 1
+ self._current_line = 1
self._line_mutex = threading.RLock()
self._resendDelta = None
@@ -2488,7 +2488,7 @@ class MachineCom(object):
self._send_queue.clear()
with self._line_mutex:
- self._currentLine = 0
+ self._current_line = 0
self._lastLines.clear()
self.sayHello(tags={"trigger:comm.on_external_reset"})
@@ -2894,17 +2894,17 @@ class MachineCom(object):
if lineToResend is None:
return False
- if self._resendDelta is None and lineToResend == self._currentLine == 1:
+ if self._resendDelta is None and lineToResend == self._current_line == 1:
# We probably just handled a resend and this request originates from lines sent before that
self._logger.info("Got a resend request for line 1 which is also our current line. It looks "
"like we just handled a reset and this is a left over of this")
return False
- elif self._resendDelta is None and lineToResend == self._currentLine:
+ elif self._resendDelta is None and lineToResend == self._current_line:
# We don't expect to have an active resend request and the printer is requesting a resend of
# a line we haven't yet sent.
#
- # This means the printer got a line from us with N = self._currentLine - 1 but had already
+ # This means the printer got a line from us with N = self._current_line - 1 but had already
# acknowledged that. This can happen if the last line was resent due to a timeout during
# an active (prior) resend request.
#
@@ -2916,7 +2916,7 @@ class MachineCom(object):
lastCommError = self._lastCommError
self._lastCommError = None
- resendDelta = self._currentLine - lineToResend
+ resendDelta = self._current_line - lineToResend
if lastCommError is not None \
and ("line number" in lastCommError.lower() or "expected line" in lastCommError.lower()) \
@@ -2947,7 +2947,7 @@ class MachineCom(object):
if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0 or self._resendDelta < 0:
error_text = "Printer requested line {} but no sufficient history is available, can't resend".format(lineToResend)
self._log(error_text)
- self._logger.warn(error_text + ". Printer requested line {}, current line is {}, line history has {} entries.".format(lineToResend, self._currentLine, len(self._lastLines)))
+ self._logger.warn(error_text + ". Printer requested line {}, current line is {}, line history has {} entries.".format(lineToResend, self._current_line, len(self._lastLines)))
if self.isPrinting():
# abort the print & disconnect, there's nothing we can do to rescue it
self._trigger_error(error_text, "resend")
@@ -2969,7 +2969,7 @@ class MachineCom(object):
self._log_resends_rate_count = 0
self._to_logfile_with_terminal(u"Got a resend request from the printer: requested line = {}, "
- u"current line = {}".format(lineToResend, self._currentLine))
+ u"current line = {}".format(lineToResend, self._current_line))
self._log_resends_rate_count += 1
self._send_queue.resend_active = True
@@ -3013,7 +3013,7 @@ class MachineCom(object):
return False
cmd = self._lastLines[-self._resendDelta]
- lineNumber = self._currentLine - self._resendDelta
+ lineNumber = self._current_line - self._resendDelta
result = self._enqueue_for_sending(cmd, linenumber=lineNumber, resend=True)
@@ -3417,9 +3417,9 @@ class MachineCom(object):
def _do_increment_and_send_with_checksum(self, cmd):
with self._line_mutex:
- linenumber = self._currentLine
+ linenumber = self._current_line
self._addToLastLines(cmd)
- self._currentLine += 1
+ self._current_line += 1
self._do_send_with_checksum(cmd, linenumber)
def _do_send_with_checksum(self, command, linenumber):
@@ -3704,7 +3704,7 @@ class MachineCom(object):
self._logger.info("M110 detected, setting current line number to {}".format(newLineNumber))
# send M110 command with new line number
- self._currentLine = newLineNumber
+ self._current_line = newLineNumber
# after a reset of the line number we have no way to determine what line exactly the printer now wants
self._lastLines.clear()
From ea1bcf8e5def281c2f6732c667a2daead1fc7d96 Mon Sep 17 00:00:00 2001
From: Aliaksei Pilko
Date: Wed, 17 Jul 2019 19:08:35 +0100
Subject: [PATCH 059/105] Add user accounts cli
Add forgot password link at login
Update AUTHORS.md
---
AUTHORS.md | 1 +
src/octoprint/cli/__init__.py | 3 +-
src/octoprint/cli/user.py | 77 +++++++++++++++++++
.../templates/forcelogin_index.jinja2 | 1 +
src/octoprint/users.py | 8 +-
5 files changed, 86 insertions(+), 4 deletions(-)
create mode 100644 src/octoprint/cli/user.py
diff --git a/AUTHORS.md b/AUTHORS.md
index b8ad940d9..99c995aa4 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -106,6 +106,7 @@ date of first contribution):
* [Janne Mäntyharju](https://github.com/JanneMantyharju)
* [Steven Spungin](https://github.com/flamenco)
* [Piotr Usewicz](https://github.com/pusewicz)
+ * [Aliaksei Pilko](https://github.com/aliaksei135)
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/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py
index 34ad3f30e..f2df742b9 100644
--- a/src/octoprint/cli/__init__.py
+++ b/src/octoprint/cli/__init__.py
@@ -137,9 +137,10 @@ from .dev import dev_commands
from .client import client_commands
from .config import config_commands
from .analysis import analysis_commands
+from .user import user_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
- sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
+ sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands])
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py
new file mode 100644
index 000000000..052759a46
--- /dev/null
+++ b/src/octoprint/cli/user.py
@@ -0,0 +1,77 @@
+# coding=utf-8
+from __future__ import absolute_import, division, print_function
+
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+
+import click
+import logging
+
+from octoprint import init_settings
+from octoprint.cli import get_ctx_obj_option
+from octoprint.users import FilebasedUserManager, UnknownUser
+
+#~~ "octoprint user" commands
+
+
+@click.group()
+def user_commands():
+ pass
+
+
+@user_commands.group(name="user")
+@click.pass_context
+def user(ctx):
+ """User account management"""
+ try:
+ logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
+ settingz = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
+ ctx.obj.users = FilebasedUserManager(settingz=settingz)
+ except Exception:
+ click.echo("Could not instantiate user manager")
+ return
+
+
+@user.command(name="add_user")
+@click.argument("username", type=click.STRING, required=True)
+@click.password_option("--password", "password", help="Password for user")
+@click.option("--is-admin", "is_admin", type=click.BOOL, default=False,
+ help="Sets user role as admin")
+@click.pass_context
+def add_user_command(ctx, username, password, is_admin):
+ """Adds new user account"""
+ ctx.obj.users.addUser(
+ username,
+ password,
+ roles=("admin" if is_admin else "user"),
+ active=True
+ )
+
+
+@user.command(name="remove_user")
+@click.argument("username", type=click.STRING)
+@click.pass_context
+def remove_user_command(ctx, username):
+ """Removes user account"""
+ confirm = click.prompt(
+ "This is will irreversibly destroy the user account! Enter 'yes' to confirm",
+ type=click.STRING)
+
+ if confirm == 'yes':
+ ctx.obj.users.removeUser(username)
+ else:
+ click.echo("User NOT removed")
+
+
+@user.command(name="change_password")
+@click.argument("username", type=click.STRING)
+@click.password_option("--password", "password", help="New password for user")
+@click.pass_context
+def change_password_command(ctx, username, password):
+ """Changes an existing user password"""
+ try:
+ ctx.obj.users.changeUserPassword(username, password)
+ except UnknownUser:
+ click.echo("User does not exist!")
+
diff --git a/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
index 0d1e6b1af..99055b532 100644
--- a/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
+++ b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
@@ -23,6 +23,7 @@
+ {{ _('Forgot password?') }}
diff --git a/src/octoprint/users.py b/src/octoprint/users.py
index eed6a15a7..fddb36a9a 100644
--- a/src/octoprint/users.py
+++ b/src/octoprint/users.py
@@ -216,10 +216,12 @@ class UserManager(object):
##~~ FilebasedUserManager, takes available users from users.yaml file
class FilebasedUserManager(UserManager):
- def __init__(self):
+ def __init__(self, settingz=None):
UserManager.__init__(self)
-
- userfile = settings().get(["accessControl", "userfile"])
+ if settingz is None:
+ userfile = settings().get(["accessControl", "userfile"])
+ else:
+ userfile = settingz.get(["accessControl", "userfile"])
if userfile is None:
userfile = os.path.join(settings().getBaseFolder("base"), "users.yaml")
self._userfile = userfile
From 799b86b2879ccefc0d6ab60d732ce67369fb0a32 Mon Sep 17 00:00:00 2001
From: Aliaksei Pilko
Date: Thu, 18 Jul 2019 15:41:32 +0100
Subject: [PATCH 060/105] Update copyright
---
src/octoprint/cli/user.py | 2 +-
src/octoprint/users.py | 11 +++++------
2 files changed, 6 insertions(+), 7 deletions(-)
diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py
index 052759a46..32ea02482 100644
--- a/src/octoprint/cli/user.py
+++ b/src/octoprint/cli/user.py
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
-__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
+__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
diff --git a/src/octoprint/users.py b/src/octoprint/users.py
index fddb36a9a..72afb1d70 100644
--- a/src/octoprint/users.py
+++ b/src/octoprint/users.py
@@ -18,7 +18,7 @@ import wrapt
import logging
from builtins import range, bytes
-from octoprint.settings import settings
+import octoprint.settings
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
@@ -216,12 +216,11 @@ class UserManager(object):
##~~ FilebasedUserManager, takes available users from users.yaml file
class FilebasedUserManager(UserManager):
- def __init__(self, settingz=None):
+ def __init__(self, settings=None):
UserManager.__init__(self)
- if settingz is None:
- userfile = settings().get(["accessControl", "userfile"])
- else:
- userfile = settingz.get(["accessControl", "userfile"])
+ if settings is None:
+ settings = octoprint.settings.settings()
+ userfile = settings.get(["accessControl", "userfile"])
if userfile is None:
userfile = os.path.join(settings().getBaseFolder("base"), "users.yaml")
self._userfile = userfile
From 09e023917ca0f20232fbf7198a0a01834fe41e4e Mon Sep 17 00:00:00 2001
From: Aliaksei Pilko
Date: Fri, 19 Jul 2019 18:08:31 +0100
Subject: [PATCH 061/105] Amend settings ref
---
src/octoprint/users.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/users.py b/src/octoprint/users.py
index 72afb1d70..30cc67135 100644
--- a/src/octoprint/users.py
+++ b/src/octoprint/users.py
@@ -222,7 +222,7 @@ class FilebasedUserManager(UserManager):
settings = octoprint.settings.settings()
userfile = settings.get(["accessControl", "userfile"])
if userfile is None:
- userfile = os.path.join(settings().getBaseFolder("base"), "users.yaml")
+ userfile = os.path.join(settings.getBaseFolder("base"), "users.yaml")
self._userfile = userfile
self._users = {}
self._dirty = False
From f249563b2c7442934d74c84e83efa4f44514388c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 22 Jul 2019 13:57:09 +0200
Subject: [PATCH 062/105] =?UTF-8?q?=F0=9F=90=9B=20At=20least=20use=20confi?=
=?UTF-8?q?gured=20user=20manager=20class?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Making the plugin hook work would be a ton of overhead due to the
components dictionary that needs to be supplied to it for user manager
initialization, however at the very least we should support
configuration of the used user manager class.
Both features are rarely used if at all, but we should be aware of this.
Also changed some wording, fixed to unicode and removed redundancy from
the sub commands (e.g. just "add" instead of "add_user") and flags.
---
src/octoprint/cli/user.py | 71 ++++++++++++++++++++++++---------------
1 file changed, 44 insertions(+), 27 deletions(-)
diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py
index 32ea02482..07026c553 100644
--- a/src/octoprint/cli/user.py
+++ b/src/octoprint/cli/user.py
@@ -1,5 +1,5 @@
# coding=utf-8
-from __future__ import absolute_import, division, print_function
+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) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -11,6 +11,9 @@ import logging
from octoprint import init_settings
from octoprint.cli import get_ctx_obj_option
from octoprint.users import FilebasedUserManager, UnknownUser
+from octoprint.util import get_class
+
+click.disable_unicode_literals_warning = True
#~~ "octoprint user" commands
@@ -23,55 +26,69 @@ def user_commands():
@user_commands.group(name="user")
@click.pass_context
def user(ctx):
- """User account management"""
+ """
+ User management.
+
+ Note that this currently only supports managing user accounts stored in the configured user manager, not any
+ user managers added through plugins and the "octoprint.users.factory" hook.
+ """
try:
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
- settingz = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
- ctx.obj.users = FilebasedUserManager(settingz=settingz)
+ settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
+
+ name = settings.get(["accessControl", "userManager"])
+ try:
+ clazz = get_class(name)
+ manager = clazz(settings=settings)
+ except Exception:
+ click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True)
+ manager = FilebasedUserManager(settings=settings)
+ finally:
+ manager.enabled = settings.getBoolean(["accessControl", "enabled"])
+
+ ctx.obj.user_manager = manager
+
except Exception:
- click.echo("Could not instantiate user manager")
+ click.echo("Could not instantiate user manager", err=True)
return
-@user.command(name="add_user")
+@user.command(name="add")
@click.argument("username", type=click.STRING, required=True)
@click.password_option("--password", "password", help="Password for user")
-@click.option("--is-admin", "is_admin", type=click.BOOL, default=False,
- help="Sets user role as admin")
+@click.option("--admin", "is_admin", type=click.BOOL, default=False,
+ help="Sets admin role on user")
@click.pass_context
def add_user_command(ctx, username, password, is_admin):
- """Adds new user account"""
- ctx.obj.users.addUser(
- username,
- password,
- roles=("admin" if is_admin else "user"),
- active=True
- )
+ """Add a new user"""
+ ctx.obj.user_manager.addUser(username,
+ password,
+ roles=("admin" if is_admin else "user"),
+ active=True)
-@user.command(name="remove_user")
+@user.command(name="remove")
@click.argument("username", type=click.STRING)
@click.pass_context
def remove_user_command(ctx, username):
- """Removes user account"""
- confirm = click.prompt(
- "This is will irreversibly destroy the user account! Enter 'yes' to confirm",
- type=click.STRING)
+ """Remove a user"""
+ confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm",
+ type=click.STRING)
- if confirm == 'yes':
- ctx.obj.users.removeUser(username)
+ if confirm.lower() == "yes":
+ ctx.obj.user_manager.removeUser(username)
else:
- click.echo("User NOT removed")
+ click.echo("User not removed")
-@user.command(name="change_password")
+@user.command(name="password")
@click.argument("username", type=click.STRING)
@click.password_option("--password", "password", help="New password for user")
@click.pass_context
def change_password_command(ctx, username, password):
- """Changes an existing user password"""
+ """Changes an existing user's password"""
try:
- ctx.obj.users.changeUserPassword(username, password)
+ ctx.obj.user_manager.changeUserPassword(username, password)
except UnknownUser:
- click.echo("User does not exist!")
+ click.echo("This user does not exist!", err=True)
From 9976f2b7a3e870cc989496aaafaa07ed9a01b848 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 22 Jul 2019 14:00:54 +0200
Subject: [PATCH 063/105] =?UTF-8?q?=F0=9F=90=9B=20Fix=20a=20broken=20impor?=
=?UTF-8?q?t?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/octoprint/users.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/users.py b/src/octoprint/users.py
index 30cc67135..5b80b2e12 100644
--- a/src/octoprint/users.py
+++ b/src/octoprint/users.py
@@ -18,7 +18,7 @@ import wrapt
import logging
from builtins import range, bytes
-import octoprint.settings
+from octoprint.settings import settings
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
From accbfc2b45d42c40e2e6b1cf12c7be85ea8ca8b7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 22 Jul 2019 15:04:27 +0200
Subject: [PATCH 064/105] =?UTF-8?q?=F0=9F=90=9B=20Fix=20settings=20passing?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/octoprint/users.py | 43 ++++++++++++++++++++++++++----------------
1 file changed, 27 insertions(+), 16 deletions(-)
diff --git a/src/octoprint/users.py b/src/octoprint/users.py
index 5b80b2e12..82a2fa290 100644
--- a/src/octoprint/users.py
+++ b/src/octoprint/users.py
@@ -18,19 +18,23 @@ import wrapt
import logging
from builtins import range, bytes
-from octoprint.settings import settings
+from octoprint.settings import settings as s
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
class UserManager(object):
valid_roles = ["user", "admin"]
- def __init__(self):
+ def __init__(self, settings=None):
self._logger = logging.getLogger(__name__)
self._session_users_by_session = dict()
self._sessionids_by_userid = dict()
self._enabled = True
+ if settings is None:
+ settings = s()
+ self._settings = settings
+
self._callbacks = []
@property
@@ -128,16 +132,18 @@ class UserManager(object):
self.logout_user(user)
@staticmethod
- def createPasswordHash(password, salt=None):
+ def createPasswordHash(password, salt=None, settings=None):
if not salt:
- salt = settings().get(["accessControl", "salt"])
+ if settings is None:
+ settings = s()
+ salt = settings.get(["accessControl", "salt"])
if salt is None:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
salt = "".join(choice(chars) for _ in range(32))
- settings().set(["accessControl", "salt"], salt)
- settings().save()
+ settings.set(["accessControl", "salt"], salt)
+ settings.save()
return hashlib.sha512(to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)).hexdigest()
@@ -146,13 +152,15 @@ class UserManager(object):
if not user:
return False
- hash = UserManager.createPasswordHash(password)
+ hash = UserManager.createPasswordHash(password,
+ settings=self._settings)
if user.check_password(hash):
# new hash matches, correct password
return True
else:
# new hash doesn't match, but maybe the old one does, so check that!
- oldHash = UserManager.createPasswordHash(password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW")
+ oldHash = UserManager.createPasswordHash(password,
+ salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW")
if user.check_password(oldHash):
# old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
self.changeUserPassword(username, password)
@@ -216,13 +224,11 @@ class UserManager(object):
##~~ FilebasedUserManager, takes available users from users.yaml file
class FilebasedUserManager(UserManager):
- def __init__(self, settings=None):
- UserManager.__init__(self)
- if settings is None:
- settings = octoprint.settings.settings()
- userfile = settings.get(["accessControl", "userfile"])
+ def __init__(self, **kwargs):
+ UserManager.__init__(self, **kwargs)
+ userfile = self._settings.get(["accessControl", "userfile"])
if userfile is None:
- userfile = os.path.join(settings.getBaseFolder("base"), "users.yaml")
+ userfile = os.path.join(self._settings.getBaseFolder("base"), "users.yaml")
self._userfile = userfile
self._users = {}
self._dirty = False
@@ -277,7 +283,11 @@ class FilebasedUserManager(UserManager):
if username in self._users.keys() and not overwrite:
raise UserAlreadyExists(username)
- self._users[username] = User(username, UserManager.createPasswordHash(password), active, roles, apikey=apikey)
+ self._users[username] = User(username,
+ UserManager.createPasswordHash(password, settings=self._settings),
+ active,
+ roles,
+ apikey=apikey)
self._dirty = True
self._save()
@@ -328,7 +338,8 @@ class FilebasedUserManager(UserManager):
if not username in self._users.keys():
raise UnknownUser(username)
- passwordHash = UserManager.createPasswordHash(password)
+ passwordHash = UserManager.createPasswordHash(password,
+ settings=self._settings)
user = self._users[username]
if user._passwordHash != passwordHash:
user._passwordHash = passwordHash
From c6c5328418354d2694476a2bf248d0bd7d61e52e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 22 Jul 2019 15:05:51 +0200
Subject: [PATCH 065/105] =?UTF-8?q?=E2=9C=A8=20Add=20list/activate/deactiv?=
=?UTF-8?q?ate=20commands?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/octoprint/cli/user.py | 83 ++++++++++++++++++++++++++++++++++-----
1 file changed, 73 insertions(+), 10 deletions(-)
diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py
index 07026c553..c35b518e3 100644
--- a/src/octoprint/cli/user.py
+++ b/src/octoprint/cli/user.py
@@ -10,7 +10,7 @@ import logging
from octoprint import init_settings
from octoprint.cli import get_ctx_obj_option
-from octoprint.users import FilebasedUserManager, UnknownUser
+from octoprint.users import FilebasedUserManager, UnknownUser, UserAlreadyExists
from octoprint.util import get_class
click.disable_unicode_literals_warning = True
@@ -53,6 +53,14 @@ def user(ctx):
return
+@user.command(name="list")
+@click.pass_context
+def list_users_command(ctx):
+ """Lists user information"""
+ users = ctx.obj.user_manager.getAllUsers()
+ _print_list(users)
+
+
@user.command(name="add")
@click.argument("username", type=click.STRING, required=True)
@click.password_option("--password", "password", help="Password for user")
@@ -60,25 +68,34 @@ def user(ctx):
help="Sets admin role on user")
@click.pass_context
def add_user_command(ctx, username, password, is_admin):
- """Add a new user"""
- ctx.obj.user_manager.addUser(username,
- password,
- roles=("admin" if is_admin else "user"),
- active=True)
+ """Add a new user."""
+ try:
+ ctx.obj.user_manager.addUser(username,
+ password,
+ roles=(("user", "admin") if is_admin else ("user",)),
+ active=True)
+
+ user = ctx.obj.user_manager.findUser(username)
+ if user:
+ click.echo("User created:")
+ click.echo("\t{}".format(_user_to_line(user.asDict())))
+ except UserAlreadyExists:
+ click.echo("A user with the name {} does already exist!".format(username), err=True)
@user.command(name="remove")
@click.argument("username", type=click.STRING)
@click.pass_context
def remove_user_command(ctx, username):
- """Remove a user"""
+ """Remove an existing user."""
confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm",
type=click.STRING)
if confirm.lower() == "yes":
ctx.obj.user_manager.removeUser(username)
+ click.echo("User {} removed.".format(username))
else:
- click.echo("User not removed")
+ click.echo("User {} not removed.".format(username))
@user.command(name="password")
@@ -86,9 +103,55 @@ def remove_user_command(ctx, username):
@click.password_option("--password", "password", help="New password for user")
@click.pass_context
def change_password_command(ctx, username, password):
- """Changes an existing user's password"""
+ """Change an existing user's password."""
try:
ctx.obj.user_manager.changeUserPassword(username, password)
+ click.echo("Password changed for user {}.".format(username))
except UnknownUser:
- click.echo("This user does not exist!", err=True)
+ click.echo("User {} does not exist!".format(username), err=True)
+
+@user.command(name="activate")
+@click.argument("username", type=click.STRING)
+@click.pass_context
+def activate_command(ctx, username):
+ """Activate a user account."""
+ try:
+ ctx.obj.user_manager.changeUserActivation(username, True)
+ click.echo("User {} activated.".format(username))
+
+ user = ctx.obj.user_manager.findUser(username)
+ if user:
+ click.echo("User created:")
+ click.echo("\t{}".format(_user_to_line(user.asDict())))
+ except UnknownUser:
+ click.echo("User {} does not exist!".format(username), err=True)
+
+
+@user.command(name="deactivate")
+@click.argument("username", type=click.STRING)
+@click.pass_context
+def deactivate_command(ctx, username):
+ """Activate a user account."""
+ try:
+ ctx.obj.user_manager.changeUserActivation(username, False)
+ click.echo("User {} activated.".format(username))
+
+ user = ctx.obj.user_manager.findUser(username)
+ if user:
+ click.echo("User created:")
+ click.echo("\t{}".format(_user_to_line(user.asDict())))
+ except UnknownUser:
+ click.echo("User {} does not exist!".format(username), err=True)
+
+
+def _print_list(users):
+ click.echo("{} users registered in the system:".format(len(users)))
+ for user in sorted(users, key=lambda x: x.get("name")):
+ click.echo("\t{}".format(_user_to_line(user)))
+
+
+def _user_to_line(user):
+ return "{} (active: {}, admin: {})".format(user.get("name"),
+ "yes" if user.get("active", False) else "no",
+ "yes" if user.get("admin", False) else "no")
From f67f9b93992537f9a6f4089c85bb85dfdd561066 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 22 Jul 2019 15:06:09 +0200
Subject: [PATCH 066/105] =?UTF-8?q?=F0=9F=90=9B=20Fix=20--admin=20flag=20o?=
=?UTF-8?q?n=20add=20command?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/octoprint/cli/user.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py
index c35b518e3..fcf4cac74 100644
--- a/src/octoprint/cli/user.py
+++ b/src/octoprint/cli/user.py
@@ -64,7 +64,7 @@ def list_users_command(ctx):
@user.command(name="add")
@click.argument("username", type=click.STRING, required=True)
@click.password_option("--password", "password", help="Password for user")
-@click.option("--admin", "is_admin", type=click.BOOL, default=False,
+@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False,
help="Sets admin role on user")
@click.pass_context
def add_user_command(ctx, username, password, is_admin):
From e007dbaf4c8cb1624bb2a1739c3028ca156bbd7e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 29 Jul 2019 13:27:08 +0200
Subject: [PATCH 067/105] =?UTF-8?q?=F0=9F=90=9B=20Fix=20file=20selection?=
=?UTF-8?q?=20not=20being=20cleared=20on=20disconnect?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3224
---
src/octoprint/static/js/app/viewmodels/files.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js
index 088d4104a..325771fbe 100644
--- a/src/octoprint/static/js/app/viewmodels/files.js
+++ b/src/octoprint/static/js/app/viewmodels/files.js
@@ -200,7 +200,7 @@ $(function() {
};
self.highlightFilename = function(filename) {
- if (filename === undefined) {
+ if (filename === undefined || filename === null) {
self.listHelper.selectNone();
} else {
self.listHelper.selectItem(function(item) {
From 372b3662e9ecd5c2d02a4a97b1b05eb61658d619 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 29 Jul 2019 16:37:20 +0200
Subject: [PATCH 068/105] =?UTF-8?q?=F0=9F=93=9D=20Add=20docs=20for=20print?=
=?UTF-8?q?TimeLeftOrigin=20field?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3203
---
docs/api/datamodel.rst | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst
index a55554e9e..2af4f727f 100644
--- a/docs/api/datamodel.rst
+++ b/docs/api/datamodel.rst
@@ -218,6 +218,17 @@ Progress information
- 1
- Integer
- Estimate of time left to print, in seconds
+ * - ``printTimeLeftOrigin``
+ - 1
+ - String
+ - Origin of the current time left estimate. Can currently be either of:
+
+ * ``linear``: based on an linear approximation of the progress in file in bytes vs time
+ * ``analysis``: based on an analysis of the file
+ * ``estimate``: calculated estimate after stabilization of linear estimation
+ * ``average``: based on the average total from past prints of the same model against the same printer profile
+ * ``mixed-analysis``: mixture of ``estimate`` and ``analysis``
+ * ``mixed-average``: mixture of ``estimate`` and ``average``
.. _sec-api-datamodel-files:
From 89255e2ec9cae74570383cf587970b8be9281936 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 29 Jul 2019 16:52:05 +0200
Subject: [PATCH 069/105] =?UTF-8?q?=E2=98=94=20Harden=20against=20corrupt?=
=?UTF-8?q?=20recovery=20data?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #3199
---
src/octoprint/filemanager/__init__.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py
index 6551d7090..e54eb8054 100644
--- a/src/octoprint/filemanager/__init__.py
+++ b/src/octoprint/filemanager/__init__.py
@@ -658,6 +658,8 @@ class FileManager(object):
try:
with open(self._recovery_file) as f:
data = yaml.safe_load(f)
+ if not isinstance(data, dict) or not all(map(lambda x: x in data, ("origin", "path", "pos", "date"))):
+ raise ValueError("Invalid recovery data structure")
return data
except:
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
From 4c602cba2e0fe055009de9a00c6265aff0383666 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 29 Jul 2019 16:55:32 +0200
Subject: [PATCH 070/105] =?UTF-8?q?=E2=98=94=20Further=20hardening=20again?=
=?UTF-8?q?st=20corrupt=20recovery=20data?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/octoprint/printer/standard.py | 18 +++++++++++-------
1 file changed, 11 insertions(+), 7 deletions(-)
diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py
index 55176befa..107ebebad 100644
--- a/src/octoprint/printer/standard.py
+++ b/src/octoprint/printer/standard.py
@@ -483,14 +483,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
path_on_disk = self._fileManager.path_on_disk(origin, path)
path_in_storage = self._fileManager.path_in_storage(origin, path_on_disk)
- recovery_data = self._fileManager.get_recovery_data()
- if recovery_data:
- # clean up recovery data if we just selected a different file than is logged in that
- actual_origin = recovery_data.get("origin", None)
- actual_path = recovery_data.get("path", None)
+ try:
+ recovery_data = self._fileManager.get_recovery_data()
+ if recovery_data:
+ # clean up recovery data if we just selected a different file
+ actual_origin = recovery_data.get("origin", None)
+ actual_path = recovery_data.get("path", None)
- if actual_origin is None or actual_path is None or actual_origin != origin or actual_path != path_in_storage:
- self._fileManager.delete_recovery_data()
+ if actual_origin is None or actual_path is None or actual_origin != origin or actual_path != path_in_storage:
+ self._fileManager.delete_recovery_data()
+ except Exception:
+ # anything goes wrong with the recovery data, we ignore it
+ self._logger.exception("Something was wrong with processing the recovery data")
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
From 0e67906d1e818fcb42a4f8c35f0f8ba57f99960a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 29 Jul 2019 17:28:36 +0200
Subject: [PATCH 071/105] =?UTF-8?q?=E2=99=BB=20tracking:=20Send=20plugin?=
=?UTF-8?q?=20list=20only=20once=20per=20day?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/octoprint/plugins/tracking/__init__.py | 33 ++++++++++++++-----
.../templates/tracking_settings.jinja2 | 5 ++-
2 files changed, 28 insertions(+), 10 deletions(-)
diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py
index 732ebefbe..3655aef66 100644
--- a/src/octoprint/plugins/tracking/__init__.py
+++ b/src/octoprint/plugins/tracking/__init__.py
@@ -44,6 +44,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._printer_connection_parameters = None
self._url = None
self._ping_worker = None
+ self._pong_worker = None
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
self._record_next_firmware_info = False
@@ -60,7 +61,9 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
unique_id=None,
server=TRACKING_URL,
ping=15*60,
- events=dict(startup=True,
+ pong=24*60*60,
+ events=dict(pong=True,
+ startup=True,
printjob=True,
commerror=True,
plugin=True,
@@ -172,10 +175,16 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
return
if self._ping_worker is None:
- ping = self._settings.get_int(["ping"])
- if ping:
- self._ping_worker = RepeatedTimer(ping, self._track_ping, run_first=True)
+ ping_interval = self._settings.get_int(["ping"])
+ if ping_interval:
+ self._ping_worker = RepeatedTimer(ping_interval, self._track_ping, run_first=True)
self._ping_worker.start()
+
+ if self._pong_worker is None:
+ pong_interval = self._settings.get(["pong"])
+ if pong_interval:
+ self._pong_worker = RepeatedTimer(pong_interval, self._track_pong, run_first=True)
+ self._pong_worker.start()
if self._helpers_get_throttle_state is None:
# cautiously look for the get_throttled helper from pi_support
@@ -193,6 +202,16 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
uptime = int(monotonic_time() - self._startup_time)
self._track("ping", octoprint_uptime=uptime)
+ def _track_pong(self):
+ if not self._settings.get_boolean(["events", "pong"]):
+ return
+
+ plugins = self._plugin_manager.enabled_plugins
+ plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled]
+ payload = dict(plugins=",".join(map(lambda x: "{}:{}".format(x.key.lower(), x.version.lower()), plugins_thirdparty)))
+
+ self._track("pong", body=True, **payload)
+
def _track_startup(self):
if not self._settings.get_boolean(["events", "startup"]):
return
@@ -211,11 +230,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
if b"octopi_version" in self._environment[b"plugins"][b"pi_support"]:
payload[b"octopi_version"] = self._environment[b"plugins"][b"pi_support"][b"octopi_version"]
- plugins = self._plugin_manager.enabled_plugins
- plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled]
- payload[b"plugins"] = ",".join(map(lambda x: "{}:{}".format(x.key.lower(), x.version.lower()), plugins_thirdparty))
-
- self._track("startup", body=True, **payload)
+ self._track("startup", **payload)
def _track_shutdown(self):
if not self._settings.get_boolean([b"enabled"]):
diff --git a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2
index 9d1d572a9..f0057ecd7 100644
--- a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2
+++ b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2
@@ -20,7 +20,10 @@