Merge branch 'maintenance' into devel

This commit is contained in:
Gina Häußge committed 2022-02-22 17:49:09 +01:00
commit 581ce02504
45 files changed
+2098 -2173

No files matched your search

+6 -3
View File
@@ -9,7 +9,8 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
@@ -41,8 +42,10 @@ extensions = [
"sphinx.ext.intersphinx",
]
todo_include_todos = True
intersphinx_mapping = {'python': ('https://docs.python.org/3', None),
'pyserial': ('https://pythonhosted.org/pyserial', None)}
intersphinx_mapping = {
"python": ("https://docs.python.org/3", None),
"pyserial": ("https://pythonhosted.org/pyserial", None),
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
+9 -1
View File
@@ -561,6 +561,14 @@ plugins are tracked:
_forcedCompatible:
- ...
# Custom sorting of hooks and implementations provided by plugins. Two-tiered dictionary
# structure, plugin identifier mapping to a dictionary of order overrides mapped by
# sorting context/hook name
_sortingOrder:
some_plugin:
some_hook: 1
some_other_hook: 200
# The rest are individual plugin settings, each tracked by their identifier, e.g.:
some_plugin:
some_setting: true
@@ -692,7 +700,7 @@ Use the following settings to configure the serial connection to the printer:
maxWritePasses: 5
# Use this to define additional patterns to consider for serial port listing. Must be a valid
# "glob" pattern (see http://docs.python.org/2/library/glob.html). Defaults to not set.
# "glob" pattern (see http://docs.python.org/3/library/glob.html). Defaults to not set.
additionalPorts:
- /dev/myPrinterSymlink
+1 -1
View File
@@ -3,7 +3,7 @@
General Concepts
================
OctoPrint's plugins are `Python Packages <https://docs.python.org/2/tutorial/modules.html#packages>`_ which in their
OctoPrint's plugins are :ref:`Python Packages <tut-packages>` which in their
top-level module define a bunch of :ref:`control properties <sec-plugins-controlproperties>` defining
metadata (like name, version etc of the plugin) as well as information on how to initialize the plugin and into what
parts of the system the plugin will actually plug in to perform its job.
+1 -1
View File
@@ -120,7 +120,7 @@ up and ready to serve requests.
You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system
injects :ref:`a some useful objects <sec-plugins-mixins-injectedproperties>` into our plugin implementation classes,
one of those being a fully instantiated `python logger <https://docs.python.org/2/library/logging.html>`_ ready to be
one of those being a fully instantiated :ref:`python logger <logging>` ready to be
used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld``
for our little plugin here, or more generally ``octoprint.plugins.<plugin identifier>``.
+2
View File
@@ -600,6 +600,7 @@ def init_pluginsystem(
]
plugin_entry_points = ["octoprint.plugin"]
plugin_disabled_list = settings.get(["plugins", "_disabled"])
plugin_sorting_order = settings.get(["plugins", "_sortingOrder"], merged=True)
plugin_blacklist = []
if not ignore_blacklist and settings.getBoolean(
@@ -631,6 +632,7 @@ def init_pluginsystem(
plugin_folders=plugin_folders,
plugin_entry_points=plugin_entry_points,
plugin_disabled_list=plugin_disabled_list,
plugin_sorting_order=plugin_sorting_order,
plugin_blacklist=plugin_blacklist,
plugin_validators=plugin_validators,
compatibility_ignored_list=compatibility_ignored_list,
+8
View File
@@ -325,6 +325,14 @@ def plugins():
pass
@subcommands.group(
name="timelapse", cls=LazyGroup, import_name="octoprint.cli.timelapse:cli"
)
def timelapse():
"""Timelapse related commands."""
pass
@subcommands.group(name="user", cls=LazyGroup, import_name="octoprint.cli.user:cli")
def user():
"""User management."""
+91
View File
@@ -0,0 +1,91 @@
__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 logging
import os
from concurrent.futures import ThreadPoolExecutor, wait
import click
from octoprint import FatalStartupError, init_pluginsystem, init_settings
from octoprint.cli import get_ctx_obj_option, standard_options
from octoprint.timelapse import create_thumbnail_path, valid_timelapse
from octoprint.util import is_hidden_path
click.disable_unicode_literals_warning = True
@click.group()
@click.pass_context
def cli(ctx):
"""Basic config manipulation."""
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
try:
ctx.obj.settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
overlays=get_ctx_obj_option(ctx, "overlays", None),
)
ctx.obj.plugin_manager = init_pluginsystem(
ctx.obj.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False)
)
except FatalStartupError as e:
click.echo(str(e), err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
@cli.command(name="create_thumbnails")
@standard_options(hidden=True)
@click.option(
"--missing",
is_flag=True,
help="Create thumbnails for all timelapses that don't yet have one",
)
@click.option(
"--processes",
type=int,
help="Number of processes to use for creating thumbnails",
default=1,
)
@click.argument("paths", nargs=-1, type=click.Path())
@click.pass_context
def extract_thumbnails(ctx, missing, processes, paths):
"""Extract missing thumbnails from timelapses."""
if not paths and not missing:
click.echo(
"No paths specified and no --missing flag either, nothing to do.", err=True
)
ctx.exit(-1)
if missing:
paths = []
timelapse_folder = ctx.obj.settings.getBaseFolder("timelapse")
for entry in os.scandir(timelapse_folder):
if is_hidden_path(entry.path) or not valid_timelapse(entry.path):
continue
thumb = create_thumbnail_path(entry.path)
if not os.path.isfile(thumb):
paths.append(entry.path)
ffmpeg = ctx.obj.settings.get(["webcam", "ffmpeg"])
click.echo(f"Creating thumbnails for {len(paths)} timelapses")
executor = ThreadPoolExecutor(max_workers=processes)
futures = [executor.submit(_create_thumbnail, ffmpeg, path) for path in paths]
wait(futures)
click.echo("Done!")
def _create_thumbnail(ffmpeg, path):
from octoprint.timelapse import TimelapseRenderJob
click.echo(f"Creating thumbnail for {path}...")
return TimelapseRenderJob._try_generate_thumbnail(ffmpeg, path)
+1 -1
View File
@@ -139,7 +139,7 @@ class Events:
return name, event
# based on https://stackoverflow.com/a/1176023
_first_cap_re = re.compile("(.)([A-Z][a-z]+)")
_first_cap_re = re.compile("([^_])([A-Z][a-z]+)")
_all_cap_re = re.compile("([a-z0-9])([A-Z])")
@classmethod
+4
View File
@@ -39,6 +39,7 @@ def plugin_manager(
plugin_bases=None,
plugin_entry_points=None,
plugin_disabled_list=None,
plugin_sorting_order=None,
plugin_blacklist=None,
plugin_restart_needing_hooks=None,
plugin_obsolete_hooks=None,
@@ -64,6 +65,8 @@ def plugin_manager(
this defaults to the entry point ``octoprint.plugin``.
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
defaults to all plugins for which ``enabled`` is set to ``False`` in the settings.
plugin_sorting_order (dict): A dict containing a custom sorting orders for plugins. The keys are plugin identifiers,
mapped to dictionaries containing the sorting contexts as key and the custom sorting value as value.
plugin_blacklist (list): A list of plugin identifiers/identifier-requirement tuples
that are currently blacklisted.
plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order
@@ -121,6 +124,7 @@ def plugin_manager(
plugin_entry_points,
logging_prefix="octoprint.plugins.",
plugin_disabled_list=plugin_disabled_list,
plugin_sorting_order=plugin_sorting_order,
plugin_blacklist=plugin_blacklist,
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
plugin_obsolete_hooks=plugin_obsolete_hooks,
+25 -3
View File
@@ -796,6 +796,7 @@ class PluginManager:
plugin_timings_logtarget = "PLUGIN_TIMINGS"
plugin_timings_message = "{func} - {timing:05.2f}ms"
default_order = 1000
def __init__(
self,
@@ -804,6 +805,7 @@ class PluginManager:
plugin_entry_points,
logging_prefix=None,
plugin_disabled_list=None,
plugin_sorting_order=None,
plugin_blacklist=None,
plugin_restart_needing_hooks=None,
plugin_obsolete_hooks=None,
@@ -823,6 +825,8 @@ class PluginManager:
plugin_entry_points = []
if plugin_disabled_list is None:
plugin_disabled_list = []
if plugin_sorting_order is None:
plugin_sorting_order = {}
if plugin_blacklist is None:
plugin_blacklist = []
if compatibility_ignored_list is None:
@@ -850,6 +854,7 @@ class PluginManager:
self.plugin_bases = plugin_bases
self.plugin_entry_points = plugin_entry_points
self.plugin_disabled_list = plugin_disabled_list
self.plugin_sorting_order = plugin_sorting_order
self.plugin_blacklist = processed_blacklist
self.plugin_restart_needing_hooks = plugin_restart_needing_hooks
self.plugin_obsolete_hooks = plugin_obsolete_hooks
@@ -1638,6 +1643,13 @@ class PluginManager:
)
continue
if not order:
order = self.default_order
override = self.plugin_sorting_order.get(name, {}).get(hook, None)
if override:
order = override
self._plugin_hooks[hook].append((order, name, callback))
self._sort_hooks(hook)
@@ -1681,6 +1693,9 @@ class PluginManager:
)
continue
if not order:
order = self.default_order
try:
self._plugin_hooks[hook].remove((order, name, callback))
self._sort_hooks(hook)
@@ -2125,11 +2140,18 @@ class PluginManager:
impl[0], sorting_context
)
)
sorting_value = None
sorting_value = self.default_order
else:
sorting_value = self.default_order
override = self.plugin_sorting_order.get(impl[0], {}).get(
sorting_context, None
)
if override:
sorting_value = override
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
return (
sorting_value is None,
sv(sorting_value),
not plugin_info.bundled if plugin_info else True,
sv(impl[0]),
@@ -2223,7 +2245,7 @@ class PluginManager:
def _sort_hooks(self, hook):
self._plugin_hooks[hook] = sorted(
self._plugin_hooks[hook],
key=lambda x: (x[0] is None, sv(x[0]), sv(x[1]), sv(x[2])),
key=lambda x: (sv(x[0]), sv(x[1]), sv(x[2])),
)
def _get_callback_and_order(self, hook):
+21 -10
View File
@@ -23,7 +23,7 @@ from octoprint.server.util.flask import (
no_firstrun_access,
with_revalidation_checking,
)
from octoprint.util import count, utmify
from octoprint.util import count, deserialize, serialize, utmify
from octoprint.util.text import sanitize
@@ -428,12 +428,22 @@ class AnnouncementPlugin(
ttl *= 60
now = time.time()
if os.stat(channel_path).st_mtime + ttl > now:
d = feedparser.parse(channel_path)
if now > os.stat(channel_path).st_mtime + ttl:
return None
try:
d = deserialize(channel_path)
self._logger.debug(f"Loaded channel {key} from cache at {channel_path}")
return d
return None
except Exception:
self._logger.exception(
f"Could not read channel {key} from cache {channel_path}"
)
try:
os.remove(channel_path)
except OSError:
pass
return None
def _get_channel_data_from_network(self, key, config):
"""Fetch channel feed from network."""
@@ -456,11 +466,12 @@ class AnnouncementPlugin(
)
return None
response = r.text
channel_path = self._get_channel_cache_path(key)
with open(channel_path, mode="wt", encoding="utf-8") as f:
f.write(response)
return feedparser.parse(response)
response = feedparser.parse(r.text)
try:
serialize(self._get_channel_cache_path(key), response)
except Exception:
self._logger.exception(f"Failed to cache data for channel {key}")
return response
def _to_internal_feed(self, feed, read_until=None):
"""Convert feed to internal data structure."""
@@ -1 +1 @@
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}#plugin_announcements_dialog .modal-footer .configurelink{float:left}
table th.settings_plugin_announcements_channels_name,table td.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_announcements_channels_actions,table td.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table th.settings_plugin_announcements_channels_actions a,table td.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table th.settings_plugin_announcements_channels_actions a.disabled,table td.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:bold}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:black}#plugin_announcements_dialog .modal-footer .configurelink{float:left}
@@ -154,7 +154,8 @@ GCODE.gCodeReader = (function () {
this.clear();
var totalSize = reader.target.result.length;
lines = reader.target.result.split(/[\r\n]/g);
// With a regex split below as previous, memory usage is huge & takes longer.
lines = reader.target.result.replace("\r\n", "\n").split("\n");
reader.target.result = null;
prepareGCode(totalSize);
@@ -159,7 +159,7 @@ $(function () {
return (
self.piSupport &&
self.piSupport.currentIssue() &&
!self.settings.settings.plugins.pluginmanager.ignore_throttled()
!self.settings.settings.plugins.softwareupdate.ignore_throttled()
);
});
+2 -1
View File
@@ -64,6 +64,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._targetTemp = None
self._targetBedTemp = None
self._targetChamberTemp = None
self._custom = None
self._temps = DataHistory(
cutoff=settings().getInt(["temperature", "cutoff"]) * 60
@@ -275,7 +276,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
try:
additional = hook(initial=initial)
if additional and isinstance(additional, dict):
octoprint.util.json.dump({name: additional})
octoprint.util.json.dumps({name: additional})
plugin_data[name] = additional
except ValueError:
self._logger.exception(
+4
View File
@@ -215,6 +215,10 @@ def getSettings():
"waitForStart": s.getBoolean(["serial", "waitForStartOnConnect"]),
"alwaysSendChecksum": s.getBoolean(["serial", "alwaysSendChecksum"]),
"neverSendChecksum": s.getBoolean(["serial", "neverSendChecksum"]),
"sendChecksumWithUnknownCommands": s.getBoolean(
["serial", "sendChecksumWithUnknownCommands"]
),
"unknownCommandsNeedAck": s.getBoolean(["serial", "unknownCommandsNeedAck"]),
"sdRelativePath": s.getBoolean(["serial", "sdRelativePath"]),
"sdAlwaysAvailable": s.getBoolean(["serial", "sdAlwaysAvailable"]),
"sdLowerCase": s.getBoolean(["serial", "sdLowerCase"]),
+2 -2
View File
@@ -24,7 +24,7 @@ from octoprint.access.permissions import Permissions
from octoprint.access.users import LoginStatusListener
from octoprint.events import Events
from octoprint.settings import settings
from octoprint.util.json import dump as json_dump
from octoprint.util.json import dumps as json_dumps
from octoprint.util.version import get_python_version_string
@@ -65,7 +65,7 @@ class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session):
class JsonEncodingSessionWrapper(wrapt.ObjectProxy):
def send_message(self, msg, stats=True, binary=False):
self.send_jsonified(
json_dump(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg)),
json_dumps(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg)),
stats,
)
+60 -56
View File
@@ -415,7 +415,7 @@ default_settings = {
"remoteUserHeader": "REMOTE_USER",
"addRemoteUsers": False,
},
"slicing": {"enabled": True, "defaultSlicer": None, "defaultProfiles": None},
"slicing": {"enabled": True, "defaultSlicer": None, "defaultProfiles": {}},
"events": {"enabled": True, "subscriptions": []},
"api": {"allowCrossOrigin": False, "apps": {}},
"terminalFilters": [
@@ -437,7 +437,7 @@ default_settings = {
"regex": r"Recv: (echo:\s*)?busy:\s*processing",
},
],
"plugins": {"_disabled": [], "_forcedCompatible": []},
"plugins": {"_disabled": [], "_forcedCompatible": [], "_sortingOrder": {}},
"scripts": {
"gcode": {
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0",
@@ -554,35 +554,9 @@ class HierarchicalChainMap:
"""
@staticmethod
def _unflatten(kv_pairs, prefix=""):
"""
:type kv_pairs: Iterable[Tuple[str, any]]
"""
result = dict()
for key, value in kv_pairs:
if not key.startswith(prefix):
continue
subkeys = key[len(prefix) :].split(_CHAINMAP_SEP)
current = result
for subkey in subkeys[:-1]:
if subkey not in current:
current[subkey] = {}
current = current[subkey]
current[subkeys[-1]] = value
def _flatten(d: dict, parent_key: str = "") -> dict:
"""Flattens a hierarchical dictionary."""
return result
def __init__(self, *maps):
self._chainmap = ChainMap(*map(self._flatten, maps))
@staticmethod
def from_layers(*layers):
result = HierarchicalChainMap()
result._chainmap.maps = layers
return result
@staticmethod
def _flatten(d, parent_key=""):
if d is None:
return {}
@@ -595,8 +569,26 @@ class HierarchicalChainMap:
items.append((new_key, v))
return dict(items)
def deep_dict(self):
return self._unflatten(self._chainmap.items())
@staticmethod
def _unflatten(d: dict, prefix: str = "") -> dict:
"""Unflattens a flattened dictionary."""
if d is None:
return {}
result = dict()
for key, value in d.items():
if not key.startswith(prefix):
continue
subkeys = key[len(prefix) :].split(_CHAINMAP_SEP)
current = result
for subkey in subkeys[:-1]:
if subkey not in current or current[subkey] is None:
current[subkey] = {}
current = current[subkey]
current[subkeys[-1]] = value
return result
@staticmethod
def _path_to_key(path):
@@ -605,6 +597,18 @@ class HierarchicalChainMap:
"""
return _CHAINMAP_SEP.join(path)
@staticmethod
def from_layers(*layers):
result = HierarchicalChainMap()
result._chainmap.maps = layers
return result
def __init__(self, *maps):
self._chainmap = ChainMap(*map(self._flatten, maps))
def deep_dict(self):
return self._unflatten(self._chainmap)
def has_path(self, path, only_local=False, only_defaults=False):
if only_defaults:
current = self._chainmap.parents
@@ -625,30 +629,30 @@ class HierarchicalChainMap:
key = self._path_to_key(path)
# we do something a bit odd here: if merged is not true, we don't include the
# full contents of the key. Instead, we only include the contents of the key on
# the first level where we find the value.
if not merged and not only_local:
if key in current:
# found it, return
return current[key]
# if we arrived here we might be trying to grab a dict, look for children
key = key + _CHAINMAP_SEP
# TODO 2.0.0 remove this & make 'merged' the default
if not merged and hasattr(current, "maps"):
# we do something a bit odd here: if merged is not true, we don't include the
# full contents of the key. Instead, we only include the contents of the key
# on the first level where we find the value.
for layer in current.maps:
for k in layer:
if k.startswith(key):
current = layer
break
else:
continue
break
if any(k.startswith(key) for k in layer):
current = layer
break
if key not in current:
# we might be trying to grab a dict, look for children
key = key + _CHAINMAP_SEP
result = self._unflatten(
((k, v) for k, v in current.items() if k.startswith(key)), prefix=key
)
if not result:
raise KeyError("Could not find entry for " + str(path))
return result
return current[key]
result = self._unflatten(
{k: v for k, v in current.items() if k.startswith(key)}, prefix=key
)
if not result:
raise KeyError("Could not find entry for " + str(path))
return result
def set_by_path(self, path, value):
current = self._chainmap
@@ -728,7 +732,7 @@ class HierarchicalChainMap:
@property
def top_map(self):
"""This is the layer that is written to"""
return self._unflatten(self._chainmap.maps[0].items())
return self._unflatten(self._chainmap.maps[0])
@top_map.setter
def top_map(self, value):
@@ -1861,7 +1865,7 @@ class Settings:
for key in keys:
try:
value = chain.get_by_path(
parent_path + [key], only_local=not incl_defaults
parent_path + [key], only_local=not incl_defaults, merged=merged
)
except KeyError:
raise NoSuchSettingsPath()
+1 -1
View File
@@ -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 / 100;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)Line 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 / 100;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)Line truncated
@@ -15,6 +15,7 @@
this.options = {
timeouts: [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100],
connectTimeout: 5000,
transportTimeout: 4000,
rateSlidingWindowSize: 20
};
@@ -168,6 +169,31 @@
}, timeout);
}
/*
* We define both a connectTimeout and a transportTimeout because they do
* different things:
*
* - connectTimeout defines how long this socket class abstraction will wait
* for sockjs to get to a connected state, regardless of which transport
* connects.
* - transportTimeout defines how long sockjs will wait on the
* initial websocket to connect before falling back to a worse
* (but might work) transport.
*
* We need to define transportTimeout because the default in
* sockjs is very low, around 200ms. This limit hinders the performance of
* remote OctoPrint plugins and other remote OctoPrint connections and forces
* them to fall back to the inferior http polling based sockjs transports.
* This change will also help lower powered OctoPrint devices that might
* need more time to process the influx of requests on OctoPrint initial load.
*/
var transportTimeout = self.options.transportTimeout;
if (opts.hasOwnProperty("transportTimeout")) {
transportTimeout = opts.transportTimeout;
delete opts.transportTimeout;
}
opts.timeout = transportTimeout;
self.socket = new SockJS(url + "sockjs", undefined, opts);
self.socket.onopen = onOpen;
self.socket.onclose = onClose;
@@ -48,7 +48,7 @@ $(function () {
self.enablePrint = ko.pureComputed(function () {
return (
self.isOperational() &&
self.isReady() &&
(self.isReady() || self.isPaused()) &&
!self.isPrinting() &&
!self.isCancelling() &&
!self.isPausing() &&
@@ -219,6 +219,8 @@ $(function () {
self.serial_triggerOkForM29 = ko.observable(undefined);
self.serial_waitForStart = ko.observable(undefined);
self.serial_sendChecksum = ko.observable("print");
self.serial_sendChecksumWithUnknownCommands = ko.observable(undefined);
self.serial_unknownCommandsNeedAck = ko.observable(undefined);
self.serial_sdRelativePath = ko.observable(undefined);
self.serial_sdLowerCase = ko.observable(undefined);
self.serial_sdAlwaysAvailable = ko.observable(undefined);
+33 -25
View File
@@ -335,7 +335,6 @@ table {
.name {
text-overflow: ellipsis;
text-align: left;
font-weight: 800;
margin: 0 0 0 0;
}
.detail {
@@ -349,38 +348,47 @@ table {
&.timelapse_files_thumb {
@thumb-size: 110px;
@thumb-coner: 3px;
@thumb-corner: 3px;
width: @thumb-size;
position: relative;
img {
max-width: 100%;
max-height: @thumb-size;
border-radius: @thumb-coner;
}
div {
.thumb {
width: @thumb-size;
height: calc(@thumb-size * 9 / 16);
border-radius: @thumb-coner;
border-radius: @thumb-corner;
background-color: rgb(238, 238, 238);
}
position: relative;
a {
background-image: url(/static/img/play.svg);
background-position: center;
background-repeat: no-repeat;
background-size: 32px 32px;
width: 100%;
height: 100%;
opacity: 0.8;
position: absolute;
top: 0;
left: 0;
content: "";
&.letterbox {
background-color: #000;
}
&:hover {
opacity: 1;
img {
max-width: 100%;
max-height: 100%;
border-radius: @thumb-corner;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
a {
background-image: url(/static/img/play.svg);
background-position: center;
background-repeat: no-repeat;
background-size: 32px 32px;
width: 100%;
height: 100%;
opacity: 0.8;
position: absolute;
top: 0;
left: 0;
content: "";
&:hover {
opacity: 1;
}
}
}
}
@@ -37,7 +37,7 @@
<label class="control-label" for="settings-serialAdditionalPorts">{{ _('Additional serial ports') }}</label>
<div class="controls">
<textarea rows="4" class="block" id="settings-serialAdditionalPorts" data-bind="value: serial_additionalPorts"></textarea>
<span class="help-inline">{{ _('Use this to define additional <a href="%%(glob_url)s">glob patterns</a> matching serial ports to list for connecting against, e.g. <code>/dev/ttyAMA*</code>. One entry per line. Please note that ports will only be offered to connect to if they get also detected by the <em>operating system</em>. Adding a port here will not make it magically appear in OctoPrint. If the operating system doesn\'t see your printer you need to solve this first.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
<span class="help-inline">{{ _('Use this to define additional <a href="%%(glob_url)s">glob patterns</a> matching serial ports to list for connecting against, e.g. <code>/dev/ttyAMA*</code>. One entry per line. Please note that ports will only be offered to connect to if they get also detected by the <em>operating system</em>. Adding a port here will not make it magically appear in OctoPrint. If the operating system doesn\'t see your printer you need to solve this first.')|format(glob_url="http://docs.python.org/3/library/glob.html") }}</span>
</div>
</div>
<div class="control-group">
@@ -51,7 +51,7 @@
<label class="control-label" for="settings-serialBlacklistedPorts">{{ _('Blacklisted serial ports') }}</label>
<div class="controls">
<textarea rows="4" class="block" id="settings-serialBlacklistedPorts" data-bind="value: serial_blacklistedPorts"></textarea>
<span class="help-inline">{{ _('Use this to define <a href="%%(glob_url)s">glob patterns</a> matching serial ports to blacklist for connecting against, e.g. <code>/dev/ttyS*</code>. One entry per line.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
<span class="help-inline">{{ _('Use this to define <a href="%%(glob_url)s">glob patterns</a> matching serial ports to blacklist for connecting against, e.g. <code>/dev/ttyS*</code>. One entry per line.')|format(glob_url="http://docs.python.org/3/library/glob.html") }}</span>
</div>
</div>
<div class="control-group">
@@ -343,7 +343,23 @@
</label>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Send line numbers & checksums for non-GCODE commands')|edq }}">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_sendChecksumWithUnknownCommands" id="settings-sendChecksumWithUnknownCommands"> {{ _('Send line numbers & checksums for non-GCODE commands') }} <span class="label">{{ _('Prusa Firmware') }}</span>
<span class="help-block">{{ _('Check this if your printer supports commands outside of the GCODE format (e.g. <code>Tx</code> or similar) but requires them to be treated identical to GCODE.') }}</span>
</label>
</div>
</div>
<div class="control-group" title="{{ _('Wait for \'ok\' for non-GCODE commands')|edq }}">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_unknownCommandsNeedAck" id="settings-unknownCommandsNeedAck"> {{ _('Wait for acknowledging <code>ok</code> for non-GCODE commands') }} <span class="label">{{ _('Prusa Firmware') }}</span>
<span class="help-block">{{ _('Check this if your printer supports commands outside of the GCODE format (e.g. <code>Tx</code> or similar) but requires them to be treated identical to GCODE.') }}</span>
</label>
</div>
</div>
</div>
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#settings_serial_protocol_firmware .hide' }"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
@@ -457,7 +473,8 @@
<label class="control-label" for="settings-serialEmergencyCommands">{{ _('Emergency commands') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialEmergencyCommands" data-bind="value: serial_emergencyCommands">
<span class="help-inline">{{ _('Use this to specify emergency commands which should jump any queues and - if supported by the firmware - be force sent. Just the G or M code, comma separated. Defaults to <code>M112</code>, <code>M108</code> and <code>M410</code>.') }}</span> </div>
<span class="help-inline">{{ _('Use this to specify emergency commands which should jump any queues and - if supported by the firmware - be force sent. Just the G or M code, comma separated. Defaults to <code>M112</code>, <code>M108</code> and <code>M410</code>.') }}</span>
</div>
</div>
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#settings_serial_protocol_finetuning .hide' }"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
@@ -6,7 +6,6 @@
{% assets "less_plugins" %}<link rel="preload" as="style" href="{{ ASSET_URL }}">{% endassets %}
{% for fa in ("fa-brands-400", "fa-regular-400", "fa-solid-900") %}
<link rel="preload" as="font" href="{{ url_for('static', filename='vendor/font-awesome-5.15.1/webfonts/' + fa + '.woff2') }}?v=5.15.1" type="font/woff2" crossorigin="anonymous">
<link rel="preload" as="font" href="{{ url_for('static', filename='vendor/font-awesome-5.15.1/webfonts/' + fa + '.woff') }}?v=5.15.1" type="font/woff" crossorigin="anonymous">
<link rel="preload" as="font" href="{{ url_for('static', filename='vendor/font-awesome-5.15.1/webfonts/' + fa + '.woff2') }}" type="font/woff2" crossorigin="anonymous">
{% endfor %}
<link rel="preload" as="font" href="{{ url_for('static', filename='vendor/font-awesome-3.2.1/fonts/fontawesome-webfont.woff') }}?v=3.2.1" type="font/woff" crossorigin="anonymous">
<link rel="preload" as="font" href="{{ url_for('static', filename='vendor/font-awesome-3.2.1/fonts/fontawesome-webfont.woff') }}" type="font/woff" crossorigin="anonymous">
@@ -146,13 +146,12 @@
<tr data-bind="attr: {title: name}">
<td class="timelapse_files_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForFileDeletion, invisible: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)()"></td>
<td class="timelapse_files_thumb">
<!-- ko if: $data.thumbnail -->
<img data-bind="attr:{src: thumbnail}" loading="lazy" />
<!-- /ko -->
<!-- ko ifnot: $data.thumbnail -->
<div></div>
<!-- /ko -->
<a href="javascript:void(0)" data-bind="css: {disabled: !$root.isTimelapseViewable($data)}, click: $root.showTimelapsePreview"></a>
<div class="thumb" data-bind="css: { letterbox: $data.thumbnail }">
<!-- ko if: $data.thumbnail -->
<img data-bind="attr:{src: thumbnail}" loading="lazy" />
<!-- /ko -->
<a href="javascript:void(0)" data-bind="css: {disabled: !$root.isTimelapseViewable($data)}, click: $root.showTimelapsePreview"></a>
</div>
</td>
<td class="timelapse_files_details">
<p class="name" data-bind="text: name"></p>
+9 -4
View File
@@ -1121,11 +1121,14 @@ class TimelapseRenderJob:
if duration is not None:
self._parsed_duration = self._convert_time(*duration.groups())
def _try_generate_thumbnail(self, ffmpeg, movie_path):
@classmethod
def _try_generate_thumbnail(cls, ffmpeg, movie_path):
logger = logging.getLogger(__name__)
try:
thumb_path = create_thumbnail_path(movie_path)
commandline = settings().get(["webcam", "ffmpegThumbnailCommandline"])
thumb_command_str = self._create_ffmpeg_command_string(
thumb_command_str = cls._create_ffmpeg_command_string(
commandline=commandline,
ffmpeg=ffmpeg,
input=movie_path,
@@ -1140,16 +1143,18 @@ class TimelapseRenderJob:
thumb_command_str, delimiter=b"\r", buffer_size=512
)
if returncode != 0:
self._logger.warning(
logger.warning(
"Failed to generate optional thumbnail %r: %s"
% (returncode, stderr_text)
)
return True
except Exception as ex:
self._logger.warning(
logger.warning(
"Failed to generate thumbnail from {} to {} ({})".format(
movie_path, thumb_path, ex
)
)
return False
@staticmethod
def _convert_time(hours, minutes, seconds):
+13 -6
View File
@@ -11,7 +11,6 @@ import codecs
import collections
import contextlib
import copy
import json
import logging
import os
import pickle
@@ -1719,9 +1718,13 @@ def serialize(filename, data, encoding="utf-8", compressed=True):
"""
Serializes data to a file
In the current implementation this uses json.dumps and - if compressed is True (the
default) - zlib.compress. Only data that can be serialized by json.dumps in the stock
configuration is supported.
In the current implementation this uses json.dumps.
If `compressed` is True (the default), the serialized data put through zlib.compress.
Supported data types are listed at the bottom of
:ref:`octoprint.util.comprehensive_json`, and include some data types that are not
supported by json.dumps by default.
This is not thread-safe, if concurrent access is required, the caller needs to ensure
that only one thread is writing to the file at any given time.
@@ -1732,7 +1735,9 @@ def serialize(filename, data, encoding="utf-8", compressed=True):
encoding (str): The encoding to use for the file
compressed (bool): Whether to compress the data before writing it to the file
"""
serialized = json.dumps(data).encode(encoding)
from octoprint.util import json
serialized = json.serializing.dumps(data).encode(encoding)
if compressed:
serialized = zlib.compress(serialized)
@@ -1763,4 +1768,6 @@ def deserialize(filename, encoding="utf-8"):
except zlib.error:
pass
return json.loads(serialized.decode(encoding))
from octoprint.util import json
return json.serializing.loads(serialized.decode(encoding))
+2
View File
@@ -2816,6 +2816,8 @@ class MachineCom:
)
self._sdLowerCase = True
self._sendChecksumWithUnknownCommands = True
self._unknownCommandsNeedAck = True
self._firmware_info_received = True
self._firmware_info = data
+9 -42
View File
@@ -1,46 +1,13 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.util import deprecated
import collections
import json
from . import serializing # noqa: F401
from .encoding import JsonEncoding, dumps, loads # noqa: F401
from frozendict import frozendict
from octoprint.util import to_unicode
def dump(obj):
return json.dumps(
obj,
separators=(",", ":"),
default=JsonEncoding.encode,
allow_nan=False,
)
class JsonEncoding:
encoders = collections.OrderedDict()
@classmethod
def add_encoder(cls, type, encoder):
cls.encoders[type] = encoder
@classmethod
def remove_encoder(cls, type):
try:
del cls.encoders[type]
except KeyError:
pass
@classmethod
def encode(cls, obj):
for type, encoder in cls.encoders.items():
if isinstance(obj, type):
return encoder(obj)
raise TypeError
JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj))
JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj))
dump = deprecated(
"dump has been renamed to dumps, please adjust your implementation",
includedoc="dump has been renamed to dumps",
since="1.8.0",
)(dumps)
+69
View File
@@ -0,0 +1,69 @@
__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"
import json
from collections import OrderedDict
from typing import Any, Callable, Dict
try:
from typing import OrderedDict as OrderedDictType
except ImportError:
OrderedDictType = Dict # py3.7.{0,1}
from frozendict import frozendict
from octoprint.util import to_unicode
class JsonEncoding:
encoders: OrderedDictType[type, Callable[[Any], Any]] = OrderedDict()
@classmethod
def add_encoder(cls, typ: type, encoder: Callable[[Any], Any]) -> None:
"""
Add an encoder for a type.
:param typ: the type to add an encoder for
:param encoder: the encoder. Must take a single argument and return a
tuple (name, parameters...)
"""
cls.encoders[typ] = encoder
@classmethod
def remove_encoder(cls, typ):
try:
del cls.encoders[typ]
except KeyError:
pass
@classmethod
def dumps(cls, obj: Any) -> str:
"""
Dump an object to JSON, handles additional types that the JSON encoder can't, like
bytes and frozendicts.
"""
return json.dumps(
obj,
default=cls.encode,
separators=(",", ":"),
indent=None,
allow_nan=False,
)
@classmethod
def loads(cls, s: str) -> Any:
return json.loads(s)
@classmethod
def encode(cls, obj):
for type, encoder in cls.encoders.items():
if isinstance(obj, type):
return encoder(obj)
raise TypeError(f"Unserializable type {type(obj)}")
JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj))
JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj))
dumps = JsonEncoding.dumps
loads = JsonEncoding.loads
+158
View File
@@ -0,0 +1,158 @@
__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"
import base64
import datetime
import json
import time
from collections import OrderedDict
from typing import Any, Callable, Dict, List
try:
from typing import OrderedDict as OrderedDictType
except ImportError:
OrderedDictType = Dict # py3.7.{0,1}
from frozendict import frozendict
from .encoding import JsonEncoding
class SerializableJsonEncoding(JsonEncoding):
"""
A JSON encoding that can serialize and deserialize objects, including additional
objects otherwise not serializable by the standard JSON encoder:
* ``bytes``
* ``frozendict.frozendict``
* ``datetime.datetime``
* ``time.struct_time``
"""
encoders: OrderedDictType[type, Callable[[Any], Any]] = OrderedDict()
decoders: OrderedDictType[str, Callable[[dict], object]] = OrderedDict()
@classmethod
def add_decoder(cls, classname, decoder):
cls.decoders[classname] = decoder
@classmethod
def remove_decoder(cls, classname):
try:
del cls.decoders[classname]
except KeyError:
pass
@classmethod
def dumps(cls, obj: Any) -> str:
return json.dumps(
cls.encode(obj), separators=(",", ":"), indent=None, allow_nan=False
)
@classmethod
def loads(cls, s: str) -> Any:
return json.loads(s, object_hook=cls.decode)
@classmethod
def encode(cls, val):
"""
Recursively replace all instances of encodable types with their encoded
value. This is useful over the ``default=`` functionallity of the JSON
encoder because JSON will not call default for tuples, lists, ints, etc:
https://docs.python.org/3/library/json.html#json.JSONEncoder
Cannot handle circular references.
"""
if isinstance(val, tuple(cls.encoders.keys())):
# we can't directly index into the encoders dict because
# we need to be able to handle subclasses
encoder = next(
encoder for typ, encoder in cls.encoders.items() if isinstance(val, typ)
)
return cls.encode(encoder(val))
elif isinstance(val, dict):
return {k: cls.encode(v) for k, v in val.items()}
elif isinstance(val, (tuple, list)):
return [cls.encode(v) for v in val]
elif isinstance(val, (bool, int, float, str)) or val is None:
return val
else:
raise TypeError(f"Unserializable type {type(val)}")
@classmethod
def decode(cls, dct):
"""
Recursively replace all instances of decodable types with their decoded
values.
You'll want to have used ``class_encode()`` in your encoder to get this
to work properly.
"""
if "__jsonclass__" not in dct:
return dct
if len(dct["__jsonclass__"]) == 0:
raise ValueError("__jsonclass__ must not be empty")
decoded_name = dct["__jsonclass__"][0]
params = dct["__jsonclass__"][1:]
for classname, decoder in cls.decoders.items():
if decoded_name == classname:
return decoder(*params)
return dct
def class_encode(name: str, *params: Any) -> Dict[str, List]:
"""
Encode a class name and parameters into a serializable dict. You'll
probably want to use this if you're going to set a custom decoder.
This stores the class names in a format inspired by the JSON-RPC spec at
https://www.jsonrpc.org/specification_v1#a3.JSONClasshinting
"""
return {"__jsonclass__": [name] + list(params)}
# frozendict
SerializableJsonEncoding.add_encoder(
frozendict, lambda obj: class_encode("frozendict.frozendict", dict(obj))
)
SerializableJsonEncoding.add_decoder("frozendict.frozendict", lambda obj: frozendict(obj))
# bytes
SerializableJsonEncoding.add_encoder(
bytes, lambda obj: class_encode("bytes", base64.b85encode(obj).decode("ascii"))
)
SerializableJsonEncoding.add_decoder("bytes", lambda obj: base64.b85decode(obj))
# time.struct_time
def _struct_time_decoder(params):
if len(params) == 9 and all(isinstance(p, int) and p >= 0 for p in params):
return time.struct_time(params)
raise ValueError(f"Invalid time.struct_time params `{params}`")
SerializableJsonEncoding.add_encoder(
time.struct_time, lambda obj: class_encode("time.struct_time", list(obj))
)
SerializableJsonEncoding.add_decoder("time.struct_time", _struct_time_decoder)
# datetime.datetime
SerializableJsonEncoding.add_encoder(
datetime.datetime, lambda obj: class_encode("datetime.datetime", obj.isoformat())
)
SerializableJsonEncoding.add_decoder(
"datetime.datetime", lambda params: datetime.datetime.fromisoformat(params)
)
# shortcut for dumps and loads
dumps = SerializableJsonEncoding.dumps
loads = SerializableJsonEncoding.loads
+3 -1
View File
@@ -6,5 +6,7 @@
"pluginsFile": "plugins/index.js",
"supportFile": "support/index.js",
"screenshotsFolder": "screenshots",
"videosFolder": "videos"
"videosFolder": "videos",
"modifyObstructiveCode": false,
"retries": 3
}
-2
View File
@@ -58,8 +58,6 @@ context("Login tests", () => {
context("Successful logout", () => {
it("logs out", () => {
Cypress.currentTest.retries(3);
// login
login(username, password);
+7 -3
View File
@@ -1,8 +1,9 @@
import {prepare_server, login, await_coreui} from "../util/util";
import {prepare_server, login, ensure_file_unknown, await_coreui} from "../util/util";
context("Upload tests", () => {
const username = "admin";
const password = "test";
const upload = "e2e-test.gcode";
beforeEach(() => {
prepare_server();
@@ -10,13 +11,16 @@ context("Upload tests", () => {
// login
login(username, password);
// clean up file if needed
ensure_file_unknown("local", upload);
cy.visit("/");
await_coreui();
});
it("uploads file to local via button", () => {
cy.get("[data-test-id=upload-local]").attachFile("e2e-test.gcode");
cy.get("[data-test-id=upload-local]").attachFile(upload);
cy.wait("@files");
cy.get("[data-test-id=files-list]").contains("e2e-test.gcode");
cy.get("[data-test-id=files-list]").contains(upload);
});
});
+1252 -1947
View File
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -17,10 +17,9 @@
},
"homepage": "https://octoprint.org",
"dependencies": {
"cypress": "^4.12.0",
"cypress": "^9.4.1",
"cypress-commands": "^1.1.0",
"cypress-file-upload": "^4.0.7",
"cypress-plugin-retries": "^1.5.2",
"cypress-terminal-report": "^1.4.1",
"cypress-wait-until": "^1.7.1",
"ini": "^2.0.0"
-1
View File
@@ -19,5 +19,4 @@ module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
require("cypress-terminal-report/src/installLogsPrinter")(on);
require("cypress-plugin-retries/lib/plugin")(on);
};
-1
View File
@@ -21,4 +21,3 @@ import "./commands";
require("cypress-terminal-report/src/installLogsCollector")();
require("cypress-commands");
require("cypress-plugin-retries");
+16 -9
View File
@@ -1,13 +1,12 @@
export const prepare_server = () => {
cy.server();
cy.route("POST", "/api/login").as("login");
cy.route("POST", "/api/logout").as("logout");
cy.route("GET", "/api/settings").as("settings");
cy.route("GET", "/api/files?recursive=true").as("files");
cy.route("GET", "/plugin/softwareupdate/check").as("softwareupdate");
cy.route("GET", "/plugin/pluginmanager/plugins").as("pluginmanager");
cy.route("POST", "/api/connection").as("connectionCommand");
cy.route("GET", "/api/connection").as("connectionDetails");
cy.intercept("POST", "/api/login").as("login");
cy.intercept("POST", "/api/logout").as("logout");
cy.intercept("GET", "/api/settings").as("settings");
cy.intercept("GET", "/api/files?recursive=true").as("files");
cy.intercept("GET", "/plugin/softwareupdate/check").as("softwareupdate");
cy.intercept("GET", "/plugin/pluginmanager/plugins").as("pluginmanager");
cy.intercept("POST", "/api/connection").as("connectionCommand");
cy.intercept("GET", "/api/connection").as("connectionDetails");
};
export const await_loginui = () => {
@@ -63,3 +62,11 @@ export const disconnect = () => {
}
});
};
export const ensure_file_unknown = (location, name) => {
cy.request({
method: "DELETE",
url: `/api/files/${location}/${name}`,
failOnStatusCode: false
});
};
+52
View File
@@ -0,0 +1,52 @@
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
from unittest import mock
from octoprint.util import TemporaryDirectory
RSS_EXAMPLE = """<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>RSS Title</title>
<description>This is an example of an RSS feed</description>
<link>https://www.example.com/main.html</link>
<copyright>2020 Example.com All rights reserved</copyright>
<lastBuildDate>Mon, 06 Sep 2010 00:01:00 +0000</lastBuildDate>
<pubDate>Sun, 06 Sep 2009 16:20:00 +0000</pubDate>
<ttl>1800</ttl>
<item>
<title>Example entry</title>
<description>Here is some text containing an interesting description.</description>
<link>https://www.example.com/blog/post/1</link>
<guid isPermaLink="false">7bd204c6-1655-4c27-aeee-53f933c5395f</guid>
<pubDate>Sun, 06 Sep 2009 16:20:00 +0000</pubDate>
</item>
</channel>
</rss>
"""
class TestAnnouncements(unittest.TestCase):
def test_caches(self):
from octoprint.plugins.announcements import AnnouncementPlugin
plugin = AnnouncementPlugin()
plugin._logger = mock.MagicMock()
with TemporaryDirectory() as data_folder:
plugin._data_folder = data_folder
with mock.patch("requests.get") as mock_get:
mock_get.return_value = mock.MagicMock(status_code=200)
mock_get.return_value.text = RSS_EXAMPLE
network_response = plugin._get_channel_data_from_network(
"test", {"url": "https://example.com/feed.xml"}
)
cache_response = plugin._get_channel_data_from_cache("test", {"ttl": 1000})
self.maxDiff = 100000
self.assertDictEqual(network_response, cache_response)
+72 -1
View File
@@ -24,7 +24,7 @@ import octoprint.settings
@ddt.ddt
class TestSettings(unittest.TestCase):
class SettingsTest(unittest.TestCase):
def _load_yaml(self, fname):
with open(fname, encoding="utf-8") as f:
return yaml.safe_load(f)
@@ -693,3 +693,74 @@ class TestSettings(unittest.TestCase):
yield basedir, fresh_config_path
finally:
octoprint.settings.default_settings = orig_defaults
@ddt.ddt
class HelpersTest(unittest.TestCase):
@ddt.data(
(True, True),
("true", True),
("True", True),
("tRuE", True),
("yes", True),
("YES", True),
("y", True),
("Y", True),
("1", True),
(1, True),
(False, False),
("Truuuuuuuuue", False),
("Nope", False),
(None, False),
)
@ddt.unpack
def test_valid_boolean_trues(self, value, expected):
self.assertEqual(expected, value in octoprint.settings.valid_boolean_trues)
def _key(*path):
return octoprint.settings._CHAINMAP_SEP.join(path)
@ddt.ddt
class ChainmapTest(unittest.TestCase):
@ddt.data(
(
{"a": 1},
{_key("a"): 1},
),
({"a": {"b": "b"}}, {_key("a", "b"): "b"}),
(
{"a": {"b": "b", "c": "c", "d": {"e": "e"}}},
{_key("a", "b"): "b", _key("a", "c"): "c", _key("a", "d", "e"): "e"},
),
)
@ddt.unpack
def test_flatten(self, value, expected):
self.assertEqual(
expected, octoprint.settings.HierarchicalChainMap._flatten(value)
)
@ddt.data(
(
{_key("a"): 1},
{"a": 1},
),
(
{_key("a", "b"): "b"},
{"a": {"b": "b"}},
),
(
{_key("a", "b"): "b", _key("a", "c"): "c", _key("a", "d", "e"): "e"},
{"a": {"b": "b", "c": "c", "d": {"e": "e"}}},
),
(
{_key("a"): None, _key("a", "b"): "b"},
{"a": {"b": "b"}},
),
)
@ddt.unpack
def test_unflatten(self, value, expected):
self.assertEqual(
expected, octoprint.settings.HierarchicalChainMap._unflatten(value)
)
+22
View File
@@ -0,0 +1,22 @@
__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"
import unittest
import ddt
import octoprint.events
@ddt.ddt
class TestEvents(unittest.TestCase):
@ddt.data(
("plugin_example_event", "PLUGIN_EXAMPLE_EVENT"),
("plugin_Example_event", "PLUGIN_EXAMPLE_EVENT"),
("plugin_ExAmple_Event", "PLUGIN_EX_AMPLE_EVENT"),
("plugin_exAmple_EvEnt", "PLUGIN_EX_AMPLE_EV_ENT"),
)
@ddt.unpack
def test_to_identifier(self, value, expected):
actual = octoprint.events.Events._to_identifier(value)
self.assertEqual(actual, expected)
-31
View File
@@ -1,31 +0,0 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import ddt
import octoprint.settings
@ddt.ddt
class TestHelpers(unittest.TestCase):
@ddt.data(
(True, True),
("true", True),
("True", True),
("tRuE", True),
("yes", True),
("YES", True),
("y", True),
("Y", True),
("1", True),
(1, True),
(False, False),
("Truuuuuuuuue", False),
("Nope", False),
(None, False),
)
@ddt.unpack
def test_valid_boolean_trues(self, value, expected):
self.assertEqual(expected, value in octoprint.settings.valid_boolean_trues)
+80
View File
@@ -0,0 +1,80 @@
__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"
import datetime
import time
import warnings
import pytest
from frozendict import frozendict
from octoprint.util import json
class SomeClass:
...
class SomeSubclass(frozendict):
...
def test_deprecated_dump():
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
assert json.dump({"foo": "bar"}) == '{"foo":"bar"}'
assert len(w) == 1
assert issubclass(w[-1].category, DeprecationWarning)
assert "dump has been renamed to dumps" in str(w[-1].message)
@pytest.mark.parametrize(
"val,expected",
[
pytest.param({"foo": "bar"}, '{"foo":"bar"}', id="dict"),
pytest.param(frozendict({"foo": "bar"}), '{"foo":"bar"}', id="frozendict"),
pytest.param(b"foo", '"foo"', id="bytes"),
],
)
def test_encoding_dumps(val, expected):
assert json.encoding.dumps(val) == expected
def test_encoding_loads():
assert json.encoding.loads('{"foo":"bar"}') == {"foo": "bar"}
def test_encoding_dumps_typeerror():
with pytest.raises(TypeError):
json.encoding.dumps(SomeClass())
@pytest.mark.parametrize(
"val",
[
pytest.param({"foo": "bar"}, id="dict"),
pytest.param(b"\x00\x01\x02\x03", id="bytes"),
# invalid bytes from https://stackoverflow.com/a/3886015
pytest.param(
b"\xc3\x28\xa0\xa1\xe2\x28\xa1\xe2\x82\x28\xf0"
b"\x28\x8c\xbc\xf0\x90\x28\xbc\xf0\x28\x8c\x28",
id="invalid utf-8",
),
pytest.param(frozendict({"foo": "bar"}), id="frozendict"),
pytest.param(time.struct_time((2018, 1, 1, 0, 0, 0, 0, 0, 0)), id="struct_time"),
pytest.param(
datetime.datetime(2022, 3, 21, 5, 24, 0, 0, tzinfo=datetime.timezone.utc),
id="datetime",
),
pytest.param(frozendict({"a": b"b"}), id="nested"),
pytest.param(SomeSubclass({"a": b"b"}), id="subclass"),
],
)
def test_serializing_roundtrips(val):
assert json.serializing.loads(json.serializing.dumps(val)) == val
def test_serializing_dumps_typeerror():
with pytest.raises(TypeError):
json.serializing.dumps(SomeClass())