Merge branch 'maintenance' into devel

This commit is contained in:
Gina Häußge committed 2021-12-06 16:25:53 +01:00
commit 0dba51181c
64 files changed
+1241 -273

No files matched your search

+2 -2
View File
@@ -50,7 +50,7 @@ jobs:
name: 🧪 Unit tests
strategy:
matrix:
python: ["3.7", "3.8", "3.9"]
python: ["3.7", "3.8", "3.9", "3.10"]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
@@ -70,7 +70,7 @@ jobs:
needs: build
strategy:
matrix:
python: ["3.7", "3.8", "3.9"]
python: ["3.7", "3.8", "3.9", "3.10"]
installable: ["wheel", "sdist"]
runs-on: ubuntu-latest
steps:
+13 -8
View File
@@ -109,6 +109,11 @@ jobs:
issue_number: context.issue.number,
})
const comment = comments.data.find(c => c.user.login === "github-actions[bot]" && c.body.includes(marker));
if (comment) {
console.log("Found comment, id=" + comment.id);
} else {
console.log("No comment found");
}
if (!labels.includes("triage") || labels.includes("approved")) {
console.log("Deleting comment if it exists...");
@@ -127,20 +132,20 @@ jobs:
if (!found) {
console.log("No bundle found, posting/updating reminder");
const text = REMINDER + "\n" + marker;
if (comment && comment.body !== text) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: comment.id,
body: text
});
} else {
if (!comment) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: text
});
} else if (comment.body !== text) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: comment.id,
body: text
});
}
} else if (found && comment) {
console.log("Bundle found, saying thanks");
+2 -2
View File
@@ -14,7 +14,7 @@ jobs:
strategy:
matrix:
os: ["ubuntu-latest"]
python: ["3.7", "3.8", "3.9"]
python: ["3.7", "3.8", "3.9", "3.10"]
branch: ["master"]
runs-on: ${{ matrix.os }}
steps:
@@ -49,7 +49,7 @@ jobs:
strategy:
matrix:
os: ["ubuntu-latest"]
python: ["3.7", "3.8", "3.9"]
python: ["3.7", "3.8", "3.9", "3.10"]
runs-on: ${{ matrix.os }}
steps:
- name: 👀 Determine latest release
+3
View File
@@ -154,6 +154,9 @@ date of first contribution):
* [Bryan Kenote](https://github.com/bryankenote)
* [Quinn Damerell](https://github.com/QuinnDamerell)
* [Sven Samoray](https://github.com/thelastWallE)
* [Christian Würthner](https://github.com/crysxd)
* [Maciej Urbański](https://github.com/rooterkyberian)
* [Adam Wolf](https://github.com/adamwolf)
* [Carey Metcalfe](https://github.com/pR0Ps)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
+1 -1
View File
@@ -97,7 +97,7 @@ following section *completely* and also follow the instructions in the
**safe mode**, either by selecting "Restart OctoPrint in safe mode" from
the "System" menu, or by starting OctoPrint from the command line with
`octoprint serve --safe`. Then try to reproduce your issue. Find out
more about safe mode in the [docs](http://docs.octoprint.org/en/master/features/safemode.html).
more about safe mode in the [docs](https://docs.octoprint.org/en/master/features/safemode.html).
You might also want to try the current development version of OctoPrint
(if you aren't already). Refer to the [FAQ](https://faq.octoprint.org)
+5 -5
View File
@@ -17,7 +17,7 @@
</p>
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
and released under the [GNU Affero General Public License V3](https://www.gnu.org/licenses/agpl-3.0.html).
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
@@ -27,7 +27,7 @@ An invite to the Discord server can be found at [discord.octoprint.org](https://
The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme).
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
The documentation is located at [docs.octoprint.org](https://docs.octoprint.org).
The official plugin repository can be reached at [plugins.octoprint.org](https://plugins.octoprint.org/?utm_source=github&utm_medium=readme).
@@ -38,14 +38,14 @@ 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/) might be of more interest for you. You might also want to subscribe to join
want to find out how to use it, [the documentation](https://docs.octoprint.org/) 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.
## Contributing
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/), debugging help
[official documentation](https://docs.octoprint.org/), debugging help
in the [bug tracker](https://github.com/OctoPrint/OctoPrint/issues), support of other users on
[the community forum at community.octoprint.org](https://community.octoprint.org) or
[the official discord at discord.octoprint.org](https://discord.octoprint.org)
@@ -140,7 +140,7 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows
at `~/Library/Application Support/OctoPrint` on MacOS.
A comprehensive overview of all available configuration settings can be found
[in the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html).
[in the docs](https://docs.octoprint.org/en/master/configuration/config_yaml.html).
Please note that the most commonly used configuration settings can also easily
be edited from OctoPrint's settings dialog.
+64 -1
View File
@@ -50,7 +50,70 @@ Clients must ignore any unknown messages.
The data model of the attached payloads is described further below.
OctoPrint's SockJS socket also accepts two commands from the client to the server.
OctoPrint's SockJS socket also accepts three commands from the client to the server.
* ``subscribe`` (since 1.8.0): With the ``subscribe`` message, clients may selectively
subscribe to certain message types. The payload should be a dict of message types with
supported keys as follows:
* ``state``: Either a boolean value indicating whether to generally receive state updates (``current`` and ``history``)
or not, or a dict with further options for received state updates. Currently the following options are recognized here:
* ``logs``: A boolean value whether to include all log lines (``True``, default) or not (``False``). Alternatively a string with
a regex pattern can be provided, in which case only log lines matching the pattern will be returned.
* ``messages``: Like ``logs`` but for the returned message lines.
* ``plugins``: Either a boolean value indicating whether to generally receive plugin messages, or a list of plugin
identifiers to receive plugin messages for.
* ``events``: Either a boolean value indicating whether to generally receive event messages, or a list of event
types to receive event messages for.
If you send a ``subscribe`` message, OctoPrint will default the connection to not subscribe you to anything you did't explicitly
request. ``subscribe`` messages do replace previous ones.
Example for a ``subscribe`` message subscribing only to updates from plugin ``example`` but neither state nor events:
.. sourcecode:: javascript
{
"subscribe": {
"plugins": ["example"]
}
}
Example for a ``subscribe`` message subscribing to state, event and plugin updates,
but filtering logs in state updates to only contain lines matching ``^Recv: Cap`` and also
filtering out all messages:
.. sourcecode:: javascript
{
"subscribe": {
"state": {
"logs": "^Recv: Cap",
"messages": false
},
"events": true,
"plugins": true
}
}
Example for a ``subscribe`` message subscribing only to events of type ``PrintFailed``:
.. sourcecode:: javascript
{
"subscribe": {
"events": ["PrintFailed"]
}
}
.. note::
Per default, OctoPrint will subscribe connecting clients to all state, event and plugin updates
without any filtering in place. If you wish to have your more selective subscription active
right from the start of your socket session, be sure to send the ``subscribe`` message
**before** the ``auth`` message.
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
existing user session with the socket. That is of special importance to receive
+4 -4
View File
@@ -134,7 +134,7 @@ Open the Git Bash you just installed and in that:
cd /c/Devel
git clone https://github.com/OctoPrint/OctoPrint.git
cd OctoPrint
virtualenv --python=C:\Python38\python.exe venv
virtualenv --python=C:/Python3/python.exe venv3
source ./venv/Scripts/activate
python -m pip install --upgrade pip
python -m pip install -e '.[develop,plugins,docs]'
@@ -394,7 +394,7 @@ Visual Studio Code (vscode)
}
]
}
In the terminal install the python extension by running this command:
.. code-block:: bash
@@ -414,7 +414,7 @@ Visual Studio Code (vscode)
* Your terminal inside vscode uses the virtual python environment
* Saving a file will run an auto formatter and import sort
* ``Ctrl+Shift+B`` can be used to run the ``build docs`` task to rebuild the documentation
+1
View File
@@ -184,6 +184,7 @@ further down there's also a dedicated list of steps for OctoPi specifically.
autologinAs: "<yourUsername>"
localNetworks:
- "127.0.0.0/8"
- "::1/128"
- "<yourAddressRange>"
4. Restart OctoPrint, check that everything works.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Do not edit this file with editors other than diagrams.net -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" style="background-color: rgb(255, 255, 255);" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="800px" height="436px" viewBox="-0.5 -0.5 800 436" content="&lt;mxfile host=&quot;app.diagrams.net&quot; modified=&quot;2021-11-30T12:48:38.412Z&quot; agent=&quot;5.0 (Windows)&quot; version=&quot;15.8.7&quot; etag=&quot;dRCYf0ldIAGVQo3_ZfcA&quot; type=&quot;google&quot;&gt;&lt;diagram id=&quot;KSxbcLmsFqmVZw95xxym&quot; name=&quot;Page-1&quot;&gt;7VxZb+M2EP41ebSh2/Zjkj1aYAsskId2nxa0RdtsJFGl6Fy/vqREHbxsyZYdp1sDgaUhRXGObzhDjnPj36cvXwnIt3/gGCY3nhO/3Pifbjz2Cebsi1NeK8p85lWEDUFxRXJbwgN6g4LoCOoOxbCQOlKME4pymbjCWQZXVKIBQvCz3G2NE/FWMX4ONlDqwQkPK5Do1D9RTLeCCy9q6b9BtNnWb3ajRdWSgrqzeFOxBTF+7pD8zzf+PcGYVlfpyz1MuPCQNMMvltZmYgRmtM8D3tzxYhA7UewvHehMfKGIgr7WzMKY8S5uMaFbvMEZSD631DuCd1kM+YgOu9vSNGGXLruEL4j+xcnTWShuf9RNGSWvVVtY3/4QI+hMCL4KvCMrMS1hQhSQDaQWZoSQOQedcYQkvkKcQvZW1oHABFD0JGsXCCPZNP3Eo7eEgNdOhxyjjBadkb9zAusg7H3iR2E1pDB3f6YoRXtgsfcBdlHNob7rMNOSSk2btS7s9AkkO8GzrvUkYWiCsj6Ztea8vWBSpw8UUN6+RklyjxNMygd9p/zwzpTgR2hqser3CRIKX/aqqhZRUPsCIaJASOy5xWOt/m0HijXNpNyOePdKb9ZDegcx05Eq5xox53KboE3GaEtMKU5LUMS33FvxQXKYVRThDed7JXwyuiIdXfOzgOmw8bt+KI9RTUo81qrNDktJscOQ0lhmq+wEg1hTODNbKmuVwAK9gWXZoRS7fweEgldM8pAYNJ+iOC6tIwFLmNyB1eOm9K0dFa/Lz0B41RarwqtZIcU8pUXICDtn6srKqe5O1bk86MSXB8DrdQHpiZqca4qMUcH51pXZrmdckc9bROFDDkpoPLOARtbzko83hkMLFbN3dY/megaXFo3g0haacGB2xbLxZheUjetqQhghJKqvf8hOumlqPHbZdsRaeiBWWpzFmw8PjTx5GXfFOm4PjZQHfCdUlHlaaOT6Fih8MJfv2lB2lM93XcXtj+T3ozM4evc8KYwdr84QvG4xQW84o8AW/TUG0QvZCx3Z54nTBiM7mO0F6uEHFFdwOrIDWwTw0aDtjQVtZ+oEQSBJfRKOg2wlPTsP0vWY7saLEq66nEBJpdE/O76lcsc1OxGau+VslrFC08yuNuK7HKbIQWYcJ0EZnNSRBh/InXr2Yda4lM0arORRvu1WKAas5R5nBeaG2I5geCkfZlKU+V/5Sid/0d+ZJ7sNyn6mIAMbSKbVbVHPhIm0mow8QUauWNXIpSBrqgKTejtgtSPJ6x1hBs59kDEolMNGu7VroKrY5TtIfrmH1MFkCavvuEAUYf5MAte0A8NvSnMDRytOCaZAdNZc9Vj7FrOF4uUMYb4pkm2Ip4Synu4Ca1XH6KmnoYcsHFiwz3wehuHC5TZYCcdRwVUqZFRQdE182njvQ6Zd8iZT343dVWP0bcfS/NkyoD0bQwI3qOBIYNaA8WMPHP83mEVpnsCU4awC5Ifi+niLlrme4uyn8ObtVsUgQVj8dYbLjdsDyXvlpOvzDbfjnIWj5TMQu5Eul5eyEXxcbDPcoUaKQ50bHGpo8KjzMRyqaSf9w5pfneh+JLANcjG/kDf96L7UMAlrMF7GxWuQouS1Gpo1gTSvBOQHfJ41BFYNBOQOzSx7cTTUfTebqXuj7ePxW4+wJAZ19tfytejeyMa7zux3hrAvbKHgmy8cQk55vSYghc+YPHJ/UrXyg1GuaGeXl+Ptm/4ywatH/iJzqpoCwmynmpXT+QuczvSXmMQ8T+KdMpzBpiEHcYyyjXjcZLTvjO1ebwymVaywCP1oFvj72BiUqkfjOluU/c3LTDwnhjlkeW62QpCbA8ooPsIBW1LxK0bsWTQ6djiNMkQRY+ntuBDHSu3ieGyPbpmhYSLvuHr8CmlGky7UaUbo62lGYEgz3GA2Qp6hVDYZDmwPQXEYoEf2phfc+ZxW9Rlj+NiT7PoqrdhXzljq3Ll7jm4qmwrGyJUt1XlHV6HxYqija9AU9YwhXK0kzdele66aNE24vi7LMeo4vdHrOA0nmNdaxxl4V1bHqQoq0CG1y66+Xq3rGj2j2dise4wTUD+aL2Ql3Zx0ADrqCafG+PADnF9m3a8t/ZpXfu9qVv7AMZTQXWzp71OA3hY/lxsbzMJBsW2OkDvyVgW8rzDHKkpp/Yl6rjcd2ZlOGGrayRXRSs2bppNqPdUqovWRQiWLUUMPS2n1GJ6rT9X8O6rckmBdjQkoZQPq4VV/C9D8wMUswFStM54FWOtqrfrvRqF1ZcS16DtScgnXOVbhalndJTVu2qW4Xsz7V2YDKuYDtQSoP+gjFfQXs4HAM9jAsIj12Bo9Y/AotrfPe2QYTec8dHPdIAichdejTE+cEP7Uy/VOCFd71OV1E8CeJXoqDutwt1LTGcryrGAeEP6Gij81/YLE+AOS0A7bY6PfQP+JwYWSuHe3eiU9HKfEtS6OMoBn/BTwf0xZMdW3lPUITLHb9jfx1arU/mcB//O/&lt;/diagram&gt;&lt;/mxfile&gt;"><defs><linearGradient x1="0%" y1="0%" x2="0%" y2="100%" id="mx-gradient-dae8fc-1-7ea6e0-1-s-0"><stop offset="0%" style="stop-color: rgb(218, 232, 252); stop-opacity: 1;"/><stop offset="100%" style="stop-color: rgb(126, 166, 224); stop-opacity: 1;"/></linearGradient><linearGradient x1="0%" y1="0%" x2="0%" y2="100%" id="mx-gradient-ffffff-0.9-ffffff-0.1-s-0"><stop offset="0%" style="stop-color: rgb(255, 255, 255); stop-opacity: 0.9;"/><stop offset="100%" style="stop-color: rgb(255, 255, 255); stop-opacity: 0.1;"/></linearGradient></defs><g><path d="M 464 140 L 464 335 L 434 335 L 434 388.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 434 393.88 L 430.5 386.88 L 434 388.63 L 437.5 386.88 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/><ellipse cx="434" cy="25" rx="11" ry="11" fill="#000000" stroke="#000000" pointer-events="all"/><path d="M 434 40 L 434 77.76" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 429.5 69.88 L 434 78.88 L 438.5 69.88" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="all"/><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 56px; margin-left: 435px;"><div style="box-sizing: border-box; font-size: 0px; text-align: center;" data-drawio-colors="color: rgb(0, 0, 0); background-color: #ffffff; "><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; background-color: rgb(255, 255, 255); white-space: nowrap;">load</div></div></div></foreignObject><text x="435" y="59" fill=Line truncated

After

Width:  |  Height:  |  Size: 23 KiB

+1 -1
View File
@@ -7,7 +7,7 @@ Welcome to OctoPrint's documentation!
:align: right
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
and released under the `GNU Affero General Public License V3 <http://www.gnu.org/licenses/agpl.html>`_.
and released under the `GNU Affero General Public License V3 <https://www.gnu.org/licenses/agpl-3.0.html>`_.
Its website can be found at `octoprint.org <https://octoprint.org/>`_.
+1 -1
View File
@@ -52,6 +52,6 @@ regardless of whether the plugin requires a restart of OctoPrint to be fully uni
that the Plugin Manager is not the only way to uninstall a plugin from the system, a user may also uninstall it
manually through the command line, circumventing Plugin Manager completely.
.. image:: ../images/plugins_lifecycle.png
.. image:: ../images/plugins_lifecycle.svg
:align: center
:alt: The lifecycle of OctoPrint plugins.
+10 -8
View File
@@ -52,17 +52,16 @@ INSTALL_REQUIRES = [
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.7,<6",
"Click>=7.1.2,<8",
"psutil>=5.8,<6",
"Click>=8.0.3,<9",
"feedparser>=6.0.8,<7",
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
"websocket-client>=0.57,<1",
"websocket-client>=1.2.1,<2",
"wrapt>=1.12.1,<2",
"emoji>=0.5.4,<1",
"immutabledict>=2.1,<3",
"sentry-sdk>=0.15.1,<1",
"emoji>=1.4.2,<2",
"sentry-sdk>=1.5.0,<2",
"filetype>=1.0.7,<2",
"zeroconf>=0.33,<0.34",
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
"zipstream-ng>=1.3.1,<2.0.0",
"pathvalidate>=2.4.1,<3",
"colorlog>=5.0.1,<6",
@@ -80,7 +79,8 @@ INSTALL_REQUIRES_OSX = [
EXTRA_REQUIRES = {
"develop": [
# Testing dependencies
"pytest>=5.4.3,<6",
"mock>=4,<5",
"pytest>=6.2.5,<7",
"pytest-doctest-custom>=1.0.0,<2",
"ddt",
# pre-commit
@@ -230,6 +230,8 @@ def params():
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
+26 -3
View File
@@ -1,7 +1,8 @@
__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) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import datetime
import logging
import os
@@ -13,7 +14,9 @@ from octoprint.cli import init_platform_for_cli, standard_options
click.disable_unicode_literals_warning = True
def get_systeminfo(environment_detector, connectivity_checker, additional_fields=None):
def get_systeminfo(
environment_detector, connectivity_checker, settings, additional_fields=None
):
from octoprint import __version__
from octoprint.util import dict_flatten
@@ -22,10 +25,30 @@ def get_systeminfo(environment_detector, connectivity_checker, additional_fields
environment_detector.run_detection(notify_plugins=False)
safe_mode_file = os.path.join(settings.getBaseFolder("data"), "last_safe_mode")
last_safe_mode = {"date": "unknown", "reason": "unknown"}
try:
if os.path.exists(safe_mode_file):
with open(safe_mode_file) as f:
last_safe_mode["reason"] = f.readline().strip()
last_safe_mode["date"] = (
datetime.datetime.utcfromtimestamp(
os.path.getmtime(safe_mode_file)
).isoformat()[:19]
+ "Z"
)
except Exception as ex:
logging.getLogger(__name__).error(
"Error while retrieving last safe mode information from {}: {}".format(
safe_mode_file, ex
)
)
systeminfo = {
"octoprint": {"version": __version__},
"octoprint": {"version": __version__, "last_safe_mode": last_safe_mode},
"connectivity": connectivity_checker.as_dict(),
"env": environment_detector.environment,
"systeminfo": {"generated": datetime.datetime.utcnow().isoformat()[:19] + "Z"},
}
# flatten and filter
+1 -1
View File
@@ -834,7 +834,7 @@ class PluginManager:
processed_blacklist = []
for entry in plugin_blacklist:
if isinstance(entry, tuple):
if isinstance(entry, (tuple, list)):
key, version = entry
try:
processed_blacklist.append(
+66 -4
View File
@@ -7,10 +7,15 @@ import flask
from flask_babel import gettext
import octoprint.plugin
from octoprint.access import ADMIN_GROUP
from octoprint.access import ADMIN_GROUP, USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.server import NO_CONTENT, admin_permission, current_user
from octoprint.server.util.flask import no_firstrun_access, restricted_access
from octoprint.server.util import require_login_with
from octoprint.server.util.flask import (
add_non_caching_response_headers,
no_firstrun_access,
restricted_access,
)
from octoprint.settings import valid_boolean_trues
from octoprint.util import ResettableTimer, atomic_write, generate_api_key, yaml
@@ -120,7 +125,14 @@ class AppKeysPlugin(
"roles": ["admin"],
"dangerous": True,
"default_groups": [ADMIN_GROUP],
}
},
{
"key": "GRANT",
"name": "Grant access",
"description": gettext("Allows to grant app access"),
"roles": ["user"],
"default_groups": [USER_GROUP],
},
]
##~~ TemplatePlugin
@@ -164,6 +176,9 @@ class AppKeysPlugin(
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
auth_dialog = flask.url_for(
"plugin.appkeys.handle_auth_dialog", app_token=app_token, _external=True
) + (f"?user={user_id}" if user_id else "")
self._plugin_manager.send_plugin_message(
self._identifier,
@@ -174,7 +189,7 @@ class AppKeysPlugin(
"user_id": user_id,
},
)
response = flask.jsonify(app_token=app_token)
response = flask.jsonify(app_token=app_token, auth_dialog=auth_dialog)
response.status_code = 201
response.headers["Location"] = flask.url_for(
".handle_decision_poll", app_token=app_token, _external=True
@@ -199,12 +214,59 @@ class AppKeysPlugin(
return flask.abort(404)
@octoprint.plugin.BlueprintPlugin.route("/auth/<app_token>")
@no_firstrun_access
def handle_auth_dialog(self, app_token):
user_id = current_user.get_name()
required_user = flask.request.args.get("user", None)
pendings = self._get_pending_by_app_token(app_token)
if not pendings:
return flask.abort(404)
response = require_login_with(
permissions=[Permissions.PLUGIN_APPKEYS_GRANT], user_id=required_user
)
if response:
return response
pending = None
for p in pendings:
if p.user_id == required_user or (not required_user and p.user_id == user_id):
pending = p
break
else:
return flask.abort(404)
app_id = pending.app_id
user_token = pending.user_token
redirect_url = flask.request.args.get("redirect", "")
response = flask.make_response(
flask.render_template(
"plugin_appkeys/appkeys_authdialog.jinja2",
app=app_id,
user=user_id,
user_token=user_token,
redirect_url=redirect_url,
theming=[],
request_text=gettext(
'"<strong>%(app)s</strong>" has requested access to control OctoPrint through the API.'
).replace("%(app)s", app_id),
)
)
return add_non_caching_response_headers(response)
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if "decision" not in data:
flask.abort(400, description="No decision provided")
if not Permissions.PLUGIN_APPKEYS_GRANT.can():
flask.abort(403, description="No permission to grant app access")
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
@@ -0,0 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}#auth-choice,#auth-done,#auth-error,#auth-offline{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05);text-align:center}.form-auth-heading{margin-bottom:10px}
@@ -0,0 +1,91 @@
/*
* Will get included into the auth dialog, NOT into the regular OctoPrint
* web application.
*/
$(function () {
var OctoPrint = window.OctoPrint;
OctoPrint.authui = {
startedUp: false
};
var offlineElement = $("#auth-offline");
var grantButtonElement = $("#auth-grant");
var rejectButtonElement = $("#auth-reject");
var choiceElement = $("#auth-choice");
var doneElement = $("#auth-done");
var errorElement = $("#auth-error");
var showDone = function () {
choiceElement.hide();
doneElement.show();
};
var showError = function () {
choiceElement.hide();
errorElement.show();
};
var showOffline = function () {
choiceElement.hide();
offlineElement.show();
};
grantButtonElement.click(function () {
errorElement.removeClass("in");
OctoPrint.plugins.appkeys
.decide(USER_TOKEN, true)
.done(function () {
if (REDIRECT_URL) {
window.location.href = REDIRECT_URL;
} else {
showDone();
}
})
.fail(showError);
return false;
});
rejectButtonElement.click(function () {
OctoPrint.plugins.appkeys
.decide(USER_TOKEN, false)
.done(function () {
if (REDIRECT_URL) {
window.location.href = REDIRECT_URL;
} else {
showDone();
}
})
.fail(showError);
return false;
});
OctoPrint.options.baseurl = BASE_URL;
OctoPrint.socket.onConnected = function () {
OctoPrint.browser.passiveLogin().done(function (login) {
OctoPrint.socket.sendAuth(login.name, login.session);
OctoPrint.authui.startedUp = true;
});
};
OctoPrint.socket.onDisconnected = function () {
showOffline();
};
OctoPrint.socket.onMessage("plugin", function (event) {
if (event.data.plugin !== "appkeys") return;
var type = event.data.data.type;
if (type !== "end_request") return;
var token = event.data.data.user_token;
if (token !== USER_TOKEN) return;
showDone();
});
OctoPrint.socket.connect();
});
@@ -0,0 +1,27 @@
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
#auth-choice,
#auth-done,
#auth-error,
#auth-offline {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
-moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
text-align: center;
}
.form-auth-heading {
margin-bottom: 10px;
}
@@ -0,0 +1,77 @@
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OctoPrint App Authentication</title>
<link rel="shortcut icon" href="{{ url_for('static', filename='img/tentacle-32x32.png') }}">
<link rel="mask-icon" href="{{ url_for('static', filename='img/mask.svg') }}" color="#56BE37">
<link rel="mask-icon-theme" href="{{ url_for('static', filename='img/mask-theme.svg') }}" color="#56BE37">
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
<!-- le CSS -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-responsive.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/font-awesome-5.15.1/css/all.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/font-awesome-5.15.1/css/v4-shims.css') }}">
<link rel="stylesheet" href="{{ url_for('plugin.appkeys.static', filename='css/authdialog.css') }}">
{% for url in theming %}
<link rel="stylesheet" href="{{ url }}">
{% endfor %}
<!-- le javascript -->
<script>
var BASE_URL = "{{ url_for('index') }}";
var USER_TOKEN = "{{ user_token|e }}";
var DECISION_URL = "{{ url_for('plugin.appkeys.handle_decision', user_token=user_token) }}";
var REDIRECT_URL = "{{ redirect_url|e }}";
</script>
<script src="{{ url_for('static', filename='js/lib/jquery/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/lib/sockjs.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/lib/bootstrap/bootstrap.js') }}"></script>
<script src="{{ url_for('static', filename='js/lib/lodash.min.js') }}"></script>
{% assets "js_client" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
<script src="{{ url_for('plugin.appkeys.static', filename='js/authdialog.js') }}"></script>
</head>
<body>
<div class="container">
<form id="auth-choice" class="form-auth">
<h2 class="form-auth-heading" data-test-id="login-title">{{ _('Access Request') }}</h2>
<p>{% trans %}Hello {{ user }}!{% endtrans %}</p>
<p>{{ request_text }}</p>
<p>{% trans %}
Do you want to allow access to this application with your user account?
{% endtrans %}</p>
<button class="btn btn-block btn-primary" id="auth-grant" data-test-id="auth-grant" type="submit">{{ _('Allow') }}</button>
<button class="btn btn-block" id="auth-reject" data-test-id="auth-reject" type="submit">{{ _('Deny') }}</button>
</form>
<div id="auth-done" class="hide">
<p>{% trans %}
The access request has been processed. You may now close this tab.
{% endtrans %}</p>
</div>
<div id="auth-error" class="hide">
<p class="text-error">{% trans %}
Something went wrong while processing the access request. You may now close this tab.
{% endtrans %}</p>
</div>
<div id="auth-offline" class="hide">
<p class="text-error">{% trans %}
The server has gone offline. You may now close this tab.
{% endtrans %}</p>
</div>
</div>
</body>
</html>
+1 -1
View File
@@ -786,7 +786,7 @@ class DiscoveryPlugin(
__plugin_name__ = "Discovery"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/discovery.html"
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/discovery.html"
__plugin_description__ = (
"Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
)
@@ -617,12 +617,19 @@ GCODE.renderer = (function () {
ctx.circle(0, 0, 2);
ctx.stroke();
ctx.strokeStyle = renderOptions["colorGrid"];
ctx.lineWidth = lineWidthFactor;
//~~ grid starting from origin
ctx.beginPath();
ctx.strokeStyle = renderOptions["colorGrid"];
var gridline = 0;
for (x = 0; x <= maxX; x += gridStep) {
ctx.beginPath();
if (gridline % 5 === 0) {
// every fifth line, including the center
ctx.lineWidth = 1.5 * lineWidthFactor;
} else {
ctx.lineWidth = lineWidthFactor;
}
gridline += 1;
ctx.moveTo(x, minY);
ctx.lineTo(x, maxY);
@@ -630,11 +637,20 @@ GCODE.renderer = (function () {
ctx.moveTo(-1 * x, minY);
ctx.lineTo(-1 * x, maxY);
}
ctx.stroke();
}
ctx.stroke();
ctx.beginPath();
gridline = 0;
for (y = 0; y <= maxY; y += gridStep) {
ctx.beginPath();
if (gridline % 5 === 0) {
// every fifth line, including the center
ctx.lineWidth = 1.5 * lineWidthFactor;
} else {
ctx.lineWidth = lineWidthFactor;
}
gridline += 1;
ctx.moveTo(minX, y);
ctx.lineTo(maxX, y);
@@ -642,8 +658,8 @@ GCODE.renderer = (function () {
ctx.moveTo(minX, -1 * y);
ctx.lineTo(maxX, -1 * y);
}
ctx.stroke();
}
ctx.stroke();
};
var drawCircularGrid = function () {
@@ -2121,7 +2121,7 @@ def _register_custom_events(*args, **kwargs):
__plugin_name__ = "Plugin Manager"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
@@ -1 +1 @@
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox{text-align:center;width:10px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox],#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdiLine truncated
@@ -58,6 +58,10 @@ $(function () {
],
0
);
self.plugins.currentFilters.subscribe(function () {
self.clearPluginsSelection();
});
self.pluginLookup = {};
self.repositoryplugins = new ItemListHelper(
"plugin.pluginmanager.repositoryplugins",
@@ -169,6 +173,8 @@ $(function () {
0
);
self.selectedPlugins = ko.observableArray([]);
self.uploadElement = $("#settings_plugin_pluginmanager_repositorydialog_upload");
self.uploadButton = $(
"#settings_plugin_pluginmanager_repositorydialog_upload_start"
@@ -274,14 +280,21 @@ $(function () {
return !self.printerState.isBusy();
});
self.enableToggle = function (data) {
self.enableBulk = function (data) {
return self.enableToggle(data, true) && !data.bundled;
};
self.enableToggle = function (data, ignoreToggling) {
var command = self._getToggleCommand(data);
var not_safemode_victim = !data.safe_mode_victim;
var not_blacklisted = !data.blacklisted;
var not_incompatible = !data.incompatible;
ignoreToggling = !!ignoreToggling;
return (
self.enableManagement() &&
!self.toggling() &&
(ignoreToggling || !self.toggling()) &&
(command === "disable" ||
(not_safemode_victim && not_blacklisted && not_incompatible)) &&
data.key !== "pluginmanager"
@@ -508,7 +521,9 @@ $(function () {
var installedPlugins = [];
var noticeCount = 0;
var lookup = {};
_.each(data, function (plugin) {
lookup[plugin.key] = plugin;
installedPlugins.push(plugin.key);
if (evalNotices && plugin.notifications && plugin.notifications.length) {
@@ -537,6 +552,7 @@ $(function () {
if (evalNotices) self.noticeCount(noticeCount);
self.installedPlugins(installedPlugins);
self.plugins.updateItems(data);
self.pluginLookup = lookup;
};
self.fromOrphanResponse = function (data) {
@@ -802,6 +818,171 @@ $(function () {
}
};
self._bulkOperation = function (
plugins,
title,
message,
successText,
failureText,
statusText,
callback,
alreadyCheck
) {
var deferred = $.Deferred();
var promise = deferred.promise();
var options = {
title: title,
message: _.sprintf(message, {count: plugins.length}),
max: plugins.length,
output: true
};
showProgressModal(options, promise);
var handle = function (key) {
var d = $.Deferred();
var plugin = self.pluginLookup[key];
if (!plugin) {
deferred.notify(
_.sprintf(
gettext("Can't resolve plugin with key %(key)s, skipping..."),
{key: key}
),
false
);
d.reject();
return d.promise();
}
if (!self.enableBulk(plugin)) {
deferred.notify(
_.sprintf(
gettext(
"Plugin %(plugin)s doesn't support bulk operations, skipping..."
),
{plugin: plugin.name || key}
),
false
);
d.reject();
return d.promise();
}
if (alreadyCheck(plugin)) {
deferred.notify(
_.sprintf(
gettext(
"Plugin %(plugin)s is already %(status)s (or pending), skipping..."
),
{
plugin: plugin.name || key,
status: statusText
}
),
true
);
d.reject();
return d.promise();
}
callback(plugin)
.done(function () {
deferred.notify(
_.sprintf(successText, {plugin: plugin.name || key}),
true
);
d.resolve();
})
.fail(function () {
deferred.notify(
_.sprintf(failureText, {plugin: plugin.name || key}),
false
);
d.reject();
});
return d.promise();
};
var operations = [];
_.each(plugins, function (key) {
operations.push(handle(key));
});
$.when.apply($, _.map(operations, wrapPromiseWithAlways)).done(function () {
deferred.resolve();
self.requestPluginData();
});
return promise;
};
self.enableSelectedPlugins = function () {
if (self.selectedPlugins().length === 0) return;
var callback = function (plugin) {
return OctoPrint.plugins.pluginmanager.enable(plugin.key);
};
var check = function (plugin) {
return plugin.enabled || plugin.pending_enable;
};
self.toggling(true);
self._bulkOperation(
self.selectedPlugins(),
gettext("Enabling plugins"),
gettext("Enabling %(count)i plugins"),
gettext("Enabled plugin %(plugin)s..."),
gettext("Enabling plugin %(plugin)s failed, continuing..."),
gettext("enabled"),
callback,
check
)
.done(function () {
self.selectedPlugins([]);
})
.always(function () {
self.toggling(false);
});
};
self.disableSelectedPlugins = function () {
if (self.selectedPlugins().length === 0) return;
var callback = function (plugin) {
return OctoPrint.plugins.pluginmanager.disable(plugin.key);
};
var check = function (plugin) {
return !plugin.enabled || plugin.pending_disable;
};
self.toggling(true);
self._bulkOperation(
self.selectedPlugins(),
gettext("Disabling plugins"),
gettext("Disabling %(count)i plugins"),
gettext("Disabled plugin %(plugin)s..."),
gettext("Disabling plugin %(plugin)s failed, continuing..."),
gettext("disabled"),
callback,
check
)
.done(function () {
self.selectedPlugins([]);
})
.always(function () {
self.toggling(false);
});
};
self.selectAllVisiblePlugins = function () {
var selection = [];
_.each(self.plugins.paginatedItems(), function (plugin) {
if (!self.enableBulk(plugin)) return;
selection.push(plugin.key);
});
self.selectedPlugins(selection);
};
self.clearPluginsSelection = function () {
self.selectedPlugins([]);
};
self.showRepository = function () {
self.repositoryDialog.modal({
minHeight: function () {
@@ -19,6 +19,15 @@
table {
th,
td {
&.settings_plugin_plugin_manager_plugins_checkbox {
text-align: center;
width: 10px;
input[type="checkbox"] {
margin-top: 0;
}
}
&.settings_plugin_plugin_manager_plugins_name {
text-overflow: ellipsis;
text-align: left;
@@ -107,6 +107,16 @@
<input type="text" class="input-block search-query pull-left" data-bind="value: listingSearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
<div class="pull-right">
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="far fa-square"></i> <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: selectAllVisiblePlugins">{{ _('Select all visible') }}</a></li>
<li><a href="javascript:void(0)" data-bind="click: clearPluginsSelection">{{ _('Clear selection') }}</a></li>
<li class="divider"></li>
<li><a href="javascript:void(0)" data-bind="click: disableSelectedPlugins, css: {disabled: selectedPlugins().length == 0}"><i class="fa fa-toggle-off"></i> {{ _('Disable selected') }}</a></li>
<li><a href="javascript:void(0)" data-bind="click: enableSelectedPlugins, css: {disabled: selectedPlugins().length == 0}"><i class="fa fa-toggle-on"></i> {{ _('Enable selected') }}</a></li>
</ul>
</div>
<div class="btn-group">
<button class="btn btn-small" data-bind="click: function() { plugins.removeFilter('bundled'); plugins.removeFilter('3rdparty'); }, css: {active: !_.contains(plugins.currentFilters(), 'bundled') && !_.contains(plugins.currentFilters(), '3rdparty')}" title="{{ _('Show both bundled and third-party plugins')|edq }}">All</button>
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('bundled') }, css: {active: _.contains(plugins.currentFilters(), 'bundled')}" title="{{ _('Show only bundled plugins')|edq }}">{{ _('Bundled') }}</button>
@@ -124,12 +134,17 @@
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_plugin_manager_plugins_checkbox">
</th>
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_checkbox">
<input type="checkbox" data-bind="value: key, checked: $root.selectedPlugins, enable: $root.enableBulk($data)" title="{{ _('Bundled and incompatible plugins do not support bulk operations') | edq }}">
</td>
<td class="settings_plugin_plugin_manager_plugins_name">
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint')|edq }}" class="fas fa-th-large" data-bind="visible: bundled"></i> <i class="fas fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint')|edq }}" data-bind="visible: !managable"></i> <i class="fas fa-bolt" title="{{ _('Incompatible to OctoPrint or the underlying Python environment')|edq }}" data-bind="visible: incompatible"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect')|edq }}" class="fas fa-sync" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install')|edq }}" class="fas fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall')|edq }}" class="fas fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode')|edq }}" class="fas fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fas fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin')|edq }}" data-bind="visible: notifications && notifications.length"></i> <i class="fas fa-ban" title="{{ _('This plugin is blacklisted')|edq }}" data-bind="visible: blacklisted"></i></div>
<div data-bind="css: {muted: !enabled}">
@@ -151,6 +166,7 @@
</tbody>
</table>
</div>
<small>{{ _('Please note that bundled and incompatible plugins do not support bulk operations.') }}</small>
</div>
<div class="tab-pane" id="settings_plugin_pluginmanager_cleanup">
<div class="pull-right">
@@ -33,6 +33,8 @@ from octoprint.util.version import (
get_comparable_version,
get_python_version_string,
is_python_compatible,
is_released_octoprint_version,
is_stable,
)
from . import cli, exceptions, updaters, util, version_checks
@@ -60,6 +62,7 @@ class SoftwareUpdatePlugin(
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
CURRENT_TRACKING_TYPES = COMMIT_TRACKING_TYPES + ("etag", "lastmodified", "jsondata")
RELEASE_TRACKING_TYPES = ("github_release",)
OCTOPRINT_RESTART_TYPES = ("pip", "single_file_plugin")
@@ -1529,6 +1532,9 @@ class SoftwareUpdatePlugin(
if not check:
continue
if "type" not in check:
continue
try:
populated_check = self._populated_check(target, check)
future = executor.submit(
@@ -2177,12 +2183,6 @@ class SoftwareUpdatePlugin(
result = dict(check)
if target == "octoprint":
from octoprint.util.version import (
is_released_octoprint_version,
is_stable_octoprint_version,
)
displayName = check.get("displayName")
if displayName is None:
# displayName missing or set to None
@@ -2195,13 +2195,6 @@ class SoftwareUpdatePlugin(
displayVersion = "{octoprint_version}"
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
stable_branch = "master"
release_branches = []
if "stable_branch" in check:
release_branches.append(check["stable_branch"]["branch"])
stable_branch = check["stable_branch"]["branch"]
if "prerelease_branches" in check:
release_branches += [x["branch"] for x in check["prerelease_branches"]]
result["released_version"] = is_released_octoprint_version()
if check["type"] in self.COMMIT_TRACKING_TYPES:
@@ -2209,39 +2202,6 @@ class SoftwareUpdatePlugin(
else:
result["current"] = VERSION
if check["type"] == "github_release" and (
check.get("prerelease", None) or not is_stable_octoprint_version()
):
# we are tracking github releases and are either also tracking prerelease OR are currently running
# a non stable version => we need to change some parameters
# we compare versions fully, not just the base so that we see a difference
# between RCs + stable for the same version release
result["force_base"] = False
if check.get("prerelease", None):
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
channel = check.get("prerelease_channel", None)
if channel:
# if we have a release channel, we also set our update_branch here to our release channel
# in case it's not already set
result["update_branch"] = check.get("update_branch", channel)
else:
# we are not tracking prereleases, but aren't on the stable branch either => switch back
# to stable branch on update
result["update_branch"] = check.get(
"update_branch", stable_branch
)
if check.get("update_script", None):
# we force an exact version & python unequality check, to be able to downgrade
result["force_exact_version"] = True
result["release_compare"] = "python_unequal"
elif check.get("pip", None):
# we force python unequality check for pip installs, to be able to downgrade
result["release_compare"] = "python_unequal"
elif target == "pip":
import pkg_resources
@@ -2284,6 +2244,43 @@ class SoftwareUpdatePlugin(
"current", check.get("displayVersion", None)
)
if (
check["type"] in self.RELEASE_TRACKING_TYPES
and result["current"]
and (check.get("prerelease", None) or not is_stable(result["current"]))
):
# we are tracking releases and are either also tracking prerelease OR are currently running
# a non stable version => we need to change some parameters
# we compare versions fully, not just the base so that we see a difference
# between RCs + stable for the same version release
result["force_base"] = False
if check["type"] == "github_release":
if check.get("prerelease", None):
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
channel = check.get("prerelease_channel", None)
if channel:
# if we have a release channel, we also set our update_branch here to our release channel
# in case it's not already set
result["update_branch"] = check.get("update_branch", channel)
else:
# we are not tracking prereleases, but aren't on the stable branch either => switch back
# to stable branch on update
result["update_branch"] = check.get(
"update_branch",
check.get("stable_branch", {"branch": "main"})["branch"],
)
if check.get("update_script", None):
# we force an exact version & python unequality check, to be able to downgrade
result["force_exact_version"] = True
result["release_compare"] = "python_unequal"
elif check.get("pip", None):
# we force python unequality check for pip installs, to be able to downgrade
result["release_compare"] = "python_unequal"
if result.get("pip", None):
if "pip_command" not in result:
local_pip_command = self._settings.global_get(
@@ -2408,7 +2405,7 @@ def _register_custom_events(*args, **kwargs):
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
__plugin_description__ = "Allows receiving update notifications and performing updates of OctoPrint and plugins"
__plugin_disabling_discouraged__ = gettext(
"Without this plugin OctoPrint will no longer be able to "
@@ -82,6 +82,10 @@ $(function () {
});
self.enableUpdateAll = ko.pureComputed(function () {
return self.enableUpdate() && self.availableAndPossible().length > 0;
});
self.enableUpdateEnabled = ko.pureComputed(function () {
return (
self.enableUpdate() && self.availableAndPossibleAndEnabled().length > 0
);
@@ -370,6 +374,17 @@ $(function () {
});
};
information.notificationIconTitle = function () {
var update = information.updateAvailable
? gettext("Update available")
: gettext("Up-to-date");
var notifications = information.disabled
? gettext("notifications are muted")
: gettext("notifications are enabled");
return update + " (" + notifications + ")";
};
return information;
};
@@ -12,7 +12,7 @@
If you have a local OctoPrint checkout folder switched to another branch,
<strong>simply switching over to "Commit" tracking</strong> will already
take care of that. Otherwise please take a look at the
<a href="http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" target="_blank">Documentation</a>.
<a href="https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" target="_blank">Documentation</a>.
</p>
{% endtrans %}</div>
<div class="alert" data-bind="visible: !environmentSupported()">{% trans %}
@@ -85,28 +85,31 @@
<div class="tab-content">
<div class="tab-pane active" id="settings_plugin_softwareupdate_updates">
<div class="pull-right">
<button class="btn btn-primary" data-bind="click: function() { $root.updateAll(); }, enable: enableUpdateAll, css: {disabled: !enableUpdateAll}"><i class="fas fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
<button class="btn" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for updates') }}</button>
<div class="btn-group">
<button class="btn btn-primary" data-bind="click: function() { $root.updateEnabled(); }, enable: enableUpdateEnabled, css: {disabled: !enableUpdateEnabled}" title="{{ _('Update all enabled') | edq }}"><i class="fas fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: function() { $root.updateAll(); }, enable: enableUpdateAll, css: {disabled: !enableUpdateAll}" title="{{ _('Update all muted & enabled') | edq }}">{{ _('Update all available') }}</a></li>
</ul>
</div>
<div class="btn-group">
<button class="btn" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for updates') }}</button>
<button class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}">{{ _('Force check for updates') }}</a></li>
</ul>
</div>
<button class="btn" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fas fa-wrench"></i></button>
</div>
<h3>{{ _('Current versions') }}</h3>
<div class="swupdate-advanced">
<div><small><a href="javascript:void(0)" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<small class="muted" style="display: block">{{ _('Last cache refresh:') }} <span data-bind="text: cacheTimestampText"></span></small>
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.updateAll(true); }, enable: enableUpdate() && !checking(), css: {disabled: !enableUpdate() || checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force update all (even if no new versions are available)') }}</button>
</div>
</div>
<div id="settings_plugin_softwareupdate_updatelist">
<table class="table table-striped table-hover table-condensed table-hover">
<tbody data-bind="foreach: versions.paginatedItems">
<tr data-bind="attr: {title: displayName}">
<tr>
<td class="settings_plugin_softwareupdate_column_update">
<a href="javascript:void(0)" data-bind="visible: compatible, click: toggleDisabled"><i class="far" data-bind="css: { muted: !updateAvailable, 'fa-bell': !disabled, 'fa-bell-slash': disabled }" title="{{ _('Update available')|edq }}"></i></a>
<a href="javascript:void(0)" data-bind="visible: compatible, click: toggleDisabled"><i class="far" data-bind="css: { muted: !updateAvailable, 'fa-bell': !disabled, 'fa-bell-slash': disabled }, attr: { title: notificationIconTitle() }"></i></a>
<span data-bind="visible: !compatible" class="muted"><i class="fas fa-power-off" title="{{ _('Not compatible') }}|edq"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
@@ -126,6 +129,17 @@
</tr>
</tbody>
</table>
<small class="muted">
<i class="far fa-bell"></i> = {{ _('Update notifications enabled') }},
<i class="far fa-bell-slash"></i> = {{ _('Update notifications muted') }},
{{ _('click to toggle') }}.
{% trans %}
"Update all" will update all items for which updates are availalbe &
update notifications are enabled as well, "Update all available" will
update all items for which updates are available regardless of update
notifications being enabled or muted.
{% endtrans %}
</small>
</div>
</div>
<div class="tab-pane" id="settings_plugin_softwareupdate_updatelog">
@@ -71,6 +71,8 @@ class VirtualPrinterPlugin(
"enable_eeprom": True,
"support_M503": True,
"resend_ratio": 0,
"locked": False,
"passcode": "1234",
}
def get_settings_version(self):
@@ -165,6 +165,8 @@ class VirtualPrinter:
self._capabilities = self._settings.get(["capabilities"], merged=True)
self._locked = self._settings.get_boolean(["locked"])
self._temperature_reporter = None
self._sdstatus_reporter = None
self._pos_reporter = None
@@ -185,6 +187,7 @@ class VirtualPrinter:
self._calculate_resend_every_n(self._settings.get_int(["resend_ratio"]))
self._dont_answer = False
self._broken_klipper_connection = False
self._debug_drop_connection = False
@@ -268,6 +271,7 @@ class VirtualPrinter:
self._sleepAfter.clear()
self._dont_answer = False
self._broken_klipper_connection = False
self._debug_drop_connection = False
@@ -294,6 +298,8 @@ class VirtualPrinter:
for item in self._settings.get(["resetLines"]):
self._send(item + "\n")
self._locked = self._settings.get_boolean(["locked"])
@property
def timeout(self):
return self._read_timeout
@@ -488,9 +494,19 @@ class VirtualPrinter:
# actual command handling
command_match = VirtualPrinter.command_regex.match(data)
if command_match is not None:
if self._broken_klipper_connection:
self._send("!! Lost communication with MCU 'mcu'")
self._sendOk()
continue
command = command_match.group(0)
letter = command_match.group(1)
if self._locked and command != "M511":
self._send("echo:Printer locked! (Unlock with M511 or LCD)")
self._sendOk()
continue
try:
# if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first
letter_handler = f"_gcode_{letter}"
@@ -835,6 +851,22 @@ class VirtualPrinter:
else:
time.sleep(timeout)
# Passcode Feature - lock with M510, unlock with M511 P<passcode>.
# https://marlinfw.org/docs/gcode/M510.html / https://marlinfw.org/docs/gcode/M511.html
def _gcode_M510(self, data):
self._locked = True
def _gcode_M511(self, data):
if self._locked:
matchP = re.search(r"P([0-9]+)", data)
if matchP:
passcode = matchP.group(1)
if passcode == self._settings.get(["passcode"]):
self._locked = False
else:
self._send("Incorrect passcode")
# EEPROM management commands
def _gcode_M500(self, data):
@@ -1202,6 +1234,9 @@ class VirtualPrinter:
resend_ratio <int:percentage>
| Sets the resend ratio to the given percentage, simulating noisy lines.
| Set to 0 to disable noise simulation.
toggle_klipper_connection
| Toggles the Klipper connection state. If disabled, the printer will
| respond to all commands with "!! Lost communication with MCU 'mcu'"
# Reply Timing / Sleeping
@@ -1241,6 +1276,8 @@ class VirtualPrinter:
self._send("// action:disconnect")
elif data == "dont_answer":
self._dont_answer = True
elif data == "toggle_klipper_connection":
self._broken_klipper_connection = not self._broken_klipper_connection
elif data == "trigger_resend_lineno":
self._prepared_errors.append(
lambda cur, last, ln: self._triggerResend(expected=last, actual=last + 1)
@@ -1380,6 +1417,8 @@ class VirtualPrinter:
dosname = get_dos_filename(
entry.name, existing_filenames=list(result.keys())
).lower()
if entry.name.startswith("."):
dosname = "." + dosname
result[dosname] = {
"name": entry.name,
"path": entry.path,
+5 -5
View File
@@ -12,7 +12,7 @@ import os
import threading
import time
from immutabledict import immutabledict
from frozendict import frozendict
import octoprint.util.json
from octoprint import util as util
@@ -47,7 +47,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._logger_job = logging.getLogger(f"{__name__}.job")
self._dict = (
immutabledict
frozendict
if settings().getBoolean(["devel", "useFrozenDictForPrinterState"])
else dict
)
@@ -192,7 +192,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
@property
def firmware_info(self):
return immutabledict(self._firmware_info) if self._firmware_info else None
return frozendict(self._firmware_info) if self._firmware_info else None
# ~~ handling of PrinterCallbacks
@@ -819,11 +819,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return self._comm.getErrorString()
def get_current_data(self, *args, **kwargs):
return util.thaw_immutabledict(self._stateMonitor.get_current_data())
return util.thaw_frozendict(self._stateMonitor.get_current_data())
def get_current_job(self, *args, **kwargs):
currentData = self._stateMonitor.get_current_data()
return util.thaw_immutabledict(currentData["job"])
return util.thaw_frozendict(currentData["job"])
def get_current_temperatures(self, *args, **kwargs):
if self._comm is not None:
+14
View File
@@ -300,6 +300,9 @@ class Server:
debug = self._debug
safe_mode = self._safe_mode
if safe_mode:
self._log_safe_mode_start(safe_mode)
if self._v6_only and not octoprint.util.net.HAS_V6:
raise RuntimeError(
"IPv6 only mode configured but system doesn't support IPv6"
@@ -334,6 +337,7 @@ class Server:
# monkey patch/fix some stuff
util.tornado.fix_json_encode()
util.tornado.fix_websocket_check_origin()
util.tornado.enable_per_message_deflate_extension()
util.flask.fix_flask_jsonify()
cli_key = self._setup_cli_key()
@@ -1270,6 +1274,16 @@ class Server:
)
self._logger.exception("Stacktrace follows:")
def _log_safe_mode_start(self, self_mode):
self_mode_file = os.path.join(
self._settings.getBaseFolder("data"), "last_safe_mode"
)
try:
with open(self_mode_file, "w+", encoding="utf-8") as f:
f.write(self_mode)
except Exception as ex:
self._logger.warn(f"Could not write safe mode file {self_mode_file}: {ex}")
def _create_socket_connection(self, session):
global printer, fileManager, analysisQueue, userManager, eventManager, connectivityChecker
return util.sockjs.PrinterStateConnection(
+13 -2
View File
@@ -145,6 +145,7 @@ def getSettings():
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
"rememberFileFolder": s.getBoolean(["feature", "rememberFileFolder"]),
"printStartConfirmation": s.getBoolean(["feature", "printStartConfirmation"]),
"printCancelConfirmation": s.getBoolean(
["feature", "printCancelConfirmation"]
@@ -258,6 +259,7 @@ def getSettings():
"capExtendedM20": s.getBoolean(["serial", "capabilities", "extended_m20"]),
"resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]),
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
},
"folder": {
"uploads": s.getBaseFolder("uploads"),
@@ -449,9 +451,9 @@ def _saveSettings(data):
for folder in FOLDER_TYPES:
future[folder] = s.getBaseFolder(folder)
if folder in folders:
future[folder] = data["folder"][folder]
future[folder] = folders[folder]
for folder in data["folder"]:
for folder in folders:
if folder not in FOLDER_TYPES:
continue
for other_folder in FOLDER_TYPES:
@@ -616,6 +618,11 @@ def _saveSettings(data):
s.setBoolean(
["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"]
)
if "rememberFileFolder" in data["feature"]:
s.setBoolean(
["feature", "rememberFileFolder"],
data["feature"]["rememberFileFolder"],
)
if "printStartConfirmation" in data["feature"]:
s.setBoolean(
["feature", "printStartConfirmation"],
@@ -935,6 +942,10 @@ def _saveSettings(data):
)
if "resendRatioStart" in data["serial"]:
s.setInt(["serial", "resendRatioStart"], data["serial"]["resendRatioStart"])
if "ignoreEmptyPorts" in data["serial"]:
s.setBoolean(
["serial", "ignoreEmptyPorts"], data["serial"]["ignoreEmptyPorts"]
)
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"]:
+1
View File
@@ -44,6 +44,7 @@ def getSystemInfo():
systeminfo = get_systeminfo(
environmentDetector,
connectivityChecker,
s(),
{
"browser.user_agent": request.headers.get("User-Agent"),
"octoprint.safe_mode": safe_mode is not None,
+37
View File
@@ -365,6 +365,43 @@ def has_permissions(*permissions):
return all(map(lambda p: p.can(), permissions))
def require_login_with(permissions=None, user_id=None):
"""
Requires a login with the given permissions and/or user id.
Args:
permissions: list of all permissions required to pass the check
user_id: required user to pass the check
Returns: a flask redirect response to return if a login is required, or None
"""
from octoprint.server import current_user, userManager
login_kwargs = {"redirect": _flask.request.script_root + _flask.request.full_path}
if (
_flask.request.headers.get("X-Preemptive-Recording", "no") == "no"
and userManager.has_been_customized()
):
requires_login = False
if current_user.is_anonymous:
requires_login = True
if permissions is not None and not has_permissions(*permissions):
requires_login = True
login_kwargs["permissions"] = ",".join([x.key for x in permissions])
if user_id is not None and current_user.get_id() != user_id:
requires_login = True
login_kwargs["user_id"] = user_id
if requires_login:
return _flask.redirect(_flask.url_for("login", **login_kwargs))
return None
def require_login(*permissions):
"""
Returns a redirect response to the login view if the permission requirements are
+111 -3
View File
@@ -3,6 +3,7 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import re
import threading
import time
@@ -167,6 +168,10 @@ class PrinterStateConnection(
self._registered = False
self._authed = False
self._initial_data_sent = False
self._subscriptions_active = False
self._subscriptions = {"state": False, "plugins": [], "events": []}
@staticmethod
def _get_remote_address(info):
@@ -310,10 +315,77 @@ class PrinterStateConnection(
)
)
elif "subscribe" in message:
if not self._subscriptions_active:
self._subscriptions_active = True
self._logger.debug("Client makes use of subscriptions")
def list_or_boolean(value):
if isinstance(value, list):
return value
elif isinstance(value, bool):
return [] if not value else None
else:
raise ValueError("value must be a list or boolean")
def regex_or_boolean(value):
if isinstance(value, str):
try:
return re.compile(value)
except Exception:
raise ValueError("value must be a valid regex")
elif isinstance(value, bool):
return value
else:
raise ValueError("value must be a string or boolean")
try:
subscribe = message["subscribe"]
state = subscribe.get("state", False)
if isinstance(state, bool):
if state:
state = {"logs": True, "messages": False}
elif isinstance(state, dict):
logs = regex_or_boolean(state.get("logs", False))
messages = regex_or_boolean(state.get("messages", False))
state = {
"logs": logs,
"messages": messages,
}
plugins = list_or_boolean(subscribe.get("plugins", []))
events = list_or_boolean(subscribe.get("events", []))
except ValueError as e:
self._logger.warning(
"Got invalid subscription message from client {}, ignoring: {!r} ({}) ".format(
self._remoteAddress, message["subscribe"], str(e)
)
)
else:
old_state = self._subscriptions["state"]
self._subscriptions["state"] = state
self._subscriptions["plugins"] = plugins
self._subscriptions["events"] = events
if state and not old_state:
# trigger initial data
self._printer.send_initial_callback(self)
elif old_state and not state:
self._initial_data_sent = False
def on_printer_send_current_data(self, data):
if not self._user.has_permission(Permissions.STATUS):
return
if self._subscriptions_active and not self._subscriptions["state"]:
return
if not self._initial_data_sent:
self._logger.debug("Initial data not yet send, dropping current message")
return
# make sure we rate limit the updates according to our throttle factor
with self._held_back_mutex:
if self._held_back_current is not None:
@@ -339,11 +411,11 @@ class PrinterStateConnection(
self._temperatureBacklog = []
with self._logBacklogMutex:
logs = self._logBacklog
logs = self._filter_logs(self._logBacklog)
self._logBacklog = []
with self._messageBacklogMutex:
messages = self._messageBacklog
messages = self._filter_messages(self._messageBacklog)
self._messageBacklog = []
busy_files = [
@@ -370,7 +442,7 @@ class PrinterStateConnection(
{
"serverTime": time.time(),
"temps": temperatures,
"logs": logs,
"logs": self._filter_logs(logs),
"messages": messages,
"busyFiles": busy_files,
}
@@ -378,10 +450,32 @@ class PrinterStateConnection(
self._emit("current", payload=data)
def on_printer_send_initial_data(self, data):
self._initial_data_sent = True
if self._subscriptions_active and not self._subscriptions["state"]:
self._logger.debug("Not subscribed to state, dropping history")
return
data_to_send = dict(data)
data_to_send["logs"] = self._filter_logs(data_to_send.get("logs", []))
data_to_send["messages"] = self._filter_messages(data_to_send.get("messages", []))
data_to_send["serverTime"] = time.time()
self._emit("history", payload=data_to_send)
def _filter_state_subscription(self, sub, values):
if not self._subscriptions_active or self._subscriptions["state"][sub] is True:
return values
if self._subscriptions["state"][sub] is False:
return []
return [line for line in values if self._subscriptions["state"][sub].search(line)]
def _filter_logs(self, logs):
return self._filter_state_subscription("logs", logs)
def _filter_messages(self, messages):
return self._filter_state_subscription("messages", messages)
def sendEvent(self, type, payload=None):
permissions = self._event_permissions.get(type, self._event_permissions["*"])
permissions = [x(self._user) if callable(x) else x for x in permissions]
@@ -420,6 +514,13 @@ class PrinterStateConnection(
self._emit("renderProgress", {"progress": progress})
def on_plugin_message(self, plugin, data, permissions=None):
if (
self._subscriptions_active
and self._subscriptions["plugins"] is not None
and plugin not in self._subscriptions["plugins"]
):
return
self._emit(
"plugin", payload={"plugin": plugin, "data": data}, permissions=permissions
)
@@ -470,6 +571,13 @@ class PrinterStateConnection(
self._sendReauthRequired("modified")
def _onEvent(self, event, payload):
if (
self._subscriptions_active
and self._subscriptions["events"] is not None
and event not in self._subscriptions["events"]
):
return
self.sendEvent(event, payload)
def _register(self):
+13
View File
@@ -45,6 +45,18 @@ def fix_json_encode():
tornado.escape.json_encode = fixed_json_encode
def enable_per_message_deflate_extension():
"""
This configures tornado.websocket.WebSocketHandler.get_compression_options to support the permessage-deflate extension
to the websocket protocol, minimizing data bandwidth if clients support the extension as well
"""
def get_compression_options(self):
return {"compression_level": 1, "mem_level": 1}
tornado.websocket.WebSocketHandler.get_compression_options = get_compression_options
def fix_websocket_check_origin():
"""
This fixes tornado.websocket.WebSocketHandler.check_origin to do the same origin check against the Host
@@ -1560,6 +1572,7 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
systeminfo = get_systeminfo(
environmentDetector,
connectivityChecker,
settings(),
{
"browser.user_agent": self.request.headers.get("User-Agent"),
"octoprint.safe_mode": safe_mode is not None,
+12 -7
View File
@@ -38,7 +38,7 @@ from octoprint.server import ( # noqa: F401
preemptiveCache,
userManager,
)
from octoprint.server.util import has_permissions, require_login
from octoprint.server.util import has_permissions, require_login_with
from octoprint.settings import settings
from octoprint.util import sv, to_bytes, to_unicode
from octoprint.util.version import get_python_version_string
@@ -184,13 +184,18 @@ def login():
if not permissions:
permissions = [Permissions.STATUS, Permissions.SETTINGS_READ]
if has_permissions(*permissions):
user_id = request.args.get("user_id", "")
if (not user_id or current_user.get_id() == user_id) and has_permissions(
*permissions
):
return redirect(redirect_url)
render_kwargs = {
"theming": [],
"redirect_url": redirect_url,
"permission_names": map(lambda x: x.get_name(), permissions),
"user_id": user_id,
"logged_in": not current_user.is_anonymous,
}
@@ -211,7 +216,7 @@ def login():
@app.route("/recovery")
@app.route("/recovery/")
def recovery():
response = require_login(Permissions.ADMIN)
response = require_login_with(permissions=[Permissions.ADMIN])
if response:
return response
@@ -623,7 +628,7 @@ def index():
plugin.implementation, octoprint.plugin.UiPlugin
):
permissions = plugin.implementation.get_ui_permissions()
response = require_login(*permissions)
response = require_login_with(permissions=permissions)
if not response:
response = plugin_view(plugin.implementation)
if _logger.isEnabledFor(logging.DEBUG) and isinstance(
@@ -633,7 +638,7 @@ def index():
"X-Ui-Plugin"
] = plugin.implementation._identifier
else:
response = require_login(*default_permissions)
response = require_login_with(permissions=default_permissions)
if not response:
response = default_view()
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
@@ -649,7 +654,7 @@ def index():
if plugin.will_handle_ui(request):
# plugin claims responsibility, let it render the UI
permissions = plugin.get_ui_permissions()
response = require_login(*permissions)
response = require_login_with(permissions=permissions)
if not response:
response = plugin_view(plugin)
if response is not None:
@@ -672,7 +677,7 @@ def index():
extra={"plugin": plugin._identifier},
)
else:
response = require_login(*default_permissions)
response = require_login_with(permissions=default_permissions)
if not response:
response = default_view()
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
+2
View File
@@ -166,6 +166,7 @@ default_settings = {
},
"resendRatioThreshold": 10,
"resendRatioStart": 100,
"ignoreEmptyPorts": False,
# command specific flags
"triggerOkForM29": True,
},
@@ -267,6 +268,7 @@ default_settings = {
"keyboardControl": True,
"pollWatched": False,
"modelSizeDetection": True,
"rememberFileFolder": False,
"printStartConfirmation": False,
"printCancelConfirmation": True,
"uploadOverwriteConfirmation": True,
+9 -2
View File
@@ -344,6 +344,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
hide: false
});
} else if (type === "Error" && payload.error) {
severity = "error";
switch (payload.reason) {
case "firmware": {
title = gettext("Error reported by printer");
@@ -388,7 +389,13 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
break;
}
case "autodetect": {
// ignore
title = gettext("Could not autodetect your printer");
text = _.sprintf(
gettext(
'No working connection parameters could be found. Are you sure your printer is physically connected and supported? Refer to <a href="%(url)s" target="_blank" rel="noopener noreferer">the FAQ</a> for help in debugging this.'
),
{url: "https://faq.octoprint.org/connection-error"}
);
break;
}
default: {
@@ -410,7 +417,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
self._printerErrorDisconnectNotification = new PNotify({
title: title,
text: text,
type: "error",
type: severity,
hide: false
});
}
+2 -1
View File
@@ -56,9 +56,10 @@ function ItemListHelper(
for (var i = 0; i < itemList.length; i++) {
if (matcher(itemList[i])) {
self.selectedItem(itemList[i]);
break;
return true;
}
}
return false;
};
self.selectNone = function () {
@@ -38,11 +38,38 @@ $(function () {
self.isReady = ko.observable(undefined);
self.isLoading = ko.observable(undefined);
self.enableConnect = ko.pureComputed(function () {
return self.enablePort() || !self.isErrorOrClosed();
});
self.buttonText = ko.pureComputed(function () {
if (self.isErrorOrClosed()) return gettext("Connect");
else return gettext("Disconnect");
});
self.portCaption = ko.pureComputed(function () {
return self.validPort() ? "AUTO" : gettext("No serial port found");
});
self.validPort = ko.pureComputed(function () {
return (
self.portOptions().length > 0 ||
self.settings.settings.serial.ignoreEmptyPorts()
);
});
self.enablePort = ko.pureComputed(function () {
return self.validPort() && self.isErrorOrClosed();
});
self.enableSaveSettings = ko.pureComputed(function () {
return self.enableConnect() && self.isErrorOrClosed();
});
self.enableAutoConnect = ko.pureComputed(function () {
return self.enableConnect() && self.isErrorOrClosed();
});
self.previousIsOperational = undefined;
self.refreshVisible = ko.observable(true);
+72 -20
View File
@@ -117,7 +117,27 @@ $(function () {
self.uploadFilename = ko.observable(undefined);
self.allItems = ko.observable(undefined);
var optionsLocalStorageKey = "gcodeFiles.options";
self._toLocalStorage = function () {
saveToLocalStorage(optionsLocalStorageKey, {currentPath: self.currentPath()});
};
self._fromLocalStorage = function () {
var data = loadFromLocalStorage(optionsLocalStorageKey);
if (
data["currentPath"] !== undefined &&
self.settingsViewModel.feature_rememberFileFolder()
) {
self.currentPath(data["currentPath"]);
}
};
self.currentPath = ko.observable("");
self.currentPath.subscribe(function () {
self._toLocalStorage();
});
self.uploadProgressText = ko.observable();
self.uploadProgressPercentage = ko.observable();
@@ -232,6 +252,7 @@ $(function () {
listHelperExclusiveFilters,
0
);
self.selectedFile = undefined;
self.availableFiletypes = ko.pureComputed(function () {
var mapping = {
@@ -311,34 +332,47 @@ $(function () {
);
});
self.printerState.filepath.subscribe(function (newValue) {
self.highlightFilename(newValue);
});
self.highlightCurrentFilename = function () {
self.highlightFilename(self.printerState.filepath());
self.highlightCurrentFile = function () {
self.highlightFile(self.selectedFile);
};
self.highlightFilename = function (filename) {
if (filename === undefined || filename === null) {
self.highlightFile = function (file) {
if (!file || !file.origin || !file.path) {
self.listHelper.selectNone();
return;
}
var result = self.listHelper.selectItem(function (item) {
if (item.origin !== file.origin) return false;
if (item.type === "folder") {
return _.startsWith(file.path, item.path + "/");
} else {
return item.path === file.path;
}
});
if (!result) {
if (log.getLevel() <= log.levels.DEBUG) {
log.info(
"Couldn't find file " +
file.origin +
":" +
file.path +
" in current items, not selecting"
);
}
self.listHelper.selectNone();
} else {
self.listHelper.selectItem(function (item) {
if (item.type === "folder") {
return _.startsWith(filename, item.path + "/");
} else {
return item.path === filename;
}
});
}
};
self.fromCurrentData = function (data) {
self._processStateData(data.state);
self._processJobData(data.job);
};
self.fromHistoryData = function (data) {
self._processStateData(data.state);
self._processJobData(data.job);
};
self._processStateData = function (data) {
@@ -352,6 +386,21 @@ $(function () {
self.isSdReady(data.flags.sdReady);
};
self._processJobData = function (data) {
if (!data) return;
if (
self.selectedFile &&
self.file &&
self.selectedFile.origin === data.file.origin &&
self.selectedFile.path === data.file.path
)
return;
self.selectedFile = data.file;
self.highlightFile(data.file);
};
self._otherRequestInProgress = undefined;
self._focus = undefined;
self._switchToPath = undefined;
@@ -512,7 +561,7 @@ $(function () {
self.totalSpace(response.total);
}
self.highlightCurrentFilename();
self.highlightCurrentFile();
};
self.changeFolder = function (data) {
@@ -525,7 +574,7 @@ $(function () {
self.currentPath(data.path);
self.listHelper.updateItems(data.children);
self.highlightCurrentFilename();
self.highlightCurrentFile();
};
self.navigateUp = function () {
@@ -543,7 +592,7 @@ $(function () {
self.currentPath("");
self.listHelper.updateItems(self.allItems());
}
self.highlightCurrentFilename();
self.highlightCurrentFile();
};
self.showAddFolderDialog = function () {
@@ -652,7 +701,9 @@ $(function () {
if (
printAfterLoad &&
self.listHelper.isSelected(data) &&
self.listHelper.isSelectedByMatcher(function (item) {
return item && item.origin === data.origin && item.path === data.path;
}) &&
self.enablePrint(data)
) {
// file was already selected, just start the print job
@@ -1248,6 +1299,7 @@ $(function () {
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.updateButtons();
self.requestData();
self._fromLocalStorage();
};
self.onStartup = function () {
@@ -173,6 +173,7 @@ $(function () {
self.feature_keyboardControl = ko.observable(undefined);
self.feature_pollWatched = ko.observable(undefined);
self.feature_modelSizeDetection = ko.observable(undefined);
self.feature_rememberFileFolder = ko.observable(undefined);
self.feature_printStartConfirmation = ko.observable(undefined);
self.feature_printCancelConfirmation = ko.observable(undefined);
self.feature_uploadOverwriteConfirmation = ko.observable(undefined);
+7 -2
View File
@@ -37,9 +37,14 @@ $(function () {
window.location.href = REDIRECT_URL;
})
.fail(function () {
usernameElement.val("");
usernameElement.val(USER_ID);
passwordElement.val("");
usernameElement.focus();
if (USER_ID) {
passwordElement.focus();
} else {
usernameElement.focus();
}
overlayElement.removeClass("in");
errorElement.addClass("in");
@@ -9,7 +9,7 @@
<li><i class="fa-li fab fa-discourse"></i> Community Forum: <a href="https://community.octoprint.org" target="_blank" rel="noreferrer noopener">community.octoprint.org</a></li>
<li><i class="fa-li fab fa-discord"></i> Discord Server: <a href="https://discord.octoprint.org" target="_blank" rel="noreferrer noopener">discord.octoprint.org</a></li>
<li><i class="fa-li fas fa-question-circle"></i> FAQ: <a href="https://faq.octoprint.org" target="_blank" rel="noreferrer noopener">faq.octoprint.org</a></li>
<li><i class="fa-li fas fa-book"></i> Documentation: <a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener">docs.octoprint.org</a></li>
<li><i class="fa-li fas fa-book"></i> Documentation: <a href="https://docs.octoprint.org" target="_blank" rel="noreferrer noopener">docs.octoprint.org</a></li>
<li><i class="fa-li fab fa-github"></i> Source Code: <a href="https://github.com/OctoPrint/OctoPrint" target="_blank" rel="noreferrer noopener">github.com/OctoPrint/OctoPrint</a></li>
<li><i class="fa-li fas fa-code-branch"></i> Changelog: <a href="https://github.com/OctoPrint/OctoPrint/releases" target="_blank" rel="noreferrer noopener">github.com/OctoPrint/OctoPrint/releases</a></li>
<li><i class="fa-li fas fa-heart"></i> Financial Support: <a href="https://support.octoprint.org" target="_blank" rel="noreferrer noopener">support.octoprint.org</a></li>
@@ -1,11 +1,14 @@
<h3>{{ _('System Information') }}</h3>
<p>{% trans %}Please always share a Systeminfo Bundle when requesting support on the forums or
when opening a new bug report:{% endtrans %}</p>
<p>{% trans %}Sharing a Systeminfo Bundle when requesting support on the forums or
when opening a new bug report is <strong>mandatory!</strong>{% endtrans %}</p>
<p>{% trans %}Download the bundle and share as provided. Do not rename, unpack,
repack or otherwise modify, provide <em>exactly</em> as downloaded.{% endtrans %}</p>
<p><a href="{{ url_for('index', _external=True) }}downloads/systeminfo.zip" class="btn btn-primary"><i class="fas fa-download"></i> {{ _('Download Systeminfo Bundle') }}</a></p>
<p>{% trans %}You can view Systeminfo Bundles at <a href="https://bundleviewer.octoprint.org" target="_blank" rel="noopener noreferrer">bundleviewer.octoprint.org</a>{% endtrans %}</p>
<p><small>{% trans %}You can view Systeminfo Bundles at <a href="https://bundleviewer.octoprint.org" target="_blank" rel="noopener noreferrer">bundleviewer.octoprint.org</a>{% endtrans %}</small></p>
<div class="more">
<div><small><a href="javascript:void(0)" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.more', container: '.hide' }"><i class="fas fa-caret-right"></i> {{ _('More') }}</a></small></div>
@@ -13,7 +16,5 @@
<p data-bind="foreach: systeminfo">
<strong data-bind="text: key"></strong>: <span data-bind="text: value"></span><br />
</p>
<a href="javascript:void(0)" class="btn" data-bind="click: copySystemInfo"><i class="far fa-copy"></i> {{ _('Copy') }}</a>
</div>
</div>
@@ -14,6 +14,13 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_rememberFileFolder" id="settings-rememberFileFolder"> {{ _('Remember selected folder in file list') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
+5 -2
View File
@@ -26,6 +26,7 @@
<script>
var BASE_URL = "{{ url_for('index') }}";
var REDIRECT_URL = "{{ redirect_url|e }}";
var USER_ID = "{{ user_id|e }}";
</script>
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
@@ -46,11 +47,13 @@
<div id="login-error" class="alert alert-error" data-test-id="login-error">{{ _('Incorrect username or password. Hint: Both are case sensitive!') }}</div>
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
{% if logged_in %}<p>
{% if user_id %}<p>
{{ _('The following account is required:') }} {{ user_id }}
</p>{% elif logged_in %}<p>
{{ _('An account with the following permissions is required:') }} {{ permission_names|join(", ") }}
</p>{% endif %}
<input type="text" id="login-user" data-test-id="login-username" class="input-block-level" placeholder="{{ _('Username')|edq }}" autofocus autocapitalize="none">
<input type="text" id="login-user" data-test-id="login-username" class="input-block-level" placeholder="{{ _('Username')|edq }}" {% if user_id %}value="{{ user_id }}" disabled{% endif %} autofocus autocapitalize="none">
<input type="password" id="login-password" data-test-id="login-password" class="input-block-level" placeholder="{{ _('Password')|edq }}">
<span class="pull-right"><small><a href="https://faq.octoprint.org/forgotten-password" id="login-forgotpassword" target="_blank" tabindex="-1">{{ _('Forgot password?') }}</a></small></span>
<label class="checkbox">
@@ -1,3 +1,3 @@
<a href="https://faq.octoprint.org/connectivity-offline" target="_blank" title="{{ _('There is no connection to the internet') }}" rel="noopener noreferrer" data-bind="visible: offline(), popover: { placement: 'bottom', title: '{{ _('There is no connection to the internet')|esq }}', html: true, content: offlinePopoverContent, trigger: 'hover' }" style="display: none">
<i class="far fa-unlink"></i>
<i class="fas fa-unlink"></i>
</a>
@@ -1,13 +1,17 @@
<div style="margin-bottom: 10px" class="alert alert-error" data-bind="visible: !validPort()"><small>{% trans link="<a href='https://faq.octoprint.org/no-candidates' target='_blank' rel='noopener noreferer'>", endlink="</a>", refresh="<a href='javascript:void(0)' data-bind='click: $root.requestData'>", endrefresh="</a>" %}
No serial port found, are you sure your printer is physically connected and supported?
Try {{ refresh }}refreshing{{ endrefresh }} and if that doesn't help please see {{ link }}the FAQ{{ endlink }}.
{% endtrans %}</small></div>
<label for="connection_ports" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Serial Port') }}</label>
<select id="connection_ports" data-test-id="connection-ports" data-bind="options: portOptions, optionsCaption: 'AUTO', value: selectedPort, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<select id="connection_ports" data-test-id="connection-ports" data-bind="options: portOptions, optionsCaption: portCaption, value: selectedPort, css: {disabled: !isErrorOrClosed()}, enable: enablePort()"></select>
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Baudrate') }}</label>
<select id="connection_baudrates" data-test-id="connection-baudrates" data-bind="options: baudrateOptions, optionsCaption: 'AUTO', value: selectedBaudrate, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label for="connection_printers" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Printer Profile') }}</label>
<select id="connection_printers" data-test-id="connection-printer-profiles" data-bind="options: printerOptions, optionsText: 'name', optionsValue: 'id', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label class="checkbox">
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Save connection settings') }}
<label class="checkbox" data-bind="css: {muted: !enableSaveSettings()}">
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, enable: enableSaveSettings()"> {{ _('Save connection settings') }}
</label>
<label class="checkbox">
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Auto-connect on server startup') }}
<label class="checkbox" data-bind="css: {muted: !enableAutoConnect()}">
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, enable: enableAutoConnect()"> {{ _('Auto-connect on server startup') }}
</label>
<button class="btn btn-block" id="printer_connect" data-test-id="connection-connect" data-bind="click: connect, text: buttonText">{{ _('Connect') }}</button>
<button class="btn btn-block" id="printer_connect" data-test-id="connection-connect" data-bind="click: connect, text: buttonText, enable: enableConnect">{{ _('Connect') }}</button>
@@ -3367,7 +3367,7 @@ msgid ""
"will already\n"
" take care of that. Otherwise please take a look at the\n"
" <a "
"href=\"http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
"href=\"https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
" target=\"_blank\">Documentation</a>.\n"
" </p>\n"
msgstr ""
@@ -3379,7 +3379,7 @@ msgstr ""
"Checkoutverzeichnis auf einen anderen Branch gewechselt hast, dann "
"<strong>wechsle das Tracking einfach auf \"Commit\"</strong>. Ansonsten "
"wirf einen Blick in die <a "
"href=\"http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
"href=\"https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
" target=\"_blank\">Dokumentation</a>. </p>\n"
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:18
@@ -7881,7 +7881,7 @@ msgstr "Gedruckt"
#: src/octoprint/templates/sidebar/state.jinja2:29
msgid "Restart"
msgstr "Restart"
msgstr "Neustart"
#: src/octoprint/templates/sidebar/state.jinja2:29
msgid "Print"
+11 -6
View File
@@ -28,7 +28,7 @@ from collections.abc import Iterable, MutableMapping, Set
from functools import wraps
from typing import Union
from immutabledict import immutabledict
from frozendict import frozendict
from octoprint import UMASK
from octoprint.util.connectivity import ConnectivityChecker # noqa: F401
@@ -1163,20 +1163,25 @@ glob_escape = deprecated(
)(glob.escape)
def thaw_immutabledict(obj):
if not isinstance(obj, (dict, immutabledict)):
raise ValueError("obj must be a dict or immutabledict instance")
def thaw_frozendict(obj):
if not isinstance(obj, (dict, frozendict)):
raise ValueError("obj must be a dict or frozendict instance")
# only true love can thaw a frozen dict
letitgo = {}
for key, value in obj.items():
if isinstance(value, (dict, immutabledict)):
letitgo[key] = thaw_immutabledict(value)
if isinstance(value, (dict, frozendict)):
letitgo[key] = thaw_frozendict(value)
else:
letitgo[key] = copy.deepcopy(value)
return letitgo
thaw_immutabledict = deprecated(
"thaw_immutabledict has been renamed back to thaw_frozendict", since="1.8.0"
)(thaw_frozendict)
def utmify(link, source=None, medium=None, name=None, term=None, content=None):
if source is None:
return link
+31 -19
View File
@@ -1663,6 +1663,10 @@ class MachineCom:
# we aren't even printing, nothing to cancel...
return
if self.isCancelling():
# we are already cancelling
return
if "source:plugin" in tags:
for tag in tags:
if tag.startswith("plugin:"):
@@ -4575,9 +4579,9 @@ class MachineCom:
# send it through the phase specific handlers provided by plugins
for name, hook in self._gcode_hooks[phase].items():
new_results = []
for command, command_type, gcode, subcode, tags in results:
try:
try:
new_results = []
for command, command_type, gcode, subcode, tags in results:
hook_results = hook(
self,
phase,
@@ -4587,17 +4591,7 @@ class MachineCom:
subcode=subcode,
tags=tags,
)
except Exception:
self._logger.exception(
"Error while processing hook {name} for phase "
"{phase} and command {command}:".format(
name=name,
phase=phase,
command=to_unicode(command, errors="replace"),
),
extra={"plugin": name},
)
else:
normalized = _normalize_command_handler_result(
command,
command_type,
@@ -4629,10 +4623,23 @@ class MachineCom:
new_results.append((command, command_type, gcode, subcode, tags))
else:
new_results += normalized
if not new_results:
# hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result
return []
results = new_results
except Exception:
self._logger.exception(
"Error while processing hook {name} for phase "
"{phase}:".format(
name=name,
phase=phase,
),
extra={"plugin": name},
)
else:
if not new_results:
# hook handler returned None or empty list for all commands, so
# we'll stop here and return a full out empty result
return []
results = new_results
# if it's a gcode command send it through the specific handler if it exists
new_results = []
@@ -5373,6 +5380,7 @@ class MachineCom:
},
)
return (None,)
if gcode in self._ignored_commands:
message = "Not sending {} to printer, it's configured as an ignored command".format(
gcode
@@ -5392,7 +5400,11 @@ class MachineCom:
def _command_phase_sending(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
if gcode is not None and gcode in self._long_running_commands:
if (
gcode is not None
and gcode in self._long_running_commands
or cmd in self._long_running_commands
):
self._long_running_command = True
+2 -6
View File
@@ -5,11 +5,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
import collections
import json
try:
from immutabledict import immutabledict
except ImportError:
# Python 2
from frozendict import frozendict as immutabledict
from frozendict import frozendict
from octoprint.util import to_unicode
@@ -46,5 +42,5 @@ class JsonEncoding:
raise TypeError
JsonEncoding.add_encoder(immutabledict, lambda obj: dict(obj))
JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj))
JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj))
+63 -49
View File
@@ -21,60 +21,15 @@ def get_octoprint_version(cut=None, **kwargs):
def is_released_octoprint_version(version=None):
"""
>>> import pkg_resources
>>> is_released_octoprint_version(version=pkg_resources.parse_version("1.3.6rc3"))
True
>>> is_released_octoprint_version(version=pkg_resources.parse_version("1.3.6rc3.dev2+g1234"))
False
>>> is_released_octoprint_version(version=pkg_resources.parse_version("1.3.6"))
True
>>> is_released_octoprint_version(version=pkg_resources.parse_version("1.3.6.post1+g1234"))
True
>>> is_released_octoprint_version(version=pkg_resources.parse_version("1.3.6.post1.dev0+g1234"))
False
>>> is_released_octoprint_version(version=pkg_resources.parse_version("1.3.7.dev123+g23545"))
False
"""
if version is None:
version = get_octoprint_version()
if isinstance(version, tuple):
# old setuptools
return "*@" not in version
else:
# new setuptools
return "dev" not in version.public
return is_release(version)
def is_stable_octoprint_version(version=None):
"""
>>> import pkg_resources
>>> is_stable_octoprint_version(version=pkg_resources.parse_version("1.3.6rc3"))
False
>>> is_stable_octoprint_version(version=pkg_resources.parse_version("1.3.6rc3.dev2+g1234"))
False
>>> is_stable_octoprint_version(version=pkg_resources.parse_version("1.3.6"))
True
>>> is_stable_octoprint_version(version=pkg_resources.parse_version("1.3.6.post1+g1234"))
True
>>> is_stable_octoprint_version(version=pkg_resources.parse_version("1.3.6.post1.dev0+g1234"))
False
>>> is_stable_octoprint_version(version=pkg_resources.parse_version("1.3.7.dev123+g23545"))
False
"""
if version is None:
version = get_octoprint_version()
if not is_released_octoprint_version(version=version):
return False
if isinstance(version, tuple):
return "*a" not in version and "*b" not in version and "*c" not in version
else:
return not version.is_prerelease
return is_stable(version)
def is_octoprint_compatible(*compatibility_entries, **kwargs):
@@ -193,8 +148,67 @@ def get_comparable_version(version_string, cut=None, **kwargs):
return version
def is_prerelease(version_string):
version = get_comparable_version(version_string)
def is_stable(version):
"""
>>> import pkg_resources
>>> is_stable(pkg_resources.parse_version("1.3.6rc3"))
False
>>> is_stable(pkg_resources.parse_version("1.3.6rc3.dev2+g1234"))
False
>>> is_stable(pkg_resources.parse_version("1.3.6"))
True
>>> is_stable(pkg_resources.parse_version("1.3.6.post1+g1234"))
True
>>> is_stable(pkg_resources.parse_version("1.3.6.post1.dev0+g1234"))
False
>>> is_stable(pkg_resources.parse_version("1.3.7.dev123+g23545"))
False
"""
if isinstance(version, str):
version = get_comparable_version(version)
if not is_release(version):
return False
if isinstance(version, tuple):
return "*a" not in version and "*b" not in version and "*c" not in version
else:
return not version.is_prerelease
def is_release(version):
"""
>>> import pkg_resources
>>> is_release(pkg_resources.parse_version("1.3.6rc3"))
True
>>> is_release(pkg_resources.parse_version("1.3.6rc3.dev2+g1234"))
False
>>> is_release(pkg_resources.parse_version("1.3.6"))
True
>>> is_release(pkg_resources.parse_version("1.3.6.post1+g1234"))
True
>>> is_release(pkg_resources.parse_version("1.3.6.post1.dev0+g1234"))
False
>>> is_release(pkg_resources.parse_version("1.3.7.dev123+g23545"))
False
"""
if isinstance(version, str):
version = get_comparable_version(version)
if isinstance(version, tuple):
# old setuptools
return "*@" not in version
else:
# new setuptools
return "dev" not in version.public
pass
def is_prerelease(version):
if isinstance(version, str):
version = get_comparable_version(version)
if isinstance(version, tuple):
# old setuptools
+9 -14
View File
@@ -5,12 +5,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
import unittest
import ddt
try:
from immutabledict import immutabledict
except ImportError:
# Python 2
from frozendict import frozendict as immutabledict
from frozendict import frozendict
import octoprint.util
@@ -68,35 +63,35 @@ class MiscTestCase(unittest.TestCase):
self.assertEqual(actual, expected)
@ddt.data(
(immutabledict(a=1, b=2, c=3), {"a": 1, "b": 2, "c": 3}),
(frozendict(a=1, b=2, c=3), {"a": 1, "b": 2, "c": 3}),
(
immutabledict(a=1, b=2, c=immutabledict(c1=1, c2=2)),
frozendict(a=1, b=2, c=frozendict(c1=1, c2=2)),
{"a": 1, "b": 2, "c": {"c1": 1, "c2": 2}},
),
({"a": 1, "b": 2, "c": 3}, {"a": 1, "b": 2, "c": 3}),
(
{"a": 1, "b": 2, "c": immutabledict(c1=1, c2=2)},
{"a": 1, "b": 2, "c": frozendict(c1=1, c2=2)},
{"a": 1, "b": 2, "c": {"c1": 1, "c2": 2}},
),
(
{
"a": 1,
"b": 2,
"c": {"c1": 1, "c2": 2, "c3": immutabledict(c11=11, c12=12)},
"c": {"c1": 1, "c2": 2, "c3": frozendict(c11=11, c12=12)},
},
{"a": 1, "b": 2, "c": {"c1": 1, "c2": 2, "c3": {"c11": 11, "c12": 12}}},
),
)
@ddt.unpack
def test_unfreeze_immutabledict(self, input, expected):
result = octoprint.util.thaw_immutabledict(input)
def test_unfreeze_frozendict(self, input, expected):
result = octoprint.util.thaw_frozendict(input)
self.assertIsInstance(result, dict)
self.assertDictEqual(result, expected)
@ddt.data(None, "invalid", 3, [1, 2], (3, 4))
def test_unfreeze_immutabledict_invalid(self, input):
def test_unfreeze_frozendict_invalid(self, input):
try:
octoprint.util.thaw_immutabledict(input)
octoprint.util.thaw_frozendict(input)
self.fail("expected ValueError")
except ValueError:
# expected
Binary file not shown.
+3 -4
View File
@@ -3367,7 +3367,7 @@ msgid ""
"will already\n"
" take care of that. Otherwise please take a look at the\n"
" <a "
"href=\"http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
"href=\"https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
" target=\"_blank\">Documentation</a>.\n"
" </p>\n"
msgstr ""
@@ -3379,7 +3379,7 @@ msgstr ""
"Checkoutverzeichnis auf einen anderen Branch gewechselt hast, dann "
"<strong>wechsle das Tracking einfach auf \"Commit\"</strong>. Ansonsten "
"wirf einen Blick in die <a "
"href=\"http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
"href=\"https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
" target=\"_blank\">Dokumentation</a>. </p>\n"
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:18
@@ -7881,7 +7881,7 @@ msgstr "Gedruckt"
#: src/octoprint/templates/sidebar/state.jinja2:29
msgid "Restart"
msgstr "Restart"
msgstr "Neustart"
#: src/octoprint/templates/sidebar/state.jinja2:29
msgid "Print"
@@ -8998,4 +8998,3 @@ msgstr "Ungerenderte Zeitrafferaufnahme löschen"
#: src/octoprint/templates/tabs/timelapse.jinja2:201
msgid "Render timelapse"
msgstr "Zeitrafferaufnahme rendern"
+1 -1
View File
@@ -2934,7 +2934,7 @@ msgid ""
"will already\n"
" take care of that. Otherwise please take a look at the\n"
" <a "
"href=\"http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
"href=\"https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\""
" target=\"_blank\">Documentation</a>.\n"
" </p>\n"
msgstr ""