Merge devel into py23

This commit is contained in:
Matthias Urlichs committed 2019-01-31 20:08:40 +01:00
commit 24d2efd3ce
23 files changed
+388 -162

No files matched your search

+6 -6
View File
@@ -383,10 +383,10 @@ octoprint.cli.commands
OctoPrint's CLI.
:rtype: list
.. _sec-plugins-hook-comm-firmware-info:
.. _sec-plugins-hook-comm-protocol-firmware-info:
octoprint.comm.firmware.info
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
octoprint.comm.protocol.firmware.info
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs)
@@ -416,10 +416,10 @@ octoprint.comm.firmware.info
:param str firmware_name: The name of the parsed capability
:param dict firmware_data: All data contained in the ``M115`` report
.. _sec-plugins-hook-comm-firmware-capabilities:
.. _sec-plugins-hook-comm-protocol-firmware-capabilities:
octoprint.comm.firmware.capabilities
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
octoprint.comm.firmware.protocol.capabilities
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs)
-2
View File
@@ -258,8 +258,6 @@ class EventManager(object):
except ValueError:
# not registered
pass
else:
self._logger.debug("Unsubscribed listener %r for event %s", callback, event)
def join(self, timeout=None):
self._worker.join(timeout)
+59 -55
View File
@@ -38,7 +38,9 @@ import inspect
import pkg_resources
import pkginfo
from past.builtins import basestring
from past.builtins import unicode
from octoprint.util import to_unicode
try:
from os import scandir
@@ -208,13 +210,13 @@ class PluginInfo(object):
def __str__(self):
if self.version:
return "{name} ({version})".format(name=self.name, version=self.version)
return u"{name} ({version})".format(name=self.name, version=self.version)
else:
return self.name
return to_unicode(self.name)
def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""),
show_location=False, location_str=" - {location}",
show_enabled=False, enabled_strs=("* ", " ", "X ")):
def long_str(self, show_bundled=False, bundled_strs=(u" [B]", u""),
show_location=False, location_str=u" - {location}",
show_enabled=False, enabled_strs=(u"* ", u" ", u"X ")):
"""
Long string representation of the plugin's information. Will return a string of the format ``<enabled><str(self)><bundled><location>``.
@@ -243,17 +245,19 @@ class PluginInfo(object):
str: The long string representation of the plugin as described above
"""
if show_enabled:
ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1])
ret = to_unicode(enabled_strs[2]) if self.blacklisted \
else (to_unicode(enabled_strs[0]) if self.enabled
else to_unicode(enabled_strs[1]))
else:
ret = ""
ret = u""
ret += str(self)
ret += unicode(self)
if show_bundled:
ret += bundled_strs[0] if self.bundled else bundled_strs[1]
ret += to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1])
if show_location and self.location:
ret += location_str.format(location=self.location)
ret += to_unicode(location_str).format(location=self.location)
return ret
@@ -654,7 +658,7 @@ class PluginManager(object):
result_added.update(added)
result_found += found
except Exception:
self.logger.exception("Error fetching plugins from folders")
self.logger.exception(u"Error fetching plugins from folders")
if self.plugin_entry_points:
existing.update(result_added)
@@ -665,7 +669,7 @@ class PluginManager(object):
result_added.update(added)
result_found += found
except Exception:
self.logger.exception("Error fetching plugins from entry points")
self.logger.exception(u"Error fetching plugins from entry points")
return result_added, result_found
@@ -684,7 +688,7 @@ class PluginManager(object):
actual_readonly = not os.access(folder, os.W_OK)
if not os.path.exists(folder):
self.logger.warning("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
self.logger.warning(u"Plugin folder {folder} could not be found, skipping it".format(folder=folder))
continue
for entry in scandir(folder):
@@ -723,9 +727,9 @@ class PluginManager(object):
plugin.enabled = False
added[key] = plugin
except Exception:
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
self.logger.exception(u"Error processing folder entry {!r} from folder {}".format(entry, folder))
except Exception:
self.logger.exception("Error processing folder {}".format(folder))
self.logger.exception(u"Error processing folder {}".format(folder))
return added, found
@@ -755,8 +759,8 @@ class PluginManager(object):
try:
yield entry
except Exception:
self.logger.exception("Something went wrong while processing the entry points of a package in the "
"Python environment - broken entry_points.txt in some package?")
self.logger.exception(u"Something went wrong while processing the entry points of a package in the "
u"Python environment - broken entry_points.txt in some package?")
for group in groups:
for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)):
@@ -775,7 +779,7 @@ class PluginManager(object):
try:
entry_point_metadata = EntryPointMetadata(entry_point)
except Exception:
self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name))
self.logger.exception(u"Something went wrong while retrieving metadata for module {}".format(module_name))
else:
kwargs.update(dict(
name=entry_point_metadata.name,
@@ -805,7 +809,7 @@ class PluginManager(object):
added[key] = plugin
except Exception:
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
self.logger.exception(u"Error processing entry point {!r} for group {}".format(entry_point, group))
return added, found
@@ -820,7 +824,7 @@ class PluginManager(object):
else:
return None
except Exception:
self.logger.warning("Could not locate plugin {key}".format(key=key))
self.logger.warn(u"Could not locate plugin {key}".format(key=key))
return None
# Create a simple dummy entry first ...
@@ -829,11 +833,11 @@ class PluginManager(object):
plugin.bundled = bundled
if self._is_plugin_disabled(key):
self.logger.info("Plugin {} is disabled.".format(plugin))
self.logger.info(u"Plugin {} is disabled.".format(plugin))
plugin.forced_disabled = True
if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)):
self.logger.warning("Plugin {} is blacklisted.".format(plugin))
self.logger.warning(u"Plugin {} is blacklisted.".format(plugin))
plugin.blacklisted = True
if not plugin.validate("before_import", additional_validators=self.plugin_validators):
@@ -860,13 +864,13 @@ class PluginManager(object):
parsed_metadata=parsed_metadata)
plugin.bundled = bundled
except Exception:
self.logger.exception("Error loading plugin {key}".format(key=key))
self.logger.exception(u"Error loading plugin {key}".format(key=key))
return None
if plugin.check():
return plugin
else:
self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
self.logger.info(u"Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
return None
def _is_plugin_disabled(self, key):
@@ -886,7 +890,7 @@ class PluginManager(object):
self.plugin_blacklist))
def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None):
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(
self.logger.info(u"Loading plugins from {folders} and installed plugin packages...".format(
folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders))
))
@@ -930,7 +934,7 @@ class PluginManager(object):
try:
if plugin.loaded and not plugin.forced_disabled:
if plugin.blacklisted:
self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin))
self.logger.warning(u"Plugin {} is blacklisted. Not enabling it.".format(plugin))
continue
self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup)
except PluginNeedsRestart:
@@ -943,9 +947,9 @@ class PluginManager(object):
force_reload=force_reload)
if len(self.enabled_plugins) <= 0:
self.logger.info("No plugins found")
self.logger.info(u"No plugins found")
else:
self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format(
self.logger.info(u"Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format(
count=len(self.enabled_plugins) + len(self.disabled_plugins),
implementations=len(self.plugin_implementations),
hooks=sum(map(lambda x: len(x), self.plugin_hooks.values()))
@@ -953,7 +957,7 @@ class PluginManager(object):
def mark_plugin(self, name, **kwargs):
if not name in self.plugins:
self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals()))
self.logger.debug(u"Trying to mark an unknown plugin {name}".format(**locals()))
for key, value in kwargs.items():
if value is None:
@@ -972,7 +976,7 @@ class PluginManager(object):
def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True):
if not name in self.plugins:
self.logger.warning("Trying to load an unknown plugin {name}".format(**locals()))
self.logger.warning(u"Trying to load an unknown plugin {name}".format(**locals()))
return
if plugin is None:
@@ -987,15 +991,15 @@ class PluginManager(object):
self.on_plugin_loaded(name, plugin)
plugin.loaded = True
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
self.logger.debug(u"Loaded plugin {name}: {plugin}".format(**locals()))
except PluginLifecycleException as e:
raise e
except Exception:
self.logger.exception("There was an error loading plugin %s" % name)
self.logger.exception(u"There was an error loading plugin %s" % name)
def unload_plugin(self, name):
if not name in self.plugins:
self.logger.warning("Trying to unload unknown plugin {name}".format(**locals()))
self.logger.warning(u"Trying to unload unknown plugin {name}".format(**locals()))
return
plugin = self.plugins[name]
@@ -1015,11 +1019,11 @@ class PluginManager(object):
plugin.loaded = False
self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals()))
self.logger.debug(u"Unloaded plugin {name}: {plugin}".format(**locals()))
except PluginLifecycleException as e:
raise e
except Exception:
self.logger.exception("There was an error unloading plugin {name}".format(**locals()))
self.logger.exception(u"There was an error unloading plugin {name}".format(**locals()))
# make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins
if name in self.enabled_plugins:
@@ -1029,7 +1033,7 @@ class PluginManager(object):
def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False):
if not name in self.disabled_plugins:
self.logger.warning("Tried to enable plugin {name}, however it is not disabled".format(**locals()))
self.logger.warning(u"Tried to enable plugin {name}, however it is not disabled".format(**locals()))
return
if plugin is None:
@@ -1065,13 +1069,13 @@ class PluginManager(object):
plugin.implementation.on_plugin_enabled()
self.on_plugin_enabled(name, plugin)
self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals()))
self.logger.debug(u"Enabled plugin {name}: {plugin}".format(**locals()))
return True
def disable_plugin(self, name, plugin=None):
if not name in self.enabled_plugins:
self.logger.warning("Tried to disable plugin {name}, however it is not enabled".format(**locals()))
self.logger.warning(u"Tried to disable plugin {name}, however it is not enabled".format(**locals()))
return
if plugin is None:
@@ -1086,7 +1090,7 @@ class PluginManager(object):
except PluginLifecycleException as e:
raise e
except Exception:
self.logger.exception("There was an error while disabling plugin {name}".format(**locals()))
self.logger.exception(u"There was an error while disabling plugin {name}".format(**locals()))
return False
else:
if name in self.enabled_plugins:
@@ -1098,7 +1102,7 @@ class PluginManager(object):
plugin.implementation.on_plugin_disabled()
self.on_plugin_disabled(name, plugin)
self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals()))
self.logger.debug(u"Disabled plugin {name}: {plugin}".format(**locals()))
return True
@@ -1110,7 +1114,7 @@ class PluginManager(object):
try:
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
self.logger.warning(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
continue
self._plugin_hooks[hook].append((order, name, callback))
@@ -1129,7 +1133,7 @@ class PluginManager(object):
try:
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
self.logger.warning(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
continue
try:
@@ -1276,7 +1280,7 @@ class PluginManager(object):
additional_pre_inits=additional_pre_inits,
additional_post_inits=additional_post_inits)
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
self.logger.info(u"Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
if plugin.implementation is None:
@@ -1331,7 +1335,7 @@ class PluginManager(object):
try:
return_value = factory(name, implementation)
except Exception:
self.logger.exception("Exception while executing injection factory %r" % factory)
self.logger.exception(u"Exception while executing injection factory %r" % factory)
else:
if return_value is not None:
if isinstance(return_value, dict):
@@ -1355,12 +1359,12 @@ class PluginManager(object):
if isinstance(e, PluginLifecycleException):
raise e
else:
self.logger.exception("Exception while initializing plugin {name}, disabling it".format(**locals()))
self.logger.exception(u"Exception while initializing plugin {name}, disabling it".format(**locals()))
return False
else:
self.on_plugin_implementations_initialized(name, plugin)
self.logger.debug("Initialized plugin mixin implementation for plugin {name}".format(**locals()))
self.logger.debug(u"Initialized plugin mixin implementation for plugin {name}".format(**locals()))
return True
@@ -1377,7 +1381,7 @@ class PluginManager(object):
self.logger.log(level, message)
if len(all_plugins) <= 0:
_log("No plugins available")
_log(u"No plugins available")
else:
formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
bundled_strs=bundled_str,
@@ -1385,9 +1389,9 @@ class PluginManager(object):
location_str=location_str,
show_enabled=show_enabled,
enabled_strs=enabled_str),
sorted(self.plugins.values(), key=lambda x: str(x).lower())))
_log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins),
plugins=formatted_plugins))
sorted(self.plugins.values(), key=lambda x: unicode(x).lower())))
_log(u"{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins),
plugins=formatted_plugins))
def get_plugin(self, identifier, require_enabled=True):
"""
@@ -1479,17 +1483,17 @@ class PluginManager(object):
try:
sorting_value = impl[1].get_sorting_key(sorting_context)
except Exception:
self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
self.logger.exception(u"Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
if sorting_value is not None:
try:
sorting_value = int(sorting_value)
except ValueError:
self.logger.warning("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
self.logger.warning(u"The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
sorting_value = None
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
return sorting_value is None, sorting_value, not plugin_info.bundled, impl[0]
return sorting_value is None, sorting_value, not plugin_info.bundled if plugin_info else True, impl[0]
return [impl[1] for impl in sorted(result, key=sort_func)]
@@ -1572,7 +1576,7 @@ class PluginManager(object):
try:
client(plugin, data, permissions=permissions)
except Exception:
self.logger.exception("Exception while sending plugin data to client")
self.logger.exception(u"Exception while sending plugin data to client")
def _sort_hooks(self, hook):
self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
@@ -9,6 +9,7 @@ import octoprint.plugin
from octoprint.server import user_permission
from octoprint.access import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
import flask
from flask_babel import gettext
@@ -36,17 +37,28 @@ class Prompt(object):
class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
COMMAND = "M876"
CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT"
# noinspection PyMissingConstructor
def __init__(self):
self._prompt = None
self._selection_command = None
self._enable = "detected"
self._command = None
self._enable_emergency_sending = False
self._enable_signal_support = False
self._cap_prompt_support = False
def initialize(self):
self._selection_command = self._settings.get(["selection_command"])
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
# Additional permissions hook
@@ -65,14 +77,26 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
return dict(js=["js/action_command_prompt.js"],
clientjs=["clientjs/action_command_prompt.js"])
#~ EventHandlerPlugin
def on_event(self, event, payload):
if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
#~ SettingsPlugin
def get_settings_defaults(self):
return dict(selection_command=None)
return dict(enable="detected",
command=self.COMMAND,
enable_emergency_sending=True,
enable_signal_support=True)
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._selection_command = self._settings.get(["selection_command"])
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
#~ SimpleApiPlugin
@@ -112,10 +136,6 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
if not action.startswith("prompt_"):
return
if self._selection_command is None:
self._logger.info("Got a prompt command from the printer but no selection command is defined")
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
@@ -151,21 +171,55 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
self._close_prompt()
self._prompt = None
#~ queuing handling
def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs):
if gcode != self._command:
return
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending:
return
if not "S" in cmd:
# we only force-send M876 Sx
return
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(cmd, u"Force-sending {} to the printer".format(self._command), gcode=gcode)
#~ capability reporting
def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs):
if capability == self.CAP_PROMPT_SUPPORT and enabled:
self._cap_prompt_support = True
if self._enable == "detected" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
#~ prompt handling
def _show_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
self._prompt.activate()
self._plugin_manager.send_plugin_message(self._identifier, dict(action="show",
text=self._prompt.text,
choices=self._prompt.choices))
def _close_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
self._prompt = None
self._plugin_manager.send_plugin_message(self._identifier, dict(action="close"))
def _answer_prompt(self, choice):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
self._close_prompt()
self._printer.commands([self._selection_command.format(choice=choice)])
self._printer.commands(["{command} S{choice}".format(command=self._command,
choice=choice)])
__plugin_name__ = "Action Command Prompt Support"
@@ -177,5 +231,7 @@ __plugin_license__ = "AGPLv3"
__plugin_implementation__ = ActionCommandPromptPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
@@ -2,10 +2,43 @@
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Selection Command') }}</label>
<label class="control-label">{{ _('Enable support')}}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.selection_command">
<div class="help-block">{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace <code>{choice}</code> with the index of the selected choice. E.g. <code>M876 S{choice}</code> will become <code>M123 S1</code>') }}</div>
<label class="radio">
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="detected" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('If detected as supported by the firmware (<code>PROMPT_SUPPORT</code> capability)') }}
</label>
<label class="radio">
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="always" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('Always') }}
</label>
<label class="radio">
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="never" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('Never') }}
</label>
</div>
</div>
<div class="advanced_options">
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.advanced_options', container: '.hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<div class="control-group">
<label class="control-label">{{ _('Dialog command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.command">
<div class="help-block">{{ _('Use this to define the dialog command. Default is <code>M876</code>. You normally should not have to change this.') }}</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.action_command_prompt.enable_emergency_sending"> {{ _('Enable force sending of the configured command to bypass blocking firmware routines if detected as supported. You normally should not have to change this.') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.action_command_prompt.enable_signal_support"> {{ _('Enable signaling to the firmware that we support <code>prompt_*</code> actions if detected as supported. You normally should not have to change this.') }}
</label>
</div>
</div>
</div>
</div>
</form>
+18 -2
View File
@@ -17,6 +17,9 @@ from octoprint.server.util.flask import restricted_access, no_firstrun_access
from octoprint.server import NO_CONTENT, current_user, admin_permission
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
@@ -95,6 +98,18 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
self._load_keys()
# Additional permissions hook
def get_additional_permissions(self):
return [
dict(key="ADMIN",
name="Admin access",
description=gettext("Allows administrating all application keys"),
roles=["admin"],
dangerous=True,
default_groups=[ADMIN_GROUP])
]
##~~ TemplatePlugin
def get_template_configs(self):
@@ -192,7 +207,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
if not user_id:
return flask.abort(403)
if request.values.get("all") in valid_boolean_trues and admin_permission.can():
if request.values.get("all") in valid_boolean_trues and Permissions.PLUGIN_APPKEYS_ADMIN.can():
keys = self._all_api_keys()
else:
keys = self._api_keys_for_user(user_id)
@@ -402,5 +417,6 @@ __plugin_disabling_discouraged__ = gettext(u"Without this plugin third party cli
u"obtain an API key without you manually copy-pasting it.")
__plugin_implementation__ = AppKeysPlugin()
__plugin_hooks__ = {
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
+7 -2
View File
@@ -74,7 +74,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
default_groups=[ADMIN_GROUP])
]
##~~ StarupPlugin
##~~ StartupPlugin
def on_after_startup(self):
self._clean_dir_backup(self._settings._basedir,
@@ -88,6 +88,11 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
css=["css/backup.css"],
less=["less/backup.less"])
##~~ TemplatePlugin
def get_template_configs(self):
return [dict(type="settings", name=gettext(u"Backup & Restore"))]
##~~ BlueprintPlugin
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@@ -939,7 +944,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
class InsufficientSpace(Exception):
pass
__plugin_name__ = gettext(u"Backup & Restore")
__plugin_name__ = u"Backup & Restore"
__plugin_author__ = u"Gina Häußge"
__plugin_description__ = u"Backup & restore your OctoPrint settings and data"
__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup "
@@ -1009,6 +1009,6 @@ def __plugin_load__():
__plugin_hooks__ = {
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
@@ -209,7 +209,7 @@ __plugin_hooks__ = {
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received,
"octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.events.register_custom_events": register_custom_events
"octoprint.events.register_custom_events": register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
@@ -1254,6 +1254,6 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.cli.commands": cli.commands,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.events.register_custom_events": _register_custom_events
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
+1 -1
View File
@@ -96,7 +96,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
#hook card upload
self.sd_card_upload_hooks = plugin_manager().get_hooks("octoprint.printer.sdcardupload")
# comm
self._comm = None
+17 -1
View File
@@ -12,6 +12,8 @@ import threading
from flask import request, make_response, jsonify, url_for
from flask_babel import gettext
import psutil
from octoprint.settings import settings as s
from octoprint.server import NO_CONTENT
@@ -20,6 +22,21 @@ from octoprint.server.util.flask import no_firstrun_access, get_remote_address
from octoprint.access.permissions import Permissions
from octoprint.logging import prefix_multilines
@api.route("/system/usage", methods=["GET"])
@no_firstrun_access
@Permissions.SYSTEM.require(403)
def readUsageForFolders():
return jsonify(usage=_usageForFolders())
def _usageForFolders():
data = {}
for folder_name in s().get(['folder']).keys():
path = s().getBaseFolder(folder_name, check_writable=False)
if path is not None:
usage = psutil.disk_usage(path)
data[folder_name] = { 'free': usage.free, 'total': usage.total }
return data
@api.route("/system", methods=["POST"])
@no_firstrun_access
@Permissions.SYSTEM.require(403)
@@ -134,7 +151,6 @@ def executeSystemCommand(source, command):
return NO_CONTENT
def _to_client_specs(specs):
result = list()
for spec in specs.values():
+86 -34
View File
@@ -544,11 +544,13 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
#~~ passive login helper
def passive_login():
logger = logging.getLogger(__name__)
user = flask_login.current_user
remoteAddr = get_remote_address(flask.request)
ipCheckEnabled = settings().getBoolean(["server", "ipCheck", "enabled"])
ipCheckTrusted = settings().get(["server", "ipCheck", "trustedSubnets"])
remote_address = get_remote_address(flask.request)
ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"])
ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"])
if isinstance(user, LocalProxy):
# noinspection PyProtectedMember
@@ -568,7 +570,7 @@ def passive_login():
if user is not None and user.is_active:
# login known user
logging.getLogger(__name__).info("Passively logging in user {} from {}".format(user.get_id(), remoteAddr))
logger.info("Passively logging in user {} from {}".format(user.get_id(), remote_address))
user = login(user)
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
@@ -581,20 +583,36 @@ def passive_login():
localNetworks.add(ip)
try:
if netaddr.IPAddress(remoteAddr) in localNetworks:
autologin_user = octoprint.server.userManager.find_user(autologinAs)
if autologin_user is not None and user.is_active:
if netaddr.IPAddress(remote_address) in local_networks:
autologin_user = octoprint.server.userManager.findUser(autologin_as)
if autologin_user is not None and autologin_user.is_active:
autologin_user = octoprint.server.userManager.login_user(autologin_user)
logging.getLogger(__name__).info("Passively logging in user {} from {} via autologin".format(user.get_id(), remoteAddr))
logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(), local_networks))
user = login(autologin_user)
if netaddr.IPAddress(remote_address) in local_networks:
user = octoprint.server.userManager.findUser(autologin_as)
if user is not None and user.is_active():
user = octoprint.server.userManager.login_user(user)
flask.session["usersession.id"] = user.session
flask.g.user = user
flask_login.login_user(user)
flask_principal.identity_changed.send(flask.current_app._get_current_object(),
identity=flask_principal.Identity(user.get_id()))
logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(),
remote_address))
response = user.asDict()
response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address,
additional_private=ip_check_trusted)
return flask.jsonify(response)
except Exception:
logger = logging.getLogger(__name__)
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
logger.exception("Could not autologin user {} for networks {}".format(autologin_as, local_networks))
response = user.as_dict()
response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr,
additional_private=ipCheckTrusted)
response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address,
additional_private=ip_check_trusted)
return flask.jsonify(response)
@@ -862,11 +880,15 @@ class PreemptiveCache(object):
if cache_data is None:
cache_data = dict()
if not self._validate_data(cache_data):
self._logger.warn("Preemptive cache data was invalid, ignoring it")
cache_data = dict()
return cache_data
def get_data(self, root):
cache_data = self.get_all_data()
return cache_data.get(root, dict())
return cache_data.get(root, list())
def set_all_data(self, data):
from octoprint.util import atomic_write
@@ -909,7 +931,7 @@ class PreemptiveCache(object):
def get_newest(entries):
result = None
for entry in entries:
if "_timestamp" in entry and (result is None or ("_timestamp" in entry and result["_timestamp"] < entry["_timestamp"])):
if "_timestamp" in entry and (result is None or ("_timestamp" in result and result["_timestamp"] < entry["_timestamp"])):
result = entry
return result
@@ -935,12 +957,32 @@ class PreemptiveCache(object):
return set(strip_ignored(a).items()) == set(strip_ignored(b).items())
def _validate_data(self, data):
if not isinstance(data, dict):
return False
for root, entries in data.items():
if not isinstance(entries, list):
return False
for entry in entries:
if not self._validate_entry(entry):
return False
return True
def _validate_entry(self, entry):
return isinstance(entry, dict) and "_timestamp" in entry and "_count" in entry
def preemptively_cached(cache, data, unless=None):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
cache.record(data, unless=unless)
try:
cache.record(data, unless=unless)
except:
logging.getLogger(__name__).exception(u"Error while recording preemptive cache entry: {!r}".format(data))
return f(*args, **kwargs)
return decorated_function
return decorator
@@ -952,11 +994,14 @@ def etagged(etag):
def decorated_function(*args, **kwargs):
rv = f(*args, **kwargs)
if isinstance(rv, flask.Response):
result = etag
if callable(result):
result = result(rv)
if result:
rv.set_etag(result)
try:
result = etag
if callable(result):
result = result(rv)
if result:
rv.set_etag(result)
except:
logging.getLogger(__name__).exception(u"Error while calculating the etag value for response {!r}".format(rv))
return rv
return decorated_function
return decorator
@@ -968,16 +1013,19 @@ def lastmodified(date):
def decorated_function(*args, **kwargs):
rv = f(*args, **kwargs)
if not "Last-Modified" in rv.headers:
result = date
if callable(result):
result = result(rv)
try:
result = date
if callable(result):
result = result(rv)
if not isinstance(result, basestring):
from werkzeug.http import http_date
result = http_date(result)
if not isinstance(result, basestring):
from werkzeug.http import http_date
result = http_date(result)
if result:
rv.headers["Last-Modified"] = result
if result:
rv.headers["Last-Modified"] = result
except:
logging.getLogger(__name__).exception(u"Error while calculating the lastmodified value for response {!r}".format(rv))
return rv
return decorated_function
return decorator
@@ -987,12 +1035,15 @@ def conditional(condition, met):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
if callable(condition) and condition():
# condition has been met, return met-response
rv = met
if callable(met):
rv = met()
return rv
try:
if callable(condition) and condition():
# condition has been met, return met-response
rv = met
if callable(met):
rv = met()
return rv
except:
logging.getLogger(__name__).exception(u"Error while evaluating conditional {!r} or met {!r}".format(condition, met))
# condition hasn't been met, call decorated function
return f(*args, **kwargs)
@@ -1419,6 +1470,7 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
assets["clientjs"] = [
"js/app/client/base.js",
"js/app/client/socket.js",
"js/app/client/access.js",
"js/app/client/browser.js",
"js/app/client/connection.js",
"js/app/client/control.js",
+2
View File
@@ -17,6 +17,7 @@ import octoprint.timelapse
import octoprint.server
import octoprint.events
import octoprint.plugin
import octoprint.access.users
from octoprint.events import Events
from octoprint.settings import settings
@@ -353,6 +354,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
# TODO remove when central job management becomes available and takes care of this for us
self._emit("event", payload=dict(type=Events.MOVIE_RENDERING,
payload=octoprint.timelapse.current_render_job))
self._registered = True
def _unregister(self):
"""Unregister this socket from the system"""
+3 -2
View File
@@ -123,6 +123,7 @@ default_settings = {
"helloCommand": "M110 N0",
"disconnectOnErrors": True,
"ignoreErrorsFromFirmware": False,
"terminalLogSize": 20,
"logResends": True,
"supportResendsWithoutOk": "detect",
"logPositionOnPause": True,
@@ -359,9 +360,9 @@ default_settings = {
"apps": {}
},
"terminalFilters": [
{ "name": "Suppress temperature messages", "regex": r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)" },
{ "name": "Suppress temperature messages", "regex": r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+((P|B|N)\d+\s+)*)?(B|T\d*):\d+)" },
{ "name": "Suppress SD status messages", "regex": r"(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)" },
{ "name": "Suppress wait responses", "regex": r"Recv: wait"}
{ "name": "Suppress wait responses", "regex": "Recv: wait"}
],
"plugins": {
"_disabled": []
+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,.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;*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.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.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:focus,.btn:hover{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:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;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{color:#fff;text-shadow:0 -1px 0 rgba(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;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.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,.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;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine 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,.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;*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.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.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:focus,.btn:hover{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:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;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{color:#fff;text-shadow:0 -1px 0 rgba(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;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.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,.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;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
@@ -4,7 +4,7 @@ $(function() {
self.loginState = parameters[0];
self.access = parameters[1];
self.settings = parameters[1];
self.settings = parameters[2];
self.renderProgressBar = undefined;
self.timelapsePopup = undefined;
+1 -2
View File
@@ -150,6 +150,7 @@
{% try "<!-- There was an error with the template {filename} at line number {lineno}: {exception} -->" %}{% include data.template ignore missing %}{% endtry %}
{% endfor %}
<!-- End of generic plugin template files -->
<!-- /ko -->
</div>
<div id="page-container-loading" data-bind="visible: loading">
@@ -178,7 +179,5 @@
<button class="btn btn-block btn-large btn-primary" type="submit" data-bind="click: login">{{ _('Log in') }}</button>
</form>
</div>
{% include 'javascripts.jinja2' %}
</body>
</html>
@@ -1,4 +1,4 @@
<div style="display: none;" data-bind="visible: loginState.isUser">
<div data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_ADMIN)">
<div style="display: none;" data-bind="visible: settings.webcam_snapshotUrl() && settings.webcam_ffmpegPath()">
<div class="alert" data-bind="visible: isPrinting()">
{{ _('Take note that timelapse configuration is disabled while your printer is printing.') }}
@@ -10,7 +10,7 @@
<div class="control-group">
<label class="control-label" for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
<div class="controls">
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: !isPrinting() && loginState.isUser()">
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: !isPrinting()">
<option value="off">{{ _('Off') }}</option>
<option value="timed">{{ _('Timed') }}</option>
<option value="zchange">{{ _('On Z Change') }}</option>
@@ -23,7 +23,7 @@
<label class="control-label" for="webcam_timelapse_minDelay">{{ _('Minimum interval') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_minDelay" data-bind="value: timelapseMinDelay, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser()">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_minDelay" data-bind="value: timelapseMinDelay, valueUpdate: 'afterkeydown', enable: !isPrinting()">
<span class="add-on">{{ _('sec') }}</span>
</div>
<span class="help-block">{{ _('OctoPrint will rate limit snapshots to this minimum interval. This it to prevent against performance issues with vase mode/continous z prints.') }}</span>
@@ -34,7 +34,7 @@
<label class="control-label" for="webcam_timelapse_interval">{{ _('Snapshot interval') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser()">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: !isPrinting()">
<span class="add-on">{{ _('sec') }}</span>
</div>
</div>
@@ -44,7 +44,7 @@
<label class="control-label" for="webcam_timelapse_fps">{{ _('Timelapse frame rate') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_fps" data-bind="value: timelapseFps, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_fps" data-bind="value: timelapseFps, valueUpdate: 'afterkeydown', enable: !isPrinting() && timelapseTypeSelected()">
<span class="add-on">{{ _('fps') }}</span>
</div>
</div>
@@ -54,7 +54,7 @@
<label class="control-label" for="webcam_timelapse_postRoll">{{ _('Timelapse post roll') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="0" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
<input type="number" min="0" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: !isPrinting() && timelapseTypeSelected()">
<span class="add-on">{{ _('sec') }}</span>
</div>
<span class="help-block">{{ _('OctoPrint will use the final picture to add this many seconds to the end of your rendered timelapse.') }}</span>
@@ -65,14 +65,14 @@
<label class="control-label" for="webcam_timelapse_retractionZHop">{{ _('Retraction Z-Hop') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="0.0" class="input-mini" id="webcam_timelapse_retractionZHop" data-bind="value: timelapseRetractionZHop, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser()">
<input type="number" min="0.0" class="input-mini" id="webcam_timelapse_retractionZHop" data-bind="value: timelapseRetractionZHop, valueUpdate: 'afterkeydown', enable: !isPrinting()">
<span class="add-on">{{ _('mm') }}</span>
</div>
<span class="help-block">{{ _('Enter the retraction z-hop used in the firmware or the gcode file to trigger snapshots for the timelapse only if a real layer change happens. For this to work properly your retraction z-hop has to be different from your layerheight!') }}</span>
</div>
</div>
<div class="control-group" data-bind="visible: loginState.isAdmin">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: persist, enable: isOperational() && !isPrinting() && loginState.isUser()"> {{ _('Save as default') }}
+21 -26
View File
@@ -472,7 +472,8 @@ class MachineCom(object):
self._resendActive = False
self._terminal_log = deque([], 20)
terminal_log_size = settings().getInt(["serial", "terminalLogSize"])
self._terminal_log = deque([], min(20, terminal_log_size))
self._disconnect_on_errors = settings().getBoolean(["serial", "disconnectOnErrors"])
self._ignore_errors = settings().getBoolean(["serial", "ignoreErrorsFromFirmware"])
@@ -1889,7 +1890,7 @@ class MachineCom(object):
self._logger.info("Firmware states that it supports sd status autoreporting")
self._set_autoreport_sdstatus_interval()
elif capability == self.CAPABILITY_EMERGENCY_PARSER and enabled:
self._logger.info("Firmware states that it supports emergency GCODEs M108 and M410 to be sent without waiting for an acknowledgement first")
self._logger.info("Firmware states that it supports emergency GCODEs to be sent without waiting for an acknowledgement first")
# notify plugins
for name, hook in self._firmware_info_hooks["capabilities"].items():
@@ -3370,7 +3371,7 @@ class MachineCom(object):
# may be busy, so give things a little time before we try again. Extend this
# period each time we fail until either we write the data or run out of retry attempts.
if passes > 1:
sleep((passes-1)/10.0)
time.sleep((passes-1)/10.0)
##~~ command handlers
@@ -3563,7 +3564,7 @@ class MachineCom(object):
self._resendDelta = None
def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
self._logger.info("Force-sending M112 to the printer")
self._logger.info(u"Force-sending M112 to the printer")
# emergency stop, jump the queue with the M112, regardless of whether the EMERGENCY_PARSER capability is
# available or not
@@ -3597,30 +3598,10 @@ class MachineCom(object):
return None,
def _gcode_M108_queuing(self, cmd, gcode=None, *args, **kwargs):
# only jump the queue with M108 if the EMERGENCY_PARSER capability is available
if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False):
return
self._logger.info("Force-sending M108 to the printer")
self._do_send(cmd, gcode=gcode)
# use up an ok since we will get one back for this command and don't want to get out of sync
self._clear_to_send.clear()
return None,
return self._emergency_force_send(cmd, u"Force-sending M108 to the printer", gcode=gcode, *args, **kwargs)
def _gcode_M410_queuing(self, cmd, gcode=None, *args, **kwargs):
# only jump the queue with M410 if the EMERGENCY_PARSER capability is available
if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False):
return
self._logger.info("Force-sending M410 to the printer")
self._do_send(cmd, gcode=gcode)
# use up an ok since we will get one back for this command and don't want to get out of sync
self._clear_to_send.clear()
return None,
return self._emergency_force_send(cmd, u"Force-sending M410 to the printer", gcode=gcode, *args, **kwargs)
def _gcode_M114_queued(self, *args, **kwargs):
self._reset_position_timers()
@@ -3640,6 +3621,20 @@ class MachineCom(object):
self._timeout = self._get_new_communication_timeout() + _timeout
self._dwelling_until = time.time() + _timeout
def _emergency_force_send(self, cmd, message, gcode=None, *args, **kwargs):
# only jump the queue with our command if the EMERGENCY_PARSER capability is available
if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) \
or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False):
return
self._logger.info(message)
self._do_send(cmd, gcode=gcode)
# use up an ok since we will get one back for this command and don't want to get out of sync
self._clear_to_send.clear()
return None,
def _validate_tool(self, tool):
return tool < self._printerProfileManager.get_current_or_default()["extruder"]["count"] and not tool in self._knownInvalidTools
+10
View File
@@ -0,0 +1,10 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server.api``.
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
+35
View File
@@ -0,0 +1,35 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server.api`` system.
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
import mock
import unittest
class GetFolderUsageTest(unittest.TestCase):
def test_readUsageForFolder(self):
from octoprint.server.api.system import _usageForFolders
with mock.patch("psutil.disk_usage") as disk_usage_mock:
disk_usage = mock.MagicMock()
disk_usage.free = 50
disk_usage.total = 512
disk_usage_mock.return_value = disk_usage
with mock.patch("octoprint.server.api.system.s") as settings_mock:
settings = mock.MagicMock()
settings.get.return_value = dict(uploads="mocked")
settings.getBaseFolder.return_value = "mocked"
settings_mock.return_value = settings
data = _usageForFolders()
self.assertEquals(data['uploads']['free'], 50)
self.assertEquals(data['uploads']['total'], 512)
+6 -2
View File
@@ -156,6 +156,7 @@ class TestSettings(unittest.TestCase):
'Send: N71667 G1 X163.151 Y35.424 E0.02043*83',
'Send: N85343 G1 Z29.880 F10800.000*15',
'Recv: ok',
'Recv: FIRMWARE_NAME:Marlin 1.1.7-C2 (Github) SOURCE_CODE_URL:https://github.com/Robo3D/Marlin-C2 PROTOCOL_VERSION:C2 MACHINE_TYPE:RoboC2 EXTRUDER_COUNT:1 UUID:cede2a2f-41a2-4748-9b12-c55c62f367ff EMERGENCY_CODES:M108,M112,M410'
]
filters = octoprint.settings.Settings().get(["terminalFilters"])
@@ -165,7 +166,7 @@ class TestSettings(unittest.TestCase):
for terminal_string in bad_terminal_entries:
match_result = matcher.match(terminal_string)
# can switch to assertIsNone after 3.x upgrade.
self.assertFalse(match_result, "string matched and it shouldn't have.")
self.assertFalse(match_result, "string matched and it shouldn't have: {!r}".format(terminal_string))
def test_temperature_regex_matches(self):
@@ -173,8 +174,11 @@ class TestSettings(unittest.TestCase):
#with self.mocked_config():
common_terminal_entries = [
'Send: M105',
'Send: N123 M105*456',
'Recv: ok N5993 P15 B15 T:59.2 /0.0 B:31.8 /0.0 T0:59.2 /0.0 @:0 B@:100:', # monoprice mini delta
'Recv: ok T:210.3 /210.0 B:60.3 /60.0 T0:210.3 /210.0 @:79 B@:0 P:35.9 A:40.0', # Prusa mk3
'Recv: T:210.3 /210.0',
]
filters = octoprint.settings.Settings().get(["terminalFilters"])
@@ -184,7 +188,7 @@ class TestSettings(unittest.TestCase):
for terminal_string in common_terminal_entries:
match_result = matcher.match(terminal_string)
# can switch to assertIsNotNone after 3.x upgrade.
self.assertTrue(match_result, "string did not match and it should have.")
self.assertTrue(match_result, "string did not match and it should have: {!r}".format(terminal_string))
##~~ test getters