Merge branch 'maintenance' into devel
This commit is contained in:
commit
a8e9105769
71 files changed
+701
-1031
No files matched your search
@@ -76,10 +76,10 @@ body:
|
||||
Issues caused by a third party plugin are a major cause of bugs reported here, so we really need to
|
||||
rule out that a plugin is at fault here. [Safe mode](https://docs.octoprint.org/en/master/features/safemode.html) is an easy way to do that. Only skip safe mode
|
||||
if your particular problem *absolutely requires* third party plugins to be enabled. "It would take
|
||||
too long" is **not** a reason to skip testing in safe mode, neither is "I do not know how to
|
||||
too long" or "I have a long print running right now" are **not** a reason to skip testing in safe mode, neither is "I do not know how to
|
||||
enable it" as you can find info on that [here](https://docs.octoprint.org/en/master/features/safemode.html).
|
||||
|
||||
If you really *cannot* test in safe mode, leave a short explanation as to why.
|
||||
If you really *cannot* test in safe mode at all, leave a short explanation as to why. If you,can but just not right now, then wait with reporting until you can.
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
name: 🧪 Unit tests
|
||||
strategy:
|
||||
matrix:
|
||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10", "3.11"]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -84,7 +84,7 @@ jobs:
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10", "3.11"]
|
||||
installable: ["wheel", "sdist"]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: ["ubuntu-latest"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10", "3.11"]
|
||||
branch: ["master"]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: ["ubuntu-latest"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10", "3.11"]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: 👀 Determine latest release
|
||||
|
||||
@@ -48,10 +48,11 @@ repos:
|
||||
- id: black
|
||||
additional_dependencies:
|
||||
- click==8.0.4
|
||||
- repo: https://gitlab.com/pycqa/flake8
|
||||
- repo: https://github.com/pycqa/flake8
|
||||
rev: 3.9.2
|
||||
hooks:
|
||||
- id: flake8
|
||||
args: [--config=setup.cfg]
|
||||
additional_dependencies:
|
||||
- flake8-bugbear==22.3.20
|
||||
- importlib-metadata<5.0
|
||||
|
||||
@@ -87,7 +87,7 @@ access control as necessary.
|
||||
OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing
|
||||
OctoPrint via `pip`.
|
||||
|
||||
OctoPrint currently supports Python 3.7, 3.8, 3.9 and 3.10.
|
||||
OctoPrint currently supports Python 3.7, 3.8, 3.9, 3.10 and 3.11.
|
||||
|
||||
## Usage
|
||||
|
||||
|
||||
@@ -605,6 +605,17 @@ GcodeScript${ScriptName}Finished
|
||||
|
||||
.. versionadded:: 1.6.0
|
||||
|
||||
ChartMarked
|
||||
A time-based marking has been made on the UI's temperature chart.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``type``: the marking's ID. Built-in types are ``print``, ``done``, ``cancel``, ``pause``, and ``resume``. Plugins may set arbitrary types
|
||||
* ``label``: the human-readable short label of the marking
|
||||
* ``time``: the epoch time of marking
|
||||
|
||||
.. versionadded:: 1.9.0
|
||||
|
||||
.. _sec-events-available_events-gcode_processing:
|
||||
|
||||
GCODE processing
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=40.8.0", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[tool.black]
|
||||
line-length = 90
|
||||
include = '''
|
||||
|
||||
@@ -10,19 +10,24 @@
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from distutils.command.build_py import build_py as _build_py
|
||||
|
||||
import versioneer # noqa: F401
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
|
||||
import setuptools # noqa: F401,E402
|
||||
|
||||
import octoprint_setuptools # noqa: F401,E402
|
||||
try:
|
||||
import octoprint_setuptools # noqa: F401,E402
|
||||
except ImportError:
|
||||
octoprint_setuptools = None
|
||||
|
||||
import versioneer # noqa: F401
|
||||
|
||||
# ----------------------------------------------------------------------------------------
|
||||
|
||||
# Supported python versions
|
||||
PYTHON_REQUIRES = ">=3.7, <4"
|
||||
PYTHON_REQUIRES = ">=3.7, <3.12"
|
||||
|
||||
# Requirements for setup.py
|
||||
SETUP_REQUIRES = []
|
||||
@@ -55,6 +60,7 @@ core_deps = [
|
||||
"pathvalidate>=2.4.1,<3",
|
||||
"pkginfo>=1.7.1,<2",
|
||||
"psutil>=5.8,<6",
|
||||
"pydantic>=1.10.2,<2",
|
||||
"pylru>=1.2,<2",
|
||||
"pyserial>=3.4,<4",
|
||||
"PyYAML>=5.4.1,<6",
|
||||
@@ -69,16 +75,19 @@ core_deps = [
|
||||
"wrapt>=1.14,<1.15",
|
||||
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
|
||||
"zipstream-ng>=1.3.4,<2.0.0",
|
||||
"pydantic>=1.9.1,<2",
|
||||
"pydantic-settings>=0.2.5,<1", # TODO: replace with vendored with_attrs_docs
|
||||
]
|
||||
vendored_deps = [
|
||||
"blinker>=1.4,<2", # dependency of flask_principal
|
||||
"class-doc>=0.2.6,<0.3", # dependency of with_attrs_docs
|
||||
"regex", # dependency of awesome-slugify
|
||||
"unidecode", # dependency of awesome-slugify
|
||||
]
|
||||
plugin_deps = [
|
||||
"OctoPrint-Setuptools>=1.0.1", # makes sure plugins can import this on setup.py based install
|
||||
"wheel", # makes sure plugins can be built as wheels in OctoPrint's venv, see #4682
|
||||
]
|
||||
|
||||
INSTALL_REQUIRES = bundled_plugins + core_deps + vendored_deps
|
||||
INSTALL_REQUIRES = bundled_plugins + core_deps + vendored_deps + plugin_deps
|
||||
|
||||
# Additional requirements for optional install options and/or OS-specific dependencies
|
||||
EXTRA_REQUIRES = {
|
||||
@@ -161,28 +170,29 @@ def get_cmdclass():
|
||||
|
||||
cmdclass = versioneer.get_cmdclass()
|
||||
|
||||
# add clean command
|
||||
cmdclass.update(
|
||||
{
|
||||
"clean": octoprint_setuptools.CleanCommand.for_options(
|
||||
source_folder="src", eggs=["OctoPrint*.egg-info"]
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
# add translation commands
|
||||
translation_dir = "translations"
|
||||
pot_file = os.path.join(translation_dir, "messages.pot")
|
||||
bundled_dir = os.path.join("src", "octoprint", "translations")
|
||||
cmdclass.update(
|
||||
octoprint_setuptools.get_babel_commandclasses(
|
||||
pot_file=pot_file,
|
||||
output_dir=translation_dir,
|
||||
pack_name_prefix="OctoPrint-i18n-",
|
||||
pack_path_prefix="",
|
||||
bundled_dir=bundled_dir,
|
||||
if octoprint_setuptools:
|
||||
# add clean command
|
||||
cmdclass.update(
|
||||
{
|
||||
"clean": octoprint_setuptools.CleanCommand.for_options(
|
||||
source_folder="src", eggs=["OctoPrint*.egg-info"]
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
# add translation commands
|
||||
translation_dir = "translations"
|
||||
pot_file = os.path.join(translation_dir, "messages.pot")
|
||||
bundled_dir = os.path.join("src", "octoprint", "translations")
|
||||
cmdclass.update(
|
||||
octoprint_setuptools.get_babel_commandclasses(
|
||||
pot_file=pot_file,
|
||||
output_dir=translation_dir,
|
||||
pack_name_prefix="OctoPrint-i18n-",
|
||||
pack_path_prefix="",
|
||||
bundled_dir=bundled_dir,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
cmdclass["build_py"] = copy_files_build_py_factory(
|
||||
{
|
||||
@@ -198,6 +208,22 @@ def get_cmdclass():
|
||||
return cmdclass
|
||||
|
||||
|
||||
def package_data_dirs(source, sub_folders):
|
||||
dirs = []
|
||||
|
||||
for d in sub_folders:
|
||||
folder = os.path.join(source, d)
|
||||
if not os.path.exists(folder):
|
||||
continue
|
||||
|
||||
for dirname, _, files in os.walk(folder):
|
||||
dirname = os.path.relpath(dirname, source)
|
||||
for f in files:
|
||||
dirs.append(os.path.join(dirname, f))
|
||||
|
||||
return dirs
|
||||
|
||||
|
||||
def params():
|
||||
# make sure these are always available, even when run by dependabot
|
||||
global versioneer, get_cmdclass, read_file_contents, here, PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES
|
||||
@@ -235,6 +261,8 @@ def params():
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3 :: Only",
|
||||
"Programming Language :: Python :: Implementation :: CPython",
|
||||
"Programming Language :: JavaScript",
|
||||
"Topic :: Printing",
|
||||
@@ -258,7 +286,7 @@ def params():
|
||||
"": "src",
|
||||
}
|
||||
package_data = {
|
||||
"octoprint": octoprint_setuptools.package_data_dirs(
|
||||
"octoprint": package_data_dirs(
|
||||
"src/octoprint", ["static", "templates", "plugins", "translations"]
|
||||
)
|
||||
+ ["util/piptestballoon/setup.py"]
|
||||
|
||||
@@ -185,7 +185,7 @@ class PluginIdentityContext:
|
||||
# check the permission here
|
||||
if not permission.can():
|
||||
if self.http_exception:
|
||||
abort(self.http_exception, permission)
|
||||
abort(self.http_exception)
|
||||
raise PermissionDenied(permission)
|
||||
|
||||
def __exit__(self, *args):
|
||||
@@ -419,16 +419,16 @@ class Permissions(metaclass=PermissionsMetaClass):
|
||||
RoleNeed("timelapse_delete"),
|
||||
default_groups=[USER_GROUP],
|
||||
)
|
||||
TIMELAPSE_MANAGE_UNRENDERED = OctoPrintPermission(
|
||||
"Timelapse Manage Unrendered",
|
||||
gettext("Allows to list, delete and render unrendered timelapses"),
|
||||
RoleNeed("timelapse_manage_unrendered"),
|
||||
default_groups=[USER_GROUP],
|
||||
)
|
||||
TIMELAPSE_ADMIN = OctoPrintPermission(
|
||||
"Timelapse Admin",
|
||||
gettext(
|
||||
"Allows to change the timelapse settings and delete or "
|
||||
'render unrendered timelapses. Includes the "Timelapse List",'
|
||||
'"Timelapse Delete" and "Timelapse Download" permissions'
|
||||
),
|
||||
gettext("Allows to change the timelapse settings."),
|
||||
RoleNeed("timelapse_admin"),
|
||||
TIMELAPSE_LIST,
|
||||
TIMELAPSE_DOWNLOAD,
|
||||
default_groups=[USER_GROUP],
|
||||
)
|
||||
|
||||
|
||||
@@ -81,6 +81,7 @@ class Events:
|
||||
PRINT_PAUSED = "PrintPaused"
|
||||
PRINT_RESUMED = "PrintResumed"
|
||||
ERROR = "Error"
|
||||
CHART_MARKED = "ChartMarked"
|
||||
|
||||
# print/gcode events
|
||||
POWER_ON = "PowerOn"
|
||||
|
||||
@@ -29,7 +29,7 @@ $(function () {
|
||||
};
|
||||
|
||||
self.fromResponse = function (data) {
|
||||
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
|
||||
if (data && data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
|
||||
self.text(data.text);
|
||||
self.buttons(data.choices);
|
||||
self.showPrompt();
|
||||
|
||||
@@ -17,7 +17,9 @@ class EventManagerPlugin(
|
||||
}
|
||||
events = self._settings.global_get(["events"])
|
||||
if events:
|
||||
my_settings["subscriptions"] = events.get("subscriptions", [])
|
||||
my_settings["subscriptions"] = sorted(
|
||||
events.get("subscriptions", []), key=(lambda x: x["event"])
|
||||
)
|
||||
return my_settings
|
||||
|
||||
def on_settings_save(self, data):
|
||||
|
||||
@@ -16,6 +16,7 @@ $(function () {
|
||||
return {
|
||||
event: ko.observable(""),
|
||||
command: ko.observable(""),
|
||||
name: ko.observable(""),
|
||||
type: ko.observable(""),
|
||||
enabled: ko.observable(true),
|
||||
debug: ko.observable(false)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
</div>
|
||||
<div class="row-fluid">
|
||||
<div class="span4">{{ _('Event') }}</div>
|
||||
<div class="span6">{{ _('Command') }}</div>
|
||||
<div class="span6">{{ _('Name') }}</div>
|
||||
<div class="span2 btn-group">
|
||||
<button class="btn btn-mini" data-bind="click: addEvent"><i class="fa fa-plus"></i> {{ _('Add') }}</button>
|
||||
</div>
|
||||
@@ -12,7 +12,7 @@
|
||||
<div data-bind="foreach: settingsViewModel.settings.plugins.eventmanager.subscriptions" class="row-fluid">
|
||||
<div class="row-fluid">
|
||||
<div class="span4" data-bind="text: event"></div>
|
||||
<div class="span6" data-bind="text: command"></div>
|
||||
<div class="span6" data-bind="attr: {title: command}, text: name() ? name() : command()"></div>
|
||||
<div class="span2 btn-group">
|
||||
<button class="btn btn-mini" data-bind="click: $root.editEvent"><i class="fa fa-pencil"></i></button>
|
||||
<button class="btn btn-mini btn-danger" data-bind="click: $root.removeEvent"><i class="fa fa-trash-alt"></i></button>
|
||||
@@ -32,6 +32,13 @@
|
||||
<select class="input-block-level" data-bind="value: event, options: $root.settingsViewModel.settings.plugins.eventmanager.availableEvents().sort(), optionsCaption: 'Select Event', valueAllowUnset: true"></select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: name" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Command') }}</label>
|
||||
<div class="controls">
|
||||
|
||||
@@ -339,6 +339,7 @@ $(function () {
|
||||
|
||||
self.loadedFilepath = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
self.loadedFileSize = undefined;
|
||||
self.status = "idle";
|
||||
self.enabled = false;
|
||||
|
||||
@@ -417,6 +418,7 @@ $(function () {
|
||||
self.enableReload(false);
|
||||
self.loadedFilepath = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
self.loadedFileSize = undefined;
|
||||
self.clear();
|
||||
};
|
||||
|
||||
@@ -505,7 +507,7 @@ $(function () {
|
||||
});
|
||||
};
|
||||
|
||||
self.loadFile = function (path, date) {
|
||||
self.loadFile = function (path, date, size) {
|
||||
self.enableReload(false);
|
||||
self.needsLoad = false;
|
||||
if (self.status === "idle" && self.errorCount < 3) {
|
||||
@@ -513,9 +515,11 @@ $(function () {
|
||||
|
||||
self.cachedPath = path;
|
||||
self.cachedDate = date;
|
||||
self.cachedSize = size;
|
||||
var par = {
|
||||
url: OctoPrint.files.downloadPath("local", path),
|
||||
path: path,
|
||||
size: size,
|
||||
skipUntil: self.settings.settings.plugins.gcodeviewer.skipUntilThis()
|
||||
};
|
||||
|
||||
@@ -535,13 +539,14 @@ $(function () {
|
||||
self._onFileLoaded = function () {
|
||||
self.loadedFilepath = self.cachedPath;
|
||||
self.loadedFileDate = self.cachedDate;
|
||||
self.loadedFileSize = self.cachedSize;
|
||||
self.status = "idle";
|
||||
self.enableReload(true);
|
||||
};
|
||||
|
||||
self.reload = function () {
|
||||
if (!self.enableReload()) return;
|
||||
self.loadFile(self.loadedFilepath, self.loadedFileDate);
|
||||
self.loadFile(self.loadedFilepath, self.loadedFileDate, self.loadedFileSize);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function (data) {
|
||||
@@ -576,6 +581,7 @@ $(function () {
|
||||
|
||||
self.loadedFilepath = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
self.loadedFileSize = undefined;
|
||||
self.selectedFile.path(undefined);
|
||||
self.selectedFile.date(undefined);
|
||||
self.selectedFile.size(undefined);
|
||||
@@ -591,7 +597,8 @@ $(function () {
|
||||
if (
|
||||
self.loadedFilepath &&
|
||||
self.loadedFilepath === data.job.file.path &&
|
||||
self.loadedFileDate === data.job.file.date
|
||||
self.loadedFileDate === data.job.file.date &&
|
||||
self.loadedFileSize === data.job.file.size
|
||||
) {
|
||||
if (
|
||||
OctoPrint.coreui.browserTabVisible &&
|
||||
@@ -611,7 +618,8 @@ $(function () {
|
||||
self.status !== "request" &&
|
||||
(!self.waitForApproval() ||
|
||||
self.selectedFile.path() !== data.job.file.path ||
|
||||
self.selectedFile.date() !== data.job.file.date)
|
||||
self.selectedFile.date() !== data.job.file.date ||
|
||||
self.selectedFile.size() !== data.job.file.size)
|
||||
) {
|
||||
self.selectedFile.path(data.job.file.path);
|
||||
self.selectedFile.date(data.job.file.date);
|
||||
@@ -627,10 +635,15 @@ $(function () {
|
||||
self.waitForApproval(true);
|
||||
self.loadedFilepath = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
self.loadedFileSize = undefined;
|
||||
} else {
|
||||
self.waitForApproval(false);
|
||||
if (self.tabActive) {
|
||||
self.loadFile(data.job.file.path, data.job.file.date);
|
||||
self.loadFile(
|
||||
data.job.file.path,
|
||||
data.job.file.date,
|
||||
data.job.file.size
|
||||
);
|
||||
} else {
|
||||
self.needsLoad = true;
|
||||
}
|
||||
@@ -647,7 +660,11 @@ $(function () {
|
||||
|
||||
self.approveLargeFile = function () {
|
||||
self.waitForApproval(false);
|
||||
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
|
||||
self.loadFile(
|
||||
self.selectedFile.path(),
|
||||
self.selectedFile.date(),
|
||||
self.selectedFile.size()
|
||||
);
|
||||
};
|
||||
|
||||
self._onProgress = function (type, percentage) {
|
||||
@@ -872,7 +889,8 @@ $(function () {
|
||||
self.onTabChange = function (current, previous) {
|
||||
self.tabActive = current === "#gcode";
|
||||
if (self.tabActive && self.needsLoad) {
|
||||
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
|
||||
self.loadFile(self.selectedFile.path(), self.selectedFile.date()),
|
||||
self.selectedFile.size();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -214,7 +214,7 @@ GCODE.gCodeReader = (function () {
|
||||
gCodeOptions["forceCompression"] ||
|
||||
gCodeOptions["alwaysCompress"] ||
|
||||
(gCodeOptions["compressionSizeThreshold"] > 0 &&
|
||||
gCodeOptions["compressionSizeThreshold"] <= totalSize);
|
||||
gCodeOptions["compressionSizeThreshold"] <= reader.size);
|
||||
|
||||
GCODE.ui.worker.postMessage({
|
||||
cmd: "downloadAndParseGCode",
|
||||
|
||||
@@ -54,6 +54,7 @@ class VirtualPrinterPlugin(
|
||||
"AUTOREPORT_POS": False,
|
||||
"EMERGENCY_PARSER": True,
|
||||
"EXTENDED_M20": False,
|
||||
"LFN_WRITE": False,
|
||||
},
|
||||
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
|
||||
"m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}",
|
||||
|
||||
@@ -10,6 +10,7 @@ import queue
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from serial import SerialTimeoutException
|
||||
|
||||
@@ -52,7 +53,7 @@ class VirtualPrinter:
|
||||
self._plugin_data_folder = data_folder
|
||||
|
||||
self._seriallog = logging.getLogger(
|
||||
"octoprint.plugin.virtual_printer.VirtualPrinter.serial"
|
||||
"octoprint.plugins.virtual_printer.VirtualPrinter.serial"
|
||||
)
|
||||
self._seriallog.setLevel(logging.CRITICAL)
|
||||
self._seriallog.propagate = False
|
||||
@@ -665,8 +666,7 @@ class VirtualPrinter:
|
||||
filename = data.split(None, 1)[1].strip()
|
||||
if filename.startswith("/"):
|
||||
filename = filename[1:]
|
||||
files = self._mappedSdList()
|
||||
file = files.get(filename.lower())
|
||||
file = self._getSdFileData(filename)
|
||||
if file is not None:
|
||||
self._send(file["name"])
|
||||
|
||||
@@ -700,10 +700,27 @@ class VirtualPrinter:
|
||||
# we'll just use this to echo a message, to allow playing around with pause triggers
|
||||
if self._echoOnM117:
|
||||
try:
|
||||
self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1))
|
||||
result = re.search(r"M117\s+(.*)", data).group(1)
|
||||
self._send(f"echo:{result}")
|
||||
except AttributeError:
|
||||
self._send("echo:")
|
||||
|
||||
def _gcode_M118(self, data: str) -> None:
|
||||
match = re.search(r"M118 (?:(?P<parameter>A1|E1|Pn[012])\s)?(?P<text>.*)", data)
|
||||
if not match:
|
||||
self._send("Unrecognized command parameters for M118")
|
||||
else:
|
||||
result = match.groupdict()
|
||||
text = result["text"]
|
||||
parameter = result["parameter"]
|
||||
|
||||
if parameter == "A1":
|
||||
self._send(f"//{text}")
|
||||
elif parameter == "E1":
|
||||
self._send(f"echo:{text}")
|
||||
else:
|
||||
self._send(text)
|
||||
|
||||
def _gcode_M154(self, data: str) -> None:
|
||||
matchS = re.search(r"S([0-9]+)", data)
|
||||
if matchS is not None:
|
||||
@@ -1394,16 +1411,13 @@ class VirtualPrinter:
|
||||
else:
|
||||
line += " {name}"
|
||||
|
||||
files = self._mappedSdList()
|
||||
items = map(lambda x: line.format(**x), files.values())
|
||||
|
||||
self._send("Begin file list")
|
||||
for item in items:
|
||||
for item in map(lambda x: line.format(**x), self._getSdFiles()):
|
||||
self._send(item)
|
||||
self._send("End file list")
|
||||
|
||||
def _mappedSdList(self) -> collections.OrderedDict:
|
||||
result = collections.OrderedDict()
|
||||
def _mappedSdList(self) -> Dict[str, Dict[str, Any]]:
|
||||
result = {}
|
||||
for entry in os.scandir(self._virtualSd):
|
||||
if not entry.is_file():
|
||||
continue
|
||||
@@ -1412,27 +1426,41 @@ class VirtualPrinter:
|
||||
).lower()
|
||||
if entry.name.startswith("."):
|
||||
dosname = "." + dosname
|
||||
result[dosname] = {
|
||||
data = {
|
||||
"name": entry.name,
|
||||
"path": entry.path,
|
||||
"dosname": dosname,
|
||||
"size": entry.stat().st_size,
|
||||
"timestamp": unix_timestamp_to_m20_timestamp(entry.stat().st_mtime),
|
||||
}
|
||||
# index by lower case, we simulate a case insensitive filesystem like FAT,
|
||||
# which should be closest to what we encounter in reality
|
||||
result[entry.name.lower()] = data
|
||||
result[dosname.lower()] = entry.name.lower()
|
||||
return result
|
||||
|
||||
def _getSdFileData(self, filename: str) -> Optional[Dict[str, Any]]:
|
||||
files = self._mappedSdList()
|
||||
data = files.get(filename.lower())
|
||||
if isinstance(data, str):
|
||||
data = files.get(data.lower())
|
||||
return data
|
||||
|
||||
def _getSdFiles(self) -> List[Dict[str, Any]]:
|
||||
files = self._mappedSdList()
|
||||
return [x for x in files.values() if isinstance(x, dict)]
|
||||
|
||||
def _selectSdFile(self, filename: str, check_already_open: bool = False) -> None:
|
||||
if filename.startswith("/"):
|
||||
filename = filename[1:]
|
||||
|
||||
files = self._mappedSdList()
|
||||
file = files.get(filename)
|
||||
file = self._getSdFileData(filename)
|
||||
if (
|
||||
file is None
|
||||
or not os.path.exists(file["path"])
|
||||
or not os.path.isfile(file["path"])
|
||||
):
|
||||
self._send("open failed, File: %s." % filename)
|
||||
self._send(f"open failed, File: {file['name']}.")
|
||||
return
|
||||
|
||||
if self._selectedSdFile == file["path"] and check_already_open:
|
||||
@@ -1441,7 +1469,7 @@ class VirtualPrinter:
|
||||
self._selectedSdFile = file["path"]
|
||||
self._selectedSdFileSize = file["size"]
|
||||
if self._settings.get_boolean(["includeFilenameInOpened"]):
|
||||
self._send("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
|
||||
self._send(f"File opened: {file['name']} Size: {self._selectedSdFileSize}")
|
||||
else:
|
||||
self._send("File opened")
|
||||
self._send("File selected")
|
||||
@@ -1463,8 +1491,7 @@ class VirtualPrinter:
|
||||
def _reportSdStatus(self):
|
||||
if self._sdPrinter is not None and self._sdPrintingSemaphore.is_set:
|
||||
self._send(
|
||||
"SD printing byte %d/%d"
|
||||
% (self._selectedSdFilePos, self._selectedSdFileSize)
|
||||
f"SD printing byte {self._selectedSdFilePos}/{self._selectedSdFileSize}"
|
||||
)
|
||||
else:
|
||||
self._send("Not SD printing")
|
||||
@@ -1779,10 +1806,9 @@ class VirtualPrinter:
|
||||
self._lastE = 0
|
||||
|
||||
def _writeSdFile(self, filename: str) -> None:
|
||||
filename = filename
|
||||
if filename.startswith("/"):
|
||||
filename = filename[1:]
|
||||
file = os.path.join(self._virtualSd, filename.lower())
|
||||
file = os.path.join(self._virtualSd, filename)
|
||||
if os.path.exists(file):
|
||||
if os.path.isfile(file):
|
||||
os.remove(file)
|
||||
@@ -1798,7 +1824,7 @@ class VirtualPrinter:
|
||||
self._writingToSdFile = file
|
||||
self._writingToSd = True
|
||||
self._selectedSdFile = file
|
||||
self._send("Writing to file: %s" % filename)
|
||||
self._send(f"Writing to file: {filename}")
|
||||
|
||||
def _finishSdFile(self):
|
||||
try:
|
||||
@@ -1910,8 +1936,7 @@ class VirtualPrinter:
|
||||
def _deleteSdFile(self, filename: str) -> None:
|
||||
if filename.startswith("/"):
|
||||
filename = filename[1:]
|
||||
files = self._mappedSdList()
|
||||
file = files.get(filename)
|
||||
file = self._getSdFileData(filename)
|
||||
if (
|
||||
file is not None
|
||||
and os.path.exists(file["path"])
|
||||
|
||||
@@ -645,6 +645,18 @@ class PrinterProfileManager:
|
||||
|
||||
value[path[-1]] = converter(value[path[-1]])
|
||||
|
||||
def validate_value(profile, path, validator):
|
||||
value = profile
|
||||
for part in path[:-1]:
|
||||
if not isinstance(value, dict) or part not in value:
|
||||
raise RuntimeError("%s is not contained in profile" % ".".join(path))
|
||||
value = value[part]
|
||||
|
||||
if not isinstance(value, dict) or path[-1] not in value:
|
||||
raise RuntimeError("%s is not contained in profile" % ".".join(path))
|
||||
|
||||
return validator(value[path[-1]])
|
||||
|
||||
# convert ints
|
||||
for path in (
|
||||
("extruder", "count"),
|
||||
@@ -696,6 +708,21 @@ class PrinterProfileManager:
|
||||
)
|
||||
return False
|
||||
|
||||
# validate volume size range
|
||||
for path in (
|
||||
("volume", "width"),
|
||||
("volume", "depth"),
|
||||
("volume", "height"),
|
||||
):
|
||||
if not validate_value(profile, path, lambda x: x > 0 and x < 10000):
|
||||
return False
|
||||
|
||||
# validate extruder count range
|
||||
if not validate_value(
|
||||
profile, ("extruder", "count"), lambda x: x > 0 and x < 100
|
||||
):
|
||||
return False
|
||||
|
||||
# validate form factor
|
||||
if profile["volume"]["formFactor"] not in BedFormFactor.values():
|
||||
self._logger.warning(
|
||||
|
||||
@@ -78,7 +78,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
# sd handling
|
||||
self._sdPrinting = False
|
||||
self._sdStreaming = False
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._streamingFinishedCallback = None
|
||||
self._streamingFailedCallback = None
|
||||
|
||||
@@ -163,6 +162,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
eventManager().subscribe(
|
||||
Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated
|
||||
)
|
||||
eventManager().subscribe(Events.CHART_MARKED, self._on_event_ChartMarked)
|
||||
|
||||
self._handle_connect_hooks = plugin_manager().get_hooks(
|
||||
"octoprint.printer.handle_connect"
|
||||
@@ -306,6 +306,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._selectedFile["user"],
|
||||
)
|
||||
|
||||
# ~~ chart marking insertions
|
||||
|
||||
def _on_event_ChartMarked(self, event, data):
|
||||
self._markings.append(
|
||||
{
|
||||
"type": data.get("type", "unknown"),
|
||||
"label": data.get("label"),
|
||||
"time": data.get("time", time.time()),
|
||||
}
|
||||
)
|
||||
|
||||
# ~~ progress plugin reporting
|
||||
|
||||
def _reportPrintProgressToPlugins(self, progress):
|
||||
@@ -713,14 +724,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return self._comm.getFilePosition()
|
||||
|
||||
def add_marking(self, type):
|
||||
self._markings.append(
|
||||
{
|
||||
"type": type,
|
||||
"time": time.time(),
|
||||
}
|
||||
)
|
||||
|
||||
def get_markings(self):
|
||||
return self._markings
|
||||
|
||||
@@ -1003,12 +1006,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
remote_name = self._get_free_remote_name(filename)
|
||||
self._create_estimator("stream")
|
||||
self._comm.startFileTransfer(
|
||||
remote_name = self._comm.startFileTransfer(
|
||||
path,
|
||||
filename,
|
||||
"/" + remote_name,
|
||||
special=not valid_file_type(filename, "gcode"),
|
||||
tags=tags | {"trigger:printer.add_sd_file"},
|
||||
)
|
||||
@@ -1045,12 +1046,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"""
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._comm.refreshSdFiles(
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"}
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"},
|
||||
blocking=blocking,
|
||||
timeout=kwargs.get("timeout", 10),
|
||||
)
|
||||
if blocking and not self.is_printing():
|
||||
self._sdFilelistAvailable.wait(kwargs.get("timeout", 10))
|
||||
|
||||
# ~~ state monitoring
|
||||
|
||||
@@ -1221,7 +1221,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
)
|
||||
)
|
||||
|
||||
def _setJobData(self, filename, filesize, sd, user=None):
|
||||
def _setJobData(self, filename, filesize, sd, user=None, data=None):
|
||||
with self._selectedFileMutex:
|
||||
if filename is not None:
|
||||
if sd:
|
||||
@@ -1274,11 +1274,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
date = None
|
||||
filament = None
|
||||
display_name = name_in_storage
|
||||
|
||||
if path_on_disk:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# Use an int for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(path_on_disk).st_mtime)
|
||||
date = int(os.stat(path_on_disk).st_mtime)
|
||||
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(
|
||||
@@ -1325,6 +1325,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
|
||||
self._selectedFile["estimatedPrintTimeType"] = "analysis"
|
||||
|
||||
elif data:
|
||||
display_name = data.longname
|
||||
date = data.timestamp
|
||||
|
||||
self._stateMonitor.set_job_data(
|
||||
self._dict(
|
||||
file=self._dict(
|
||||
@@ -1535,9 +1539,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
def on_comm_sd_files(self, files):
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
self._sdFilelistAvailable.set()
|
||||
|
||||
def on_comm_file_selected(self, full_path, size, sd, user=None):
|
||||
def on_comm_file_selected(self, full_path, size, sd, user=None, data=None):
|
||||
if full_path is not None:
|
||||
payload = self._payload_for_print_job_event(
|
||||
location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
@@ -1560,7 +1563,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"Print job deselected - user: {}".format(user if user else "n/a")
|
||||
)
|
||||
|
||||
self._setJobData(full_path, size, sd, user=user)
|
||||
self._setJobData(full_path, size, sd, user=user, data=data)
|
||||
self._stateMonitor.set_state(
|
||||
self._dict(
|
||||
text=self.get_state_string(),
|
||||
@@ -1583,7 +1586,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
payload = self._payload_for_print_job_event(print_job_user=user, action_user=user)
|
||||
if payload:
|
||||
eventManager().fire(Events.PRINT_STARTED, payload)
|
||||
self.add_marking("print")
|
||||
eventManager().fire(
|
||||
Events.CHART_MARKED,
|
||||
{"type": "print", "label": "Start"},
|
||||
)
|
||||
self._logger_job.info(
|
||||
"Print job started - origin: {}, path: {}, owner: {}, user: {}".format(
|
||||
payload.get("origin"),
|
||||
@@ -1607,7 +1613,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
payload = self._payload_for_print_job_event()
|
||||
if payload:
|
||||
payload["time"] = self._comm.getPrintTime()
|
||||
self.add_marking("done")
|
||||
eventManager().fire(
|
||||
Events.CHART_MARKED,
|
||||
{"type": "done", "label": "Done"},
|
||||
)
|
||||
self._updateProgressData(
|
||||
completion=1.0,
|
||||
filepos=payload["size"],
|
||||
@@ -1684,7 +1693,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
payload["time"] = self._comm.getPrintTime()
|
||||
|
||||
eventManager().fire(Events.PRINT_CANCELLED, payload)
|
||||
self.add_marking("cancel")
|
||||
eventManager().fire(
|
||||
Events.CHART_MARKED,
|
||||
{"type": "cancel", "label": "Cancel"},
|
||||
)
|
||||
self._logger_job.info(
|
||||
"Print job cancelled - origin: {}, path: {}, owner: {}, user: {}".format(
|
||||
payload.get("origin"),
|
||||
@@ -1736,7 +1748,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
payload.get("user"),
|
||||
)
|
||||
)
|
||||
self.add_marking("pause")
|
||||
eventManager().fire(
|
||||
Events.CHART_MARKED,
|
||||
{"type": "pause", "label": "Pause"},
|
||||
)
|
||||
if not suppress_script:
|
||||
self.script(
|
||||
"afterPrintPaused",
|
||||
@@ -1749,7 +1764,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
payload = self._payload_for_print_job_event(action_user=user)
|
||||
if payload:
|
||||
eventManager().fire(Events.PRINT_RESUMED, payload)
|
||||
self.add_marking("resume")
|
||||
eventManager().fire(
|
||||
Events.CHART_MARKED,
|
||||
{"type": "resume", "label": "Resume"},
|
||||
)
|
||||
self._logger_job.info(
|
||||
"Print job resumed - origin: {}, path: {}, owner: {}, user: {}".format(
|
||||
payload.get("origin"),
|
||||
|
||||
@@ -1,2 +1,9 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from pydantic import BaseModel as PydanticBaseModel
|
||||
|
||||
|
||||
class BaseModel(PydanticBaseModel):
|
||||
class Config:
|
||||
use_enum_values = True
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import List, Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
from .access_control import AccessControlConfig
|
||||
from .api import ApiConfig
|
||||
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
from enum import Enum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
class ColorEnum(str, Enum):
|
||||
@@ -140,7 +140,7 @@ class AppearanceConfig(BaseModel):
|
||||
name: str = ""
|
||||
"""Use this to give your OctoPrint instance a name. It will be displayed in the title bar (as "<Name> [OctoPrint]") and in the navigation bar (as "OctoPrint: <>")"""
|
||||
|
||||
color: ColorEnum = "default"
|
||||
color: ColorEnum = ColorEnum.default
|
||||
"""Use this to color the navigation bar."""
|
||||
|
||||
colorTransparent: bool = False
|
||||
|
||||
@@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
from enum import Enum
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
class LayoutEnum(str, Enum):
|
||||
@@ -46,7 +46,7 @@ class ContainerConfig(BaseModel):
|
||||
name: Optional[str] = None
|
||||
"""A name to display above the container, basically a section header."""
|
||||
|
||||
layout: LayoutEnum = "vertical"
|
||||
layout: LayoutEnum = LayoutEnum.vertical
|
||||
"""The layout to use for laying out the contained children, either from top to bottom (`vertical`) or from left to right (`horizontal`)."""
|
||||
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from enum import Enum
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
class StylesheetEnum(str, Enum):
|
||||
@@ -37,7 +37,7 @@ class DevelCacheConfig(BaseModel):
|
||||
|
||||
@with_attrs_docs
|
||||
class DevelConfig(BaseModel):
|
||||
stylesheet: StylesheetEnum = "css"
|
||||
stylesheet: StylesheetEnum = StylesheetEnum.css
|
||||
"""Settings for stylesheet preference. OctoPrint will prefer to use the stylesheet type specified here. Usually (on a production install) that will be the compiled css (default). Developers may specify less here too."""
|
||||
|
||||
cache: DevelCacheConfig = DevelCacheConfig()
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -2,10 +2,10 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from enum import Enum
|
||||
from typing import List
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
class SubscriptionTypeEnum(str, Enum):
|
||||
@@ -18,6 +18,9 @@ class EventSubscription(BaseModel):
|
||||
event: str
|
||||
"""The event to subscribe to."""
|
||||
|
||||
name: Optional[str] = None
|
||||
"""The event name to show on the UI"""
|
||||
|
||||
command: str
|
||||
"""The command to execute when the event is triggered, either a GCODE or a system command."""
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -3,14 +3,14 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from enum import Enum
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
class RunAtEnum(str, Enum):
|
||||
never: str = "never"
|
||||
idle: str = "idle"
|
||||
always: str = "always"
|
||||
never = "never"
|
||||
idle = "idle"
|
||||
always = "always"
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
@@ -27,7 +27,7 @@ class GcodeAnalysisConfig(BaseModel):
|
||||
throttle_lines: int = 100
|
||||
"""GCODE line batch size."""
|
||||
|
||||
runAt: RunAtEnum = "idle"
|
||||
runAt: RunAtEnum = RunAtEnum.idle
|
||||
"""Whether to run the analysis only when idle (not printing), regardless of printing state or never."""
|
||||
|
||||
bedZ: float = 0.0
|
||||
|
||||
@@ -3,8 +3,10 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import Dict, List
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from pydantic import Field
|
||||
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
from enum import Enum
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
class AlwaysDetectNeverEnum(str, Enum):
|
||||
@@ -70,13 +70,22 @@ class SerialCapabilities(BaseModel):
|
||||
"""Whether to enable temperature autoreport in the firmware if its support is detected"""
|
||||
|
||||
autoreport_sdstatus: bool = True
|
||||
"""Whether to enable SD printing autoreport in the firmware if its support is detected"""
|
||||
|
||||
autoreport_pos: bool = True
|
||||
"""Whether to enable position autoreport in the firmware if its support is detected"""
|
||||
|
||||
busy_protocol: bool = True
|
||||
"""Whether to shorten the communication timeout if the firmware seems to support the busy protocol"""
|
||||
|
||||
emergency_parser: bool = True
|
||||
"""Whether to send emergency commands out of band if the firmware seems to support the emergency parser"""
|
||||
|
||||
extended_m20: bool = True
|
||||
"""Whether to request extended M20 (file list) output from the firmware if its support is detected"""
|
||||
|
||||
lfn_write: bool = True
|
||||
"""Whether to enable long filename support for SD card writes if the firmware reports support for it"""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
from enum import Enum
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
CONST_15MIN = 15 * 60
|
||||
CONST_1GB = 1024 * 1024 * 1024
|
||||
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -3,8 +3,10 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from pydantic import Field
|
||||
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -3,8 +3,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -4,8 +4,8 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
|
||||
from enum import Enum
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
from octoprint.schema import BaseModel
|
||||
from octoprint.vendor.with_attrs_docs import with_attrs_docs
|
||||
|
||||
|
||||
class RatioEnum(str, Enum):
|
||||
@@ -33,7 +33,7 @@ class TimelapseOptions(BaseModel):
|
||||
|
||||
@with_attrs_docs
|
||||
class TimelapseConfig(BaseModel):
|
||||
type: TimelapseTypeEnum = "off"
|
||||
type: TimelapseTypeEnum = TimelapseTypeEnum.off
|
||||
"""The timelapse type."""
|
||||
|
||||
fps: int = 25
|
||||
@@ -56,7 +56,7 @@ class WebcamConfig(BaseModel):
|
||||
|
||||
stream: Optional[str] = None
|
||||
|
||||
streamRatio: RatioEnum = "16:9"
|
||||
streamRatio: RatioEnum = RatioEnum.sixteen_nine
|
||||
|
||||
streamTimeout: int = 5
|
||||
|
||||
|
||||
@@ -95,7 +95,19 @@ environmentDetector = None
|
||||
|
||||
cli_key = None
|
||||
|
||||
principals = Principal(app)
|
||||
|
||||
class OctoPrintAnonymousIdentity(AnonymousIdentity):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
user = userManager.anonymous_user_factory()
|
||||
|
||||
self.provides.add(UserNeed(user.get_id()))
|
||||
for need in user.needs:
|
||||
self.provides.add(need)
|
||||
|
||||
|
||||
principals = Principal(app, anonymous_identity=OctoPrintAnonymousIdentity)
|
||||
|
||||
import octoprint.access.groups as groups # noqa: E402
|
||||
import octoprint.access.permissions as permissions # noqa: E402
|
||||
@@ -357,7 +369,6 @@ class Server:
|
||||
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()
|
||||
self._setup_mimetypes()
|
||||
@@ -658,7 +669,9 @@ class Server:
|
||||
|
||||
## Tornado initialization starts here
|
||||
|
||||
ioloop = IOLoop()
|
||||
ioloop = (
|
||||
IOLoop()
|
||||
) # TODO: This way to create the ioloop is deprecated and logs a warning
|
||||
ioloop.install()
|
||||
|
||||
enable_cors = settings().getBoolean(["api", "allowCrossOrigin"])
|
||||
@@ -1328,31 +1341,41 @@ class Server:
|
||||
def _get_locale(self):
|
||||
global LANGUAGES
|
||||
|
||||
l10n = None
|
||||
default_language = self._settings.get(["appearance", "defaultLanguage"])
|
||||
|
||||
if "l10n" in request.values:
|
||||
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
|
||||
# request: query param
|
||||
l10n = request.values["l10n"]
|
||||
|
||||
if "X-Locale" in request.headers:
|
||||
return Locale.negotiate([request.headers["X-Locale"]], LANGUAGES)
|
||||
elif "X-Locale" in request.headers:
|
||||
# request: header
|
||||
l10n = request.headers["X-Locale"]
|
||||
|
||||
if hasattr(g, "identity") and g.identity:
|
||||
elif hasattr(g, "identity") and g.identity:
|
||||
# user setting
|
||||
userid = g.identity.id
|
||||
try:
|
||||
user_language = userManager.get_user_setting(
|
||||
userid, ("interface", "language")
|
||||
)
|
||||
if user_language is not None and not user_language == "_default":
|
||||
return Locale.negotiate([user_language], LANGUAGES)
|
||||
l10n = user_language
|
||||
except octoprint.access.users.UnknownUser:
|
||||
pass
|
||||
|
||||
default_language = self._settings.get(["appearance", "defaultLanguage"])
|
||||
if (
|
||||
elif (
|
||||
default_language is not None
|
||||
and not default_language == "_default"
|
||||
and default_language in LANGUAGES
|
||||
):
|
||||
return Locale.negotiate([default_language], LANGUAGES)
|
||||
# instance setting
|
||||
l10n = default_language
|
||||
|
||||
if l10n:
|
||||
return Locale.negotiate([l10n], LANGUAGES)
|
||||
|
||||
# request: preference
|
||||
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
|
||||
|
||||
def _setup_heartbeat_logging(self):
|
||||
@@ -1383,7 +1406,6 @@ class Server:
|
||||
app.jinja_environment = PrefixAwareJinjaEnvironment
|
||||
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
|
||||
app.config["REMEMBER_COOKIE_DURATION"] = 90 * 24 * 60 * 60 # 90 days
|
||||
app.config["REMEMBER_COOKIE_HTTPONLY"] = True
|
||||
# REMEMBER_COOKIE_SECURE will be taken care of by our custom cookie handling
|
||||
@@ -1393,6 +1415,7 @@ class Server:
|
||||
|
||||
# setup octoprint's flask json serialization/deserialization
|
||||
app.json = OctoPrintJsonProvider(app)
|
||||
app.json.compact = False
|
||||
|
||||
s = settings()
|
||||
|
||||
@@ -1491,10 +1514,7 @@ class Server:
|
||||
|
||||
# add available translations
|
||||
for locale in locales:
|
||||
result.add(locale.language)
|
||||
if locale.territory:
|
||||
# if a territory is specified, add that too
|
||||
result.add(f"{locale.language}_{locale.territory}")
|
||||
result.add(str(locale))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -257,6 +257,7 @@ def getSettings():
|
||||
["serial", "capabilities", "emergency_parser"]
|
||||
),
|
||||
"capExtendedM20": s.getBoolean(["serial", "capabilities", "extended_m20"]),
|
||||
"capLfnWrite": s.getBoolean(["serial", "capabilities", "lfn_write"]),
|
||||
"resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]),
|
||||
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
|
||||
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
|
||||
@@ -940,6 +941,11 @@ def _saveSettings(data):
|
||||
["serial", "capabilities", "extended_m20"],
|
||||
data["serial"]["capExtendedM20"],
|
||||
),
|
||||
if "capLfnWrite" in data["serial"]:
|
||||
s.setBoolean(
|
||||
["serial", "capabilities", "lfn_write"],
|
||||
data["serial"]["capLfnWrite"],
|
||||
)
|
||||
if "resendRatioThreshold" in data["serial"]:
|
||||
s.setInt(
|
||||
["serial", "resendRatioThreshold"], data["serial"]["resendRatioThreshold"]
|
||||
|
||||
@@ -209,7 +209,7 @@ def deleteTimelapse(filename):
|
||||
|
||||
@api.route("/timelapse/unrendered/<name>", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
@Permissions.TIMELAPSE_DELETE.require(403)
|
||||
@Permissions.TIMELAPSE_MANAGE_UNRENDERED.require(403)
|
||||
def deleteUnrenderedTimelapse(name):
|
||||
octoprint.timelapse.delete_unrendered_timelapse(name)
|
||||
return NO_CONTENT
|
||||
@@ -217,7 +217,7 @@ def deleteUnrenderedTimelapse(name):
|
||||
|
||||
@api.route("/timelapse/unrendered/<name>", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.TIMELAPSE_ADMIN.require(403)
|
||||
@Permissions.TIMELAPSE_MANAGE_UNRENDERED.require(403)
|
||||
def processUnrenderedTimelapseCommand(name):
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
valid_commands = {"render": []}
|
||||
|
||||
@@ -12,7 +12,7 @@ import os
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Union
|
||||
from typing import Any, Union
|
||||
|
||||
import flask
|
||||
import flask.json
|
||||
@@ -85,11 +85,11 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
||||
continue
|
||||
dirs.append(plugin_translation_dir)
|
||||
|
||||
result = [Locale.parse(default_locale)]
|
||||
result = {Locale.parse(default_locale)}
|
||||
|
||||
for dir in dirs:
|
||||
result += list_translations(dir)
|
||||
return result
|
||||
result.update(list_translations(dir))
|
||||
return list(result)
|
||||
|
||||
def fixed_get_translations():
|
||||
"""Returns the correct gettext translations that should be used for
|
||||
@@ -237,35 +237,6 @@ def fix_webassets_convert_item_to_flask_url():
|
||||
flask_assets.FlaskResolver.convert_item_to_flask_url = fixed_convert_item_to_flask_url
|
||||
|
||||
|
||||
def fix_flask_jsonify():
|
||||
def fixed_jsonify(*args, **kwargs):
|
||||
"""Backported from https://github.com/pallets/flask/blob/7e714bd28b6e96d82b2848b48cf8ff48b517b09b/flask/json/__init__.py#L257"""
|
||||
from flask.json import current_app, dumps
|
||||
|
||||
indent = None
|
||||
separators = (",", ":")
|
||||
|
||||
if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
|
||||
indent = 2
|
||||
separators = (", ", ": ")
|
||||
|
||||
if args and kwargs:
|
||||
raise TypeError(
|
||||
"jsonify() behavior undefined when passed both args and kwargs"
|
||||
)
|
||||
elif len(args) == 1: # single args are passed directly to dumps()
|
||||
data = args[0]
|
||||
else:
|
||||
data = args or kwargs
|
||||
|
||||
return current_app.response_class(
|
||||
dumps(data, indent=indent, separators=separators, allow_nan=False) + "\n",
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
flask.jsonify = fixed_jsonify
|
||||
|
||||
|
||||
# ~~ WSGI environment wrapper for reverse proxying
|
||||
|
||||
|
||||
@@ -1939,6 +1910,10 @@ class OctoPrintJsonProvider(flask.json.provider.DefaultJSONProvider):
|
||||
except TypeError:
|
||||
return flask.json.provider.DefaultJSONProvider.default(object_)
|
||||
|
||||
def dumps(self, obj: Any, **kwargs: Any) -> str:
|
||||
kwargs.setdefault("allow_nan", False)
|
||||
return super().dumps(obj, **kwargs)
|
||||
|
||||
|
||||
##~~ Session signing
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ def _preemptive_data(
|
||||
d = {
|
||||
"path": path,
|
||||
"base_url": base_url,
|
||||
"query_string": "l10n={}".format(g.locale.language if g.locale else "en"),
|
||||
"query_string": f"l10n={_locale_str(g.locale)}",
|
||||
}
|
||||
|
||||
if key != "_default":
|
||||
@@ -103,7 +103,7 @@ def _preemptive_data(
|
||||
if data:
|
||||
if "query_string" in data:
|
||||
data["query_string"] = "l10n={}&{}".format(
|
||||
g.locale.language, data["query_string"]
|
||||
_locale_str(g.locale), data["query_string"]
|
||||
)
|
||||
d.update(data)
|
||||
except Exception:
|
||||
@@ -131,7 +131,7 @@ def _cache_key(ui, url=None, locale=None, additional_key_data=None):
|
||||
if url is None:
|
||||
url = request.base_url
|
||||
if locale is None:
|
||||
locale = g.locale.language if g.locale else "en"
|
||||
locale = _locale_str(g.locale)
|
||||
|
||||
k = f"ui:{ui}:{url}:{locale}"
|
||||
if callable(additional_key_data):
|
||||
@@ -170,6 +170,10 @@ def _add_additional_assets(hook_name):
|
||||
return result
|
||||
|
||||
|
||||
def _locale_str(locale):
|
||||
return str(locale) if locale else "en"
|
||||
|
||||
|
||||
@app.route("/login")
|
||||
@app.route("/login/")
|
||||
def login():
|
||||
@@ -359,7 +363,7 @@ def index():
|
||||
|
||||
preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"])
|
||||
|
||||
locale = g.locale.language if g.locale else "en"
|
||||
locale = _locale_str(g.locale)
|
||||
|
||||
# helper to check if wizards are active
|
||||
def wizard_active(templates):
|
||||
@@ -465,9 +469,7 @@ def index():
|
||||
|
||||
files = _get_all_templates()
|
||||
files += _get_all_assets()
|
||||
files += _get_all_translationfiles(
|
||||
g.locale.language if g.locale else "en", "messages"
|
||||
)
|
||||
files += _get_all_translationfiles(_locale_str(g.locale), "messages")
|
||||
|
||||
if callable(additional_files):
|
||||
try:
|
||||
@@ -731,8 +733,9 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
locales = {}
|
||||
for loc in LOCALES:
|
||||
try:
|
||||
locales[loc.language] = {
|
||||
"language": loc.language,
|
||||
key = _locale_str(loc)
|
||||
locales[key] = {
|
||||
"language": key,
|
||||
"display": loc.display_name,
|
||||
"english": loc.english_name,
|
||||
}
|
||||
@@ -765,7 +768,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
def fetch_template_data(refresh=False):
|
||||
global _templates, _plugin_names, _plugin_vars
|
||||
|
||||
locale = g.locale.language if g.locale else "en"
|
||||
locale = _locale_str(g.locale)
|
||||
|
||||
if (
|
||||
not refresh
|
||||
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #fff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #fff, #e6e6e6);background-image:-o-linear-gradient(top, #fff, #e6e6e6);background-image:linear-gradient(to bottom, #fff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #08c, #04c);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#04c));background-image:-webkit-linear-gradient(top, #08c, #04c);background-image:-o-linear-gradient(top, #08c, #04c);background-image:linear-gradient(to bottom, #08c, #04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btnLine truncated
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #fff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #fff, #e6e6e6);background-image:-o-linear-gradient(top, #fff, #e6e6e6);background-image:linear-gradient(to bottom, #fff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #08c, #04c);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#04c));background-image:-webkit-linear-gradient(top, #08c, #04c);background-image:-o-linear-gradient(top, #08c, #04c);background-image:linear-gradient(to bottom, #08c, #04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btnLine truncated
|
||||
@@ -619,7 +619,8 @@ function formatDate(unixTimestamp, options) {
|
||||
options = {seconds: false};
|
||||
}
|
||||
|
||||
if (!unixTimestamp) return "-";
|
||||
var placeholder = options.placeholder || "-";
|
||||
if (!unixTimestamp) return placeholder;
|
||||
|
||||
var format = gettext(/* L10N: Date format */ "YYYY-MM-DD HH:mm");
|
||||
if (options.seconds) {
|
||||
@@ -629,8 +630,9 @@ function formatDate(unixTimestamp, options) {
|
||||
return moment.unix(unixTimestamp).format(format);
|
||||
}
|
||||
|
||||
function formatTimeAgo(unixTimestamp) {
|
||||
if (!unixTimestamp) return "-";
|
||||
function formatTimeAgo(unixTimestamp, placeholder) {
|
||||
placeholder = placeholder || "-";
|
||||
if (!unixTimestamp) return placeholder;
|
||||
return moment.unix(unixTimestamp).fromNow();
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ $(function () {
|
||||
|
||||
self.systeminfo = ko.observableArray();
|
||||
|
||||
self.devmode = getQueryParameterByName("devmode") !== null;
|
||||
|
||||
self.getSystemInfo = function () {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.SYSTEM)) return;
|
||||
return OctoPrint.system.getInfo().done(self.fromSystemInfo);
|
||||
|
||||
@@ -12,13 +12,13 @@ $(function () {
|
||||
|
||||
self.onUserLoggedOut = self.onUserPermissionsChanged = function () {
|
||||
// reload if user now lacks STATUS & SETTINGS_READ permissions and is not in first run setup, or is in
|
||||
// first run setup but the ACL wizard has already run and ACL is active
|
||||
// first run setup but the ACL wizard has already run
|
||||
if (
|
||||
!self.loginState.hasAllPermissions(
|
||||
self.access.permissions.STATUS,
|
||||
self.access.permissions.SETTINGS_READ
|
||||
) &&
|
||||
CONFIG_ACCESS_CONTROL_ACTIVE
|
||||
(!CONFIG_FIRST_RUN || (self.coreWizardAcl && self.coreWizardAcl.setup()))
|
||||
) {
|
||||
location.reload();
|
||||
}
|
||||
|
||||
@@ -124,6 +124,14 @@ $(function () {
|
||||
return !self.name();
|
||||
});
|
||||
|
||||
self.sizeInvalid = ko.pureComputed(function () {
|
||||
return (
|
||||
!(self.volumeWidth() > 0 && self.volumeWidth() < 10000) ||
|
||||
!(self.volumeDepth() > 0 && self.volumeDepth() < 10000) ||
|
||||
!(self.volumeHeight() > 0 && self.volumeHeight() < 10000)
|
||||
);
|
||||
});
|
||||
|
||||
self.identifierInvalid = ko.pureComputed(function () {
|
||||
var identifier = self.identifier();
|
||||
var placeholder = self.identifierPlaceholder();
|
||||
@@ -165,7 +173,9 @@ $(function () {
|
||||
});
|
||||
|
||||
self.valid = function () {
|
||||
return !self.nameInvalid() && !self.identifierInvalid();
|
||||
return (
|
||||
!self.nameInvalid() && !self.identifierInvalid() && !self.sizeInvalid()
|
||||
);
|
||||
};
|
||||
|
||||
self.availableColors = ko.observable([
|
||||
@@ -273,11 +283,32 @@ $(function () {
|
||||
}
|
||||
return v;
|
||||
};
|
||||
var validFloat = function (value, def) {
|
||||
return valid(value, parseFloat, def);
|
||||
var runChecks = function (value, def, checks) {
|
||||
if (checks.gt !== undefined) {
|
||||
if (!(value > checks.gt)) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
if (checks.lt !== undefined) {
|
||||
if (!(value < checks.gt)) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
};
|
||||
var validInt = function (value, def) {
|
||||
return valid(value, parseInt, def);
|
||||
var validFloat = function (value, def, checks) {
|
||||
var v = valid(value, parseFloat, def);
|
||||
if (checks) {
|
||||
v = runChecks(value, def, checks);
|
||||
}
|
||||
return v;
|
||||
};
|
||||
var validInt = function (value, def, checks) {
|
||||
var v = valid(value, parseInt, def);
|
||||
if (checks) {
|
||||
v = runChecks(value, def, checks);
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
var profile = {
|
||||
@@ -286,16 +317,26 @@ $(function () {
|
||||
color: self.color(),
|
||||
model: self.model(),
|
||||
volume: {
|
||||
width: validFloat(self.volumeWidth(), defaultProfile.volume.width),
|
||||
depth: validFloat(self.volumeDepth(), defaultProfile.volume.depth),
|
||||
height: validFloat(self.volumeHeight(), defaultProfile.volume.height),
|
||||
width: validFloat(self.volumeWidth(), defaultProfile.volume.width, {
|
||||
gt: 0,
|
||||
lt: 10000
|
||||
}),
|
||||
depth: validFloat(self.volumeDepth(), defaultProfile.volume.depth, {
|
||||
gt: 0,
|
||||
lt: 10000
|
||||
}),
|
||||
height: validFloat(
|
||||
self.volumeHeight(),
|
||||
defaultProfile.volume.height,
|
||||
{gt: 0, lt: 10000}
|
||||
),
|
||||
formFactor: self.volumeFormFactor(),
|
||||
origin: self.volumeOrigin()
|
||||
},
|
||||
heatedBed: self.heatedBed(),
|
||||
heatedChamber: self.heatedChamber(),
|
||||
extruder: {
|
||||
count: parseInt(self.extruders()),
|
||||
count: runChecks(parseInt(self.extruders()), 1, {gt: 0, lt: 100}),
|
||||
offsets: [[0.0, 0.0]],
|
||||
nozzleDiameter: validFloat(
|
||||
self.nozzleDiameter(),
|
||||
@@ -309,19 +350,27 @@ $(function () {
|
||||
},
|
||||
axes: {
|
||||
x: {
|
||||
speed: validInt(self.axisXSpeed(), defaultProfile.axes.x.speed),
|
||||
speed: validInt(self.axisXSpeed(), defaultProfile.axes.x.speed, {
|
||||
gt: 0
|
||||
}),
|
||||
inverted: self.axisXInverted()
|
||||
},
|
||||
y: {
|
||||
speed: validInt(self.axisYSpeed(), defaultProfile.axes.y.speed),
|
||||
speed: validInt(self.axisYSpeed(), defaultProfile.axes.y.speed, {
|
||||
gt: 0
|
||||
}),
|
||||
inverted: self.axisYInverted()
|
||||
},
|
||||
z: {
|
||||
speed: validInt(self.axisZSpeed(), defaultProfile.axes.z.speed),
|
||||
speed: validInt(self.axisZSpeed(), defaultProfile.axes.z.speed, {
|
||||
gt: 0
|
||||
}),
|
||||
inverted: self.axisZInverted()
|
||||
},
|
||||
e: {
|
||||
speed: validInt(self.axisESpeed(), defaultProfile.axes.e.speed),
|
||||
speed: validInt(self.axisESpeed(), defaultProfile.axes.e.speed, {
|
||||
gt: 0
|
||||
}),
|
||||
inverted: self.axisEInverted()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ $(function () {
|
||||
self.dateString = ko.pureComputed(function () {
|
||||
var date = self.filedate();
|
||||
if (!date) {
|
||||
return "";
|
||||
return gettext("unknown");
|
||||
}
|
||||
|
||||
return formatDate(date, {seconds: true});
|
||||
|
||||
@@ -237,6 +237,7 @@ $(function () {
|
||||
self.serial_capBusyProtocol = ko.observable(undefined);
|
||||
self.serial_capEmergencyParser = ko.observable(undefined);
|
||||
self.serial_capExtendedM20 = ko.observable(undefined);
|
||||
self.serial_capLfnWrite = ko.observable(undefined);
|
||||
self.serial_sendM112OnError = ko.observable(undefined);
|
||||
self.serial_disableSdPrintingDetection = ko.observable(undefined);
|
||||
self.serial_ackMax = ko.observable(undefined);
|
||||
|
||||
@@ -203,29 +203,6 @@ $(function () {
|
||||
|
||||
self.markings = [];
|
||||
|
||||
self.marking_props = {
|
||||
print: {
|
||||
label: gettext("Start"),
|
||||
color: "#218656"
|
||||
},
|
||||
pause: {
|
||||
label: gettext("Pause"),
|
||||
color: "#FDC02F"
|
||||
},
|
||||
resume: {
|
||||
label: gettext("Resume"),
|
||||
color: "#27CAEE"
|
||||
},
|
||||
cancel: {
|
||||
label: gettext("Cancel"),
|
||||
color: "#DA3749"
|
||||
},
|
||||
done: {
|
||||
label: gettext("Done"),
|
||||
color: "#1B72F9"
|
||||
}
|
||||
};
|
||||
|
||||
self.showStateMarks = ko.observable(
|
||||
loadFromLocalStorage("temperatureGraph.showStateMarks", true)
|
||||
);
|
||||
@@ -485,15 +462,15 @@ $(function () {
|
||||
y: self.plot.getAxes().yaxis.max
|
||||
});
|
||||
|
||||
var markLabel = mark.type;
|
||||
if (mark.label) {
|
||||
markLabel = gettext(mark.label);
|
||||
}
|
||||
if (o.left > yAxisLabelWidth) {
|
||||
var label = $("<div></div>");
|
||||
label.html(self.marking_props[mark.type].label);
|
||||
var css = {
|
||||
backgroundColor: self.marking_props[mark.type].color
|
||||
};
|
||||
|
||||
label.css(css);
|
||||
label.html(markLabel);
|
||||
label.addClass("temperature-mark-label");
|
||||
label.addClass("temperature-mark-type-" + mark.type);
|
||||
|
||||
graph.append(label);
|
||||
|
||||
@@ -520,7 +497,7 @@ $(function () {
|
||||
}
|
||||
|
||||
return {
|
||||
color: self.marking_props[mark.type].color,
|
||||
color: label.css("background-color"),
|
||||
lineWidth: lineWidth,
|
||||
xaxis: {from: time, to: time}
|
||||
};
|
||||
@@ -529,6 +506,17 @@ $(function () {
|
||||
return marks;
|
||||
};
|
||||
|
||||
// Dummy translation requests for dynamic strings supplied by the backend
|
||||
// noinspection BadExpressionStatementJS
|
||||
[
|
||||
// mark labels
|
||||
gettext("Start"),
|
||||
gettext("Done"),
|
||||
gettext("Cancel"),
|
||||
gettext("Pause"),
|
||||
gettext("Resume")
|
||||
];
|
||||
|
||||
self._initializePlot = function (force, plotInfo) {
|
||||
var graph = $("#temperature-graph");
|
||||
if (!graph.length) return; // no graph
|
||||
|
||||
@@ -18,10 +18,9 @@ $(function () {
|
||||
};
|
||||
|
||||
self.showDialog = function () {
|
||||
if (
|
||||
!CONFIG_WIZARD ||
|
||||
!(!CONFIG_ACCESS_CONTROL_ACTIVE || self.loginState.isAdmin())
|
||||
)
|
||||
// only open a wizard if we have one and either are in first run OR logged in
|
||||
// as admin
|
||||
if (!CONFIG_WIZARD || (!CONFIG_FIRST_RUN && !self.loginState.isAdmin()))
|
||||
return;
|
||||
|
||||
self.getWizardDetails().done(function (response) {
|
||||
|
||||
@@ -575,12 +575,29 @@ table {
|
||||
.temperature-mark-label {
|
||||
position: absolute;
|
||||
color: white;
|
||||
background-color: #aeb6bf;
|
||||
padding: 0 5px;
|
||||
font-size: 8px;
|
||||
transform-origin: 0 0;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.temperature-mark-type-print {
|
||||
background-color: #218656;
|
||||
}
|
||||
.temperature-mark-type-pause {
|
||||
background-color: #fdc02f;
|
||||
}
|
||||
.temperature-mark-type-resume {
|
||||
background-color: #27caee;
|
||||
}
|
||||
.temperature-mark-type-cancel {
|
||||
background-color: #da3749;
|
||||
}
|
||||
.temperature-mark-type-done {
|
||||
background-color: #1b72f9;
|
||||
}
|
||||
|
||||
/** Various */
|
||||
|
||||
.tab-content,
|
||||
@@ -864,6 +881,7 @@ ul.dropdown-menu li a {
|
||||
overflow-y: scroll;
|
||||
height: 306px;
|
||||
padding-right: 2px;
|
||||
position: relative; // required for correct offsetParent, see #4680
|
||||
}
|
||||
|
||||
.entry {
|
||||
|
||||
@@ -10,11 +10,8 @@
|
||||
|
||||
<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>
|
||||
<div class="hide">
|
||||
<p data-bind="foreach: systeminfo">
|
||||
<strong data-bind="text: key"></strong>: <span data-bind="text: value"></span><br />
|
||||
</p>
|
||||
</div>
|
||||
<div data-bind="visible: devmode">
|
||||
<p data-bind="foreach: systeminfo">
|
||||
<strong data-bind="text: key"></strong>: <span data-bind="text: value"></span><br />
|
||||
</p>
|
||||
</div>
|
||||
@@ -411,6 +411,13 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_capLfnWrite" id="settings-serialCapLfnWrite"> {{ _('Send long names for writing files to the printer\'s SD card via <code>M28</code>, if detected as supported by the firmware') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
|
||||
@@ -11,9 +11,6 @@
|
||||
var CONFIG_LOGFILESPERPAGE = 10;
|
||||
var CONFIG_USERSPERPAGE = 10;
|
||||
var CONFIG_GROUPSPERPAGE = 10;
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}"; // deprecated, only left for compatibility reasons
|
||||
var CONFIG_ACCESS_CONTROL = true; // deprecated, only left for compatibility reasons
|
||||
var CONFIG_ACCESS_CONTROL_ACTIVE = {% if accessControlActive -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_FIRST_RUN = {% if firstRun -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_TEMPERATURE_GRAPH = {% if enableTemperatureGraph -%} true; {% else %} false; {%- endif %}
|
||||
@@ -25,7 +22,6 @@
|
||||
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
|
||||
var SOCKJS_CLOSE_NORMAL = 1000;
|
||||
|
||||
var UI_API_KEY = ""; // deprecated, only left for compatibility reasons
|
||||
var VERSION = "{{ version.number|e }}";
|
||||
var DISPLAY_VERSION = "{{ version.display|e }}";
|
||||
var BRANCH = "{{ version.branch|e }}";
|
||||
@@ -42,6 +38,13 @@
|
||||
var ADDITIONAL_VIEWMODELS = [];
|
||||
var OCTOPRINT_ADDITIONAL_BINDINGS = [];
|
||||
|
||||
// deprecated stuff only kept for backwards compatibility goes here
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}"; // deprecated, only left for compatibility reasons
|
||||
var CONFIG_ACCESS_CONTROL = true; // deprecated, only left for compatibility reasons
|
||||
var CONFIG_ACCESS_CONTROL_ACTIVE = {% if accessControlActive -%} true; {% else %} false; {%- endif %}; // deprecated, only left for compatibility reasons
|
||||
var UI_API_KEY = ""; // deprecated, only left for compatibility reasons
|
||||
// end of deprecated stuff
|
||||
|
||||
{% if templates.tab.order %}
|
||||
{% set first_tab = templates.tab.order[0] %}
|
||||
{% set entry, data = templates.tab.entries[first_tab] %}
|
||||
|
||||
@@ -15,10 +15,11 @@
|
||||
</div>
|
||||
|
||||
<script type="text/html" id="files_template_machinecode">
|
||||
<div class="btn btn-mini toggleAdditionalData pull-right" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }" title="{{ _('Additional data')|edq }}"><i class="fas fa-chevron-down"></i></div>
|
||||
<div class="btn btn-mini toggleAdditionalData pull-right" data-bind="visible: origin != 'sdcard',click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }" title="{{ _('Additional data')|edq }}"><i class="fas fa-chevron-down"></i></div>
|
||||
<div class="btn btn-mini pull-right disabled" data-bind="visible: origin == 'sdcard'" title="{{ _('On SD Card')|edq }}"><i class="fas fa-sd-card"></i></div>
|
||||
<div class="title clickable" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: $root.getSuccessClass($data), style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }, text: display"></div>
|
||||
<div class="internal" data-bind="visible: display && name != display && $root.showInternalFilename">{{ _('Internal') }}: <span data-bind="text: name"></span></div>
|
||||
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date), attr: {title: formatDate(date)}"></span></div>
|
||||
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date, '?'), attr: {title: formatDate(date, {placeholder:'{{ _('unknown') | esq }}'})}"></span></div>
|
||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
|
||||
<div class="btn-group action-buttons">
|
||||
@@ -33,7 +34,7 @@
|
||||
<script type="text/html" id="files_template_model">
|
||||
<div class="title muted" data-bind="text: display"></div>
|
||||
<div class="internal" data-bind="visible: name != display">{{ _('Internal') }}: <span data-bind="text: name"></span></div>
|
||||
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date), attr: {title: formatDate(date)}"></span></div>
|
||||
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date, '?'), attr: {title: formatDate(date, {placeholder:'{{ _('unknown') | esq }}'})}"></span></div>
|
||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||
<div class="btn-group action-buttons">
|
||||
<a class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_DOWNLOAD), attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download')|edq }}" aria-label="{{ _('Download')|edq }}" role="link"><i class="fas fa-download"></i></a>
|
||||
|
||||
+3
-3
@@ -41,7 +41,7 @@
|
||||
<label class="control-label">{{ _('Width (X)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
|
||||
<input type="number" step="0.01" min="1" max="9999" class="input-mini text-right" data-bind="value: volumeWidth, valueUpdate: 'input'" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -50,7 +50,7 @@
|
||||
<label class="control-label">{{ _('Depth (Y)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeDepth" placeholder="200">
|
||||
<input type="number" step="0.01" min="1" max="9999" class="input-mini text-right" data-bind="value: volumeDepth, valueUpdate: 'input'" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -61,7 +61,7 @@
|
||||
<label class="control-label">{{ _('Diameter (X/Y)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
|
||||
<input type="number" step="0.01" min="1" max="9999" class="input-mini text-right" data-bind="value: volumeWidth, valueUpdate: 'input'" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+89
-28
@@ -17,7 +17,7 @@ import queue
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from collections import deque, namedtuple
|
||||
|
||||
import serial
|
||||
import wrapt
|
||||
@@ -39,6 +39,7 @@ from octoprint.util import (
|
||||
filter_non_ascii,
|
||||
filter_non_utf8,
|
||||
get_bom,
|
||||
get_dos_filename,
|
||||
get_exception_string,
|
||||
sanitize_ascii,
|
||||
to_unicode,
|
||||
@@ -180,6 +181,13 @@ regex_serial_devices = re.compile(r"^(?:ttyUSB|ttyACM|tty\.usb|cu\.|cuaU|ttyS|rf
|
||||
"""Regex used to filter out valid tty devices"""
|
||||
|
||||
|
||||
MINIMAL_SD_TIMESTAMP = 1212012000
|
||||
# May 29th 2008 = RepRap 1.0 "Darwin" achieves self-replication
|
||||
|
||||
|
||||
SDFileData = namedtuple("SDFileData", ["name", "size", "timestamp", "longname"])
|
||||
|
||||
|
||||
def serialList():
|
||||
if os.name == "nt":
|
||||
candidates = []
|
||||
@@ -475,6 +483,7 @@ class MachineCom:
|
||||
CAPABILITY_EMERGENCY_PARSER = "EMERGENCY_PARSER"
|
||||
CAPABILITY_CHAMBER_TEMP = "CHAMBER_TEMPERATURE"
|
||||
CAPABILITY_EXTENDED_M20 = "EXTENDED_M20"
|
||||
CAPABILITY_LFN_WRITE = "LFN_WRITE"
|
||||
|
||||
CAPABILITY_SUPPORT_ENABLED = "enabled"
|
||||
CAPABILITY_SUPPORT_DETECTED = "detected"
|
||||
@@ -601,6 +610,9 @@ class MachineCom:
|
||||
self.CAPABILITY_EXTENDED_M20: settings().getBoolean(
|
||||
["serial", "capabilities", "extended_m20"]
|
||||
),
|
||||
self.CAPABILITY_LFN_WRITE: settings().getBoolean(
|
||||
["serial", "capabilities", "lfn_write"]
|
||||
),
|
||||
}
|
||||
|
||||
last_line_count = settings().getInt(["serial", "lastLineBufferSize"])
|
||||
@@ -749,8 +761,8 @@ class MachineCom:
|
||||
self._sdAvailable = False
|
||||
self._sdFileList = False
|
||||
self._sdFileLongName = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = {}
|
||||
self._sdFiles = {}
|
||||
self._sdFilesAvailable = threading.Event()
|
||||
self._sdFileToSelect = None
|
||||
self._sdFileToSelectUser = None
|
||||
self._ignore_select = False
|
||||
@@ -883,8 +895,7 @@ class MachineCom:
|
||||
if newState == self.STATE_CLOSED or newState == self.STATE_CLOSED_WITH_ERROR:
|
||||
if settings().getBoolean(["feature", "sdSupport"]):
|
||||
self._sdFileList = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = {}
|
||||
self._sdFiles = {}
|
||||
self._callback.on_comm_sd_files([])
|
||||
|
||||
if self._currentFile is not None:
|
||||
@@ -1246,7 +1257,7 @@ class MachineCom:
|
||||
self._changeState(self.STATE_CLOSED)
|
||||
|
||||
if settings().getBoolean(["feature", "sdSupport"]):
|
||||
self._sdFileList = []
|
||||
self._sdFiles = {}
|
||||
|
||||
def setTemperatureOffset(self, offsets):
|
||||
self._tempOffsets.update(offsets)
|
||||
@@ -1515,9 +1526,26 @@ class MachineCom:
|
||||
self._logger.exception("Error while trying to start printing")
|
||||
self._trigger_error(get_exception_string(), "start_print")
|
||||
|
||||
def startFileTransfer(
|
||||
self, path, localFilename, remoteFilename, special=False, tags=None
|
||||
):
|
||||
def _get_free_remote_name(self, filename: str) -> str:
|
||||
if not self._capability_supported(self.CAPABILITY_LFN_WRITE) and valid_file_type(
|
||||
filename, "gcode"
|
||||
):
|
||||
# figure out remote filename
|
||||
self.refreshSdFiles(blocking=True)
|
||||
existingSdFiles = list(map(lambda x: x[0], self.getSdFiles()))
|
||||
remote_name = get_dos_filename(
|
||||
filename,
|
||||
existing_filenames=existingSdFiles,
|
||||
extension="gco",
|
||||
whitelisted_extensions=["gco", "g"],
|
||||
)
|
||||
else:
|
||||
# either LFN_WRITE is supported, or this is not a gcode file
|
||||
remote_name = os.path.basename(filename)
|
||||
|
||||
return remote_name
|
||||
|
||||
def startFileTransfer(self, path, filename, remote=None, special=False, tags=None):
|
||||
if not self.isOperational() or self.isBusy():
|
||||
self._logger.info("Printer is not operational or busy")
|
||||
return
|
||||
@@ -1525,33 +1553,36 @@ class MachineCom:
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
if remote is None:
|
||||
remote = "/" + self._get_free_remote_name(filename)
|
||||
|
||||
with self._jobLock:
|
||||
self.resetLineNumbers(tags={"trigger:comm.start_file_transfer"})
|
||||
|
||||
if special:
|
||||
self._currentFile = SpecialStreamingGcodeFileInformation(
|
||||
path, localFilename, remoteFilename
|
||||
path, filename, remote
|
||||
)
|
||||
else:
|
||||
self._currentFile = StreamingGcodeFileInformation(
|
||||
path, localFilename, remoteFilename
|
||||
)
|
||||
self._currentFile = StreamingGcodeFileInformation(path, filename, remote)
|
||||
self._currentFile.start()
|
||||
|
||||
self.sendCommand(
|
||||
"M28 %s" % remoteFilename,
|
||||
"M28 %s" % remote,
|
||||
tags=tags
|
||||
| {
|
||||
"trigger:comm.start_file_transfer",
|
||||
},
|
||||
)
|
||||
self._callback.on_comm_file_transfer_started(
|
||||
localFilename,
|
||||
remoteFilename,
|
||||
filename,
|
||||
remote,
|
||||
self._currentFile.getFilesize(),
|
||||
user=self._currentFile.getUser(),
|
||||
)
|
||||
|
||||
return remote
|
||||
|
||||
def cancelFileTransfer(self, tags=None):
|
||||
if not self.isOperational() or not self.isStreaming():
|
||||
self._logger.info("Printer is not operational or not streaming")
|
||||
@@ -1973,7 +2004,15 @@ class MachineCom:
|
||||
|
||||
def getSdFiles(self):
|
||||
return list(
|
||||
map(lambda x: (x[0], x[1], self._sdFilesMap.get(x[0]), x[2]), self._sdFiles)
|
||||
map(
|
||||
lambda x: (
|
||||
x.name,
|
||||
x.size,
|
||||
x.longname if x.longname else x.name,
|
||||
x.timestamp,
|
||||
),
|
||||
self._sdFiles.values(),
|
||||
)
|
||||
)
|
||||
|
||||
def deleteSdFile(self, filename, tags=None):
|
||||
@@ -2000,7 +2039,7 @@ class MachineCom:
|
||||
)
|
||||
self.refreshSdFiles()
|
||||
|
||||
def refreshSdFiles(self, tags=None):
|
||||
def refreshSdFiles(self, tags=None, blocking=False, timeout=10):
|
||||
if not self._sdEnabled:
|
||||
return
|
||||
|
||||
@@ -2021,6 +2060,7 @@ class MachineCom:
|
||||
else:
|
||||
command = "M20"
|
||||
|
||||
self._sdFilesAvailable.clear()
|
||||
self.sendCommand(
|
||||
command,
|
||||
tags=tags
|
||||
@@ -2028,6 +2068,8 @@ class MachineCom:
|
||||
"trigger:comm.refresh_sd_files",
|
||||
},
|
||||
)
|
||||
if blocking:
|
||||
self._sdFilesAvailable.wait(timeout=timeout)
|
||||
|
||||
def initSdCard(self, tags=None):
|
||||
if not self._sdEnabled:
|
||||
@@ -2064,8 +2106,7 @@ class MachineCom:
|
||||
},
|
||||
)
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = {}
|
||||
self._sdFiles = {}
|
||||
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
self._callback.on_comm_sd_files(self.getSdFiles())
|
||||
@@ -2406,7 +2447,7 @@ class MachineCom:
|
||||
"Printer reported SD card as ejected", level=logging.INFO
|
||||
)
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._sdFiles = {}
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
elif self._sdEnabled and action_name == "sd_updated":
|
||||
self._dual_log(
|
||||
@@ -2476,9 +2517,16 @@ class MachineCom:
|
||||
filename = "/" + filename
|
||||
if self._sdLowerCase:
|
||||
filename = filename.lower()
|
||||
self._sdFiles.append((filename, size, timestamp))
|
||||
if longname is not None:
|
||||
self._sdFilesMap[filename] = longname
|
||||
if timestamp is not None and timestamp < MINIMAL_SD_TIMESTAMP:
|
||||
# sanitize timestamp, when creating a file through serial the firmware usually doesn't know the date
|
||||
# and sets something ridiculously low (e.g. 2000-01-01), so let's ignore timestamps like that here
|
||||
timestamp = None
|
||||
self._sdFiles[filename] = SDFileData(
|
||||
name=filename,
|
||||
size=size,
|
||||
timestamp=timestamp,
|
||||
longname=longname,
|
||||
)
|
||||
continue
|
||||
|
||||
elif self._sdFileLongName:
|
||||
@@ -2494,7 +2542,14 @@ class MachineCom:
|
||||
# "<short name>: <long name>" or such, but why make things easy...
|
||||
_, ext = os.path.splitext(lower_line)
|
||||
if ext and valid_file_type(lower_line, "machinecode"):
|
||||
self._sdFilesMap[self._sdFileLongName] = line
|
||||
data = self._sdFiles.get(self._sdFileLongName)
|
||||
if data is not None:
|
||||
self._sdFiles[self._sdFileLongName] = SDFileData(
|
||||
name=data.name,
|
||||
size=data.size,
|
||||
timestamp=data.timestamp,
|
||||
longname=line,
|
||||
)
|
||||
self._sdFileLongName = False
|
||||
|
||||
handled = False
|
||||
@@ -2747,6 +2802,10 @@ class MachineCom:
|
||||
self._logger.info(
|
||||
"Firmware states that it supports long filenames"
|
||||
)
|
||||
elif capability == self.CAPABILITY_LFN_WRITE and enabled:
|
||||
self._logger.info(
|
||||
"Firmware states that it supports writing long filenames"
|
||||
)
|
||||
|
||||
# notify plugins
|
||||
for name, hook in self._firmware_info_hooks[
|
||||
@@ -2945,7 +3004,7 @@ class MachineCom:
|
||||
or "SD card released" in line
|
||||
):
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._sdFiles = {}
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
elif (
|
||||
"SD card ok" in line or "Card successfully initialized" in line
|
||||
@@ -2954,10 +3013,11 @@ class MachineCom:
|
||||
self.refreshSdFiles()
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
elif "Begin file list" in line:
|
||||
self._sdFiles = []
|
||||
self._sdFiles = {}
|
||||
self._sdFileList = True
|
||||
elif "End file list" in line:
|
||||
self._sdFileList = False
|
||||
self._sdFilesAvailable.set()
|
||||
self._callback.on_comm_sd_files(self.getSdFiles())
|
||||
elif "SD printing byte" in line:
|
||||
# answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d"
|
||||
@@ -3052,6 +3112,7 @@ class MachineCom:
|
||||
self._currentFile.getFilesize(),
|
||||
True,
|
||||
user=self._currentFile.getUser(),
|
||||
data=self._sdFiles.get(self._currentFile.getFilename()),
|
||||
)
|
||||
elif "Writing to file" in line and self.isStreaming():
|
||||
self._changeState(self.STATE_PRINTING)
|
||||
@@ -5576,7 +5637,7 @@ class MachineComPrintCallback:
|
||||
def on_comm_z_change(self, newZ):
|
||||
pass
|
||||
|
||||
def on_comm_file_selected(self, filename, filesize, sd, user=None):
|
||||
def on_comm_file_selected(self, filename, filesize, sd, user=None, data=None):
|
||||
pass
|
||||
|
||||
def on_comm_sd_state_change(self, sdReady):
|
||||
|
||||
+5
-7
@@ -12,13 +12,10 @@
|
||||
__version__ = '0.4.0'
|
||||
|
||||
import sys
|
||||
|
||||
from collections import deque, namedtuple
|
||||
from functools import partial, wraps
|
||||
from collections import deque
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
from flask import g, session, current_app, abort, request
|
||||
from flask import abort, current_app, g, request, session
|
||||
from flask.signals import Namespace
|
||||
|
||||
PY3 = sys.version_info[0] == 3
|
||||
@@ -375,9 +372,10 @@ class Principal(object):
|
||||
identification.
|
||||
:param skip_static: Whether to ignore static endpoints.
|
||||
"""
|
||||
def __init__(self, app=None, use_sessions=True, skip_static=False):
|
||||
def __init__(self, app=None, use_sessions=True, skip_static=False, anonymous_identity=AnonymousIdentity):
|
||||
self.identity_loaders = deque()
|
||||
self.identity_savers = deque()
|
||||
self.anonymous_identity = anonymous_identity
|
||||
# XXX This will probably vanish for a better API
|
||||
self.use_sessions = use_sessions
|
||||
self.skip_static = skip_static
|
||||
@@ -469,7 +467,7 @@ class Principal(object):
|
||||
if self._is_static_route():
|
||||
return
|
||||
|
||||
g.identity = AnonymousIdentity()
|
||||
g.identity = self.anonymous_identity()
|
||||
for loader in self.identity_loaders:
|
||||
identity = loader()
|
||||
if identity is not None:
|
||||
|
||||
+7
-6
@@ -8,20 +8,20 @@ from __future__ import absolute_import, division, print_function, unicode_litera
|
||||
SockJS session implementation.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import asyncio
|
||||
import functools
|
||||
import logging
|
||||
|
||||
from octoprint.vendor.sockjs.tornado import sessioncontainer, periodic, proto
|
||||
from octoprint.vendor.sockjs.tornado.util import bytes_to_str
|
||||
|
||||
from tornado.ioloop import IOLoop
|
||||
from octoprint.vendor.sockjs.tornado import periodic, proto, sessioncontainer
|
||||
from octoprint.vendor.sockjs.tornado.util import bytes_to_str, get_current_ioloop
|
||||
|
||||
LOG = logging.getLogger("tornado.general")
|
||||
|
||||
|
||||
def ensure_io_loop(method):
|
||||
@functools.wraps(method)
|
||||
def wrapper(self, *args, **kwargs):
|
||||
if IOLoop.current(False):
|
||||
if get_current_ioloop():
|
||||
method(self, *args, **kwargs)
|
||||
else:
|
||||
def run():
|
||||
@@ -29,6 +29,7 @@ def ensure_io_loop(method):
|
||||
self.server.io_loop.add_callback(run)
|
||||
return wrapper
|
||||
|
||||
|
||||
class ConnectionInfo(object):
|
||||
"""Connection information object.
|
||||
|
||||
|
||||
@@ -8,12 +8,12 @@ from __future__ import absolute_import, division, print_function, unicode_litera
|
||||
Raw websocket transport implementation
|
||||
"""
|
||||
import logging
|
||||
import socket
|
||||
|
||||
from octoprint.vendor.sockjs.tornado import websocket, session
|
||||
from octoprint.vendor.sockjs.tornado.transports import base
|
||||
from tornado.websocket import WebSocketError
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
from octoprint.vendor.sockjs.tornado import session, websocket
|
||||
from octoprint.vendor.sockjs.tornado.transports import base
|
||||
from octoprint.vendor.sockjs.tornado.util import get_current_ioloop
|
||||
|
||||
LOG = logging.getLogger("tornado.general")
|
||||
|
||||
@@ -78,7 +78,7 @@ class RawWebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransport
|
||||
session.close()
|
||||
|
||||
def send_pack(self, message, binary=False):
|
||||
if IOLoop.current(False) == self.server.io_loop:
|
||||
if get_current_ioloop() == self.server.io_loop:
|
||||
# Running in Main Thread
|
||||
# Send message
|
||||
try:
|
||||
|
||||
@@ -8,13 +8,12 @@ from __future__ import absolute_import, division, print_function, unicode_litera
|
||||
Websocket transport implementation
|
||||
"""
|
||||
import logging
|
||||
import socket
|
||||
|
||||
from tornado.websocket import WebSocketError
|
||||
|
||||
from octoprint.vendor.sockjs.tornado import proto, websocket
|
||||
from octoprint.vendor.sockjs.tornado.transports import base
|
||||
from octoprint.vendor.sockjs.tornado.util import bytes_to_str
|
||||
from tornado.websocket import WebSocketError
|
||||
from tornado.ioloop import IOLoop
|
||||
from octoprint.vendor.sockjs.tornado.util import bytes_to_str, get_current_ioloop
|
||||
|
||||
LOG = logging.getLogger("tornado.general")
|
||||
|
||||
@@ -88,7 +87,7 @@ class WebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMix
|
||||
session.close()
|
||||
|
||||
def send_pack(self, message, binary=False):
|
||||
if IOLoop.current(False) == self.server.io_loop:
|
||||
if get_current_ioloop() == self.server.io_loop:
|
||||
# Running in Main Thread
|
||||
# Send message
|
||||
try:
|
||||
|
||||
+14
-1
@@ -1,8 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
import sys
|
||||
import functools
|
||||
import sys
|
||||
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
@@ -61,3 +61,16 @@ def no_auto_finish(method):
|
||||
self._auto_finish = False
|
||||
return method(self, *args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
def get_current_ioloop():
|
||||
import asyncio
|
||||
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
return IOLoop._ioloop_for_asyncio.get(loop)
|
||||
except RuntimeError:
|
||||
# no current loop
|
||||
return None
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
# Based on pydantic-settings version 0.2.5 by Daniel Daniels, licensed under MIT
|
||||
#
|
||||
# https://github.com/danields761/pydantic-settings
|
||||
|
||||
from typing import Type
|
||||
|
||||
from class_doc import extract_docs_from_cls_obj
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
def apply_attributes_docs(
|
||||
model: Type[BaseModel], override_existing: bool = True
|
||||
) -> None:
|
||||
"""
|
||||
Apply model attributes documentation in-place. Resulted docs are placed
|
||||
inside :code:`field.schema.description` for *pydantic* model field.
|
||||
:param model: any pydantic model
|
||||
:param override_existing: override existing descriptions
|
||||
"""
|
||||
docs = extract_docs_from_cls_obj(model)
|
||||
|
||||
for field in model.__fields__.values():
|
||||
if field.field_info.description and not override_existing:
|
||||
continue
|
||||
|
||||
try:
|
||||
field.field_info.description = '\n'.join(docs[field.name])
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
|
||||
def with_attrs_docs(
|
||||
model_cls: Type[BaseModel]
|
||||
) -> Type[BaseModel]:
|
||||
"""
|
||||
Applies :py:func:`.apply_attributes_docs`.
|
||||
"""
|
||||
|
||||
def decorator(maybe_model_cls: Type[BaseModel]) -> Type[BaseModel]:
|
||||
apply_attributes_docs(
|
||||
maybe_model_cls
|
||||
)
|
||||
return maybe_model_cls
|
||||
|
||||
return decorator(model_cls)
|
||||
@@ -1,685 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
### NOTE #################################################################################
|
||||
# This file has to stay format compatible to Python 2, or pip under Python 2 will
|
||||
# not be able to detect that OctoPrint requires Python 3 but instead fail with a
|
||||
# syntax error.
|
||||
#
|
||||
# So, no f-strings, no walrus operators, no pyupgrade or codemods.
|
||||
##########################################################################################
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import glob
|
||||
import os
|
||||
import shutil
|
||||
from distutils.command.clean import clean as _clean
|
||||
|
||||
from setuptools import Command
|
||||
|
||||
|
||||
def package_data_dirs(source, sub_folders):
|
||||
dirs = []
|
||||
|
||||
for d in sub_folders:
|
||||
folder = os.path.join(source, d)
|
||||
if not os.path.exists(folder):
|
||||
continue
|
||||
|
||||
for dirname, _, files in os.walk(folder):
|
||||
dirname = os.path.relpath(dirname, source)
|
||||
for f in files:
|
||||
dirs.append(os.path.join(dirname, f))
|
||||
|
||||
return dirs
|
||||
|
||||
|
||||
def recursively_handle_files(
|
||||
directory, file_matcher, folder_matcher=None, folder_handler=None, file_handler=None
|
||||
):
|
||||
applied_handler = False
|
||||
|
||||
for filename in os.listdir(directory):
|
||||
path = os.path.join(directory, filename)
|
||||
|
||||
if file_handler is not None and file_matcher(filename):
|
||||
file_handler(path)
|
||||
applied_handler = True
|
||||
|
||||
elif os.path.isdir(path) and (
|
||||
folder_matcher is None or folder_matcher(directory, filename, path)
|
||||
):
|
||||
sub_applied_handler = recursively_handle_files(
|
||||
path,
|
||||
file_matcher,
|
||||
folder_handler=folder_handler,
|
||||
file_handler=file_handler,
|
||||
)
|
||||
if sub_applied_handler:
|
||||
applied_handler = True
|
||||
|
||||
if folder_handler is not None:
|
||||
folder_handler(path, sub_applied_handler)
|
||||
|
||||
return applied_handler
|
||||
|
||||
|
||||
def has_requirement(requirement, requirements):
|
||||
if requirement is None or requirements is None:
|
||||
return False
|
||||
|
||||
requirement = requirement.lower()
|
||||
requirements = [r.lower() for r in requirements]
|
||||
compat = [
|
||||
requirement.lower() + c for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")
|
||||
]
|
||||
|
||||
return requirement in requirements or any(
|
||||
any(r.startswith(c) for c in compat) for r in requirements
|
||||
)
|
||||
|
||||
|
||||
class CleanCommand(_clean):
|
||||
user_options = _clean.user_options + [
|
||||
("orig", None, "behave like original clean command"),
|
||||
("noeggs", None, "don't clean up eggs"),
|
||||
("nopyc", None, "don't clean up pyc files"),
|
||||
]
|
||||
boolean_options = _clean.boolean_options + ["orig", "noeggs", "nopyc"]
|
||||
|
||||
source_folder = "src"
|
||||
eggs = None
|
||||
|
||||
@classmethod
|
||||
def for_options(cls, source_folder="src", eggs=None):
|
||||
if eggs is None:
|
||||
eggs = []
|
||||
return type(cls)(
|
||||
cls.__name__, (cls,), {"source_folder": source_folder, "eggs": eggs}
|
||||
)
|
||||
|
||||
def initialize_options(self):
|
||||
_clean.initialize_options(self)
|
||||
|
||||
self.orig = None
|
||||
self.noeggs = None
|
||||
self.nopyc = None
|
||||
|
||||
def finalize_options(self):
|
||||
_clean.finalize_options(self)
|
||||
|
||||
if not self.orig:
|
||||
self.all = True
|
||||
|
||||
def run(self):
|
||||
_clean.run(self)
|
||||
if self.orig:
|
||||
return
|
||||
|
||||
# eggs
|
||||
if not self.noeggs:
|
||||
for egg in self.eggs:
|
||||
globbed_eggs = glob.glob(egg)
|
||||
for globbed_egg in globbed_eggs:
|
||||
print("deleting '%s' egg" % globbed_egg)
|
||||
if not self.dry_run:
|
||||
shutil.rmtree(globbed_egg)
|
||||
|
||||
# pyc files
|
||||
if not self.nopyc:
|
||||
|
||||
def delete_folder_if_empty(path, applied_handler):
|
||||
if not applied_handler:
|
||||
return
|
||||
if len(os.listdir(path)) == 0:
|
||||
if not self.dry_run:
|
||||
shutil.rmtree(path)
|
||||
print(
|
||||
"removed %s since it was empty" % path[len(self.source_folder) :]
|
||||
)
|
||||
|
||||
def delete_file(path):
|
||||
print("removing '%s'" % path[len(self.source_folder) :])
|
||||
if not self.dry_run:
|
||||
os.remove(path)
|
||||
|
||||
import fnmatch
|
||||
|
||||
print("recursively removing *.pyc from '%s'" % self.source_folder)
|
||||
recursively_handle_files(
|
||||
os.path.abspath(self.source_folder),
|
||||
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
|
||||
folder_matcher=lambda dir, name, path: name != ".git",
|
||||
folder_handler=delete_folder_if_empty,
|
||||
file_handler=delete_file,
|
||||
)
|
||||
|
||||
|
||||
class NewTranslation(Command):
|
||||
description = "create a new translation"
|
||||
user_options = [
|
||||
("locale=", "l", "locale for the new translation"),
|
||||
]
|
||||
boolean_options = []
|
||||
|
||||
pot_file = None
|
||||
output_dir = None
|
||||
|
||||
@classmethod
|
||||
def for_options(cls, pot_file=None, output_dir=None):
|
||||
if pot_file is None:
|
||||
raise ValueError("pot_file must not be None")
|
||||
if output_dir is None:
|
||||
raise ValueError("output_dir must not be None")
|
||||
|
||||
return type(cls)(
|
||||
cls.__name__, (cls,), {"pot_file": pot_file, "output_dir": output_dir}
|
||||
)
|
||||
|
||||
def __init__(self, dist, **kw):
|
||||
from babel.messages import frontend as babel
|
||||
|
||||
self.babel_init_messages = babel.init_catalog(dist)
|
||||
Command.__init__(self, dist, **kw)
|
||||
|
||||
def initialize_options(self):
|
||||
self.locale = None
|
||||
self.babel_init_messages.initialize_options()
|
||||
|
||||
def finalize_options(self):
|
||||
self.babel_init_messages.locale = self.locale
|
||||
self.babel_init_messages.input_file = self.__class__.pot_file
|
||||
self.babel_init_messages.output_dir = self.__class__.output_dir
|
||||
self.babel_init_messages.finalize_options()
|
||||
|
||||
def run(self):
|
||||
self.babel_init_messages.run()
|
||||
|
||||
|
||||
class ExtractTranslation(Command):
|
||||
description = "extract translations"
|
||||
user_options = []
|
||||
boolean_options = []
|
||||
|
||||
mail_address = "i18n@octoprint.org"
|
||||
copyright_holder = "The OctoPrint Project"
|
||||
mapping_file = None
|
||||
pot_file = None
|
||||
input_dirs = None
|
||||
|
||||
@classmethod
|
||||
def for_options(
|
||||
cls,
|
||||
mail_address="i18n@octoprint.org",
|
||||
copyright_holder="The OctoPrint Project",
|
||||
mapping_file=None,
|
||||
pot_file=None,
|
||||
input_dirs=None,
|
||||
):
|
||||
if mapping_file is None:
|
||||
raise ValueError("mapping_file must not be None")
|
||||
if pot_file is None:
|
||||
raise ValueError("pot_file must not be None")
|
||||
if input_dirs is None:
|
||||
raise ValueError("input_dirs must not be None")
|
||||
|
||||
return type(cls)(
|
||||
cls.__name__,
|
||||
(cls,),
|
||||
{
|
||||
"mapping_file": mapping_file,
|
||||
"pot_file": pot_file,
|
||||
"input_dirs": input_dirs,
|
||||
"mail_address": mail_address,
|
||||
"copyright_holder": copyright_holder,
|
||||
},
|
||||
)
|
||||
|
||||
def __init__(self, dist, **kw):
|
||||
from babel.messages import frontend as babel
|
||||
|
||||
self.babel_extract_messages = babel.extract_messages(dist)
|
||||
Command.__init__(self, dist, **kw)
|
||||
|
||||
def initialize_options(self):
|
||||
self.babel_extract_messages.initialize_options()
|
||||
|
||||
def finalize_options(self):
|
||||
self.babel_extract_messages.mapping_file = self.__class__.mapping_file
|
||||
self.babel_extract_messages.output_file = self.__class__.pot_file
|
||||
self.babel_extract_messages.input_dirs = self.__class__.input_dirs
|
||||
self.babel_extract_messages.msgid_bugs_address = self.__class__.mail_address
|
||||
self.babel_extract_messages.copyright_holder = self.__class__.copyright_holder
|
||||
self.babel_extract_messages.finalize_options()
|
||||
|
||||
def run(self):
|
||||
self.babel_extract_messages.run()
|
||||
|
||||
|
||||
class RefreshTranslation(Command):
|
||||
description = "refresh translations"
|
||||
user_options = [
|
||||
("locale=", "l", "locale for the translation to refresh"),
|
||||
]
|
||||
boolean_options = []
|
||||
|
||||
mail_address = "i18n@octoprint.org"
|
||||
copyright_holder = "The OctoPrint Project"
|
||||
mapping_file = None
|
||||
pot_file = None
|
||||
input_dirs = None
|
||||
output_dir = None
|
||||
|
||||
@classmethod
|
||||
def for_options(
|
||||
cls,
|
||||
mail_address="i18n@octoprint.org",
|
||||
copyright_holder="The OctoPrint Project",
|
||||
mapping_file=None,
|
||||
pot_file=None,
|
||||
input_dirs=None,
|
||||
output_dir=None,
|
||||
):
|
||||
if mapping_file is None:
|
||||
raise ValueError("mapping_file must not be None")
|
||||
if pot_file is None:
|
||||
raise ValueError("pot_file must not be None")
|
||||
if input_dirs is None:
|
||||
raise ValueError("input_dirs must not be None")
|
||||
if output_dir is None:
|
||||
raise ValueError("output_dir must not be None")
|
||||
|
||||
return type(cls)(
|
||||
cls.__name__,
|
||||
(cls,),
|
||||
{
|
||||
"mapping_file": mapping_file,
|
||||
"pot_file": pot_file,
|
||||
"input_dirs": input_dirs,
|
||||
"mail_address": mail_address,
|
||||
"copyright_holder": copyright_holder,
|
||||
"output_dir": output_dir,
|
||||
},
|
||||
)
|
||||
|
||||
def __init__(self, dist, **kw):
|
||||
from babel.messages import frontend as babel
|
||||
|
||||
self.babel_extract_messages = babel.extract_messages(dist)
|
||||
self.babel_update_messages = babel.update_catalog(dist)
|
||||
Command.__init__(self, dist, **kw)
|
||||
|
||||
def initialize_options(self):
|
||||
self.locale = None
|
||||
self.babel_extract_messages.initialize_options()
|
||||
self.babel_update_messages.initialize_options()
|
||||
|
||||
def finalize_options(self):
|
||||
self.babel_extract_messages.mapping_file = self.__class__.mapping_file
|
||||
self.babel_extract_messages.output_file = self.__class__.pot_file
|
||||
self.babel_extract_messages.input_dirs = self.__class__.input_dirs
|
||||
self.babel_extract_messages.msgid_bugs_address = self.__class__.mail_address
|
||||
self.babel_extract_messages.copyright_holder = self.__class__.copyright_holder
|
||||
self.babel_extract_messages.finalize_options()
|
||||
|
||||
self.babel_update_messages.input_file = self.__class__.pot_file
|
||||
self.babel_update_messages.output_dir = self.__class__.output_dir
|
||||
self.babel_update_messages.locale = self.locale
|
||||
self.babel_update_messages.finalize_options()
|
||||
|
||||
def run(self):
|
||||
self.babel_extract_messages.run()
|
||||
self.babel_update_messages.run()
|
||||
|
||||
|
||||
class CompileTranslation(Command):
|
||||
description = "compile translations"
|
||||
user_options = []
|
||||
boolean_options = []
|
||||
|
||||
output_dir = None
|
||||
|
||||
@classmethod
|
||||
def for_options(cls, output_dir=None):
|
||||
if output_dir is None:
|
||||
raise ValueError("output_dir must not be None")
|
||||
|
||||
return type(cls)(cls.__name__, (cls,), {"output_dir": output_dir})
|
||||
|
||||
def __init__(self, dist, **kw):
|
||||
from babel.messages import frontend as babel
|
||||
|
||||
self.babel_compile_messages = babel.compile_catalog(dist)
|
||||
Command.__init__(self, dist, **kw)
|
||||
|
||||
def initialize_options(self):
|
||||
self.babel_compile_messages.initialize_options()
|
||||
|
||||
def finalize_options(self):
|
||||
self.babel_compile_messages.directory = self.__class__.output_dir
|
||||
self.babel_compile_messages.finalize_options()
|
||||
|
||||
def run(self):
|
||||
self.babel_compile_messages.run()
|
||||
|
||||
|
||||
class BundleTranslation(Command):
|
||||
description = "bundles translations"
|
||||
user_options = [("locale=", "l", "locale for the translation to bundle")]
|
||||
boolean_options = []
|
||||
|
||||
source_dir = None
|
||||
target_dir = None
|
||||
|
||||
@classmethod
|
||||
def for_options(cls, source_dir=None, target_dir=None):
|
||||
if source_dir is None:
|
||||
raise ValueError("source_dir must not be None")
|
||||
if target_dir is None:
|
||||
raise ValueError("target_dir must not be None")
|
||||
|
||||
return type(cls)(
|
||||
cls.__name__, (cls,), {"source_dir": source_dir, "target_dir": target_dir}
|
||||
)
|
||||
|
||||
def initialize_options(self):
|
||||
self.locale = None
|
||||
|
||||
def finalize_options(self):
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
locale = self.locale
|
||||
source_path = os.path.join(self.__class__.source_dir, locale)
|
||||
target_path = os.path.join(self.__class__.target_dir, locale)
|
||||
|
||||
if not os.path.exists(source_path):
|
||||
raise RuntimeError("source path " + source_path + " does not exist")
|
||||
|
||||
if os.path.exists(target_path):
|
||||
if not os.path.isdir(target_path):
|
||||
raise RuntimeError(
|
||||
"target path " + target_path + " exists and is not a directory"
|
||||
)
|
||||
shutil.rmtree(target_path)
|
||||
|
||||
print(
|
||||
"Copying translations for locale {locale} from {source_path} to {target_path}...".format(
|
||||
**locals()
|
||||
)
|
||||
)
|
||||
shutil.copytree(source_path, target_path)
|
||||
|
||||
|
||||
class PackTranslation(Command):
|
||||
description = "creates language packs for translations"
|
||||
user_options = [
|
||||
("locale=", "l", "locale for the translation to pack"),
|
||||
("author=", "a", "author of the translation"),
|
||||
("target=", "t", "target folder for the pack"),
|
||||
]
|
||||
boolean_options = []
|
||||
|
||||
source_dir = None
|
||||
pack_name_prefix = None
|
||||
pack_path_prefix = None
|
||||
|
||||
@classmethod
|
||||
def for_options(cls, source_dir=None, pack_name_prefix=None, pack_path_prefix=None):
|
||||
if source_dir is None:
|
||||
raise ValueError("source_dir must not be None")
|
||||
if pack_name_prefix is None:
|
||||
raise ValueError("pack_name_prefix must not be None")
|
||||
if pack_path_prefix is None:
|
||||
raise ValueError("pack_path_prefix must not be None")
|
||||
|
||||
return type(cls)(
|
||||
cls.__name__,
|
||||
(cls,),
|
||||
{
|
||||
"source_dir": source_dir,
|
||||
"pack_name_prefix": pack_name_prefix,
|
||||
"pack_path_prefix": pack_path_prefix,
|
||||
},
|
||||
)
|
||||
|
||||
def initialize_options(self):
|
||||
self.locale = None
|
||||
self.author = None
|
||||
self.target = None
|
||||
|
||||
def finalize_options(self):
|
||||
if self.locale is None:
|
||||
raise ValueError("locale must be provided")
|
||||
|
||||
def run(self):
|
||||
locale = self.locale
|
||||
locale_dir = os.path.join(self.__class__.source_dir, locale)
|
||||
|
||||
if not os.path.isdir(locale_dir):
|
||||
raise RuntimeError("translation does not exist, please create it first")
|
||||
|
||||
import datetime
|
||||
|
||||
now = datetime.datetime.utcnow().replace(microsecond=0)
|
||||
|
||||
if self.target is None:
|
||||
self.target = self.__class__.source_dir
|
||||
|
||||
zip_path = os.path.join(
|
||||
self.target,
|
||||
"{prefix}{locale}_{date}.zip".format(
|
||||
prefix=self.__class__.pack_name_prefix,
|
||||
locale=locale,
|
||||
date=now.strftime("%Y%m%d%H%M%S"),
|
||||
),
|
||||
)
|
||||
print("Packing translation to {zip_path}".format(**locals()))
|
||||
|
||||
def add_recursively(zip, path, prefix):
|
||||
if not os.path.isdir(path):
|
||||
return
|
||||
|
||||
for entry in os.listdir(path):
|
||||
entry_path = os.path.join(path, entry)
|
||||
new_prefix = prefix + "/" + entry
|
||||
if os.path.isdir(entry_path):
|
||||
add_recursively(zip, entry_path, new_prefix)
|
||||
elif os.path.isfile(entry_path):
|
||||
print("Adding {entry_path} as {new_prefix}".format(**locals()))
|
||||
zip.write(entry_path, new_prefix)
|
||||
|
||||
meta_str = "last_update: {date}\n".format(date=now.isoformat())
|
||||
if self.author:
|
||||
meta_str += "author: {author}\n".format(author=self.author)
|
||||
|
||||
zip_locale_root = self.__class__.pack_path_prefix + locale
|
||||
|
||||
import zipfile
|
||||
|
||||
with zipfile.ZipFile(zip_path, "w") as zip:
|
||||
add_recursively(zip, locale_dir, zip_locale_root)
|
||||
|
||||
print("Adding meta.yaml as {zip_locale_root}/meta.yaml".format(**locals()))
|
||||
zip.writestr(zip_locale_root + "/meta.yaml", meta_str)
|
||||
|
||||
|
||||
def get_babel_commandclasses(
|
||||
pot_file=None,
|
||||
mapping_file="babel.cfg",
|
||||
input_dirs=".",
|
||||
output_dir=None,
|
||||
pack_name_prefix=None,
|
||||
pack_path_prefix=None,
|
||||
bundled_dir=None,
|
||||
mail_address="i18n@octoprint.org",
|
||||
copyright_holder="The OctoPrint Project",
|
||||
):
|
||||
result = {
|
||||
"babel_new": NewTranslation.for_options(pot_file=pot_file, output_dir=output_dir),
|
||||
"babel_extract": ExtractTranslation.for_options(
|
||||
mapping_file=mapping_file,
|
||||
pot_file=pot_file,
|
||||
input_dirs=input_dirs,
|
||||
mail_address=mail_address,
|
||||
copyright_holder=copyright_holder,
|
||||
),
|
||||
"babel_refresh": RefreshTranslation.for_options(
|
||||
mapping_file=mapping_file,
|
||||
pot_file=pot_file,
|
||||
input_dirs=input_dirs,
|
||||
output_dir=output_dir,
|
||||
mail_address=mail_address,
|
||||
copyright_holder=copyright_holder,
|
||||
),
|
||||
"babel_compile": CompileTranslation.for_options(output_dir=output_dir),
|
||||
"babel_pack": PackTranslation.for_options(
|
||||
source_dir=output_dir,
|
||||
pack_name_prefix=pack_name_prefix,
|
||||
pack_path_prefix=pack_path_prefix,
|
||||
),
|
||||
}
|
||||
|
||||
if bundled_dir is not None:
|
||||
result["babel_bundle"] = BundleTranslation.for_options(
|
||||
source_dir=output_dir, target_dir=bundled_dir
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def create_plugin_setup_parameters(
|
||||
identifier="todo",
|
||||
name="TODO",
|
||||
version="0.1",
|
||||
description="TODO",
|
||||
author="TODO",
|
||||
mail="todo@example.com",
|
||||
url="TODO",
|
||||
license="AGPLv3",
|
||||
source_folder=".",
|
||||
additional_data=None,
|
||||
additional_packages=None,
|
||||
ignored_packages=None,
|
||||
requires=None,
|
||||
extra_requires=None,
|
||||
cmdclass=None,
|
||||
eggs=None,
|
||||
package=None,
|
||||
dependency_links=None,
|
||||
):
|
||||
import pkg_resources
|
||||
|
||||
if package is None:
|
||||
package = "octoprint_{identifier}".format(**locals())
|
||||
|
||||
if additional_data is None:
|
||||
additional_data = list()
|
||||
|
||||
if additional_packages is None:
|
||||
additional_packages = list()
|
||||
|
||||
if ignored_packages is None:
|
||||
ignored_packages = list()
|
||||
|
||||
if dependency_links is None:
|
||||
dependency_links = list()
|
||||
|
||||
if requires is None:
|
||||
requires = ["OctoPrint"]
|
||||
if not isinstance(requires, list):
|
||||
raise ValueError("requires must be a list")
|
||||
if not has_requirement("OctoPrint", requires):
|
||||
requires = ["OctoPrint"] + list(requires)
|
||||
|
||||
if extra_requires is None:
|
||||
extra_requires = {}
|
||||
if not isinstance(extra_requires, dict):
|
||||
raise ValueError("extra_requires must be a dict")
|
||||
|
||||
if cmdclass is None:
|
||||
cmdclass = {}
|
||||
if not isinstance(cmdclass, dict):
|
||||
raise ValueError("cmdclass must be a dict")
|
||||
|
||||
if eggs is None:
|
||||
eggs = []
|
||||
if not isinstance(eggs, list):
|
||||
raise ValueError("eggs must be a list")
|
||||
|
||||
egg = "{name}*.egg-info".format(
|
||||
name=pkg_resources.to_filename(pkg_resources.safe_name(name))
|
||||
)
|
||||
if egg not in eggs:
|
||||
eggs = [egg] + eggs
|
||||
|
||||
cmdclass.update(
|
||||
{
|
||||
"clean": CleanCommand.for_options(
|
||||
source_folder=os.path.join(source_folder, package), eggs=eggs
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
translation_dir = os.path.join(source_folder, "translations")
|
||||
pot_file = os.path.join(translation_dir, "messages.pot")
|
||||
bundled_dir = os.path.join(source_folder, package, "translations")
|
||||
cmdclass.update(
|
||||
get_babel_commandclasses(
|
||||
pot_file=pot_file,
|
||||
output_dir=translation_dir,
|
||||
bundled_dir=bundled_dir,
|
||||
pack_name_prefix="{name}-i18n-".format(**locals()),
|
||||
pack_path_prefix="_plugins/{identifier}/".format(**locals()),
|
||||
)
|
||||
)
|
||||
|
||||
from setuptools import find_packages
|
||||
|
||||
packages = set(
|
||||
[package]
|
||||
+ list(
|
||||
filter(
|
||||
lambda x: x.startswith("{package}.".format(package=package)),
|
||||
find_packages(where=source_folder, exclude=ignored_packages),
|
||||
)
|
||||
)
|
||||
+ additional_packages
|
||||
)
|
||||
print("Found packages: {packages!r}".format(**locals()))
|
||||
|
||||
return {
|
||||
"name": name,
|
||||
"version": version,
|
||||
"description": description,
|
||||
"author": author,
|
||||
"author_email": mail,
|
||||
"url": url,
|
||||
"license": license,
|
||||
# adding new commands
|
||||
"cmdclass": cmdclass,
|
||||
# we only have our plugin package to install
|
||||
"packages": packages,
|
||||
# we might have additional data files in sub folders that need to be installed too
|
||||
"package_data": {
|
||||
package: package_data_dirs(
|
||||
os.path.join(source_folder, package),
|
||||
["static", "templates", "translations"] + additional_data,
|
||||
)
|
||||
},
|
||||
"include_package_data": True,
|
||||
# If you have any package data that needs to be accessible on the file system, such as templates or static assets
|
||||
# this plugin is not zip_safe.
|
||||
"zip_safe": False,
|
||||
"install_requires": requires,
|
||||
"extras_require": extra_requires,
|
||||
"dependency_links": dependency_links,
|
||||
# Hook the plugin into the "octoprint.plugin" entry point, mapping the plugin_identifier to the plugin_package.
|
||||
# That way OctoPrint will be able to find the plugin and load it.
|
||||
"entry_points": {
|
||||
"octoprint.plugin": ["{identifier} = {package}".format(**locals())]
|
||||
},
|
||||
}
|
||||
Reference in new issue
Block a user