🎨 Change dict constructors to literals
This commit is contained in:
1 parent
559c9b4e52
commit
af60fd6428
72 files changed
+1861
-1895
No files matched your search
@@ -81,7 +81,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
after_settings_init=None, after_logging=None, after_safe_mode=None, after_settings_valid=None,
|
||||
after_event_manager=None, after_connectivity_checker=None,
|
||||
after_plugin_manager=None, after_environment_detector=None):
|
||||
kwargs = dict()
|
||||
kwargs = {}
|
||||
|
||||
logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler)
|
||||
kwargs["logger"] = logger
|
||||
@@ -422,8 +422,8 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
|
||||
plugin_validators=plugin_validators,
|
||||
compatibility_ignored_list=compatibility_ignored_list)
|
||||
|
||||
settings_overlays = dict()
|
||||
disabled_from_overlays = dict()
|
||||
settings_overlays = {}
|
||||
disabled_from_overlays = {}
|
||||
|
||||
def handle_plugin_loaded(name, plugin):
|
||||
if plugin.instance and hasattr(plugin.instance, "__plugin_settings_overlay__"):
|
||||
@@ -602,10 +602,10 @@ def init_connectivity_checker(settings, event_manager):
|
||||
connectivityName = settings.get(["server", "onlineCheck", "name"])
|
||||
|
||||
def on_connectivity_change(old_value, new_value, connection_working=None, resolution_working=None):
|
||||
event_manager.fire(Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value,
|
||||
new=new_value,
|
||||
connection=connection_working,
|
||||
resolution=resolution_working))
|
||||
event_manager.fire(Events.CONNECTIVITY_CHANGED, payload={"old": old_value,
|
||||
"new": new_value,
|
||||
"connection": connection_working,
|
||||
"resolution": resolution_working})
|
||||
|
||||
connectivityChecker = ConnectivityChecker(connectivityInterval,
|
||||
connectivityHost,
|
||||
|
||||
@@ -65,38 +65,38 @@ class GroupManager(object):
|
||||
|
||||
def _init_defaults(self):
|
||||
self._default_groups = {
|
||||
ADMIN_GROUP: dict(name="Admins",
|
||||
description="Administrators",
|
||||
permissions=self.default_permissions_for_group(ADMIN_GROUP),
|
||||
subgroups=[],
|
||||
changeable=False,
|
||||
removable=False,
|
||||
default=False,
|
||||
toggleable=True),
|
||||
USER_GROUP: dict(name="Operator",
|
||||
description="Group to gain operator access",
|
||||
permissions=self.default_permissions_for_group(USER_GROUP),
|
||||
subgroups=[],
|
||||
changeable=True,
|
||||
default=True,
|
||||
removable=False,
|
||||
toggleable=True),
|
||||
GUEST_GROUP: dict(name="Guests",
|
||||
description="Anyone who is not currently logged in",
|
||||
permissions=self.default_permissions_for_group(GUEST_GROUP),
|
||||
subgroups=[],
|
||||
changeable=True,
|
||||
default=False,
|
||||
removable=False,
|
||||
toggleable=False),
|
||||
READONLY_GROUP: dict(name="Read-only Access",
|
||||
description="Group to gain read-only access",
|
||||
permissions=self.default_permissions_for_group(READONLY_GROUP),
|
||||
subgroups=[],
|
||||
changeable=False,
|
||||
removable=False,
|
||||
default=False,
|
||||
toggleable=True)
|
||||
ADMIN_GROUP: {"name": "Admins",
|
||||
"description": "Administrators",
|
||||
"permissions": self.default_permissions_for_group(ADMIN_GROUP),
|
||||
"subgroups": [],
|
||||
"changeable": False,
|
||||
"removable": False,
|
||||
"default": False,
|
||||
"toggleable": True},
|
||||
USER_GROUP: {"name": "Operator",
|
||||
"description": "Group to gain operator access",
|
||||
"permissions": self.default_permissions_for_group(USER_GROUP),
|
||||
"subgroups": [],
|
||||
"changeable": True,
|
||||
"default": True,
|
||||
"removable": False,
|
||||
"toggleable": True},
|
||||
GUEST_GROUP: {"name": "Guests",
|
||||
"description": "Anyone who is not currently logged in",
|
||||
"permissions": self.default_permissions_for_group(GUEST_GROUP),
|
||||
"subgroups": [],
|
||||
"changeable": True,
|
||||
"default": False,
|
||||
"removable": False,
|
||||
"toggleable": False},
|
||||
READONLY_GROUP: {"name": "Read-only Access",
|
||||
"description": "Group to gain read-only access",
|
||||
"permissions": self.default_permissions_for_group(READONLY_GROUP),
|
||||
"subgroups": [],
|
||||
"changeable": False,
|
||||
"removable": False,
|
||||
"default": False,
|
||||
"toggleable": True}
|
||||
}
|
||||
|
||||
for key, g in self._default_groups.items():
|
||||
@@ -186,7 +186,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
path = os.path.join(settings().getBaseFolder("base"), "groups.yaml")
|
||||
|
||||
self._groupfile = path
|
||||
self._groups = dict()
|
||||
self._groups = {}
|
||||
self._dirty = False
|
||||
|
||||
GroupManager.__init__(self)
|
||||
@@ -201,7 +201,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
|
||||
if not "groups" in data:
|
||||
groups = data
|
||||
data = dict(groups=groups)
|
||||
data = {"groups": groups}
|
||||
|
||||
file_version = data.get("_version", 1)
|
||||
if file_version < self.FILE_VERSION:
|
||||
@@ -210,7 +210,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
"storage, migrating to version {}".format(file_version, self.FILE_VERSION))
|
||||
self._dirty = True
|
||||
|
||||
groups = data.get("groups", dict())
|
||||
groups = data.get("groups", {})
|
||||
tracked_permissions = data.get("tracked", list())
|
||||
|
||||
for key, attributes in groups.items():
|
||||
@@ -270,21 +270,19 @@ class FilebasedGroupManager(GroupManager):
|
||||
if self._groupfile is None or not self._dirty and not force:
|
||||
return
|
||||
|
||||
groups = dict()
|
||||
groups = {}
|
||||
for key in self._groups.keys():
|
||||
group = self._groups[key]
|
||||
groups[key] = dict(
|
||||
permissions=self._from_permissions(*group._permissions),
|
||||
subgroups=self._from_groups(*group._subgroups),
|
||||
default=group._default
|
||||
)
|
||||
groups[key] = {"permissions": self._from_permissions(*group._permissions),
|
||||
"subgroups": self._from_groups(*group._subgroups),
|
||||
"default": group._default}
|
||||
if not key in self._default_groups:
|
||||
groups[key]["name"] = group.get_name()
|
||||
groups[key]["description"] = group.get_description()
|
||||
|
||||
data = dict(_version=self.FILE_VERSION,
|
||||
groups=groups,
|
||||
tracked=[x.key for x in Permissions.all()])
|
||||
data = {"_version": self.FILE_VERSION,
|
||||
"groups": groups,
|
||||
"tracked": [x.key for x in Permissions.all()]}
|
||||
|
||||
with atomic_write(self._groupfile, mode='wt', permissions=0o600, max_permissions=0o666) as f:
|
||||
import yaml
|
||||
@@ -381,7 +379,8 @@ class FilebasedGroupManager(GroupManager):
|
||||
self._dirty |= group.add_permissions_to_group(added_permissions)
|
||||
|
||||
notifications.append((("permissions_changed", group),
|
||||
dict(added=added_permissions, removed=removed_permissions)))
|
||||
{"added": added_permissions,
|
||||
"removed": removed_permissions}))
|
||||
|
||||
if subgroups is not None:
|
||||
subgroups = self._to_groups(*subgroups)
|
||||
@@ -396,7 +395,8 @@ class FilebasedGroupManager(GroupManager):
|
||||
self._dirty = group.add_subgroups_to_group(added_subgroups)
|
||||
|
||||
notifications.append((("subgroups_changed", group),
|
||||
dict(added=added_subgroups, removed=removed_subgroups)))
|
||||
{"added": added_subgroups,
|
||||
"removed": removed_subgroups}))
|
||||
|
||||
if default is not None:
|
||||
group.change_default(default)
|
||||
@@ -445,18 +445,16 @@ class Group(object):
|
||||
|
||||
def as_dict(self):
|
||||
from octoprint.access.permissions import OctoPrintPermission
|
||||
return dict(
|
||||
key=self.key,
|
||||
name=self.get_name(),
|
||||
description=self._description,
|
||||
permissions=list(map(lambda p: p.key, self._permissions)),
|
||||
subgroups=list(map(lambda g: g.key, self._subgroups)),
|
||||
needs=OctoPrintPermission.convert_needs_to_dict(self.needs),
|
||||
default=self._default,
|
||||
removable=self._removable,
|
||||
changeable=self._changeable,
|
||||
toggleable=self._toggleable
|
||||
)
|
||||
return {"key": self.key,
|
||||
"name": self.get_name(),
|
||||
"description": self._description,
|
||||
"permissions": list(map(lambda p: p.key, self._permissions)),
|
||||
"subgroups": list(map(lambda g: g.key, self._subgroups)),
|
||||
"needs": OctoPrintPermission.convert_needs_to_dict(self.needs),
|
||||
"default": self._default,
|
||||
"removable": self._removable,
|
||||
"changeable": self._changeable,
|
||||
"toggleable": self._toggleable}
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
|
||||
@@ -52,14 +52,12 @@ class OctoPrintPermission(Permission):
|
||||
Permission.__init__(self, *self.convert_to_needs(needs))
|
||||
|
||||
def as_dict(self):
|
||||
return dict(
|
||||
key=self.key,
|
||||
name=self.get_name(),
|
||||
dangerous=self._dangerous,
|
||||
default_groups=self._default_groups,
|
||||
description=self.get_description(),
|
||||
needs=self.convert_needs_to_dict(self.needs)
|
||||
)
|
||||
return {"key": self.key,
|
||||
"name": self.get_name(),
|
||||
"dangerous": self._dangerous,
|
||||
"default_groups": self._default_groups,
|
||||
"description": self.get_description(),
|
||||
"needs": self.convert_needs_to_dict(self.needs)}
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
|
||||
@@ -35,8 +35,8 @@ class UserManager(GroupChangeListener, object):
|
||||
self._group_manager.register_listener(self)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._session_users_by_session = dict()
|
||||
self._sessionids_by_userid = dict()
|
||||
self._session_users_by_session = {}
|
||||
self._sessionids_by_userid = {}
|
||||
self._enabled = True
|
||||
|
||||
if settings is None:
|
||||
@@ -103,7 +103,7 @@ class UserManager(GroupChangeListener, object):
|
||||
listener.on_user_logged_in(user)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_logged_in on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
extra={"callback": fqcn(listener)})
|
||||
|
||||
self._logger.info("Logged in user: {}".format(user.get_id()))
|
||||
|
||||
@@ -139,7 +139,7 @@ class UserManager(GroupChangeListener, object):
|
||||
listener.on_user_logged_out(user, stale=stale)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_logged_out on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
extra={"callback": fqcn(listener)})
|
||||
|
||||
self._logger.info("Logged out user: {}".format(user.get_id()))
|
||||
|
||||
@@ -224,7 +224,7 @@ class UserManager(GroupChangeListener, object):
|
||||
return None
|
||||
|
||||
def get_all_user_settings(self, username):
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
def change_user_setting(self, username, key, value):
|
||||
pass
|
||||
@@ -290,7 +290,7 @@ class UserManager(GroupChangeListener, object):
|
||||
listener.on_user_modified(user)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
extra={"callback": fqcn(listener)})
|
||||
|
||||
def on_group_subgroups_changed(self, group, added=None, removed=None):
|
||||
users = self.find_sessions_for(lambda u: group in u.groups)
|
||||
@@ -301,7 +301,7 @@ class UserManager(GroupChangeListener, object):
|
||||
listener.on_user_modified(user)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
extra={"callback": fqcn(listener)})
|
||||
|
||||
def _trigger_on_user_modified(self, user):
|
||||
if isinstance(user, basestring):
|
||||
@@ -331,7 +331,7 @@ class UserManager(GroupChangeListener, object):
|
||||
listener.on_user_modified(user)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
extra={"callback": fqcn(listener)})
|
||||
|
||||
def _trigger_on_user_removed(self, username):
|
||||
for listener in self._login_status_listeners:
|
||||
@@ -339,7 +339,7 @@ class UserManager(GroupChangeListener, object):
|
||||
listener.on_user_removed(username)
|
||||
except Exception:
|
||||
self._logger.exception("Error in on_user_removed on {!r}".format(listener),
|
||||
extra=dict(callback=fqcn(listener)))
|
||||
extra={"callback": fqcn(listener)})
|
||||
|
||||
#~~ Deprecated methods follow
|
||||
|
||||
@@ -505,7 +505,7 @@ class FilebasedUserManager(UserManager):
|
||||
apikey = None
|
||||
if "apikey" in attributes:
|
||||
apikey = attributes["apikey"]
|
||||
settings = dict()
|
||||
settings = {}
|
||||
if "settings" in attributes:
|
||||
settings = attributes["settings"]
|
||||
|
||||
@@ -983,7 +983,7 @@ class User(UserMixin):
|
||||
self._apikey = apikey
|
||||
|
||||
if settings is None:
|
||||
settings = dict()
|
||||
settings = {}
|
||||
|
||||
self._settings = settings
|
||||
|
||||
@@ -1056,10 +1056,10 @@ class User(UserMixin):
|
||||
s = self._settings
|
||||
for p in path[:-1]:
|
||||
if p not in s:
|
||||
s[p] = dict()
|
||||
s[p] = {}
|
||||
|
||||
if not isinstance(s[p], dict):
|
||||
s[p] = dict()
|
||||
s[p] = {}
|
||||
|
||||
s = s[p]
|
||||
|
||||
@@ -1265,7 +1265,7 @@ class SessionUser(wrapt.ObjectProxy):
|
||||
|
||||
def as_dict(self):
|
||||
result = self.__wrapped__.as_dict()
|
||||
result.update(dict(session=self.session))
|
||||
result.update({"session": self.session})
|
||||
return result
|
||||
|
||||
def __repr__(self):
|
||||
|
||||
@@ -68,7 +68,7 @@ def client_commands():
|
||||
pass
|
||||
|
||||
|
||||
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
|
||||
@client_commands.group("client", context_settings={"ignore_unknown_options": True})
|
||||
@client_options
|
||||
@click.pass_context
|
||||
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||
@@ -175,7 +175,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
|
||||
@click.pass_context
|
||||
def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout):
|
||||
"""Sends a JSON command to the specified server path."""
|
||||
data = dict()
|
||||
data = {}
|
||||
params = str_params + int_params + float_params + bool_params
|
||||
for param in params:
|
||||
data[param[0]] = param[1]
|
||||
@@ -193,7 +193,7 @@ def command(ctx, path, command, str_params, int_params, float_params, bool_param
|
||||
@click.pass_context
|
||||
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
|
||||
"""Uploads the specified file to the specified server path."""
|
||||
data = dict()
|
||||
data = {}
|
||||
for param in params:
|
||||
data[param[0]] = param[1]
|
||||
|
||||
|
||||
+13
-15
@@ -50,7 +50,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
yield result
|
||||
|
||||
def _get_commands(self):
|
||||
result = dict()
|
||||
result = {}
|
||||
for group in self.groups:
|
||||
for command in self._get_commands_from_prefix_methods("{}_".format(group)):
|
||||
result[group + self.sep + command.name] = command
|
||||
@@ -109,7 +109,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
original_prompt_for_config = cookiecutter.main.prompt_for_config
|
||||
|
||||
def custom_prompt_for_config(context, no_input=False):
|
||||
cookiecutter_dict = dict()
|
||||
cookiecutter_dict = {}
|
||||
|
||||
env = StrictEnvironment()
|
||||
|
||||
@@ -163,20 +163,18 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
raise
|
||||
|
||||
with tempdir(onerror=onerror) as path:
|
||||
custom = dict(cookiecutters_dir=path)
|
||||
custom = {"cookiecutters_dir": path}
|
||||
with custom_cookiecutter_config(custom):
|
||||
raw_options = dict(
|
||||
plugin_identifier=identifier,
|
||||
plugin_package=package,
|
||||
plugin_name=name,
|
||||
full_name=author,
|
||||
email=email,
|
||||
plugin_description=description,
|
||||
plugin_license=license,
|
||||
plugin_homepage=homepage,
|
||||
plugin_source=source,
|
||||
plugin_installurl=installurl
|
||||
)
|
||||
raw_options = {"plugin_identifier": identifier,
|
||||
"plugin_package": package,
|
||||
"plugin_name": name,
|
||||
"full_name": author,
|
||||
"email": email,
|
||||
"plugin_description": description,
|
||||
"plugin_license": license,
|
||||
"plugin_homepage": homepage,
|
||||
"plugin_source": source,
|
||||
"plugin_installurl": installurl}
|
||||
options = dict((k, v) for k, v in raw_options.items() if v is not None)
|
||||
|
||||
with custom_cookiecutter_prompt(options):
|
||||
|
||||
@@ -61,7 +61,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
|
||||
self.settings = None
|
||||
self.plugin_manager = None
|
||||
self.hooks = dict()
|
||||
self.hooks = {}
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._initialized = False
|
||||
@@ -74,7 +74,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
if ctx.obj is None:
|
||||
ctx.obj = OctoPrintContext()
|
||||
|
||||
logging_config = dict_merge(LOGGING_CONFIG, dict(root=dict(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING)))
|
||||
logging_config = dict_merge(LOGGING_CONFIG, {"root": {"level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING}})
|
||||
logging.config.dictConfig(logging_config)
|
||||
|
||||
# initialize settings and plugin manager based on provided
|
||||
@@ -121,7 +121,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
result[name + self.sep + command.name] = command
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ class EnvironmentDetector(object):
|
||||
|
||||
def run_detection(self, notify_plugins=True):
|
||||
try:
|
||||
environment = dict()
|
||||
environment = {}
|
||||
environment["os"] = self._detect_os()
|
||||
environment["python"] = self._detect_python()
|
||||
environment["hardware"] = self._detect_hardware()
|
||||
@@ -62,16 +62,16 @@ class EnvironmentDetector(object):
|
||||
except Exception:
|
||||
self._logger.exception("Unexpected error while detecting environment")
|
||||
with self._cache_lock:
|
||||
self._cache = dict()
|
||||
self._cache = {}
|
||||
return self._cache
|
||||
|
||||
def _detect_os(self):
|
||||
return dict(id=get_os(),
|
||||
platform=sys.platform)
|
||||
return {"id": get_os(),
|
||||
"platform": sys.platform}
|
||||
|
||||
def _detect_python(self):
|
||||
result = dict(version="unknown",
|
||||
pip="unknown")
|
||||
result = {"version": "unknown",
|
||||
"pip": "unknown"}
|
||||
|
||||
# determine python version
|
||||
try:
|
||||
@@ -96,9 +96,9 @@ class EnvironmentDetector(object):
|
||||
return result
|
||||
|
||||
def _detect_hardware(self):
|
||||
result = dict(cores="unknown",
|
||||
freq="unknown",
|
||||
ram="unknown")
|
||||
result = {"cores": "unknown",
|
||||
"freq": "unknown",
|
||||
"ram": "unknown"}
|
||||
|
||||
try:
|
||||
cores = psutil.cpu_count()
|
||||
@@ -116,7 +116,7 @@ class EnvironmentDetector(object):
|
||||
return result
|
||||
|
||||
def _detect_from_plugins(self):
|
||||
result = dict()
|
||||
result = {}
|
||||
|
||||
for implementation in self._environment_plugins:
|
||||
try:
|
||||
@@ -126,7 +126,7 @@ class EnvironmentDetector(object):
|
||||
except Exception:
|
||||
self._logger.exception("Error while fetching additional "
|
||||
"environment data from plugin {}".format(implementation._identifier),
|
||||
extra=dict(plugin=implementation._identifier))
|
||||
extra={"plugin": implementation._identifier})
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -27,16 +27,10 @@ from past.builtins import basestring
|
||||
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
|
||||
|
||||
extensions = dict(
|
||||
)
|
||||
extensions = {}
|
||||
|
||||
def full_extension_tree():
|
||||
result = dict(
|
||||
# extensions for printable machine code
|
||||
machinecode=dict(
|
||||
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
|
||||
)
|
||||
)
|
||||
result = {"machinecode": {"gcode": ContentTypeMapping(["gcode", "gco", "g"], "text/plain")}}
|
||||
|
||||
def leaf_merger(a, b):
|
||||
supported_leaf_types = (ContentTypeMapping, ContentTypeDetector, list)
|
||||
@@ -82,7 +76,7 @@ def full_extension_tree():
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from SlicerPlugin {name}".format(name=plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
|
||||
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
|
||||
for name, hook in extension_tree_hooks.items():
|
||||
@@ -94,7 +88,7 @@ def full_extension_tree():
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from hook {name}".format(name=name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
return result
|
||||
|
||||
@@ -206,7 +200,7 @@ class FileManager(object):
|
||||
self._analysis_queue = analysis_queue
|
||||
self._analysis_queue.register_finish_callback(self._on_analysis_finished)
|
||||
|
||||
self._storage_managers = dict()
|
||||
self._storage_managers = {}
|
||||
if initial_storage_managers:
|
||||
self._storage_managers.update(initial_storage_managers)
|
||||
|
||||
@@ -214,14 +208,14 @@ class FileManager(object):
|
||||
self._printer_profile_manager = printer_profile_manager
|
||||
|
||||
import threading
|
||||
self._slicing_jobs = dict()
|
||||
self._slicing_jobs = {}
|
||||
self._slicing_jobs_mutex = threading.Lock()
|
||||
|
||||
self._slicing_progress_callbacks = []
|
||||
self._last_slicing_progress = None
|
||||
|
||||
self._progress_plugins = []
|
||||
self._preprocessor_hooks = dict()
|
||||
self._preprocessor_hooks = {}
|
||||
|
||||
import octoprint.settings
|
||||
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
|
||||
@@ -336,24 +330,24 @@ class FileManager(object):
|
||||
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
try:
|
||||
if _error:
|
||||
eventManager().fire(Events.SLICING_FAILED, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
reason=_error))
|
||||
eventManager().fire(Events.SLICING_FAILED, {"slicer": slicer_name,
|
||||
"stl": source_path,
|
||||
"stl_location": source_location,
|
||||
"gcode": dest_path,
|
||||
"gcode_location": dest_location,
|
||||
"reason": _error})
|
||||
elif _cancelled:
|
||||
eventManager().fire(Events.SLICING_CANCELLED, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location))
|
||||
eventManager().fire(Events.SLICING_CANCELLED, {"slicer": slicer_name,
|
||||
"stl": source_path,
|
||||
"stl_location": source_location,
|
||||
"gcode": dest_path,
|
||||
"gcode_location": dest_location})
|
||||
else:
|
||||
source_meta = self.get_metadata(source_location, source_path)
|
||||
hash = source_meta.get("hash", "n/a")
|
||||
|
||||
import io
|
||||
links = [("model", dict(name=source_path))]
|
||||
links = [("model", {"name": source_path})]
|
||||
_, stl_name = self.split_path(source_location, source_path)
|
||||
file_obj = StreamWrapper(os.path.basename(dest_path),
|
||||
io.BytesIO(";Generated from {stl_name} (hash: {hash})\n".format(**locals()).encode("ascii", "replace")),
|
||||
@@ -365,12 +359,12 @@ class FileManager(object):
|
||||
printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = octoprint.util.monotonic_time()
|
||||
eventManager().fire(Events.SLICING_DONE, dict(slicer=slicer_name,
|
||||
stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
gcode_location=dest_location,
|
||||
time=end_time - start_time))
|
||||
eventManager().fire(Events.SLICING_DONE, {"slicer": slicer_name,
|
||||
"stl": source_path,
|
||||
"stl_location": source_location,
|
||||
"gcode": dest_path,
|
||||
"gcode_location": dest_location,
|
||||
"time": end_time - start_time})
|
||||
|
||||
if callback is not None:
|
||||
if callback_args is None:
|
||||
@@ -439,7 +433,7 @@ class FileManager(object):
|
||||
callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while pushing slicing progress",
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
extra={"callback": fqcn(callback)})
|
||||
|
||||
if progress_int:
|
||||
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
@@ -448,7 +442,7 @@ class FileManager(object):
|
||||
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier,
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
|
||||
import threading
|
||||
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
|
||||
@@ -474,7 +468,7 @@ class FileManager(object):
|
||||
if isinstance(destinations, basestring):
|
||||
destinations = [destinations]
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
for dst in destinations:
|
||||
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive, force_refresh=force_refresh)
|
||||
return result
|
||||
@@ -487,7 +481,7 @@ class FileManager(object):
|
||||
try:
|
||||
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
except Exception:
|
||||
self._logger.exception("Error when calling preprocessor hook for plugin {}, ignoring".format(name), extra=dict(plugin=name))
|
||||
self._logger.exception("Error when calling preprocessor hook for plugin {}, ignoring".format(name), extra={"plugin": name})
|
||||
continue
|
||||
|
||||
if hook_file_object is not None:
|
||||
@@ -505,11 +499,11 @@ class FileManager(object):
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name,
|
||||
type=get_file_type(name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
eventManager().fire(Events.FILE_ADDED, {"storage": destination,
|
||||
"path": path_in_storage,
|
||||
"name": name,
|
||||
"type": get_file_type(name)})
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
return path_in_storage
|
||||
|
||||
def remove_file(self, destination, path):
|
||||
@@ -518,11 +512,11 @@ class FileManager(object):
|
||||
self._storage(destination).remove_file(path)
|
||||
|
||||
_, name = self._storage(destination).split_path(path)
|
||||
eventManager().fire(Events.FILE_REMOVED, dict(storage=destination,
|
||||
path=path,
|
||||
name=name,
|
||||
type=get_file_type(name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
eventManager().fire(Events.FILE_REMOVED, {"storage": destination,
|
||||
"path": path,
|
||||
"name": name,
|
||||
"type": get_file_type(name)})
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
|
||||
def copy_file(self, destination, source, dst):
|
||||
path_in_storage = self._storage(destination).copy_file(source, dst)
|
||||
@@ -532,11 +526,11 @@ class FileManager(object):
|
||||
self._analysis_queue.enqueue(queue_entry)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name,
|
||||
type=get_file_type(name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
eventManager().fire(Events.FILE_ADDED, {"storage": destination,
|
||||
"path": path_in_storage,
|
||||
"name": name,
|
||||
"type": get_file_type(name)})
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
|
||||
def move_file(self, destination, source, dst):
|
||||
queue_entry = self._analysis_queue_entry(destination, source)
|
||||
@@ -552,24 +546,24 @@ class FileManager(object):
|
||||
dst_path_in_storage = self._storage(destination).path_in_storage(dst)
|
||||
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
|
||||
|
||||
eventManager().fire(Events.FILE_REMOVED, dict(storage=destination,
|
||||
path=source_path_in_storage,
|
||||
name=source_name,
|
||||
type=get_file_type(source_name)))
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
path=dst_path_in_storage,
|
||||
name=dst_name,
|
||||
type=get_file_type(dst_name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
eventManager().fire(Events.FILE_REMOVED, {"storage": destination,
|
||||
"path": source_path_in_storage,
|
||||
"name": source_name,
|
||||
"type": get_file_type(source_name)})
|
||||
eventManager().fire(Events.FILE_ADDED, {"storage": destination,
|
||||
"path": dst_path_in_storage,
|
||||
"name": dst_name,
|
||||
"type": get_file_type(dst_name)})
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
|
||||
def add_folder(self, destination, path, ignore_existing=True, display=None):
|
||||
path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing, display=display)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
eventManager().fire(Events.FOLDER_ADDED, {"storage": destination,
|
||||
"path": path_in_storage,
|
||||
"name": name})
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
return path_in_storage
|
||||
|
||||
def remove_folder(self, destination, path, recursive=True):
|
||||
@@ -579,20 +573,20 @@ class FileManager(object):
|
||||
self._analysis_queue.resume()
|
||||
|
||||
_, name = self._storage(destination).split_path(path)
|
||||
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
|
||||
path=path,
|
||||
name=name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
eventManager().fire(Events.FOLDER_REMOVED, {"storage": destination,
|
||||
"path": path,
|
||||
"name": name})
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
|
||||
def copy_folder(self, destination, source, dst):
|
||||
path_in_storage = self._storage(destination).copy_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=path_in_storage)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
eventManager().fire(Events.FOLDER_ADDED, {"storage": destination,
|
||||
"path": path_in_storage,
|
||||
"name": name})
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
|
||||
def move_folder(self, destination, source, dst):
|
||||
self._analysis_queue.dequeue_folder(destination, source)
|
||||
@@ -605,13 +599,13 @@ class FileManager(object):
|
||||
_, source_name = self._storage(destination).split_path(source_path_in_storage)
|
||||
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
|
||||
|
||||
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
|
||||
path=source_path_in_storage,
|
||||
name=source_name))
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
path=dst_path_in_storage,
|
||||
name=dst_name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
eventManager().fire(Events.FOLDER_REMOVED, {"storage": destination,
|
||||
"path": source_path_in_storage,
|
||||
"name": source_name})
|
||||
eventManager().fire(Events.FOLDER_ADDED, {"storage": destination,
|
||||
"path": dst_path_in_storage,
|
||||
"name": dst_name})
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
|
||||
def has_analysis(self, destination, path):
|
||||
return self._storage(destination).has_analysis(path)
|
||||
@@ -628,10 +622,16 @@ class FileManager(object):
|
||||
def log_print(self, destination, path, timestamp, print_time, success, printer_profile):
|
||||
try:
|
||||
if success:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
|
||||
self._storage(destination).add_history(path, {"timestamp": timestamp,
|
||||
"printTime": print_time,
|
||||
"success": success,
|
||||
"printerProfile": printer_profile})
|
||||
else:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
|
||||
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path))
|
||||
self._storage(destination).add_history(path, {"timestamp": timestamp,
|
||||
"success": success,
|
||||
"printerProfile": printer_profile})
|
||||
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, {"storage": destination,
|
||||
"path": path})
|
||||
except NoSuchStorage:
|
||||
# if there's no storage configured where to log the print, we'll just not log it
|
||||
pass
|
||||
@@ -641,10 +641,10 @@ class FileManager(object):
|
||||
import yaml
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
data = dict(origin=origin,
|
||||
path=self.path_in_storage(origin, path),
|
||||
pos=pos,
|
||||
date=time.time())
|
||||
data = {"origin": origin,
|
||||
"path": self.path_in_storage(origin, path),
|
||||
"pos": pos,
|
||||
"date": time.time()}
|
||||
try:
|
||||
with atomic_write(self._recovery_file, mode='wt', max_permissions=0o666) as f:
|
||||
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=2, allow_unicode=True)
|
||||
|
||||
@@ -68,7 +68,7 @@ class AnalysisQueue(object):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._callbacks = []
|
||||
|
||||
self._queues = dict()
|
||||
self._queues = {}
|
||||
for key, queue_factory in queue_factories.items():
|
||||
self._queues[key] = queue_factory(self._analysis_finished)
|
||||
|
||||
@@ -115,7 +115,7 @@ class AnalysisQueue(object):
|
||||
callback(entry, result)
|
||||
except:
|
||||
self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback),
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
extra={"callback": fqcn(callback)})
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
|
||||
"path": entry.path,
|
||||
"origin": entry.location,
|
||||
@@ -414,13 +414,13 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
_, output = output.split("RESULTS:")
|
||||
analysis = yaml.safe_load(output)
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
result["printingArea"] = analysis["printing_area"]
|
||||
result["dimensions"] = analysis["dimensions"]
|
||||
if analysis["total_time"]:
|
||||
result["estimatedPrintTime"] = analysis["total_time"] * 60
|
||||
if analysis["extrusion_length"]:
|
||||
result["filament"] = dict()
|
||||
result["filament"] = {}
|
||||
for i in range(len(analysis["extrusion_length"])):
|
||||
result["filament"]["tool%d" % i] = {
|
||||
"length": analysis["extrusion_length"][i],
|
||||
|
||||
@@ -493,9 +493,9 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
import threading
|
||||
self._metadata_lock_mutex = threading.RLock()
|
||||
self._metadata_locks = dict()
|
||||
self._metadata_locks = {}
|
||||
self._persisted_metadata_lock_mutex = threading.RLock()
|
||||
self._persisted_metadata_locks = dict()
|
||||
self._persisted_metadata_locks = {}
|
||||
|
||||
self._metadata_cache = pylru.lrucache(100)
|
||||
self._filelist_cache = {}
|
||||
@@ -553,7 +553,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
metadata = self._get_metadata(path)
|
||||
if not metadata:
|
||||
metadata = dict()
|
||||
metadata = {}
|
||||
for entry in scandir(path):
|
||||
if is_hidden_path(entry.name):
|
||||
continue
|
||||
@@ -657,7 +657,7 @@ class LocalFileStorage(StorageInterface):
|
||||
os.mkdir(folder_path)
|
||||
|
||||
if display_name != name:
|
||||
metadata = self._get_metadata_entry(path, name, default=dict())
|
||||
metadata = self._get_metadata_entry(path, name, default={})
|
||||
metadata["display"] = display_name
|
||||
self._update_metadata_entry(path, name, metadata)
|
||||
|
||||
@@ -713,18 +713,14 @@ class LocalFileStorage(StorageInterface):
|
||||
if (must_not_equal or source_display == destination_canon_name) and source_fullpath == destination_fullpath:
|
||||
raise StorageError("Source {} and destination {} are the same folder".format(source_path, destination_path), code=StorageError.SOURCE_EQUALS_DESTINATION)
|
||||
|
||||
source_data = dict(
|
||||
path=source_path,
|
||||
name=source_name,
|
||||
display=source_display,
|
||||
fullpath=source_fullpath,
|
||||
)
|
||||
destination_data = dict(
|
||||
path=destination_path,
|
||||
name=destination_name,
|
||||
display=destination_canon_name,
|
||||
fullpath=destination_fullpath,
|
||||
)
|
||||
source_data = {"path": source_path,
|
||||
"name": source_name,
|
||||
"display": source_display,
|
||||
"fullpath": source_fullpath}
|
||||
destination_data = {"path": destination_path,
|
||||
"name": destination_name,
|
||||
"display": destination_canon_name,
|
||||
"fullpath": destination_fullpath}
|
||||
return source_data, destination_data
|
||||
|
||||
def _set_display_metadata(self, destination_data, source_data=None):
|
||||
@@ -736,7 +732,7 @@ class LocalFileStorage(StorageInterface):
|
||||
display = None
|
||||
|
||||
destination_meta = self._get_metadata_entry(destination_data["path"], destination_data["name"],
|
||||
default=dict())
|
||||
default={})
|
||||
if display:
|
||||
destination_meta["display"] = display
|
||||
self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta)
|
||||
@@ -802,11 +798,11 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
# save the file's hash to the metadata of the folder
|
||||
file_hash = self._create_hash(file_path)
|
||||
metadata = self._get_metadata_entry(path, name, default=dict())
|
||||
metadata = self._get_metadata_entry(path, name, default={})
|
||||
metadata_dirty = False
|
||||
if not "hash" in metadata or metadata["hash"] != file_hash:
|
||||
# hash changed -> throw away old metadata
|
||||
metadata = dict(hash=file_hash)
|
||||
metadata = {"hash": file_hash}
|
||||
metadata_dirty = True
|
||||
|
||||
if not "display" in metadata and display_name != name:
|
||||
@@ -822,7 +818,9 @@ class LocalFileStorage(StorageInterface):
|
||||
links = []
|
||||
|
||||
if printer_profile is not None:
|
||||
links.append(("printerprofile", dict(id=printer_profile["id"], name=printer_profile["name"])))
|
||||
links.append(("printerprofile",
|
||||
{"id": printer_profile["id"],
|
||||
"name": printer_profile["name"]}))
|
||||
|
||||
self._add_links(name, path, links)
|
||||
|
||||
@@ -1147,8 +1145,8 @@ class LocalFileStorage(StorageInterface):
|
||||
return
|
||||
|
||||
# collect data from history
|
||||
former_print_times = dict()
|
||||
last_print = dict()
|
||||
former_print_times = {}
|
||||
last_print = {}
|
||||
|
||||
|
||||
for history_entry in metadata[name]["history"]:
|
||||
@@ -1174,7 +1172,7 @@ class LocalFileStorage(StorageInterface):
|
||||
last_print[printer_profile] = history_entry
|
||||
|
||||
# calculate stats
|
||||
statistics = dict(averagePrintTime=dict(), lastPrintTime=dict())
|
||||
statistics = {"averagePrintTime": {}, "lastPrintTime": {}}
|
||||
|
||||
for printer_profile in former_print_times:
|
||||
if not former_print_times[printer_profile]:
|
||||
@@ -1241,10 +1239,8 @@ class LocalFileStorage(StorageInterface):
|
||||
else:
|
||||
hash = self._create_hash(ref_path)
|
||||
if not data["name"] in metadata:
|
||||
metadata[data["name"]] = dict(
|
||||
hash=hash,
|
||||
links=[]
|
||||
)
|
||||
metadata[data["name"]] = {"hash": hash,
|
||||
"links": []}
|
||||
else:
|
||||
metadata[data["name"]]["hash"] = hash
|
||||
|
||||
@@ -1256,22 +1252,18 @@ class LocalFileStorage(StorageInterface):
|
||||
metadata[data["name"]]["links"] = []
|
||||
|
||||
# add reverse link to link target file
|
||||
metadata[data["name"]]["links"].append(
|
||||
dict(rel="machinecode" if rel == "model" else "model", name=name, hash=metadata[name]["hash"])
|
||||
)
|
||||
metadata[data["name"]]["links"].append({"rel": "machinecode" if rel == "model" else "model",
|
||||
"name": name,
|
||||
"hash": metadata[name]["hash"]})
|
||||
metadata_dirty = True
|
||||
|
||||
link_dict = dict(
|
||||
rel=rel,
|
||||
name=data["name"],
|
||||
hash=hash
|
||||
)
|
||||
link_dict = {"rel": rel,
|
||||
"name": data["name"],
|
||||
"hash": hash}
|
||||
|
||||
elif rel == "web" and "href" in data:
|
||||
link_dict = dict(
|
||||
rel=rel,
|
||||
href=data["href"]
|
||||
)
|
||||
link_dict = {"rel": rel,
|
||||
"href": data["href"]}
|
||||
if "retrieved" in data:
|
||||
link_dict["retrieved"] = data["retrieved"]
|
||||
|
||||
@@ -1351,9 +1343,9 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
metadata = self._get_metadata(path)
|
||||
if not metadata:
|
||||
metadata = dict()
|
||||
metadata = {}
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
|
||||
for entry in scandir(path):
|
||||
if is_hidden_path(entry.name):
|
||||
@@ -1411,7 +1403,7 @@ class LocalFileStorage(StorageInterface):
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data = {}
|
||||
extended_entry_data.update(entry_metadata)
|
||||
extended_entry_data["name"] = entry_name
|
||||
extended_entry_data["display"] = entry_metadata.get("display", entry_name)
|
||||
@@ -1444,15 +1436,13 @@ class LocalFileStorage(StorageInterface):
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
else:
|
||||
entry_metadata = dict()
|
||||
entry_metadata = {}
|
||||
|
||||
entry_data = dict(
|
||||
name=entry_name,
|
||||
display=entry_metadata.get("display", entry_name),
|
||||
path=path_in_location,
|
||||
type="folder",
|
||||
typePath=["folder"]
|
||||
)
|
||||
entry_data = {"name": entry_name,
|
||||
"display": entry_metadata.get("display", entry_name),
|
||||
"path": path_in_location,
|
||||
"type": "folder",
|
||||
"typePath": ["folder"]}
|
||||
|
||||
result[entry_name] = entry_data
|
||||
except Exception:
|
||||
@@ -1470,7 +1460,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def _add_basic_metadata(self, path, entry, display_name=None, additional_metadata=None, save=True, metadata=None):
|
||||
if additional_metadata is None:
|
||||
additional_metadata = dict()
|
||||
additional_metadata = {}
|
||||
|
||||
if metadata is None:
|
||||
metadata = self._get_metadata(path)
|
||||
@@ -1478,17 +1468,15 @@ class LocalFileStorage(StorageInterface):
|
||||
entry_path = os.path.join(path, entry)
|
||||
|
||||
if os.path.isfile(entry_path):
|
||||
entry_data = dict(
|
||||
hash=self._create_hash(os.path.join(path, entry)),
|
||||
links=[],
|
||||
notes=[]
|
||||
)
|
||||
entry_data = {"hash": self._create_hash(os.path.join(path, entry)),
|
||||
"links": [],
|
||||
"notes": []}
|
||||
if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
|
||||
# if there is still old metadata available and that contains an analysis for this file, use it!
|
||||
entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
|
||||
|
||||
elif os.path.isdir(entry_path):
|
||||
entry_data = dict()
|
||||
entry_data = {}
|
||||
|
||||
else:
|
||||
return
|
||||
@@ -1551,7 +1539,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False, updates=None):
|
||||
with self._get_metadata_lock(source_path):
|
||||
source_data = self._get_metadata_entry(source_path, source_name, default=dict())
|
||||
source_data = self._get_metadata_entry(source_path, source_name, default={})
|
||||
if not source_data:
|
||||
return
|
||||
|
||||
@@ -1606,7 +1594,7 @@ class LocalFileStorage(StorageInterface):
|
||||
self._metadata_cache[path] = metadata
|
||||
return metadata
|
||||
else:
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
def _save_metadata(self, path, metadata):
|
||||
import json
|
||||
@@ -1640,7 +1628,7 @@ class LocalFileStorage(StorageInterface):
|
||||
@staticmethod
|
||||
def _copied_metadata(metadata, name):
|
||||
metadata = copy.copy(metadata)
|
||||
metadata[name] = copy.deepcopy(metadata.get(name, dict()))
|
||||
metadata[name] = copy.deepcopy(metadata.get(name, {}))
|
||||
return metadata
|
||||
|
||||
def _migrate_metadata(self, path):
|
||||
|
||||
@@ -215,7 +215,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
if args is None:
|
||||
args = []
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
kwargs = {}
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -231,7 +231,8 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
if callback:
|
||||
callback(plugin._identifier, plugin, result)
|
||||
except Exception as exc:
|
||||
logger.exception("Error while calling plugin %s" % plugin._identifier, extra=dict(plugin=plugin._identifier))
|
||||
logger.exception("Error while calling plugin %s" % plugin._identifier,
|
||||
extra={"plugin": plugin._identifier})
|
||||
if error_callback:
|
||||
error_callback(plugin._identifier, plugin, exc)
|
||||
|
||||
@@ -346,20 +347,20 @@ class PluginSettings(object):
|
||||
self.plugin_key = plugin_key
|
||||
|
||||
if defaults is not None:
|
||||
self.defaults = dict(plugins=dict())
|
||||
self.defaults = {"plugins": {}}
|
||||
self.defaults["plugins"][plugin_key] = defaults
|
||||
self.defaults["plugins"][plugin_key]["_config_version"] = None
|
||||
else:
|
||||
self.defaults = None
|
||||
|
||||
if get_preprocessors is None:
|
||||
get_preprocessors = dict()
|
||||
self.get_preprocessors = dict(plugins=dict())
|
||||
get_preprocessors = {}
|
||||
self.get_preprocessors = {"plugins": {}}
|
||||
self.get_preprocessors["plugins"][plugin_key] = get_preprocessors
|
||||
|
||||
if set_preprocessors is None:
|
||||
set_preprocessors = dict()
|
||||
self.set_preprocessors = dict(plugins=dict())
|
||||
set_preprocessors = {}
|
||||
self.set_preprocessors = {"plugins": {}}
|
||||
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
|
||||
|
||||
def prefix_path_in_args(args, index=0):
|
||||
@@ -392,31 +393,27 @@ class PluginSettings(object):
|
||||
def wrap_overlay(args):
|
||||
result = list(args)
|
||||
overlay = result[0]
|
||||
result[0] = dict(plugins={plugin_key: overlay})
|
||||
result[0] = {"plugins": {plugin_key: overlay}}
|
||||
return result
|
||||
|
||||
self.access_methods = dict(
|
||||
has = ("has", prefix_path_in_args, add_getter_kwargs),
|
||||
get = ("get", prefix_path_in_args, add_getter_kwargs),
|
||||
get_int = ("getInt", prefix_path_in_args, add_getter_kwargs),
|
||||
get_float = ("getFloat", prefix_path_in_args, add_getter_kwargs),
|
||||
get_boolean = ("getBoolean", prefix_path_in_args, add_getter_kwargs),
|
||||
set = ("set", prefix_path_in_args, add_setter_kwargs),
|
||||
set_int = ("setInt", prefix_path_in_args, add_setter_kwargs),
|
||||
set_float = ("setFloat", prefix_path_in_args, add_setter_kwargs),
|
||||
set_boolean = ("setBoolean", prefix_path_in_args, add_setter_kwargs),
|
||||
remove = ("remove", prefix_path_in_args, lambda x: x),
|
||||
add_overlay = ("add_overlay", wrap_overlay, lambda x: x),
|
||||
remove_overlay = ("remove_overlay", lambda x: x, lambda x: x)
|
||||
)
|
||||
self.deprecated_access_methods = dict(
|
||||
getInt ="get_int",
|
||||
getFloat ="get_float",
|
||||
getBoolean="get_boolean",
|
||||
setInt ="set_int",
|
||||
setFloat ="set_float",
|
||||
setBoolean="set_boolean"
|
||||
)
|
||||
self.access_methods = {"has": ("has", prefix_path_in_args, add_getter_kwargs),
|
||||
"get": ("get", prefix_path_in_args, add_getter_kwargs),
|
||||
"get_int": ("getInt", prefix_path_in_args, add_getter_kwargs),
|
||||
"get_float": ("getFloat", prefix_path_in_args, add_getter_kwargs),
|
||||
"get_boolean": ("getBoolean", prefix_path_in_args, add_getter_kwargs),
|
||||
"set": ("set", prefix_path_in_args, add_setter_kwargs),
|
||||
"set_int": ("setInt", prefix_path_in_args, add_setter_kwargs),
|
||||
"set_float": ("setFloat", prefix_path_in_args, add_setter_kwargs),
|
||||
"set_boolean": ("setBoolean", prefix_path_in_args, add_setter_kwargs),
|
||||
"remove": ("remove", prefix_path_in_args, lambda x: x),
|
||||
"add_overlay": ("add_overlay", wrap_overlay, lambda x: x),
|
||||
"remove_overlay": ("remove_overlay", lambda x: x, lambda x: x)}
|
||||
self.deprecated_access_methods = {"getInt": "get_int",
|
||||
"getFloat": "get_float",
|
||||
"getBoolean": "get_boolean",
|
||||
"setInt": "set_int",
|
||||
"setFloat": "set_float",
|
||||
"setBoolean": "set_boolean"}
|
||||
|
||||
def _prefix_path(self, path=None):
|
||||
if path is None:
|
||||
@@ -528,12 +525,10 @@ class PluginSettings(object):
|
||||
defaults = kwargs.get("defaults", self.defaults)
|
||||
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
|
||||
|
||||
kwargs.update(dict(
|
||||
merged=merged,
|
||||
asdict=asdict,
|
||||
defaults=defaults,
|
||||
preprocessors=preprocessors
|
||||
))
|
||||
kwargs.update({"merged": merged,
|
||||
"asdict": asdict,
|
||||
"defaults": defaults,
|
||||
"preprocessors": preprocessors})
|
||||
|
||||
return self.settings.get(self._prefix_path(), **kwargs)
|
||||
|
||||
|
||||
@@ -654,7 +654,7 @@ class PluginInfo(object):
|
||||
return self._cached_parsed_metadata
|
||||
|
||||
def _parse_metadata(self):
|
||||
result = dict()
|
||||
result = {}
|
||||
|
||||
path = self.location
|
||||
if not path:
|
||||
@@ -765,14 +765,14 @@ class PluginManager(object):
|
||||
self.compatibility_ignored_list = compatibility_ignored_list
|
||||
self.plugin_considered_bundled = plugin_considered_bundled
|
||||
|
||||
self.enabled_plugins = dict()
|
||||
self.disabled_plugins = dict()
|
||||
self.plugin_implementations = dict()
|
||||
self.enabled_plugins = {}
|
||||
self.disabled_plugins = {}
|
||||
self.plugin_implementations = {}
|
||||
self.plugin_implementations_by_type = defaultdict(list)
|
||||
|
||||
self._plugin_hooks = defaultdict(list)
|
||||
|
||||
self.implementation_injects = dict()
|
||||
self.implementation_injects = {}
|
||||
self.implementation_inject_factories = []
|
||||
self.implementation_pre_inits = []
|
||||
self.implementation_post_inits = []
|
||||
@@ -974,20 +974,20 @@ class PluginManager(object):
|
||||
continue
|
||||
|
||||
bundled = key in self.plugin_considered_bundled
|
||||
kwargs = dict(module_name=module_name, version=version, bundled=bundled)
|
||||
kwargs = {"module_name": module_name,
|
||||
"version": version,
|
||||
"bundled": bundled}
|
||||
package_name = entry_point.dist.project_name
|
||||
try:
|
||||
entry_point_metadata = EntryPointMetadata(entry_point)
|
||||
except Exception:
|
||||
self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name))
|
||||
else:
|
||||
kwargs.update(dict(
|
||||
name=entry_point_metadata.name,
|
||||
summary=entry_point_metadata.summary,
|
||||
author=entry_point_metadata.author,
|
||||
url=entry_point_metadata.home_page,
|
||||
license=entry_point_metadata.license
|
||||
))
|
||||
kwargs.update({"name": entry_point_metadata.name,
|
||||
"summary": entry_point_metadata.summary,
|
||||
"author": entry_point_metadata.author,
|
||||
"url": entry_point_metadata.home_page,
|
||||
"license": entry_point_metadata.license})
|
||||
|
||||
plugin = self._import_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
@@ -1552,7 +1552,7 @@ class PluginManager(object):
|
||||
|
||||
def initialize_implementation(self, name, plugin, implementation, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
if additional_injects is None:
|
||||
additional_injects = dict()
|
||||
additional_injects = {}
|
||||
if additional_inject_factories is None:
|
||||
additional_inject_factories = []
|
||||
if additional_pre_inits is None:
|
||||
@@ -1575,14 +1575,12 @@ class PluginManager(object):
|
||||
try:
|
||||
kwargs = dict(injects)
|
||||
|
||||
kwargs.update(dict(
|
||||
identifier=name,
|
||||
plugin_name=plugin.name,
|
||||
plugin_version=plugin.version,
|
||||
plugin_info=plugin,
|
||||
basefolder=os.path.realpath(plugin.location),
|
||||
logger=logging.getLogger(self.logging_prefix + name),
|
||||
))
|
||||
kwargs.update({"identifier": name,
|
||||
"plugin_name": plugin.name,
|
||||
"plugin_version": plugin.version,
|
||||
"plugin_info": plugin,
|
||||
"basefolder": os.path.realpath(plugin.location),
|
||||
"logger": logging.getLogger(self.logging_prefix + name)})
|
||||
|
||||
# inject the additional_injects
|
||||
for arg, value in kwargs.items():
|
||||
@@ -1705,7 +1703,7 @@ class PluginManager(object):
|
||||
"""
|
||||
|
||||
if not hook in self.plugin_hooks:
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
result = OrderedDict()
|
||||
for h in self.plugin_hooks[hook]:
|
||||
|
||||
@@ -266,7 +266,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
:return dict: a dictionary describing the static assets to publish for the plugin
|
||||
"""
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
|
||||
class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
@@ -565,7 +565,7 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
|
||||
:return dict: a dictionary containing any additional template variables to include in the renderer
|
||||
"""
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
def get_template_folder(self):
|
||||
"""
|
||||
@@ -1045,7 +1045,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
dict: a dictionary containing additional data to provide to the frontend. Whatever the plugin
|
||||
returns here will be made available on the wizard API under the plugin's identifier
|
||||
"""
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
# noinspection PyMethodMayBeStatic,PyUnusedLocal
|
||||
def on_wizard_finish(self, handled):
|
||||
@@ -1414,10 +1414,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
else:
|
||||
template_folder = os.path.join(self._basefolder, "templates")
|
||||
|
||||
return dict(
|
||||
static_folder=static_folder,
|
||||
template_folder=template_folder
|
||||
)
|
||||
return {"static_folder": static_folder,
|
||||
"template_folder": template_folder}
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_blueprint_protected(self):
|
||||
@@ -1570,15 +1568,15 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
node[key] = default_value
|
||||
else:
|
||||
if isinstance(node[key], dict):
|
||||
node[key] = dict()
|
||||
node[key] = {}
|
||||
elif isinstance(node[key], (list, tuple)):
|
||||
node[key] = []
|
||||
else:
|
||||
node[key] = None
|
||||
|
||||
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous,
|
||||
admin=lambda: current_user is not None and current_user.has_permission(Permissions.SETTINGS),
|
||||
never=lambda: False)
|
||||
conditions = {"user": lambda: current_user is not None and not current_user.is_anonymous,
|
||||
"admin": lambda: current_user is not None and current_user.has_permission(Permissions.SETTINGS),
|
||||
"never": lambda: False}
|
||||
|
||||
for level, condition in conditions.items():
|
||||
paths_for_level = restricted_paths.get(level, [])
|
||||
@@ -1614,7 +1612,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
# get the current data
|
||||
current = self._settings.get_all_data()
|
||||
if current is None:
|
||||
current = dict()
|
||||
current = {}
|
||||
|
||||
# merge our new data on top of it
|
||||
new_current = octoprint.util.dict_merge(current, data)
|
||||
@@ -1646,7 +1644,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
Override this in your plugin's implementation and return a dictionary defining your settings data structure
|
||||
with included default values.
|
||||
"""
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_settings_restricted_paths(self):
|
||||
@@ -1703,7 +1701,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
..versionadded:: 1.2.17
|
||||
"""
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_settings_preprocessors(self):
|
||||
@@ -1741,7 +1739,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
(dict, dict): A tuple consisting of two dictionaries, the first being the plugin's preprocessors for
|
||||
getters, the second the preprocessors for setters
|
||||
"""
|
||||
return dict(), dict()
|
||||
return {}, {}
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_settings_version(self):
|
||||
@@ -1910,14 +1908,12 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
Returns:
|
||||
dict: A dict describing the slicer as outlined above.
|
||||
"""
|
||||
return dict(
|
||||
type=None,
|
||||
name=None,
|
||||
same_device=True,
|
||||
progress_report=False,
|
||||
source_file_types=["model"],
|
||||
destination_extensions=["gco", "gcode", "g"]
|
||||
)
|
||||
return {"type": None,
|
||||
"name": None,
|
||||
"same_device": True,
|
||||
"progress_report": False,
|
||||
"source_file_types": ["model"],
|
||||
"destination_extensions": ["gco", "gcode", "g"]}
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_slicer_extension_tree(self):
|
||||
@@ -1934,7 +1930,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
..versionadded:: 1.3.11
|
||||
"""
|
||||
from octoprint.filemanager import ContentTypeMapping
|
||||
return dict(model=dict(stl=ContentTypeMapping(["stl"], "application/sla")))
|
||||
return {"model": {"stl": ContentTypeMapping(["stl"], "application/sla")}}
|
||||
|
||||
def get_slicer_profiles(self, profile_path):
|
||||
"""
|
||||
@@ -1957,7 +1953,7 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
|
||||
import octoprint.util
|
||||
|
||||
profiles = dict()
|
||||
profiles = {}
|
||||
for entry in scandir(profile_path):
|
||||
if not entry.name.endswith(".profile") or octoprint.util.is_hidden_path(entry.name):
|
||||
# we are only interested in profiles and no hidden files
|
||||
|
||||
@@ -28,24 +28,24 @@ class ActionCommandNotificationPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="SHOW",
|
||||
name="Show printer notifications",
|
||||
description=gettext("Allows to see printer notifications"),
|
||||
default_groups=[USER_GROUP],
|
||||
roles=["show"]),
|
||||
dict(key="CLEAR",
|
||||
name="Clear printer notifications",
|
||||
description=gettext("Allows to clear printer notifications"),
|
||||
default_groups=[USER_GROUP],
|
||||
roles=["clear"])
|
||||
{"key": "SHOW",
|
||||
"name": "Show printer notifications",
|
||||
"description": gettext("Allows to see printer notifications"),
|
||||
"default_groups": [USER_GROUP],
|
||||
"roles": ["show"]},
|
||||
{"key": "CLEAR",
|
||||
"name": "Clear printer notifications",
|
||||
"description": gettext("Allows to clear printer notifications"),
|
||||
"default_groups": [USER_GROUP],
|
||||
"roles": ["clear"]}
|
||||
]
|
||||
|
||||
#~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/action_command_notification.js"],
|
||||
clientjs=["clientjs/action_command_notification.js"],
|
||||
css=["css/action_command_notification.css"])
|
||||
return {"js": ["js/action_command_notification.js"],
|
||||
"clientjs": ["clientjs/action_command_notification.js"],
|
||||
"css": ["css/action_command_notification.css"]}
|
||||
|
||||
#~ EventHandlerPlugin
|
||||
|
||||
@@ -56,19 +56,19 @@ class ActionCommandNotificationPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(enable=True,
|
||||
enable_popups=False)
|
||||
return {"enable": True,
|
||||
"enable_popups": False}
|
||||
|
||||
#~ SimpleApiPlugin
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can():
|
||||
return flask.abort(403, "Insufficient permissions")
|
||||
return flask.jsonify(notifications=[dict(timestamp=notification[0],
|
||||
message=notification[1]) for notification in self._notifications])
|
||||
return flask.jsonify(notifications=[{"timestamp": notification[0],
|
||||
"message": notification[1]} for notification in self._notifications])
|
||||
|
||||
def get_api_commands(self):
|
||||
return dict(clear=[])
|
||||
return {"clear": []}
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if command == "clear":
|
||||
@@ -80,15 +80,15 @@ class ActionCommandNotificationPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings",
|
||||
name=gettext("Printer Notifications"),
|
||||
custom_bindings=False),
|
||||
dict(type="sidebar",
|
||||
name=gettext("Printer Notifications"),
|
||||
icon="bell-o",
|
||||
styles_wrapper=["display: none"],
|
||||
data_bind="visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
|
||||
" && settings.settings.plugins.action_command_notification.enable()")
|
||||
{"type": "settings",
|
||||
"name": gettext("Printer Notifications"),
|
||||
"custom_bindings": False},
|
||||
{"type": "sidebar",
|
||||
"name": gettext("Printer Notifications"),
|
||||
"icon": "bell-o",
|
||||
"styles_wrapper": ["display: none"],
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
|
||||
" && settings.settings.plugins.action_command_notification.enable()"}
|
||||
]
|
||||
|
||||
#~ action command handler
|
||||
@@ -109,13 +109,13 @@ class ActionCommandNotificationPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
message = parameter.strip()
|
||||
self._notifications.append((time.time(), message))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(message=message))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"message": message})
|
||||
|
||||
self._logger.info("Got a notification: {}".format(message))
|
||||
|
||||
def _clear_notifications(self):
|
||||
self._notifications = []
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict())
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {})
|
||||
self._logger.info("Notifications cleared")
|
||||
|
||||
__plugin_name__ = "Action Command Notification Support"
|
||||
|
||||
@@ -64,18 +64,18 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="INTERACT",
|
||||
name="Interact with printer prompts",
|
||||
description=gettext("Allows to see and interact with printer prompts"),
|
||||
default_groups=[USER_GROUP],
|
||||
roles=["interact"])
|
||||
{"key": "INTERACT",
|
||||
"name": "Interact with printer prompts",
|
||||
"description": gettext("Allows to see and interact with printer prompts"),
|
||||
"default_groups": [USER_GROUP],
|
||||
"roles": ["interact"]}
|
||||
]
|
||||
|
||||
#~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/action_command_prompt.js"],
|
||||
clientjs=["clientjs/action_command_prompt.js"])
|
||||
return {"js": ["js/action_command_prompt.js"],
|
||||
"clientjs": ["clientjs/action_command_prompt.js"]}
|
||||
|
||||
#~ EventHandlerPlugin
|
||||
|
||||
@@ -88,10 +88,10 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(enable="detected",
|
||||
command=self.COMMAND,
|
||||
enable_emergency_sending=True,
|
||||
enable_signal_support=True)
|
||||
return {"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)
|
||||
@@ -103,7 +103,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~ SimpleApiPlugin
|
||||
|
||||
def get_api_commands(self):
|
||||
return dict(select=["choice"])
|
||||
return {"select": ["choice"]}
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if command == "select":
|
||||
@@ -130,7 +130,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [dict(type="settings", name=gettext("Printer Dialogs"), custom_bindings=False)]
|
||||
return [{"type": "settings", "name": gettext("Printer Dialogs"), "custom_bindings": False}]
|
||||
|
||||
#~ action command handler
|
||||
|
||||
@@ -204,16 +204,16 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
|
||||
return
|
||||
|
||||
self._prompt.activate()
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(action="show",
|
||||
text=self._prompt.text,
|
||||
choices=self._prompt.choices))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"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"))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"action": "close"})
|
||||
|
||||
def _answer_prompt(self, choice):
|
||||
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
|
||||
|
||||
@@ -50,18 +50,18 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="READ",
|
||||
name="Read announcements",
|
||||
description=gettext("Allows to read announcements"),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["read"]),
|
||||
dict(key="MANAGE",
|
||||
name="Manage announcement subscriptions",
|
||||
description=gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" "
|
||||
"permission"),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["manage"],
|
||||
permissions=["PLUGIN_ANNOUNCEMENTS_READ"])
|
||||
{"key": "READ",
|
||||
"name": "Read announcements",
|
||||
"description": gettext("Allows to read announcements"),
|
||||
"default_groups": [ADMIN_GROUP],
|
||||
"roles": ["read"]},
|
||||
{"key": "MANAGE",
|
||||
"name": "Manage announcement subscriptions",
|
||||
"description": gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" "
|
||||
"permission"),
|
||||
"default_groups": [ADMIN_GROUP],
|
||||
"roles": ["manage"],
|
||||
"permissions": ["PLUGIN_ANNOUNCEMENTS_READ"]}
|
||||
]
|
||||
|
||||
# StartupPlugin
|
||||
@@ -78,37 +78,37 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
# SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
settings = dict(channels=dict(_important=dict(name="Important Announcements",
|
||||
description="Important announcements about OctoPrint.",
|
||||
priority=1,
|
||||
type="rss",
|
||||
url="https://octoprint.org/feeds/important.xml"),
|
||||
_releases=dict(name="Release Announcements",
|
||||
description="Announcements of new releases and release candidates of OctoPrint.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="https://octoprint.org/feeds/releases.xml"),
|
||||
_blog=dict(name="On the OctoBlog",
|
||||
description="Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="https://octoprint.org/feeds/octoblog.xml"),
|
||||
_plugins=dict(name="New Plugins in the Repository",
|
||||
description="Announcements of new plugins released on the official Plugin Repository.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="https://plugins.octoprint.org/feed.xml"),
|
||||
_octopi=dict(name="OctoPi News",
|
||||
description="News around OctoPi, the Raspberry Pi image including OctoPrint.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="https://octoprint.org/feeds/octopi.xml")),
|
||||
enabled_channels=[],
|
||||
forced_channels=["_important"],
|
||||
channel_order=["_important", "_releases", "_blog", "_plugins", "_octopi"],
|
||||
ttl=6*60,
|
||||
display_limit=3,
|
||||
summary_limit=300)
|
||||
settings = {"channels": {"_important": {"name": "Important Announcements",
|
||||
"description": "Important announcements about OctoPrint.",
|
||||
"priority": 1,
|
||||
"type": "rss",
|
||||
"url": "https://octoprint.org/feeds/important.xml"},
|
||||
"_releases": {"name": "Release Announcements",
|
||||
"description": "Announcements of new releases and release candidates of OctoPrint.",
|
||||
"priority": 2,
|
||||
"type": "rss",
|
||||
"url": "https://octoprint.org/feeds/releases.xml"},
|
||||
"_blog": {"name": "On the OctoBlog",
|
||||
"description": "Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.",
|
||||
"priority": 2,
|
||||
"type": "rss",
|
||||
"url": "https://octoprint.org/feeds/octoblog.xml"},
|
||||
"_plugins": {"name": "New Plugins in the Repository",
|
||||
"description": "Announcements of new plugins released on the official Plugin Repository.",
|
||||
"priority": 2,
|
||||
"type": "rss",
|
||||
"url": "https://plugins.octoprint.org/feed.xml"},
|
||||
"_octopi": {"name": "OctoPi News",
|
||||
"description": "News around OctoPi, the Raspberry Pi image including OctoPrint.",
|
||||
"priority": 2,
|
||||
"type": "rss",
|
||||
"url": "https://octoprint.org/feeds/octopi.xml"}},
|
||||
"enabled_channels": [],
|
||||
"forced_channels": ["_important"],
|
||||
"channel_order": ["_important", "_releases", "_blog", "_plugins", "_octopi"],
|
||||
"ttl": 6*60,
|
||||
"display_limit": 3,
|
||||
"summary_limit": 300}
|
||||
settings["enabled_channels"] = list(settings["channels"].keys())
|
||||
return settings
|
||||
|
||||
@@ -140,17 +140,21 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
# AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/announcements.js"],
|
||||
less=["less/announcements.less"],
|
||||
css=["css/announcements.css"])
|
||||
return {"js": ["js/announcements.js"],
|
||||
"less": ["less/announcements.less"],
|
||||
"css": ["css/announcements.css"]}
|
||||
|
||||
# Template Plugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings", name=gettext("Announcements"), template="announcements_settings.jinja2", custom_bindings=True),
|
||||
dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_READ)")
|
||||
]
|
||||
return [{"type": "settings",
|
||||
"name": gettext("Announcements"),
|
||||
"template": "announcements_settings.jinja2",
|
||||
"custom_bindings": True},
|
||||
{"type": "navbar",
|
||||
"template": "announcements_navbar.jinja2",
|
||||
"styles": ["display: none"],
|
||||
"data_bind": "visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_READ)"}]
|
||||
|
||||
# Blueprint Plugin
|
||||
|
||||
@@ -181,15 +185,15 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
last = entries[0]["published"]
|
||||
self._mark_read_until(key, last)
|
||||
|
||||
result.append(dict(key=key,
|
||||
channel=data["name"],
|
||||
url=data["url"],
|
||||
description=data.get("description", ""),
|
||||
priority=data.get("priority", 2),
|
||||
enabled=key in enabled or key in forced,
|
||||
forced=key in forced,
|
||||
data=entries,
|
||||
unread=unread))
|
||||
result.append({"key": key,
|
||||
"channel": data["name"],
|
||||
"url": data["url"],
|
||||
"description": data.get("description", ""),
|
||||
"priority": data.get("priority", 2),
|
||||
"enabled": key in enabled or key in forced,
|
||||
"forced": key in forced,
|
||||
"data": entries,
|
||||
"unread": unread})
|
||||
|
||||
return flask.jsonify(channels=result)
|
||||
|
||||
@@ -224,8 +228,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
from octoprint.server.util.flask import get_json_command_from_request
|
||||
from octoprint.server import NO_CONTENT
|
||||
|
||||
valid_commands = dict(read=["until"],
|
||||
toggle=[])
|
||||
valid_commands = {"read": ["until"],
|
||||
"toggle": []}
|
||||
|
||||
command, data, response = get_json_command_from_request(flask.request, valid_commands=valid_commands)
|
||||
if response is not None:
|
||||
@@ -263,8 +267,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
if channel_data:
|
||||
current_read_until = channel_data.get("read_until", None)
|
||||
|
||||
defaults = dict(plugins=dict(announcements=dict(channels=dict())))
|
||||
defaults["plugins"]["announcements"]["channels"][channel] = dict(read_until=current_read_until)
|
||||
defaults = {"plugins": {"announcements": {"channels": {}}}}
|
||||
defaults["plugins"]["announcements"]["channels"][channel] = {"read_until": current_read_until}
|
||||
|
||||
with self._cached_channel_configs_mutex:
|
||||
self._settings.set(["channels", channel, "read_until"], until, defaults=defaults)
|
||||
@@ -310,7 +314,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
return self._get_channel_configs(force=force).get(safe_key)
|
||||
|
||||
def _fetch_all_channels_async(self, force=False):
|
||||
thread = threading.Thread(target=self._fetch_all_channels, kwargs=dict(force=force))
|
||||
thread = threading.Thread(target=self._fetch_all_channels, kwargs={"force": force})
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
@@ -321,7 +325,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
enabled = self._settings.get(["enabled_channels"])
|
||||
forced = self._settings.get(["forced_channels"])
|
||||
|
||||
all_channels = dict()
|
||||
all_channels = {}
|
||||
for key, config in channels.items():
|
||||
if not key in enabled and not key in forced:
|
||||
continue
|
||||
@@ -424,13 +428,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
if read_until is not None:
|
||||
read = published <= read_until
|
||||
|
||||
return dict(title=entry["title"],
|
||||
title_without_tags=_strip_tags(entry["title"]),
|
||||
summary=_lazy_images(entry["summary"]),
|
||||
summary_without_images=_strip_images(entry["summary"]),
|
||||
published=published,
|
||||
link=utmify(entry["link"], source="octoprint", medium="announcements", content=OCTOPRINT_VERSION),
|
||||
read=read)
|
||||
return {"title": entry["title"],
|
||||
"title_without_tags": _strip_tags(entry["title"]),
|
||||
"summary": _lazy_images(entry["summary"]),
|
||||
"summary_without_images": _strip_images(entry["summary"]),
|
||||
"published": published,
|
||||
"link": utmify(entry["link"], source="octoprint", medium="announcements", content=OCTOPRINT_VERSION),
|
||||
"read": read}
|
||||
|
||||
def _get_channel_cache_path(self, key):
|
||||
"""Retrieve cache path for channel key."""
|
||||
|
||||
@@ -40,9 +40,9 @@ class PendingDecision(object):
|
||||
self.poll_timeout.start()
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
user_id=self.user_id,
|
||||
user_token=self.user_token)
|
||||
return {"app_id": self.app_id,
|
||||
"user_id": self.user_id,
|
||||
"user_token": self.user_token}
|
||||
|
||||
def __repr__(self):
|
||||
return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id,
|
||||
@@ -74,13 +74,13 @@ class ActiveKey(object):
|
||||
self.user_id = user_id
|
||||
|
||||
def external(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key,
|
||||
user_id=self.user_id)
|
||||
return {"app_id": self.app_id,
|
||||
"api_key": self.api_key,
|
||||
"user_id": self.user_id}
|
||||
|
||||
def internal(self):
|
||||
return dict(app_id=self.app_id,
|
||||
api_key=self.api_key)
|
||||
return {"app_id": self.app_id,
|
||||
"api_key": self.api_key}
|
||||
|
||||
@classmethod
|
||||
def for_internal(cls, internal, user_id):
|
||||
@@ -117,27 +117,27 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
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])
|
||||
{"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):
|
||||
return [dict(type="usersettings", name=gettext("Application Keys")),
|
||||
dict(type="settings", name=gettext("Application Keys"))]
|
||||
return [{"type": "usersettings", "name": gettext("Application Keys")},
|
||||
{"type": "settings", "name": gettext("Application Keys")}]
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/appkeys.js"],
|
||||
clientjs=["clientjs/appkeys.js"],
|
||||
less=["less/appkeys.less"],
|
||||
css=["css/appkeys.css"])
|
||||
return {"js": ["js/appkeys.js"],
|
||||
"clientjs": ["clientjs/appkeys.js"],
|
||||
"less": ["less/appkeys.less"],
|
||||
"css": ["css/appkeys.css"]}
|
||||
|
||||
##~~ BlueprintPlugin mixin
|
||||
|
||||
@@ -163,10 +163,10 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access",
|
||||
app_name=app_name,
|
||||
user_token=user_token,
|
||||
user_id=user_id))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"type": "request_access",
|
||||
"app_name": app_name,
|
||||
"user_token": user_token,
|
||||
"user_id": user_id})
|
||||
response = flask.jsonify(app_token=app_token)
|
||||
response.status_code = 201
|
||||
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
|
||||
@@ -204,10 +204,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
return flask.abort(404)
|
||||
|
||||
# Close access_request dialog for this request on all open OctoPrint connections
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"type": "end_request",
|
||||
"user_token": user_token})
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -217,8 +215,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
##~~ SimpleApiPlugin mixin
|
||||
|
||||
def get_api_commands(self):
|
||||
return dict(generate=["app"],
|
||||
revoke=["key"])
|
||||
return {"generate": ["app"],
|
||||
"revoke": ["key"]}
|
||||
|
||||
def on_api_get(self, request):
|
||||
user_id = current_user.get_name()
|
||||
@@ -309,10 +307,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
len_after = len(self._pending_decisions)
|
||||
|
||||
if len_after < len_before:
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(
|
||||
type="end_request",
|
||||
user_token=user_token
|
||||
))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"type": "end_request",
|
||||
"user_token": user_token})
|
||||
|
||||
def _remove_stale_pending(self):
|
||||
with self._pending_lock:
|
||||
@@ -427,7 +423,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def _save_keys(self):
|
||||
with self._keys_lock:
|
||||
to_persist = dict()
|
||||
to_persist = {}
|
||||
for user_id, keys in self._keys.items():
|
||||
to_persist[user_id] = [x.internal() for x in keys]
|
||||
|
||||
|
||||
@@ -78,12 +78,12 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="ACCESS",
|
||||
name="Backup access",
|
||||
description=gettext("Allows access to backups and restores"),
|
||||
roles=["access"],
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
{"key": "ACCESS",
|
||||
"name": "Backup access",
|
||||
"description": gettext("Allows access to backups and restores"),
|
||||
"roles": ["access"],
|
||||
"dangerous": True,
|
||||
"default_groups": [ADMIN_GROUP]}
|
||||
]
|
||||
|
||||
# Socket emit hook
|
||||
@@ -110,16 +110,16 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/backup.js"],
|
||||
clientjs=["clientjs/backup.js"],
|
||||
css=["css/backup.css"],
|
||||
less=["less/backup.less"])
|
||||
return {"js": ["js/backup.js"],
|
||||
"clientjs": ["clientjs/backup.js"],
|
||||
"css": ["css/backup.css"],
|
||||
"less": ["less/backup.less"]}
|
||||
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [dict(type="settings", name=gettext("Backup & Restore")),
|
||||
dict(type="wizard", name=gettext("Restore Backup?"))]
|
||||
return [{"type": "settings", "name": gettext("Backup & Restore")},
|
||||
{"type": "wizard", "name": gettext("Restore Backup?")}]
|
||||
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@@ -175,19 +175,19 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.append(name)
|
||||
self._send_client_message("backup_started", payload=dict(name=name))
|
||||
self._send_client_message("backup_started", payload={"name": name})
|
||||
|
||||
def on_backup_done(name, final_path, exclude):
|
||||
with self._in_progress_lock:
|
||||
self._in_progress.remove(name)
|
||||
self._send_client_message("backup_done", payload=dict(name=name))
|
||||
self._send_client_message("backup_done", payload={"name": name})
|
||||
|
||||
self._logger.info("... done creating backup zip.")
|
||||
|
||||
self._event_bus.fire(Events.PLUGIN_BACKUP_BACKUP_CREATED,
|
||||
dict(name=name,
|
||||
path=final_path,
|
||||
excludes=exclude))
|
||||
{"name": name,
|
||||
"path": final_path,
|
||||
"excludes": exclude})
|
||||
|
||||
def on_backup_error(name, exc_info):
|
||||
with self._in_progress_lock:
|
||||
@@ -197,20 +197,20 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
# we'll ignore that
|
||||
pass
|
||||
|
||||
self._send_client_message("backup_error", payload=dict(name=name,
|
||||
error="{}".format(exc_info[1])))
|
||||
self._send_client_message("backup_error", payload={"name": name,
|
||||
"error": "{}".format(exc_info[1])})
|
||||
self._logger.error("Error while creating backup zip", exc_info=exc_info)
|
||||
|
||||
thread = threading.Thread(target=self._create_backup,
|
||||
args=(backup_file,),
|
||||
kwargs=dict(exclude=exclude,
|
||||
settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
logger=self._logger,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_backup_start=on_backup_start,
|
||||
on_backup_done=on_backup_done,
|
||||
on_backup_error=on_backup_error))
|
||||
kwargs={"exclude": exclude,
|
||||
"settings": self._settings,
|
||||
"plugin_manager": self._plugin_manager,
|
||||
"logger": self._logger,
|
||||
"datafolder": self.get_plugin_data_folder(),
|
||||
"on_backup_start": on_backup_start,
|
||||
"on_backup_done": on_backup_done,
|
||||
"on_backup_error": on_backup_error})
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
@@ -268,7 +268,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
def on_log(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", dict(line=line, type="stdout"))
|
||||
self._send_client_message("logline", {"line": line, "type": "stdout"})
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
|
||||
@@ -284,34 +284,34 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
elif not os_compatible:
|
||||
self._logger.warning("Cannot install plugin {}, it is incompatible to the underlying "
|
||||
"operating system".format(plugin["id"]))
|
||||
self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"],
|
||||
octoprint_compatible=octoprint_compatible,
|
||||
os_compatible=os_compatible))
|
||||
self._send_client_message("plugin_incompatible", {"plugin": plugin["id"],
|
||||
"octoprint_compatible": octoprint_compatible,
|
||||
"os_compatible": os_compatible})
|
||||
continue
|
||||
|
||||
self._logger.info("Installing plugin {}".format(plugin["id"]))
|
||||
self._send_client_message("installing_plugin", dict(plugin=plugin["id"]))
|
||||
self._send_client_message("installing_plugin", {"plugin": plugin["id"]})
|
||||
self.__class__._install_plugin(plugin,
|
||||
force_user=force_user,
|
||||
pip_args=pip_args,
|
||||
on_log=on_log)
|
||||
|
||||
def on_report_unknown_plugins(plugins):
|
||||
self._send_client_message("unknown_plugins", payload=dict(plugins=plugins))
|
||||
self._send_client_message("unknown_plugins", payload={"plugins": plugins})
|
||||
|
||||
def on_log_progress(line):
|
||||
self._logger.info(line)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stdout"))
|
||||
self._send_client_message("logline", payload={"line": line, "stream": "stdout"})
|
||||
|
||||
def on_log_error(line, exc_info=None):
|
||||
self._logger.error(line, exc_info=exc_info)
|
||||
self._send_client_message("logline", payload=dict(line=line, stream="stderr"))
|
||||
self._send_client_message("logline", payload={"line": line, "stream": "stderr"})
|
||||
|
||||
if exc_info is not None:
|
||||
exc_type, exc_value, exc_tb = exc_info
|
||||
output = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
for line in output:
|
||||
self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr"))
|
||||
self._send_client_message("logline", payload={"line": line.rstrip(), "stream": "stderr"})
|
||||
|
||||
def on_restore_start(path):
|
||||
self._send_client_message("restore_started")
|
||||
@@ -333,17 +333,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
# noinspection PyTypeChecker
|
||||
thread = threading.Thread(target=self._restore_backup,
|
||||
args=(path,),
|
||||
kwargs=dict(settings=self._settings,
|
||||
plugin_manager=self._plugin_manager,
|
||||
datafolder=self.get_plugin_data_folder(),
|
||||
on_install_plugins=on_install_plugins,
|
||||
on_report_unknown_plugins=on_report_unknown_plugins,
|
||||
on_invalid_backup=on_invalid_backup,
|
||||
on_log_progress=on_log_progress,
|
||||
on_log_error=on_log_error,
|
||||
on_restore_start=on_restore_start,
|
||||
on_restore_done=on_restore_done,
|
||||
on_restore_failed=on_restore_failed))
|
||||
kwargs={"settings": self._settings,
|
||||
"plugin_manager": self._plugin_manager,
|
||||
"datafolder": self.get_plugin_data_folder(),
|
||||
"on_install_plugins": on_install_plugins,
|
||||
"on_report_unknown_plugins": on_report_unknown_plugins,
|
||||
"on_invalid_backup": on_invalid_backup,
|
||||
"on_log_progress": on_log_progress,
|
||||
"on_log_error": on_log_error,
|
||||
"on_restore_start": on_restore_start,
|
||||
"on_restore_done": on_restore_done,
|
||||
"on_restore_failed": on_restore_failed})
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
@@ -358,7 +358,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
return self._settings.global_get(["server", "firstRun"]) and is_os_compatible(["!windows"])
|
||||
|
||||
def get_wizard_details(self):
|
||||
return dict(required=self.is_wizard_required())
|
||||
return {"required": self.is_wizard_required()}
|
||||
|
||||
##~~ tornado hook
|
||||
|
||||
@@ -370,11 +370,11 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
from octoprint.server.util.flask import admin_validator
|
||||
|
||||
return [
|
||||
(r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(),
|
||||
as_attachment=True,
|
||||
path_validation=path_validation_factory(lambda path: not is_hidden_path(path),
|
||||
status_code=404),
|
||||
access_validation=access_validation_factory(app, admin_validator)))
|
||||
(r"/download/(.*)", LargeResponseHandler, {"path": self.get_plugin_data_folder(),
|
||||
"as_attachment": True,
|
||||
"path_validation": path_validation_factory(lambda path: not is_hidden_path(path),
|
||||
status_code=404),
|
||||
"access_validation": access_validation_factory(app, admin_validator)})
|
||||
]
|
||||
|
||||
def bodysize_hook(self, current_max_body_sizes, *args, **kwargs):
|
||||
@@ -436,7 +436,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
# register plugin manager plugin setting overlays
|
||||
plugin_info = plugin_manager.get_plugin_info("pluginmanager")
|
||||
if plugin_info and plugin_info.implementation:
|
||||
default_settings_overlay = dict(plugins=dict())
|
||||
default_settings_overlay = {"plugins": {}}
|
||||
default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults()
|
||||
settings.add_overlay(default_settings_overlay, at_end=True)
|
||||
|
||||
@@ -534,10 +534,10 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
if not entry.name.endswith(".zip"):
|
||||
continue
|
||||
|
||||
backups.append(dict(name=entry.name,
|
||||
date=entry.stat().st_mtime,
|
||||
size=entry.stat().st_size,
|
||||
url=flask.url_for("index") + "plugin/backup/download/" + entry.name))
|
||||
backups.append({"name": entry.name,
|
||||
"date": entry.stat().st_mtime,
|
||||
"size": entry.stat().st_size,
|
||||
"url": flask.url_for("index") + "plugin/backup/download/" + entry.name})
|
||||
return backups
|
||||
|
||||
def _get_unknown_plugins(self):
|
||||
@@ -617,7 +617,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
r.raise_for_status()
|
||||
except Exception:
|
||||
logger.exception("Error while fetching the plugin repository data from {}".format(url))
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
from octoprint.plugins.pluginmanager import map_repository_entry
|
||||
return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json()))
|
||||
@@ -702,7 +702,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
except Exception:
|
||||
logger.exception("Error while retrieving additional excludes "
|
||||
"from plugin {name}".format(**locals()),
|
||||
extra=dict(plugin=plugin))
|
||||
extra={"plugin": plugin})
|
||||
|
||||
configfile = settings._configfile
|
||||
basedir = settings._basedir
|
||||
@@ -747,8 +747,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
zip.write(source, arcname=target)
|
||||
|
||||
# add metadata
|
||||
metadata = dict(version=get_octoprint_version_string(),
|
||||
excludes=exclude)
|
||||
metadata = {"version": get_octoprint_version_string(),
|
||||
"excludes": exclude}
|
||||
zip.writestr("metadata.json", json.dumps(metadata))
|
||||
|
||||
# backup current config file
|
||||
@@ -774,9 +774,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
# ignore anything bundled or from the plugins folder we already include in the backup
|
||||
continue
|
||||
|
||||
plugins.append(dict(key=plugin.key,
|
||||
name=plugin.name,
|
||||
url=plugin.url))
|
||||
plugins.append({"key": plugin.key,
|
||||
"name": plugin.name,
|
||||
"url": plugin.url})
|
||||
|
||||
if len(plugins):
|
||||
zip.writestr("plugin_list.json", json.dumps(plugins))
|
||||
@@ -822,7 +822,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
cls._clean_dir_backup(basedir,
|
||||
on_log_progress=on_log_progress)
|
||||
|
||||
plugin_repo = dict()
|
||||
plugin_repo = {}
|
||||
repo_url = settings.global_get(["plugins", "pluginmanager", "repository"])
|
||||
if repo_url:
|
||||
plugin_repo = cls._get_plugin_repository_data(repo_url)
|
||||
@@ -892,7 +892,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
with io.open(configfile, "rt", encoding="utf-8") as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
|
||||
if configdata.get("accessControl", dict()).get("enabled", True):
|
||||
if configdata.get("accessControl", {}).get("enabled", True):
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
if callable(on_invalid_backup):
|
||||
@@ -1006,7 +1006,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
# restart server
|
||||
if not restart_command:
|
||||
restart_command = configdata.get("server", dict()).get("commands", dict()).get("serverRestartCommand")
|
||||
restart_command = configdata.get("server", {}).get("commands", {}).get("serverRestartCommand")
|
||||
|
||||
if restart_command:
|
||||
import sarge
|
||||
@@ -1042,7 +1042,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
def _send_client_message(self, message, payload=None):
|
||||
if payload is None:
|
||||
payload = dict()
|
||||
payload = {}
|
||||
payload["type"] = message
|
||||
self._plugin_manager.send_plugin_message(self._identifier, payload)
|
||||
|
||||
|
||||
@@ -46,11 +46,11 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
if not name:
|
||||
continue
|
||||
|
||||
config = dict(type="wizard",
|
||||
name=name,
|
||||
template="corewizard_{}_wizard.jinja2".format(key),
|
||||
div="wizard_plugin_corewizard_{}".format(key),
|
||||
suffix="_{}".format(key))
|
||||
config = {"type": "wizard",
|
||||
"name": name,
|
||||
"template": "corewizard_{}_wizard.jinja2".format(key),
|
||||
"div": "wizard_plugin_corewizard_{}".format(key),
|
||||
"suffix": "_{}".format(key)}
|
||||
if key in additional:
|
||||
additional_result = additional[key]()
|
||||
if additional_result:
|
||||
@@ -63,12 +63,10 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def get_assets(self):
|
||||
if self.is_wizard_required():
|
||||
return dict(
|
||||
js=["js/corewizard.js"],
|
||||
css=["css/corewizard.css"]
|
||||
)
|
||||
return {"js": ["js/corewizard.js"],
|
||||
"css": ["css/corewizard.css"]}
|
||||
else:
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
#~~ WizardPlugin API
|
||||
|
||||
@@ -85,7 +83,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
return any_required
|
||||
|
||||
def get_wizard_details(self):
|
||||
result = dict()
|
||||
result = {}
|
||||
|
||||
def add_result(key, method):
|
||||
result[key] = method()
|
||||
@@ -99,7 +97,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~~ helpers
|
||||
|
||||
def _get_subwizard_attrs(self, start, end, callback=None):
|
||||
result = dict()
|
||||
result = {}
|
||||
|
||||
for item in dir(self):
|
||||
if not item.startswith(start) or not item.endswith(end):
|
||||
|
||||
@@ -25,7 +25,7 @@ class ServerCommandsSubwizard(object):
|
||||
return not (system_shutdown_command and system_restart_command and server_restart_command)
|
||||
|
||||
def _get_servercommands_wizard_details(self):
|
||||
return dict(required=self._is_servercommands_wizard_required())
|
||||
return {"required": self._is_servercommands_wizard_required()}
|
||||
|
||||
def _get_servercommands_wizard_name(self):
|
||||
return gettext("Server Commands")
|
||||
@@ -44,7 +44,7 @@ class WebcamSubwizard(object):
|
||||
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
|
||||
|
||||
def _get_webcam_wizard_details(self):
|
||||
return dict(required=self._is_webcam_wizard_required())
|
||||
return {"required": self._is_webcam_wizard_required()}
|
||||
|
||||
def _get_webcam_wizard_name(self):
|
||||
return gettext("Webcam & Timelapse")
|
||||
@@ -59,13 +59,13 @@ class AclSubwizard(object):
|
||||
return self._user_manager.enabled and not self._user_manager.has_been_customized()
|
||||
|
||||
def _get_acl_wizard_details(self):
|
||||
return dict(required=self._is_acl_wizard_required())
|
||||
return {"required": self._is_acl_wizard_required()}
|
||||
|
||||
def _get_acl_wizard_name(self):
|
||||
return gettext("Access Control")
|
||||
|
||||
def _get_acl_additional_wizard_template_data(self):
|
||||
return dict(mandatory=self._is_acl_wizard_required())
|
||||
return {"mandatory": self._is_acl_wizard_required()}
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
|
||||
def acl_wizard_api(self):
|
||||
@@ -104,13 +104,13 @@ class OnlineCheckSubwizard(object):
|
||||
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
|
||||
|
||||
def _get_onlinecheck_wizard_details(self):
|
||||
return dict(required=self._is_onlinecheck_wizard_required())
|
||||
return {"required": self._is_onlinecheck_wizard_required()}
|
||||
|
||||
def _get_onlinecheck_wizard_name(self):
|
||||
return gettext("Online Connectivity Check")
|
||||
|
||||
def _get_onlinecheck_additional_wizard_template_data(self):
|
||||
return dict(mandatory=self._is_onlinecheck_wizard_required())
|
||||
return {"mandatory": self._is_onlinecheck_wizard_required()}
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
@@ -122,13 +122,13 @@ class PluginBlacklistSubwizard(object):
|
||||
return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None
|
||||
|
||||
def _get_pluginblacklist_wizard_details(self):
|
||||
return dict(required=self._is_pluginblacklist_wizard_required())
|
||||
return {"required": self._is_pluginblacklist_wizard_required()}
|
||||
|
||||
def _get_pluginblacklist_wizard_name(self):
|
||||
return gettext("Plugin Blacklist")
|
||||
|
||||
def _get_pluginblacklist_additional_wizard_template_data(self):
|
||||
return dict(mandatory=self._is_pluginblacklist_wizard_required())
|
||||
return {"mandatory": self._is_pluginblacklist_wizard_required()}
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
@@ -140,7 +140,7 @@ class PrinterProfileSubwizard(object):
|
||||
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
|
||||
|
||||
def _get_printerprofile_wizard_details(self):
|
||||
return dict(required=self._is_printerprofile_wizard_required())
|
||||
return {"required": self._is_printerprofile_wizard_required()}
|
||||
|
||||
def _get_printerprofile_wizard_name(self):
|
||||
return gettext("Default Printer Profile")
|
||||
@@ -149,4 +149,4 @@ class PrinterProfileSubwizard(object):
|
||||
Subwizards = type(to_native_str("Subwizards"),
|
||||
tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
|
||||
if clsname.endswith("Subwizard")),
|
||||
dict())
|
||||
{})
|
||||
@@ -40,12 +40,10 @@ def __plugin_load__():
|
||||
__plugin_implementation__ = plugin
|
||||
|
||||
global __plugin_helpers__
|
||||
__plugin_helpers__ = dict(
|
||||
ssdp_browse=plugin.ssdp_browse,
|
||||
zeroconf_browse = plugin.zeroconf_browse,
|
||||
zeroconf_register = plugin.zeroconf_register,
|
||||
zeroconf_unregister = plugin.zeroconf_unregister
|
||||
)
|
||||
__plugin_helpers__ = {"ssdp_browse": plugin.ssdp_browse,
|
||||
"zeroconf_browse": plugin.zeroconf_browse,
|
||||
"zeroconf_register": plugin.zeroconf_register,
|
||||
"zeroconf_unregister": plugin.zeroconf_unregister}
|
||||
|
||||
class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.ShutdownPlugin,
|
||||
@@ -315,7 +313,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
address,
|
||||
p))
|
||||
|
||||
return dict(name=n, host=address, port=p, txt_record=info.properties)
|
||||
return {"name": n,
|
||||
"host": address,
|
||||
"port": p,
|
||||
"txt_record": info.properties}
|
||||
|
||||
for address in map(lambda x: socket.inet_ntoa(x), info.addresses):
|
||||
result.append(to_result(info, address))
|
||||
@@ -472,12 +473,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
username = self._settings.get(["httpUsername"])
|
||||
password = self._settings.get(["httpPassword"])
|
||||
|
||||
entries = dict(
|
||||
path=path
|
||||
)
|
||||
entries = {"path": path}
|
||||
|
||||
if username and password:
|
||||
entries.update(dict(u=username, p=password))
|
||||
entries.update({"u": username, "p": password})
|
||||
|
||||
return entries
|
||||
|
||||
@@ -527,7 +526,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
self._ssdp_monitor_active = True
|
||||
|
||||
self._ssdp_monitor_thread = threading.Thread(target=self._ssdp_monitor, kwargs=dict(timeout=self._ssdp_notify_timeout))
|
||||
self._ssdp_monitor_thread = threading.Thread(target=self._ssdp_monitor,
|
||||
kwargs={"timeout": self._ssdp_notify_timeout})
|
||||
self._ssdp_monitor_thread.daemon = True
|
||||
self._ssdp_monitor_thread.start()
|
||||
|
||||
|
||||
@@ -16,11 +16,11 @@ from flask_babel import gettext
|
||||
SENTRY_URL_SERVER = "https://d479a74f172d4ac2b959a9a7d0536a82@o118517.ingest.sentry.io/1373987"
|
||||
SENTRY_URL_COREUI = "https://040577fb88b241ff985e408c11775720@o118517.ingest.sentry.io/1374096"
|
||||
|
||||
SETTINGS_DEFAULTS = dict(enabled=False,
|
||||
enabled_unreleased=False,
|
||||
unique_id=None,
|
||||
url_server=SENTRY_URL_SERVER,
|
||||
url_coreui=SENTRY_URL_COREUI)
|
||||
SETTINGS_DEFAULTS = {"enabled": False,
|
||||
"enabled_unreleased": False,
|
||||
"unique_id": None,
|
||||
"url_server": SENTRY_URL_SERVER,
|
||||
"url_coreui": SENTRY_URL_COREUI}
|
||||
|
||||
import serial
|
||||
import requests.exceptions
|
||||
@@ -67,24 +67,23 @@ class ErrorTrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin):
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings",
|
||||
name=gettext("Error Tracking"),
|
||||
template="errortracking_settings.jinja2",
|
||||
custom_bindings=False),
|
||||
dict(type="generic", template="errortracking_javascripts.jinja2")
|
||||
]
|
||||
return [{"type": "settings",
|
||||
"name": gettext("Error Tracking"),
|
||||
"template": "errortracking_settings.jinja2",
|
||||
"custom_bindings": False},
|
||||
{"type": "generic",
|
||||
"template": "errortracking_javascripts.jinja2"}]
|
||||
|
||||
def get_template_vars(self):
|
||||
enabled = self._settings.get_boolean(["enabled"])
|
||||
enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"])
|
||||
|
||||
return dict(enabled=_is_enabled(enabled, enabled_unreleased),
|
||||
unique_id=self._settings.get(["unique_id"]),
|
||||
url_coreui=self._settings.get(["url_coreui"]))
|
||||
return {"enabled": _is_enabled(enabled, enabled_unreleased),
|
||||
"unique_id": self._settings.get(["unique_id"]),
|
||||
"url_coreui": self._settings.get(["url_coreui"])}
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/sentry.min.js", "js/errortracking.js"])
|
||||
return {"js": ["js/sentry.min.js", "js/errortracking.js"]}
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return SETTINGS_DEFAULTS
|
||||
@@ -119,7 +118,7 @@ def _enable_errortracking():
|
||||
version = get_octoprint_version_string()
|
||||
|
||||
s = settings()
|
||||
plugin_defaults = dict(plugins=dict(errortracking=SETTINGS_DEFAULTS))
|
||||
plugin_defaults = {"plugins": {"errortracking": SETTINGS_DEFAULTS}}
|
||||
|
||||
enabled = s.getBoolean(["plugins", "errortracking", "enabled"], defaults=plugin_defaults)
|
||||
enabled_unreleased = s.getBoolean(["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults)
|
||||
@@ -142,8 +141,8 @@ def _enable_errortracking():
|
||||
|
||||
handled = True
|
||||
logger = event.get("logger", "")
|
||||
plugin = event.get("extra", dict()).get("plugin", None)
|
||||
callback = event.get("extra", dict()).get("callback", None)
|
||||
plugin = event.get("extra", {}).get("plugin", None)
|
||||
callback = event.get("extra", {}).get("callback", None)
|
||||
|
||||
for ignore in IGNORED_EXCEPTIONS:
|
||||
if isinstance(ignore, tuple):
|
||||
@@ -192,7 +191,7 @@ def _enable_errortracking():
|
||||
before_send=_before_send)
|
||||
|
||||
with sentry_sdk.configure_scope() as scope:
|
||||
scope.user = dict(id=unique_id)
|
||||
scope.user = {"id": unique_id}
|
||||
|
||||
logging.getLogger("octoprint.plugins.errortracking").info("Initialized error tracking")
|
||||
_enabled = True
|
||||
|
||||
@@ -19,27 +19,27 @@ class GcodeviewerPlugin(octoprint.plugin.AssetPlugin,
|
||||
"js/viewer/renderer.js"
|
||||
]
|
||||
|
||||
return dict(js=js,
|
||||
less=["less/gcodeviewer.less"],
|
||||
css=["css/gcodeviewer.css"])
|
||||
return {"js": js,
|
||||
"less": ["less/gcodeviewer.less"],
|
||||
"css": ["css/gcodeviewer.css"]}
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="tab",
|
||||
template="gcodeviewer_tab.jinja2",
|
||||
div="gcode",
|
||||
styles=["display: none;"],
|
||||
data_bind="visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)"),
|
||||
dict(type="settings",
|
||||
template="gcodeviewer_settings.jinja2",
|
||||
custom_bindings=True),
|
||||
dict(type="generic",
|
||||
template="gcodeviewer_initscript.jinja2")
|
||||
{"type": "tab",
|
||||
"template": "gcodeviewer_tab.jinja2",
|
||||
"div": "gcode",
|
||||
"styles": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)"},
|
||||
{"type": "settings",
|
||||
"template": "gcodeviewer_settings.jinja2",
|
||||
"custom_bindings": True},
|
||||
{"type": "generic",
|
||||
"template": "gcodeviewer_initscript.jinja2"}
|
||||
]
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(mobileSizeThreshold=2 * 1024 * 1024, # 2MB
|
||||
sizeThreshold=20 * 1024 * 1024) # 20MB
|
||||
return {"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
|
||||
"sizeThreshold": 20 * 1024 * 1024} # 20MB
|
||||
|
||||
def get_settings_version(self):
|
||||
return 1
|
||||
|
||||
@@ -36,11 +36,11 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="MANAGE",
|
||||
name="Logging management",
|
||||
description=gettext("Allows to download and delete log files and list and set log levels."),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["manage"])
|
||||
{"key": "MANAGE",
|
||||
"name": "Logging management",
|
||||
"description": gettext("Allows to download and delete log files and list and set log levels."),
|
||||
"default_groups": [ADMIN_GROUP],
|
||||
"roles": ["manage"]}
|
||||
]
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@@ -53,10 +53,10 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
levels = self._get_logging_levels()
|
||||
serial_log_enabled = self._settings.global_get_boolean(["serial", "log"])
|
||||
plugintimings_log_enabled = self._settings.global_get_boolean(["devel", "pluginTimings"])
|
||||
return jsonify(logs=dict(files=files, free=free, total=total),
|
||||
setup=dict(loggers=loggers, levels=levels),
|
||||
serial_log=dict(enabled=serial_log_enabled),
|
||||
plugintimings_log=dict(enabled=plugintimings_log_enabled))
|
||||
return jsonify(logs={"files": files, "free": free, "total": total},
|
||||
setup={"loggers": loggers, "levels": levels},
|
||||
serial_log={"enabled": serial_log_enabled},
|
||||
plugintimings_log={"enabled": plugintimings_log_enabled})
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@@ -162,10 +162,10 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
def _get_logging_levels(self):
|
||||
config = self._get_logging_config()
|
||||
if config is None or not isinstance(config, dict):
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
return dict((key, value.get("level"))
|
||||
for key, value in config.get("loggers", dict()).items()
|
||||
for key, value in config.get("loggers", {}).items()
|
||||
if isinstance(value, dict) and "level" in value)
|
||||
|
||||
def _set_logging_levels(self, new_levels):
|
||||
@@ -188,12 +188,12 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
for component in purge:
|
||||
del config["loggers"][component]
|
||||
else:
|
||||
config["loggers"] = dict()
|
||||
config["loggers"] = {}
|
||||
|
||||
# update all logging levels
|
||||
for logger, level in new_levels.items():
|
||||
if logger not in config["loggers"]:
|
||||
config["loggers"][logger] = dict()
|
||||
config["loggers"][logger] = {}
|
||||
config["loggers"][logger]["level"] = level
|
||||
|
||||
# delete empty entries
|
||||
@@ -214,17 +214,20 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return logger and (logger.startswith("octoprint") or logger.startswith("tornado"))
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="navbar", template="logging_navbar_seriallog.jinja2", suffix="_seriallog"),
|
||||
dict(type="navbar", template="logging_navbar_plugintimingslog.jinja2", suffix="_plugintimingslog"),
|
||||
dict(type="settings", custom_bindings=True)
|
||||
]
|
||||
return [{"type": "navbar",
|
||||
"template": "logging_navbar_seriallog.jinja2",
|
||||
"suffix": "_seriallog"},
|
||||
{"type": "navbar",
|
||||
"template": "logging_navbar_plugintimingslog.jinja2",
|
||||
"suffix": "_plugintimingslog"},
|
||||
{"type": "settings",
|
||||
"custom_bindings": True}]
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/logging.js"],
|
||||
clientjs=["clientjs/logging.js"],
|
||||
less=["less/logging.less"],
|
||||
css=["css/logging.css"])
|
||||
return {"js": ["js/logging.js"],
|
||||
"clientjs": ["clientjs/logging.js"],
|
||||
"less": ["less/logging.less"],
|
||||
"css": ["css/logging.css"]}
|
||||
|
||||
__plugin_name__ = "Logging"
|
||||
__plugin_author__ = "Shawn Bruce, based on work by Gina Häußge and Marc Hannappel"
|
||||
|
||||
@@ -57,13 +57,13 @@ class ThrottleState(object):
|
||||
if value == 0:
|
||||
return ThrottleState()
|
||||
|
||||
kwargs = dict(undervoltage=_FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE,
|
||||
freq_capped=_FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED,
|
||||
throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED,
|
||||
past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
|
||||
past_freq_capped=_FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
|
||||
past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
|
||||
raw_value=value)
|
||||
kwargs = {"undervoltage": _FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE,
|
||||
"freq_capped": _FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED,
|
||||
"throttled": _FLAG_THROTTLED & value == _FLAG_THROTTLED,
|
||||
"past_undervoltage": _FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
|
||||
"past_freq_capped": _FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
|
||||
"past_throttled": _FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
|
||||
"raw_value": value}
|
||||
return ThrottleState(**kwargs)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
@@ -128,13 +128,13 @@ class ThrottleState(object):
|
||||
and self._past_throttled == other._past_throttled
|
||||
|
||||
def as_dict(self):
|
||||
return dict(raw_value=self._raw_value,
|
||||
current_undervoltage=self.current_undervoltage,
|
||||
past_undervoltage=self.past_undervoltage,
|
||||
current_overheat=self.current_overheat,
|
||||
past_overheat=self.past_overheat,
|
||||
current_issue=self.current_issue,
|
||||
past_issue=self.past_issue)
|
||||
return {"raw_value": self._raw_value,
|
||||
"current_undervoltage": self.current_undervoltage,
|
||||
"past_undervoltage": self.past_undervoltage,
|
||||
"current_overheat": self.current_overheat,
|
||||
"past_overheat": self.past_overheat,
|
||||
"current_issue": self.current_issue,
|
||||
"past_issue": self.past_issue}
|
||||
|
||||
|
||||
_proc_dt_model = None
|
||||
@@ -195,21 +195,19 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="STATUS",
|
||||
name="Status",
|
||||
description=gettext("Allows to check for the Pi's throttling status and environment info"),
|
||||
roles=["check"],
|
||||
default_groups=[USER_GROUP])
|
||||
]
|
||||
return [{"key": "STATUS",
|
||||
"name": "Status",
|
||||
"description": gettext("Allows to check for the Pi's throttling status and environment info"),
|
||||
"roles": ["check"],
|
||||
"default_groups": [USER_GROUP]}]
|
||||
|
||||
#~~ EnvironmentDetectionPlugin
|
||||
|
||||
def get_additional_environment(self):
|
||||
result = dict(model=get_proc_dt_model())
|
||||
result = {"model": get_proc_dt_model()}
|
||||
|
||||
if is_octopi():
|
||||
result.update(dict(octopi_version=get_octopi_version()))
|
||||
result.update({"octopi_version": get_octopi_version()})
|
||||
|
||||
return result
|
||||
|
||||
@@ -218,26 +216,29 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
def on_api_get(self, request):
|
||||
if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can():
|
||||
return flask.abort(403)
|
||||
result = dict(throttle_state=self._throttle_state.as_dict())
|
||||
result = {"throttle_state": self._throttle_state.as_dict()}
|
||||
result.update(self.get_additional_environment())
|
||||
return flask.jsonify(**result)
|
||||
|
||||
#~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/pi_support.js"],
|
||||
clientjs=["clientjs/pi_support.js"],
|
||||
css=["css/pi_support.css"]
|
||||
)
|
||||
return {"js": ["js/pi_support.js"],
|
||||
"clientjs": ["clientjs/pi_support.js"],
|
||||
"css": ["css/pi_support.css"]}
|
||||
|
||||
#~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
configs = [dict(type="settings", name=gettext("Pi Support"), template="pi_support_settings.jinja2", custom_bindings=False)]
|
||||
configs = [{"type": "settings",
|
||||
"name": gettext("Pi Support"),
|
||||
"template": "pi_support_settings.jinja2",
|
||||
"custom_bindings": False}]
|
||||
|
||||
if is_octopi():
|
||||
configs.append(dict(type="about", name="About OctoPi", template="pi_support_about_octopi.jinja2"))
|
||||
configs.append({"type": "about",
|
||||
"name": "About OctoPi",
|
||||
"template": "pi_support_about_octopi.jinja2"})
|
||||
|
||||
return configs
|
||||
|
||||
@@ -257,11 +258,11 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
#~~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(vcgencmd_throttle_check_enabled=True,
|
||||
vcgencmd_throttle_check_command=_VCGENCMD_THROTTLE)
|
||||
return {"vcgencmd_throttle_check_enabled": True,
|
||||
"vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE}
|
||||
|
||||
def get_settings_restricted_paths(self):
|
||||
return dict(admin=[["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]])
|
||||
return {"admin": [["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]]}
|
||||
|
||||
#~~ Helpers
|
||||
|
||||
@@ -318,8 +319,8 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
|
||||
|
||||
self._logger.warning(message)
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
|
||||
state=self._throttle_state.as_dict()))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"type": "throttle_state",
|
||||
"state": self._throttle_state.as_dict()})
|
||||
|
||||
# noinspection PyUnresolvedReferences
|
||||
self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict())
|
||||
@@ -360,4 +361,4 @@ def __plugin_load__():
|
||||
}
|
||||
|
||||
global __plugin_helpers__
|
||||
__plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state)
|
||||
__plugin_helpers__ = {"get_throttled": plugin.get_throttle_state}
|
||||
@@ -58,11 +58,9 @@ def map_repository_entry(entry):
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
result["is_compatible"] = dict(
|
||||
octoprint=True,
|
||||
os=True,
|
||||
python=True
|
||||
)
|
||||
result["is_compatible"] = {"octoprint": True,
|
||||
"os": True,
|
||||
"python": True}
|
||||
|
||||
if "compatibility" in entry:
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(
|
||||
@@ -105,12 +103,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
"svn", "svn+svn", "svn+http", "svn+https", "svn+ssh",
|
||||
"bzr+http", "bzr+https", "bzr+ssh", "bzr+sftp", "bzr+ftp", "bzr+lp")
|
||||
|
||||
OPERATING_SYSTEMS = dict(windows=["win32"],
|
||||
linux=lambda x: x.startswith("linux"),
|
||||
macos=["darwin"],
|
||||
freebsd=lambda x: x.startswith("freebsd"))
|
||||
OPERATING_SYSTEMS = {"windows": ["win32"],
|
||||
"linux": lambda x: x.startswith("linux"),
|
||||
"macos": ["darwin"],
|
||||
"freebsd": lambda x: x.startswith("freebsd")}
|
||||
|
||||
PIP_INAPPLICABLE_ARGUMENTS = dict(uninstall=["--user"])
|
||||
PIP_INAPPLICABLE_ARGUMENTS = {"uninstall": ["--user"]}
|
||||
|
||||
RECONNECT_HOOKS = ["octoprint.comm.protocol.*",]
|
||||
|
||||
@@ -129,7 +127,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._repository_cache_ttl = 0
|
||||
self._repository_mtime = None
|
||||
|
||||
self._notices = dict()
|
||||
self._notices = {}
|
||||
self._notices_available = False
|
||||
self._notices_cache_path = None
|
||||
self._notices_cache_ttl = 0
|
||||
@@ -166,20 +164,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="MANAGE",
|
||||
name="Manage plugins",
|
||||
description=gettext("Allows to enable, disable and uninstall installed plugins."),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["manage"]),
|
||||
dict(key="INSTALL",
|
||||
name="Install new plugins",
|
||||
description=gettext("Allows to install new plugins. Includes the \"Manage plugins\" permission."),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["install"],
|
||||
permissions=["PLUGIN_PLUGINMANAGER_MANAGE"],
|
||||
dangerous=True)
|
||||
]
|
||||
return [{"key": "MANAGE",
|
||||
"name": "Manage plugins",
|
||||
"description": gettext("Allows to enable, disable and uninstall installed plugins."),
|
||||
"default_groups": [ADMIN_GROUP],
|
||||
"roles": ["manage"]},
|
||||
{"key": "INSTALL",
|
||||
"name": "Install new plugins",
|
||||
"description": gettext("Allows to install new plugins. Includes the \"Manage plugins\" permission."),
|
||||
"default_groups": [ADMIN_GROUP],
|
||||
"roles": ["install"],
|
||||
"permissions": ["PLUGIN_PLUGINMANAGER_MANAGE"],
|
||||
"dangerous": True}]
|
||||
|
||||
##~~ StartupPlugin
|
||||
|
||||
@@ -205,18 +201,16 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
##~~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(
|
||||
repository="https://plugins.octoprint.org/plugins.json",
|
||||
repository_ttl=24*60,
|
||||
notices="https://plugins.octoprint.org/notices.json",
|
||||
notices_ttl=6*60,
|
||||
pip_args=None,
|
||||
pip_force_user=False,
|
||||
confirm_disable=False,
|
||||
dependency_links=False,
|
||||
hidden=[],
|
||||
ignore_throttled=False
|
||||
)
|
||||
return {"repository": "https://plugins.octoprint.org/plugins.json",
|
||||
"repository_ttl": 24*60,
|
||||
"notices": "https://plugins.octoprint.org/notices.json",
|
||||
"notices_ttl": 6*60,
|
||||
"pip_args": None,
|
||||
"pip_force_user": False,
|
||||
"confirm_disable": False,
|
||||
"dependency_links": False,
|
||||
"hidden": [],
|
||||
"ignore_throttled": False}
|
||||
|
||||
def on_settings_save(self, data):
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
@@ -229,33 +223,32 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/pluginmanager.js"],
|
||||
clientjs=["clientjs/pluginmanager.js"],
|
||||
css=["css/pluginmanager.css"],
|
||||
less=["less/pluginmanager.less"]
|
||||
)
|
||||
return {"js": ["js/pluginmanager.js"],
|
||||
"clientjs": ["clientjs/pluginmanager.js"],
|
||||
"css": ["css/pluginmanager.css"],
|
||||
"less": ["less/pluginmanager.less"]}
|
||||
|
||||
##~~ TemplatePlugin
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True),
|
||||
dict(type="about", name="Plugin Licenses", template="pluginmanager_about.jinja2")
|
||||
]
|
||||
return [{"type": "settings",
|
||||
"name": gettext("Plugin Manager"),
|
||||
"template": "pluginmanager_settings.jinja2",
|
||||
"custom_bindings": True},
|
||||
{"type": "about",
|
||||
"name": "Plugin Licenses",
|
||||
"template": "pluginmanager_about.jinja2"}]
|
||||
|
||||
def get_template_vars(self):
|
||||
plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower())
|
||||
return dict(
|
||||
all=plugins,
|
||||
thirdparty=list(filter(lambda p: not p["bundled"], plugins)),
|
||||
file_extensions=self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS
|
||||
)
|
||||
return {"all": plugins,
|
||||
"thirdparty": list(filter(lambda p: not p["bundled"], plugins)),
|
||||
"file_extensions": self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS}
|
||||
|
||||
def get_template_types(self, template_sorting, template_rules, *args, **kwargs):
|
||||
return [
|
||||
("about_thirdparty", dict(), dict(template=lambda x: x + "_about_thirdparty.jinja2"))
|
||||
]
|
||||
return [("about_thirdparty",
|
||||
{},
|
||||
{"template": lambda x: x + "_about_thirdparty.jinja2"})]
|
||||
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@@ -335,22 +328,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
def view():
|
||||
return jsonify(plugins=self._get_plugins(),
|
||||
repository=dict(
|
||||
available=self._repository_available,
|
||||
plugins=self._repository_plugins
|
||||
),
|
||||
repository={"available": self._repository_available,
|
||||
"plugins": self._repository_plugins},
|
||||
orphan_data=self._get_orphans(refresh=refresh_orphan),
|
||||
os=get_os(),
|
||||
octoprint=get_octoprint_version_string(),
|
||||
pip=dict(
|
||||
available=self._pip_caller.available,
|
||||
version=self._pip_caller.version_string,
|
||||
install_dir=self._pip_caller.install_dir,
|
||||
use_user=self._pip_caller.use_user,
|
||||
virtual_env=self._pip_caller.virtual_env,
|
||||
additional_args=self._settings.get(["pip_args"]),
|
||||
python=sys.executable
|
||||
),
|
||||
pip={"available": self._pip_caller.available,
|
||||
"version": self._pip_caller.version_string,
|
||||
"install_dir": self._pip_caller.install_dir,
|
||||
"use_user": self._pip_caller.use_user,
|
||||
"virtual_env": self._pip_caller.virtual_env,
|
||||
"additional_args": self._settings.get(["pip_args"]),
|
||||
"python": sys.executable},
|
||||
safe_mode=safe_mode,
|
||||
online=self._connectivity_checker.online)
|
||||
|
||||
@@ -398,11 +387,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return make_response("There's always a plugin being installed", 409)
|
||||
|
||||
self._install_task = threading.Thread(target=self.command_install,
|
||||
kwargs=dict(url=url,
|
||||
force="force" in data and data["force"] in valid_boolean_trues,
|
||||
dependency_links="dependency_links" in data
|
||||
and data["dependency_links"] in valid_boolean_trues,
|
||||
reinstall=plugin_name))
|
||||
kwargs={"url": url,
|
||||
"force": "force" in data and data["force"] in valid_boolean_trues,
|
||||
"dependency_links": "dependency_links" in data
|
||||
and data["dependency_links"] in valid_boolean_trues,
|
||||
"reinstall": plugin_name})
|
||||
self._install_task.daemon = True
|
||||
self._install_task.start()
|
||||
|
||||
@@ -493,11 +482,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
else:
|
||||
self._logger.error("{} is neither an archive nor a python file, can't install that.".format(source))
|
||||
result = dict(result=False,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
reason="Could not install plugin from {}, was neither "
|
||||
"a plugin archive nor a single file plugin".format(source))
|
||||
result = {"result": False,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"reason": "Could not install plugin from {}, was neither "
|
||||
"a plugin archive nor a single file plugin".format(source)}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
@@ -539,7 +528,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if dependency_links or self._settings.get_boolean(["dependency_links"]):
|
||||
pip_args.append("--process-dependency-links")
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins(existing=dict())
|
||||
all_plugins_before = self._plugin_manager.find_plugins(existing={})
|
||||
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
@@ -583,11 +572,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
except IndexError:
|
||||
self._logger.error("Installing the plugin from {} failed, could not parse output from pip. "
|
||||
"See plugin_pluginmanager_console.log for generated output".format(source))
|
||||
result = dict(result=False,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
reason="Could not parse output from pip, see plugin_pluginmanager_console.log "
|
||||
"for generated output")
|
||||
result = {"result": False,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"reason": "Could not parse output from pip, see plugin_pluginmanager_console.log "
|
||||
"for generated output"}
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -615,29 +604,29 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if not result_line.startswith(success_string):
|
||||
self._logger.error("Installing the plugin from {} failed, pip did not report successful installation"
|
||||
.format(source))
|
||||
result = dict(result=False,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
reason="Pip did not report successful installation")
|
||||
result = {"result": False,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"reason": "Pip did not report successful installation"}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
installed = list(map(lambda x: x.strip(), result_line[len(success_string):].split(" ")))
|
||||
all_plugins_after = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
|
||||
all_plugins_after = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False)
|
||||
|
||||
new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after)
|
||||
|
||||
if new_plugin is None:
|
||||
self._logger.warning("The plugin was installed successfully, but couldn't be found afterwards to "
|
||||
"initialize properly during runtime. Please restart OctoPrint.")
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
needs_reconnect=True,
|
||||
was_reinstalled=False,
|
||||
plugin="unknown")
|
||||
result = {"result": True,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"needs_restart": True,
|
||||
"needs_refresh": True,
|
||||
"needs_reconnect": True,
|
||||
"was_reinstalled": False,
|
||||
"plugin": "unknown"}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
@@ -659,19 +648,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version))
|
||||
|
||||
# noinspection PyUnresolvedReferences
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, dict(id=new_plugin.key,
|
||||
version=new_plugin.version,
|
||||
source=source,
|
||||
source_type=source_type))
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, {"id": new_plugin.key,
|
||||
"version": new_plugin.version,
|
||||
"source": source,
|
||||
"source_type": source_type})
|
||||
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
needs_reconnect=needs_reconnect,
|
||||
was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None,
|
||||
plugin=self._to_external_plugin(new_plugin))
|
||||
result = {"result": True,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"needs_restart": needs_restart,
|
||||
"needs_refresh": needs_refresh,
|
||||
"needs_reconnect": needs_reconnect,
|
||||
"was_reinstalled": new_plugin.key in all_plugins_before or reinstall is not None,
|
||||
"plugin": self._to_external_plugin(new_plugin)}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
@@ -682,7 +671,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
self._logger.info("Installing single file plugin {} from {}".format(name, source))
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins(existing=dict())
|
||||
all_plugins_before = self._plugin_manager.find_plugins(existing={})
|
||||
|
||||
destination = os.path.join(self._settings.global_get_basefolder("plugins"), name)
|
||||
plugin_id, _ = os.path.splitext(name)
|
||||
@@ -692,26 +681,26 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
shutil.copy(path, destination)
|
||||
except:
|
||||
self._logger.exception("Installing plugin from {} failed".format(source))
|
||||
result = dict(result=False,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
reason="Plugin could not be copied")
|
||||
result = {"result": False,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"reason": "Plugin could not be copied"}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
plugins = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
|
||||
plugins = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False)
|
||||
new_plugin = plugins.get(plugin_id)
|
||||
if new_plugin is None:
|
||||
self._logger.warning("The plugin was installed successfully, but couldn't be found afterwards to "
|
||||
"initialize properly during runtime. Please restart OctoPrint.")
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
needs_reconnect=True,
|
||||
was_reinstalled=False,
|
||||
plugin="unknown")
|
||||
result = {"result": True,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"needs_restart": True,
|
||||
"needs_refresh": True,
|
||||
"needs_reconnect": True,
|
||||
"was_reinstalled": False,
|
||||
"plugin": "unknown"}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
@@ -726,19 +715,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._plugin_manager.log_all_plugins()
|
||||
|
||||
# noinspection PyUnresolvedReferences
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, dict(id=new_plugin.key,
|
||||
version=new_plugin.version,
|
||||
source=source,
|
||||
source_type=source_type))
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, {"id": new_plugin.key,
|
||||
"version": new_plugin.version,
|
||||
"source": source,
|
||||
"source_type": source_type})
|
||||
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
needs_reconnect=needs_reconnect,
|
||||
was_reinstalled=new_plugin.key in all_plugins_before,
|
||||
plugin=self._to_external_plugin(new_plugin))
|
||||
result = {"result": True,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"needs_restart": needs_restart,
|
||||
"needs_refresh": needs_refresh,
|
||||
"needs_reconnect": needs_reconnect,
|
||||
"was_reinstalled": new_plugin.key in all_plugins_before,
|
||||
"plugin": self._to_external_plugin(new_plugin)}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
@@ -806,7 +795,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._plugin_manager.disable_plugin(plugin.key, plugin=plugin)
|
||||
except octoprint.plugin.core.PluginLifecycleException as e:
|
||||
self._logger.exception("Problem disabling plugin {name}".format(name=plugin.key))
|
||||
result = dict(result=False, uninstalled=True, disabled=False, unloaded=False, reason=e.reason)
|
||||
result = {"result": False, "uninstalled": True, "disabled": False, "unloaded": False, "reason": e.reason}
|
||||
self._send_result_notification("uninstall", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -815,21 +804,21 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._plugin_manager.unload_plugin(plugin.key)
|
||||
except octoprint.plugin.core.PluginLifecycleException as e:
|
||||
self._logger.exception("Problem unloading plugin {name}".format(name=plugin.key))
|
||||
result = dict(result=False, uninstalled=True, disabled=True, unloaded=False, reason=e.reason)
|
||||
result = {"result": False, "uninstalled": True, "disabled": True, "unloaded": False, "reason": e.reason}
|
||||
self._send_result_notification("uninstall", result)
|
||||
return jsonify(result)
|
||||
|
||||
self._plugin_manager.reload_plugins()
|
||||
|
||||
# noinspection PyUnresolvedReferences
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, dict(id=plugin.key,
|
||||
version=plugin.version))
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, {"id": plugin.key,
|
||||
"version": plugin.version})
|
||||
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
needs_reconnect=needs_reconnect,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
result = {"result": True,
|
||||
"needs_restart": needs_restart,
|
||||
"needs_refresh": needs_refresh,
|
||||
"needs_reconnect": needs_reconnect,
|
||||
"plugin": self._to_external_plugin(plugin)}
|
||||
self._send_result_notification("uninstall", result)
|
||||
self._logger.info("Plugin {} uninstalled".format(plugin.key))
|
||||
|
||||
@@ -868,9 +857,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if settings_save:
|
||||
self._settings.save()
|
||||
|
||||
result = dict(result=result_data,
|
||||
needs_restart=True,
|
||||
plugin=result_value)
|
||||
result = {"result": result_data,
|
||||
"needs_restart": True,
|
||||
"plugin": result_value}
|
||||
if result_notifications:
|
||||
self._send_result_notification("cleanup", result)
|
||||
|
||||
@@ -892,9 +881,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
self._settings.save()
|
||||
|
||||
result = dict(result=True,
|
||||
needs_restart=len(cleaned_up) > 0,
|
||||
cleaned_up=sorted(list(cleaned_up)))
|
||||
result = {"result": True,
|
||||
"needs_restart": len(cleaned_up) > 0,
|
||||
"cleaned_up": sorted(list(cleaned_up))}
|
||||
self._send_result_notification("cleanup_all", result)
|
||||
self._logger.info("Cleaned up all data, {} left overs removed".format(len(cleaned_up)))
|
||||
|
||||
@@ -956,26 +945,26 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._mark_plugin_enabled(plugin, needs_restart=needs_restart)
|
||||
except octoprint.plugin.core.PluginLifecycleException as e:
|
||||
self._logger.exception("Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason))
|
||||
result = dict(result=False, reason=e.reason)
|
||||
result = {"result": False, "reason": e.reason}
|
||||
except octoprint.plugin.core.PluginNeedsRestart:
|
||||
result = dict(result=True,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
needs_reconnect=True,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
result = {"result": True,
|
||||
"needs_restart": True,
|
||||
"needs_refresh": True,
|
||||
"needs_reconnect": True,
|
||||
"plugin": self._to_external_plugin(plugin)}
|
||||
else:
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart_api,
|
||||
needs_refresh=needs_refresh_api,
|
||||
needs_reconnect=needs_reconnect_api,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
result = {"result": True,
|
||||
"needs_restart": needs_restart_api,
|
||||
"needs_refresh": needs_refresh_api,
|
||||
"needs_reconnect": needs_reconnect_api,
|
||||
"plugin": self._to_external_plugin(plugin)}
|
||||
|
||||
self._send_result_notification(command, result)
|
||||
return jsonify(result)
|
||||
|
||||
def _find_installed_plugin(self, packages, plugins=None):
|
||||
if plugins is None:
|
||||
plugins = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
|
||||
plugins = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False)
|
||||
|
||||
for key, plugin in plugins.items():
|
||||
if plugin.origin is None or plugin.origin.type != "entry_point":
|
||||
@@ -1004,7 +993,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return None
|
||||
|
||||
def _send_result_notification(self, action, result):
|
||||
notification = dict(type="result", action=action)
|
||||
notification = {"type": "result", "action": action}
|
||||
notification.update(result)
|
||||
self._plugin_manager.send_plugin_message(self._identifier, notification)
|
||||
|
||||
@@ -1026,7 +1015,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if additional_args:
|
||||
args.append(additional_args)
|
||||
|
||||
kwargs = dict(env=dict(PYTHONWARNINGS="ignore:DEPRECATION::pip._internal.cli.base_command"))
|
||||
kwargs = {"env": {"PYTHONWARNINGS": "ignore:DEPRECATION::pip._internal.cli.base_command"}}
|
||||
|
||||
return self._pip_caller.execute(*args, **kwargs)
|
||||
|
||||
@@ -1046,8 +1035,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if strip:
|
||||
lines = list(map(lambda x: x.strip(), lines))
|
||||
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines",
|
||||
loglines=[dict(line=line, stream=stream) for line in lines]))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"type": "loglines",
|
||||
"loglines": [{"line": line, "stream": stream} for line in lines]})
|
||||
for line in lines:
|
||||
self._console_logger.debug("{prefix} {line}".format(**locals()))
|
||||
|
||||
@@ -1069,8 +1058,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._pending_enable.add(plugin.key)
|
||||
|
||||
# noinspection PyUnresolvedReferences
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, dict(id=plugin.key,
|
||||
version=plugin.version))
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, {"id": plugin.key,
|
||||
"version": plugin.version})
|
||||
|
||||
def _mark_plugin_disabled(self, plugin, needs_restart=False):
|
||||
disabled_list = list(self._settings.global_get(["plugins", "_disabled"],
|
||||
@@ -1090,8 +1079,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._pending_disable.add(plugin.key)
|
||||
|
||||
# noinspection PyUnresolvedReferences
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, dict(id=plugin.key,
|
||||
version=plugin.version))
|
||||
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, {"id": plugin.key,
|
||||
"version": plugin.version})
|
||||
|
||||
def _fetch_all_data(self, do_async=False):
|
||||
def run():
|
||||
@@ -1231,7 +1220,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if notice_data is None:
|
||||
return False
|
||||
|
||||
notices = dict()
|
||||
notices = {}
|
||||
for notice in notice_data:
|
||||
if not "plugin" in notice or not "text" in notice or not "date" in notice:
|
||||
continue
|
||||
@@ -1265,7 +1254,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return self._orphans
|
||||
|
||||
installed_keys = self._plugin_manager.plugins.keys()
|
||||
orphans = defaultdict(lambda: dict(settings=False, data=False, disabled=False))
|
||||
orphans = defaultdict(lambda: {"settings": False, "data": False, "disabled": False})
|
||||
|
||||
# settings
|
||||
for key in list(self._settings.global_get(["plugins"]).keys()):
|
||||
@@ -1306,7 +1295,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving additional hooks for which a "
|
||||
"reconnect is required from plugin {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
return reconnect_hooks
|
||||
|
||||
@@ -1323,30 +1312,28 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return result
|
||||
|
||||
def _to_external_plugin(self, plugin):
|
||||
return dict(
|
||||
key=plugin.key,
|
||||
name=plugin.name,
|
||||
description=plugin.description,
|
||||
disabling_discouraged=gettext(plugin.disabling_discouraged) if plugin.disabling_discouraged else False,
|
||||
author=plugin.author,
|
||||
version=plugin.version,
|
||||
url=plugin.url,
|
||||
license=plugin.license,
|
||||
python=plugin.pythoncompat,
|
||||
bundled=plugin.bundled,
|
||||
managable=plugin.managable,
|
||||
enabled=plugin.enabled,
|
||||
blacklisted=plugin.blacklisted,
|
||||
forced_disabled=plugin.forced_disabled,
|
||||
incompatible=plugin.incompatible,
|
||||
safe_mode_victim=getattr(plugin, "safe_mode_victim", False),
|
||||
pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_victim", False) and plugin.key in self._pending_enable),
|
||||
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key in self._pending_disable),
|
||||
pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
|
||||
pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
|
||||
origin=plugin.origin.type,
|
||||
notifications = self._get_notifications(plugin)
|
||||
)
|
||||
return {"key": plugin.key,
|
||||
"name": plugin.name,
|
||||
"description": plugin.description,
|
||||
"disabling_discouraged": gettext(plugin.disabling_discouraged) if plugin.disabling_discouraged else False,
|
||||
"author": plugin.author,
|
||||
"version": plugin.version,
|
||||
"url": plugin.url,
|
||||
"license": plugin.license,
|
||||
"python": plugin.pythoncompat,
|
||||
"bundled": plugin.bundled,
|
||||
"managable": plugin.managable,
|
||||
"enabled": plugin.enabled,
|
||||
"blacklisted": plugin.blacklisted,
|
||||
"forced_disabled": plugin.forced_disabled,
|
||||
"incompatible": plugin.incompatible,
|
||||
"safe_mode_victim": getattr(plugin, "safe_mode_victim", False),
|
||||
"pending_enable": (not plugin.enabled and not getattr(plugin, "safe_mode_victim", False) and plugin.key in self._pending_enable),
|
||||
"pending_disable": ((plugin.enabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key in self._pending_disable),
|
||||
"pending_install": (self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
|
||||
"pending_uninstall": (self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
|
||||
"origin": plugin.origin.type,
|
||||
"notifications": self._get_notifications(plugin)}
|
||||
|
||||
def _get_notifications(self, plugin):
|
||||
key = plugin.key
|
||||
@@ -1368,12 +1355,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin_notifications))))
|
||||
|
||||
def _to_external_notification(self, key, notification):
|
||||
return dict(key=key,
|
||||
date=time.mktime(notification["timestamp"]),
|
||||
text=notification["text"],
|
||||
link=notification.get("link"),
|
||||
versions=notification.get("pluginversions", notification.get("versions", [])),
|
||||
important=notification.get("important", False))
|
||||
return {"key": key,
|
||||
"date": time.mktime(notification["timestamp"]),
|
||||
"text": notification["text"],
|
||||
"link": notification.get("link"),
|
||||
"versions": notification.get("pluginversions", notification.get("versions", [])),
|
||||
"important": notification.get("important", False)}
|
||||
|
||||
|
||||
def _filter_relevant_notification(notification, plugin_version, octoprint_version):
|
||||
|
||||
@@ -72,22 +72,22 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._get_versions_data = None
|
||||
self._get_versions_data_ready = threading.Event()
|
||||
|
||||
self._version_cache = dict()
|
||||
self._version_cache = {}
|
||||
self._version_cache_ttl = 0
|
||||
self._version_cache_path = None
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = None
|
||||
|
||||
self._overlay_cache = dict()
|
||||
self._overlay_cache = {}
|
||||
self._overlay_cache_ttl = 0
|
||||
self._overlay_cache_timestamp = None
|
||||
|
||||
self._environment_supported = True
|
||||
self._environment_versions = dict()
|
||||
self._environment_versions = {}
|
||||
self._environment_ready = threading.Event()
|
||||
|
||||
self._storage_sufficient = True
|
||||
self.storage_info = dict()
|
||||
self.storage_info = {}
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
@@ -113,23 +113,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="CHECK",
|
||||
name="Check",
|
||||
description=gettext("Allows to check for software updates"),
|
||||
roles=["check"],
|
||||
default_groups=[USER_GROUP]),
|
||||
dict(key="UPDATE",
|
||||
name="Update",
|
||||
description=gettext("Allows to perform software updates"),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["update"],
|
||||
dangerous=True),
|
||||
dict(key="CONFIGURE",
|
||||
name="Configure",
|
||||
description=gettext("Allows to configure software update"),
|
||||
default_groups=[ADMIN_GROUP],
|
||||
roles=["configure"],
|
||||
dangerous=True)
|
||||
{"key": "CHECK",
|
||||
"name": "Check",
|
||||
"description": gettext("Allows to check for software updates"),
|
||||
"roles": ["check"],
|
||||
"default_groups": [USER_GROUP]},
|
||||
{"key": "UPDATE",
|
||||
"name": "Update",
|
||||
"description": gettext("Allows to perform software updates"),
|
||||
"default_groups": [ADMIN_GROUP],
|
||||
"roles": ["update"],
|
||||
"dangerous": True},
|
||||
{"key": "CONFIGURE",
|
||||
"name": "Configure",
|
||||
"description": gettext("Allows to configure software update"),
|
||||
"default_groups": [ADMIN_GROUP],
|
||||
"roles": ["configure"],
|
||||
"dangerous": True}
|
||||
]
|
||||
|
||||
def on_startup(self, host, port):
|
||||
@@ -166,9 +166,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._configured_checks = self._settings.get(["checks"], merged=True)
|
||||
|
||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||
check_providers = dict()
|
||||
check_providers = {}
|
||||
|
||||
effective_configs = dict()
|
||||
effective_configs = {}
|
||||
|
||||
for name, hook in update_check_hooks.items():
|
||||
try:
|
||||
@@ -176,7 +176,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving update information "
|
||||
"from plugin {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
for key, default_config in hook_checks.items():
|
||||
if key in effective_configs or key == "octoprint":
|
||||
@@ -188,7 +188,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
check_providers[key] = name
|
||||
|
||||
yaml_config = dict()
|
||||
yaml_config = {}
|
||||
effective_config = default_config
|
||||
|
||||
if key in overlays:
|
||||
@@ -237,9 +237,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
local_pip = LocalPipCaller()
|
||||
|
||||
# check python and setuptools version
|
||||
versions = dict(python=get_python_version_string(),
|
||||
setuptools=pkg_resources.get_distribution("setuptools").version,
|
||||
pip=local_pip.version_string)
|
||||
versions = {"python": get_python_version_string(),
|
||||
"setuptools": pkg_resources.get_distribution("setuptools").version,
|
||||
"pip": local_pip.version_string}
|
||||
supported = get_comparable_version(versions["python"]) >= get_comparable_version(MINIMUM_PYTHON) \
|
||||
and get_comparable_version(versions["setuptools"]) >= get_comparable_version(MINIMUM_SETUPTOOLS) \
|
||||
and get_comparable_version(versions["pip"]) >= get_comparable_version(MINIMUM_PIP)
|
||||
@@ -253,14 +253,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
import tempfile
|
||||
import psutil
|
||||
|
||||
storage_info = dict()
|
||||
paths = dict(python=distutils.sysconfig.get_python_lib(),
|
||||
plugins=self._settings.global_get_basefolder("plugins"),
|
||||
temp=tempfile.gettempdir())
|
||||
storage_info = {}
|
||||
paths = {"python": distutils.sysconfig.get_python_lib(),
|
||||
"plugins": self._settings.global_get_basefolder("plugins"),
|
||||
"temp": tempfile.gettempdir()}
|
||||
|
||||
for key, path in paths.items():
|
||||
info = dict(path=path,
|
||||
free=None)
|
||||
info = {"path": path,
|
||||
"free": None}
|
||||
|
||||
try:
|
||||
data = psutil.disk_usage(path)
|
||||
@@ -304,17 +304,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
data = r.json()
|
||||
except Exception as exc:
|
||||
self._logger.error("Could not fetch check overlay from {}: {}".format(url, exc))
|
||||
self._overlay_cache = dict()
|
||||
self._overlay_cache = {}
|
||||
else:
|
||||
self._overlay_cache = data
|
||||
|
||||
else:
|
||||
self._logger.info("Not fetching check overlays, we are offline")
|
||||
self._overlay_cache = dict()
|
||||
self._overlay_cache = {}
|
||||
|
||||
self._overlay_cache_timestamp = time.time()
|
||||
|
||||
default_overlay = dict()
|
||||
default_overlay = {}
|
||||
defaults = self.get_settings_defaults()
|
||||
for key in defaults["checks"]:
|
||||
if key in self._overlay_cache:
|
||||
@@ -322,7 +322,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._settings.remove_overlay(self.CHECK_OVERLAY_KEY)
|
||||
if default_overlay:
|
||||
self._settings.add_overlay(dict(checks=default_overlay), key=self.CHECK_OVERLAY_KEY)
|
||||
self._settings.add_overlay({"checks": default_overlay}, key=self.CHECK_OVERLAY_KEY)
|
||||
|
||||
return self._overlay_cache
|
||||
|
||||
@@ -402,13 +402,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"pip": "https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip",
|
||||
"update_script": default_update_script,
|
||||
"restart": "octoprint",
|
||||
"stable_branch": dict(branch="master", commitish=["master"], name="Stable"),
|
||||
"prerelease_branches": [dict(branch="rc/maintenance",
|
||||
commitish=["rc/maintenance"], # maintenance RCs
|
||||
name="Maintenance RCs"),
|
||||
dict(branch="rc/devel",
|
||||
commitish=["rc/maintenance", "rc/devel"], # devel & maintenance RCs
|
||||
name="Devel RCs")]
|
||||
"stable_branch": {"branch": "master", "commitish": ["master"], "name": "Stable"},
|
||||
"prerelease_branches": [{"branch": "rc/maintenance",
|
||||
"commitish": ["rc/maintenance"], # maintenance RCs
|
||||
"name": "Maintenance RCs"},
|
||||
{"branch": "rc/devel",
|
||||
"commitish": ["rc/maintenance", "rc/devel"], # devel & maintenance RCs
|
||||
"name": "Devel RCs"}]
|
||||
},
|
||||
},
|
||||
"pip_command": None,
|
||||
@@ -570,9 +570,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if pip_enable_check:
|
||||
# force=True as that path is not part of the default config
|
||||
self._settings.set(["checks", "pip"],
|
||||
dict(type="pypi_release",
|
||||
package="pip",
|
||||
pip="pip=={target_version}"),
|
||||
{"type": "pypi_release",
|
||||
"package": "pip",
|
||||
"pip": "pip=={target_version}"},
|
||||
force=True)
|
||||
else:
|
||||
self._settings.remove(["checks", "pip"])
|
||||
@@ -595,7 +595,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint_check = dict(configured_checks["octoprint"])
|
||||
|
||||
if not "method" in octoprint_check and octoprint_check.get("type") == "git_commit":
|
||||
defaults = dict(plugins=dict(softwareupdate=dict(checks=dict(octoprint=dict(method="pip")))))
|
||||
defaults = {"plugins": {"softwareupdate": {"checks": {"octoprint": {"method": "pip"}}}}}
|
||||
self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults)
|
||||
|
||||
if current == 4:
|
||||
@@ -666,8 +666,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
if "octoprint" in configured_checks and "octoprint" in configured_checks["octoprint"]:
|
||||
# that's a circular reference, back to defaults
|
||||
dummy_defaults = dict(plugins=dict())
|
||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_defaults = {"plugins": {}}
|
||||
dummy_defaults["plugins"][self._identifier] = {"checks": {}}
|
||||
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
|
||||
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
|
||||
|
||||
@@ -691,8 +691,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if k in data:
|
||||
del data[k]
|
||||
|
||||
dummy_defaults = dict(plugins=dict())
|
||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_defaults = {"plugins": {}}
|
||||
dummy_defaults["plugins"][self._identifier] = {"checks": {}}
|
||||
dummy_defaults["plugins"][self._identifier]["checks"][key] = defaults
|
||||
if len(data):
|
||||
self._settings.set(["checks", key], data, defaults=dummy_defaults)
|
||||
@@ -734,7 +734,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if not data:
|
||||
continue
|
||||
|
||||
s = dict(name=name)
|
||||
s = {"name": name}
|
||||
s.update(**data)
|
||||
storage.append(s)
|
||||
|
||||
@@ -746,21 +746,21 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
elif update_available:
|
||||
status = "updateAvailable"
|
||||
|
||||
return flask.jsonify(dict(status=status,
|
||||
information=information,
|
||||
timestamp=self._version_cache_timestamp,
|
||||
environment=dict(supported=self._environment_supported,
|
||||
versions=[dict(name=gettext("Python"),
|
||||
current=self._environment_versions.get("python", "unknown"),
|
||||
minimum=MINIMUM_PYTHON),
|
||||
dict(name=gettext("pip"),
|
||||
current=self._environment_versions.get("pip", "unknown"),
|
||||
minimum=MINIMUM_PIP),
|
||||
dict(name=gettext("setuptools"),
|
||||
current=self._environment_versions.get("setuptools", "unknown"),
|
||||
minimum=MINIMUM_SETUPTOOLS)]),
|
||||
storage=dict(sufficient=self._storage_sufficient,
|
||||
free=storage)))
|
||||
return flask.jsonify({"status": status,
|
||||
"information": information,
|
||||
"timestamp": self._version_cache_timestamp,
|
||||
"environment": {"supported": self._environment_supported,
|
||||
"versions": [{"name": gettext("Python"),
|
||||
"current": self._environment_versions.get("python", "unknown"),
|
||||
"minimum": MINIMUM_PYTHON},
|
||||
{"name": gettext("pip"),
|
||||
"current": self._environment_versions.get("pip", "unknown"),
|
||||
"minimum": MINIMUM_PIP},
|
||||
{"name": gettext("setuptools"),
|
||||
"current": self._environment_versions.get("setuptools", "unknown"),
|
||||
"minimum": MINIMUM_SETUPTOOLS}]},
|
||||
"storage": {"sufficient": self._storage_sufficient,
|
||||
"free": storage}})
|
||||
except exceptions.ConfigurationInvalid as e:
|
||||
return flask.make_response("Update not properly configured, can't proceed: {}".format(e), 500)
|
||||
|
||||
@@ -778,7 +778,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
targets = sorted(targets)
|
||||
for target in targets:
|
||||
current_hash = self._get_check_hash(checks.get(target, dict()))
|
||||
current_hash = self._get_check_hash(checks.get(target, {}))
|
||||
if target in self._version_cache and not force:
|
||||
data = self._version_cache[target]
|
||||
hash_update(current_hash)
|
||||
@@ -841,7 +841,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
force = json_data.get("force", "false") in octoprint.settings.valid_boolean_trues
|
||||
|
||||
to_be_checked, checks = self.perform_updates(targets=targets, force=force)
|
||||
return flask.jsonify(dict(order=to_be_checked, checks=checks))
|
||||
return flask.jsonify({"order": to_be_checked, "checks": checks})
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/configure", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@@ -867,7 +867,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.exception("Error while populating check prior to configuration for target {}".format(target))
|
||||
continue
|
||||
|
||||
patch = dict()
|
||||
patch = {}
|
||||
|
||||
# switched release channel
|
||||
if "channel" in data:
|
||||
@@ -888,7 +888,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if patch:
|
||||
current = self._settings.get(["checks", target], incl_defaults=False)
|
||||
updated = dict_merge(current, patch)
|
||||
self._settings.set(["checks", target], updated, defaults=dict(plugins=dict(softwareupdate=dict(checks={target: dict()}))))
|
||||
self._settings.set(["checks", target], updated, defaults={"plugins": {"softwareupdate": {"checks": {target: {}}}}})
|
||||
|
||||
settings_dirty = True
|
||||
self._invalidate_version_cache(target)
|
||||
@@ -904,19 +904,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
#~~ Asset API
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
css=["css/softwareupdate.css"],
|
||||
js=["js/softwareupdate.js"],
|
||||
clientjs=["clientjs/softwareupdate.js"],
|
||||
less=["less/softwareupdate.less"]
|
||||
)
|
||||
return {"css": ["css/softwareupdate.css"],
|
||||
"js": ["js/softwareupdate.js"],
|
||||
"clientjs": ["clientjs/softwareupdate.js"],
|
||||
"less": ["less/softwareupdate.less"]}
|
||||
|
||||
##~~ TemplatePlugin API
|
||||
|
||||
def get_template_configs(self):
|
||||
from flask_babel import gettext
|
||||
return [
|
||||
dict(type="settings", name=gettext("Software Update"))
|
||||
{"type": "settings", "name": gettext("Software Update")}
|
||||
]
|
||||
|
||||
##~~ WizardPlugin API
|
||||
@@ -957,13 +955,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
update_available = False
|
||||
update_possible = False
|
||||
information = dict()
|
||||
information = {}
|
||||
|
||||
# we don't want to do the same work twice, so let's use a lock
|
||||
if self._get_versions_mutex.acquire(False):
|
||||
self._get_versions_data_ready.clear()
|
||||
try:
|
||||
futures_to_result = dict()
|
||||
futures_to_result = {}
|
||||
online = self._connectivity_checker.check_immediately()
|
||||
self._logger.debug("Looks like we are {}".format("online" if online else "offline"))
|
||||
|
||||
@@ -999,10 +997,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
target_information, target_update_available, target_update_possible, target_online, target_error = future.result()
|
||||
target_update_possible = target_update_possible and self._environment_supported
|
||||
|
||||
target_information = dict_merge(dict(local=dict(name="?", value="?"),
|
||||
remote=dict(name="?", value="?",
|
||||
release_notes=None),
|
||||
needs_online=True), target_information)
|
||||
target_information = dict_merge({"local": {"name": "?", "value": "?"},
|
||||
"remote": {"name": "?", "value": "?",
|
||||
"release_notes": None},
|
||||
"needs_online": True}, target_information)
|
||||
|
||||
target_disabled = populated_check.get("disabled", False)
|
||||
update_available = update_available or (target_update_available and not target_disabled)
|
||||
@@ -1024,33 +1022,33 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
target_name=target_information["remote"]["name"],
|
||||
target_version=target_information["remote"]["value"])
|
||||
|
||||
information[target] = dict(updateAvailable=target_update_available,
|
||||
updatePossible=target_update_possible,
|
||||
information=target_information,
|
||||
displayName=populated_check["displayName"],
|
||||
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION,
|
||||
information[target] = {"updateAvailable": target_update_available,
|
||||
"updatePossible": target_update_possible,
|
||||
"information": target_information,
|
||||
"displayName": populated_check["displayName"],
|
||||
"displayVersion": populated_check["displayVersion"].format(octoprint_version=VERSION,
|
||||
local_name=local_name,
|
||||
local_value=local_value),
|
||||
releaseNotes=release_notes,
|
||||
online=target_online,
|
||||
error=target_error,
|
||||
disabled=target_disabled,
|
||||
releaseChannels=dict())
|
||||
"releaseNotes": release_notes,
|
||||
"online": target_online,
|
||||
"error": target_error,
|
||||
"disabled": target_disabled,
|
||||
"releaseChannels": {}}
|
||||
|
||||
if populated_check["type"] == "github_release" and "stable_branch" in populated_check and "prerelease_branches" in populated_check:
|
||||
# target supports release channels via github branches and releases
|
||||
def to_release_channel(branch_info):
|
||||
return dict(name=branch_info["name"],
|
||||
channel=branch_info["branch"])
|
||||
return {"name": branch_info["name"],
|
||||
"channel": branch_info["branch"]}
|
||||
|
||||
stable_channel = populated_check["stable_branch"]["branch"]
|
||||
current_channel = populated_check.get("prerelease_channel")
|
||||
release_channels = [to_release_channel(populated_check["stable_branch"]),] + \
|
||||
list(map(to_release_channel,
|
||||
populated_check["prerelease_branches"]))
|
||||
information[target]["releaseChannels"] = dict(available=release_channels,
|
||||
current=current_channel if current_channel else stable_channel,
|
||||
stable=stable_channel)
|
||||
information[target]["releaseChannels"] = {"available": release_channels,
|
||||
"current": current_channel if current_channel else stable_channel,
|
||||
"stable": stable_channel}
|
||||
|
||||
if "released_version" in populated_check:
|
||||
information[target]["releasedVersion"] = populated_check["released_version"]
|
||||
@@ -1104,7 +1102,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# we also check that timestamp < now to not get confused too much by clock changes
|
||||
return data["information"], data["available"], data["possible"], data["online"], data.get("error", None)
|
||||
|
||||
information = dict()
|
||||
information = {}
|
||||
update_available = False
|
||||
error = None
|
||||
|
||||
@@ -1143,14 +1141,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
disabled = check.get("disabled", False)
|
||||
|
||||
self._version_cache[target] = dict(timestamp=time.time(),
|
||||
hash=current_hash,
|
||||
information=information,
|
||||
available=update_available,
|
||||
possible=update_possible,
|
||||
online=online,
|
||||
error=error,
|
||||
disabled=disabled)
|
||||
self._version_cache[target] = {"timestamp": time.time(),
|
||||
"hash": current_hash,
|
||||
"information": information,
|
||||
"available": update_available,
|
||||
"possible": update_possible,
|
||||
"online": online,
|
||||
"error": error,
|
||||
"disabled": disabled}
|
||||
self._version_cache_dirty = True
|
||||
return information, update_available, update_possible, online, error
|
||||
|
||||
@@ -1163,16 +1161,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
if not self._environment_supported:
|
||||
self._logger.error("Direct updates are unsupported in this environment")
|
||||
return [], dict()
|
||||
return [], {}
|
||||
|
||||
if not self._storage_sufficient:
|
||||
self._logger.error("Not enough free disk space for updating")
|
||||
return [], dict()
|
||||
return [], {}
|
||||
|
||||
targets = kwargs.get("targets", kwargs.get("check_targets", None))
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
populated_checks = dict()
|
||||
populated_checks = {}
|
||||
for target, check in checks.items():
|
||||
try:
|
||||
populated_checks[target] = self._populated_check(target, check)
|
||||
@@ -1207,7 +1205,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
try:
|
||||
self._update_in_progress = True
|
||||
|
||||
target_results = dict()
|
||||
target_results = {}
|
||||
error = False
|
||||
|
||||
### iterate over all configured targets
|
||||
@@ -1248,7 +1246,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
if error:
|
||||
# if there was an unignorable error, we just return error
|
||||
self._send_client_message("error", dict(results=target_results))
|
||||
self._send_client_message("error", {"results": target_results})
|
||||
|
||||
else:
|
||||
self._save_version_cache()
|
||||
@@ -1265,17 +1263,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
|
||||
if restart_command:
|
||||
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
|
||||
self._send_client_message("restarting", {"restart_type": restart_type, "results": target_results})
|
||||
try:
|
||||
self._perform_restart(restart_command)
|
||||
except exceptions.RestartFailed:
|
||||
self._send_client_message("restart_failed", dict(restart_type=restart_type, results=target_results))
|
||||
self._send_client_message("restart_failed", {"restart_type": restart_type, "results": target_results})
|
||||
else:
|
||||
# we don't have this restart type configured, we'll have to display a message that a manual
|
||||
# restart is needed
|
||||
self._send_client_message("restart_manually", dict(restart_type=restart_type, results=target_results))
|
||||
self._send_client_message("restart_manually", {"restart_type": restart_type, "results": target_results})
|
||||
else:
|
||||
self._send_client_message("success", dict(results=target_results))
|
||||
self._send_client_message("success", {"results": target_results})
|
||||
|
||||
def _perform_update(self, target, check, force):
|
||||
online = self._connectivity_checker.online
|
||||
@@ -1305,9 +1303,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED
|
||||
|
||||
payload = copy.copy(additional_payload)
|
||||
payload.update(dict(target=target,
|
||||
from_version=information["local"]["value"],
|
||||
to_version=target_version))
|
||||
payload.update({"target": target,
|
||||
"from_version": information["local"]["value"],
|
||||
"to_version": target_version})
|
||||
|
||||
self._event_bus.fire(event, payload=payload)
|
||||
|
||||
@@ -1316,7 +1314,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
populated_check = self._populated_check(target, check)
|
||||
try:
|
||||
self._logger.info("Starting update of %s to %s..." % (target, target_version))
|
||||
self._send_client_message("updating", dict(target=target, version=target_version, name=populated_check["displayName"]))
|
||||
self._send_client_message("updating", {"target": target, "version": target_version, "name": populated_check["displayName"]})
|
||||
updater = self._get_updater(target, check)
|
||||
if updater is None:
|
||||
raise exceptions.UnknownUpdateType()
|
||||
@@ -1328,12 +1326,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
except exceptions.UnknownUpdateType:
|
||||
self._logger.warning("Update of %s can not be performed, unknown update type" % target)
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type"))
|
||||
self._send_client_message("update_failed", {"target": target, "version": target_version, "name": populated_check["displayName"], "reason": "Unknown update type"})
|
||||
return False, None
|
||||
|
||||
except exceptions.CannotUpdateOffline:
|
||||
self._logger.warning("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target)
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="No internet connection"))
|
||||
self._send_client_message("update_failed", {"target": target, "version": target_version, "name": populated_check["displayName"], "reason": "No internet connection"})
|
||||
|
||||
except Exception as e:
|
||||
self._logger.exception("Update of %s can not be performed, please also check plugin_softwareupdate_console.log for possible causes of this" % target)
|
||||
@@ -1344,10 +1342,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
if isinstance(e, exceptions.UpdateError):
|
||||
target_result = ("failed", e.data)
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason=e.data))
|
||||
self._send_client_message("update_failed", {"target": target, "version": target_version, "name": populated_check["displayName"], "reason": e.data})
|
||||
else:
|
||||
target_result = ("failed", None)
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="unknown"))
|
||||
self._send_client_message("update_failed", {"target": target, "version": target_version, "name": populated_check["displayName"], "reason": "unknown"})
|
||||
|
||||
else:
|
||||
# make sure that any external changes to config.yaml are loaded into the system
|
||||
@@ -1367,9 +1365,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._settings.load()
|
||||
|
||||
dummy_default = dict(plugins=dict())
|
||||
dummy_default["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None)
|
||||
dummy_default = {"plugins": {}}
|
||||
dummy_default["plugins"][self._identifier] = {"checks": {}}
|
||||
dummy_default["plugins"][self._identifier]["checks"][target] = {"current": None}
|
||||
self._settings.set(["checks", target, "current"], current, defaults=dummy_default)
|
||||
|
||||
# we have to save here (even though that makes us save quite often) since otherwise the next
|
||||
@@ -1502,12 +1500,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if strip:
|
||||
lines = list(map(lambda x: x.strip(), lines))
|
||||
|
||||
self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines]))
|
||||
self._send_client_message("loglines", data={"loglines": [{"line": line, "stream": stream} for line in lines]})
|
||||
for line in lines:
|
||||
self._console_logger.debug("{} {}".format(prefix, line))
|
||||
|
||||
def _send_client_message(self, message_type, data=None):
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"type": message_type, "data": data})
|
||||
|
||||
def _get_version_checker(self, target, check):
|
||||
"""
|
||||
@@ -1620,12 +1618,10 @@ def __plugin_load__():
|
||||
__plugin_implementation__ = SoftwareUpdatePlugin()
|
||||
|
||||
global __plugin_helpers__
|
||||
__plugin_helpers__ = dict(
|
||||
version_checks=version_checks,
|
||||
updaters=updaters,
|
||||
exceptions=exceptions,
|
||||
util=util
|
||||
)
|
||||
__plugin_helpers__ = {"version_checks": version_checks,
|
||||
"updaters": updaters,
|
||||
"exceptions": exceptions,
|
||||
"util": util}
|
||||
|
||||
global __plugin_hooks__
|
||||
__plugin_hooks__ = {
|
||||
|
||||
@@ -39,7 +39,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
Note that the OctoPrint server needs to be running for this
|
||||
command to work as it utilizes the server API.
|
||||
"""
|
||||
params = dict(force=force)
|
||||
params = {"force": force}
|
||||
if targets:
|
||||
params["targets"] = ",".join(targets)
|
||||
|
||||
@@ -127,7 +127,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
command to work as it utilizes the server API.
|
||||
"""
|
||||
|
||||
data = dict(force=force)
|
||||
data = {"force": force}
|
||||
if targets:
|
||||
data["targets"] = targets
|
||||
|
||||
@@ -140,10 +140,8 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
flags = dict(
|
||||
waiting_for_restart=False,
|
||||
seen_close=False
|
||||
)
|
||||
flags = {"waiting_for_restart": False,
|
||||
"seen_close": False}
|
||||
|
||||
def on_message(ws, msg_type, msg):
|
||||
if msg_type != "plugin" or msg["plugin"] != "softwareupdate":
|
||||
@@ -169,7 +167,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
click.echo("\t{}{}".format(prefix, entry["line"].replace("\n", "\n\t")), err=error)
|
||||
|
||||
elif plugin_message_type == "success" or plugin_message_type == "restart_manually":
|
||||
results = plugin_message_data["results"] if "results" in plugin_message_data else dict()
|
||||
results = plugin_message_data["results"] if "results" in plugin_message_data else {}
|
||||
if results:
|
||||
click.echo("The update finished successfully.")
|
||||
if plugin_message_type == "restart_manually":
|
||||
|
||||
@@ -68,10 +68,10 @@ def _execute(command, **kwargs):
|
||||
joined_command = command
|
||||
_log_call(joined_command)
|
||||
|
||||
kwargs.update(dict(close_fds=CLOSE_FDS,
|
||||
async_=True,
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture()))
|
||||
kwargs.update({"close_fds": CLOSE_FDS,
|
||||
"async_": True,
|
||||
"stdout": sarge.Capture(),
|
||||
"stderr": sarge.Capture()})
|
||||
|
||||
try:
|
||||
p = sarge.run(command, **kwargs)
|
||||
|
||||
@@ -20,7 +20,7 @@ _ALREADY_INSTALLED = "Requirement already satisfied (use --upgrade to upgrade)"
|
||||
_POTENTIAL_EGG_PROBLEM_POSIX = "No such file or directory"
|
||||
_POTENTIAL_EGG_PROBLEM_WINDOWS = "The system cannot find the file specified"
|
||||
|
||||
_pip_callers = dict()
|
||||
_pip_callers = {}
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
def can_perform_update(target, check, online=True):
|
||||
@@ -87,7 +87,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
|
||||
logger.debug("Target: %s, executing pip install %s" % (target, install_arg))
|
||||
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
|
||||
pip_kwargs = dict(env=dict(PYTHONWARNINGS=b"ignore:DEPRECATION::pip._internal.cli.base_command"))
|
||||
pip_kwargs = {"env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"}}
|
||||
if pip_working_directory is not None:
|
||||
pip_kwargs.update(cwd=pip_working_directory)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
|
||||
def get_latest(target, check, online=True):
|
||||
current_version = check.get("current_version", "1.0.0")
|
||||
|
||||
information = dict(local=dict(name=current_version, value=current_version),
|
||||
remote=dict(name=current_version, value=current_version))
|
||||
information = {"local": {"name": current_version, "value": current_version},
|
||||
"remote": {"name": current_version, "value": current_version}}
|
||||
|
||||
return information, True
|
||||
@@ -52,18 +52,16 @@ def get_latest(target, check, online=True):
|
||||
|
||||
current = check.get("current")
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
|
||||
remote=dict(name="?", value="?"),
|
||||
needs_online=not check.get("offline", False)
|
||||
)
|
||||
information = {"local": {"name": "Commit {commit}".format(commit=current if current is not None else "unknown"), "value": current},
|
||||
"remote": {"name": "?", "value": "?"},
|
||||
"needs_online": not check.get("offline", False)}
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password)
|
||||
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
|
||||
|
||||
information["remote"] = dict(name=remote_name, value=remote_commit)
|
||||
information["remote"] = {"name": remote_name, "value": remote_commit}
|
||||
is_current = (current is not None and current == remote_commit) or remote_commit is None
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
|
||||
|
||||
@@ -39,16 +39,8 @@ def get_latest(target, check, online=True):
|
||||
remote_name = stdout_lines[-1] if len(stdout_lines) >= 1 else "unknown"
|
||||
is_current = returncode != 0
|
||||
|
||||
information =dict(
|
||||
local=dict(
|
||||
name=local_name,
|
||||
value=local_name,
|
||||
),
|
||||
remote=dict(
|
||||
name=remote_name,
|
||||
value=remote_name
|
||||
)
|
||||
)
|
||||
information ={"local": {"name": local_name, "value": local_name,},
|
||||
"remote": {"name": remote_name, "value": remote_name}}
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, local_name, remote_name))
|
||||
|
||||
@@ -56,11 +56,9 @@ def get_latest(target, check, online=True):
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit %s" % local_commit, value=local_commit),
|
||||
remote=dict(name="?", value="?"),
|
||||
needs_online=not check.get("offline", False)
|
||||
)
|
||||
information = {"local": {"name": "Commit %s" % local_commit, "value": local_commit},
|
||||
"remote": {"name": "?", "value": "?"},
|
||||
"needs_online": not check.get("offline", False)}
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
@@ -77,10 +75,10 @@ def get_latest(target, check, online=True):
|
||||
return information, True
|
||||
|
||||
if local_commit == remote_commit or remote_commit == base:
|
||||
information["remote"] = dict(name="Commit %s" % local_commit, value=local_commit)
|
||||
information["remote"] = {"name": "Commit %s" % local_commit, "value": local_commit}
|
||||
is_current = True
|
||||
else:
|
||||
information["remote"] = dict(name="Commit %s" % remote_commit, value=remote_commit)
|
||||
information["remote"] = {"name": "Commit %s" % remote_commit, "value": remote_commit}
|
||||
is_current = local_commit == remote_commit
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit")
|
||||
|
||||
@@ -48,16 +48,16 @@ def get_latest(target, check, online=True):
|
||||
|
||||
current = check.get("current")
|
||||
|
||||
information = dict(local=dict(name="Commit {commit}".format(commit=current if current is not None else "?"), value=current),
|
||||
remote=dict(name="?", value="?"),
|
||||
needs_online=not check.get("offline", False))
|
||||
information = {"local": {"name": "Commit {commit}".format(commit=current if current is not None else "?"), "value": current},
|
||||
"remote": {"name": "?", "value": "?"},
|
||||
"needs_online": not check.get("offline", False)}
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
|
||||
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
|
||||
|
||||
information["remote"] = dict(name=remote_name, value=remote_commit)
|
||||
information["remote"] = {"name": remote_name, "value": remote_commit}
|
||||
is_current = (current is not None and current == remote_commit) or remote_commit is None
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
|
||||
|
||||
@@ -257,11 +257,9 @@ def get_latest(target, check, custom_compare=None, online=True):
|
||||
if user is None or repo is None or current is None:
|
||||
raise ConfigurationInvalid("Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(target))
|
||||
|
||||
information =dict(
|
||||
local=dict(name=current, value=current),
|
||||
remote=dict(name="?", value="?", release_notes=None),
|
||||
needs_online=not check.get("offline", False)
|
||||
)
|
||||
information ={"local": {"name": current, "value": current},
|
||||
"remote": {"name": "?", "value": "?", "release_notes": None},
|
||||
"needs_online": not check.get("offline", False)}
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
@@ -294,7 +292,7 @@ def get_latest(target, check, custom_compare=None, online=True):
|
||||
else:
|
||||
remote_name = "-"
|
||||
|
||||
information["remote"] = dict(name=remote_name, value=remote_tag, release_notes=release_notes)
|
||||
information["remote"] = {"name": remote_name, "value": remote_tag, "release_notes": release_notes}
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
|
||||
|
||||
|
||||
@@ -33,8 +33,8 @@ def get_latest(target, check, online=True):
|
||||
except Exception as exc:
|
||||
raise NetworkError(cause=exc)
|
||||
|
||||
information = dict(local=dict(name="{}{}".format(prefix, current if current else "-"), value=current),
|
||||
remote=dict(name="{}{}".format(prefix, latest if latest else "-"), value=latest))
|
||||
information = {"local": {"name": "{}{}".format(prefix, current if current else "-"), "value": current},
|
||||
"remote": {"name": "{}{}".format(prefix, latest if latest else "-"), "value": latest}}
|
||||
|
||||
logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"]))
|
||||
|
||||
|
||||
@@ -29,8 +29,8 @@ def get_latest(target, check, online=True):
|
||||
|
||||
latest = data.get("version")
|
||||
|
||||
information = dict(local=dict(name=current if current else "-", value=current),
|
||||
remote=dict(name=latest if latest else "-", value=latest))
|
||||
information = {"local": {"name": current if current else "-", "value": current},
|
||||
"remote": {"name": latest if latest else "-", "value": latest}}
|
||||
|
||||
logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"]))
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ def get_latest(target, check, online=True):
|
||||
local_version = check.get("local_version", "1.0.0")
|
||||
remote_version = check.get("remote_version", "1.0.1")
|
||||
|
||||
information = dict(local=dict(name=local_version, value=local_version),
|
||||
remote=dict(name=remote_version, value=remote_version))
|
||||
information = {"local": {"name": local_version, "value": local_version},
|
||||
"remote": {"name": remote_version, "value": remote_version}}
|
||||
|
||||
return information, False
|
||||
@@ -33,7 +33,7 @@ def _filter_out_latest(releases, include_prerelease=False, python_version=None):
|
||||
'2.0.0rc1'
|
||||
>>> to_native_str(_filter_out_latest(releases, python_version="3.6.0"))
|
||||
"""
|
||||
releases = [dict(version=k, data=v[0]) for k, v in releases.items()]
|
||||
releases = [{"version": k, "data": v[0]} for k, v in releases.items()]
|
||||
|
||||
# filter out prereleases and versions incompatible to our python
|
||||
filter_function = lambda release: not is_prerelease(release["version"]) and is_python_compatible(release["data"].get("requires_python", ""), python_version=python_version)
|
||||
@@ -100,8 +100,8 @@ def get_latest(target, check, online=True):
|
||||
remote_version = _get_latest_release(package,
|
||||
include_prerelease=check.get("prerelease", False))
|
||||
|
||||
information = dict(local=dict(name=local_version, value=local_version),
|
||||
remote=dict(name=remote_version, value=remote_version))
|
||||
information = {"local": {"name": local_version, "value": local_version},
|
||||
"remote": {"name": remote_version, "value": remote_version}}
|
||||
|
||||
logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"]))
|
||||
|
||||
|
||||
@@ -57,25 +57,25 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
##~~ SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(enabled=None,
|
||||
unique_id=None,
|
||||
server=TRACKING_URL,
|
||||
ping=15*60,
|
||||
pong=24*60*60,
|
||||
events=dict(pong=True,
|
||||
startup=True,
|
||||
printjob=True,
|
||||
commerror=True,
|
||||
plugin=True,
|
||||
update=True,
|
||||
printer=True,
|
||||
printer_safety_check=True,
|
||||
throttled=True,
|
||||
slicing=True))
|
||||
return {"enabled": None,
|
||||
"unique_id": None,
|
||||
"server": TRACKING_URL,
|
||||
"ping": 15*60,
|
||||
"pong": 24*60*60,
|
||||
"events": {"pong": True,
|
||||
"startup": True,
|
||||
"printjob": True,
|
||||
"commerror": True,
|
||||
"plugin": True,
|
||||
"update": True,
|
||||
"printer": True,
|
||||
"printer_safety_check": True,
|
||||
"throttled": True,
|
||||
"slicing": True}}
|
||||
|
||||
def get_settings_restricted_paths(self):
|
||||
return dict(admin=[["enabled"], ["unique_id"], ["events"]],
|
||||
never=[["server"], ["ping"]])
|
||||
return {"admin": [["enabled"], ["unique_id"], ["events"]],
|
||||
"never": [["server"], ["ping"]]}
|
||||
|
||||
def on_settings_save(self, data):
|
||||
enabled = self._settings.get(["enabled"])
|
||||
@@ -118,8 +118,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
self._track_commerror_event(event, payload)
|
||||
|
||||
elif event in (Events.CONNECTED,):
|
||||
self._printer_connection_parameters = dict(port=payload["port"],
|
||||
baudrate=payload["baudrate"])
|
||||
self._printer_connection_parameters = {"port": payload["port"],
|
||||
"baudrate": payload["baudrate"]}
|
||||
self._record_next_firmware_info = True
|
||||
|
||||
elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info:
|
||||
@@ -149,14 +149,14 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings", name=gettext("Anonymous Usage Tracking"), template="tracking_settings.jinja2", custom_bindings=False),
|
||||
dict(type="wizard", name=gettext("Anonymous Usage Tracking"), template="tracking_wizard.jinja2", custom_bindings=True, mandatory=True)
|
||||
{"type": "settings", "name": gettext("Anonymous Usage Tracking"), "template": "tracking_settings.jinja2", "custom_bindings": False},
|
||||
{"type": "wizard", "name": gettext("Anonymous Usage Tracking"), "template": "tracking_wizard.jinja2", "custom_bindings": True, "mandatory": True}
|
||||
]
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/usage.js"])
|
||||
return {"js": ["js/usage.js"]}
|
||||
|
||||
##~~ WizardPlugin
|
||||
|
||||
@@ -260,13 +260,13 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
if not self._settings.get_boolean(["events", "throttled"]):
|
||||
return
|
||||
|
||||
args = dict(throttled_now=payload["current_issue"],
|
||||
throttled_past=payload["past_issue"],
|
||||
throttled_mask=payload["raw_value"],
|
||||
throttled_voltage_now=payload["current_undervoltage"],
|
||||
throttled_voltage_past=payload["past_undervoltage"],
|
||||
throttled_overheat_now=payload["current_overheat"],
|
||||
throttled_overheat_past=payload["past_overheat"])
|
||||
args = {"throttled_now": payload["current_issue"],
|
||||
"throttled_past": payload["past_issue"],
|
||||
"throttled_mask": payload["raw_value"],
|
||||
"throttled_voltage_now": payload["current_undervoltage"],
|
||||
"throttled_voltage_past": payload["past_undervoltage"],
|
||||
"throttled_overheat_now": payload["current_overheat"],
|
||||
"throttled_overheat_past": payload["past_overheat"]}
|
||||
|
||||
if payload["current_issue"]:
|
||||
track_event = "system_throttled"
|
||||
@@ -284,7 +284,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
return
|
||||
|
||||
track_event = "commerror_{}".format(payload["reason"])
|
||||
args = dict(commerror_text=payload["error"])
|
||||
args = {"commerror_text": payload["error"]}
|
||||
|
||||
if callable(self._helpers_get_throttle_state):
|
||||
try:
|
||||
@@ -312,7 +312,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
sha.update(unique_id.encode("utf-8"))
|
||||
|
||||
track_event = None
|
||||
args = dict(origin=payload.get("origin"), file=sha.hexdigest())
|
||||
args = {"origin": payload.get("origin"), "file": sha.hexdigest()}
|
||||
|
||||
if event == Events.PRINT_STARTED:
|
||||
track_event = "print_started"
|
||||
@@ -365,7 +365,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
return
|
||||
|
||||
if event in (Events.FIRMWARE_DATA,):
|
||||
args = dict(firmware_name=payload["name"])
|
||||
args = {"firmware_name": payload["name"]}
|
||||
if self._printer_connection_parameters:
|
||||
args["printer_port"] = self._printer_connection_parameters["port"]
|
||||
args["printer_baudrate"] = self._printer_connection_parameters["baudrate"]
|
||||
@@ -431,13 +431,13 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
pass
|
||||
|
||||
def _get_environment_payload(self):
|
||||
payload = dict(version=get_octoprint_version_string(),
|
||||
os=self._environment["os"]["id"],
|
||||
python=self._environment["python"]["version"],
|
||||
pip=self._environment["python"]["pip"],
|
||||
cores=self._environment["hardware"]["cores"],
|
||||
freq=self._environment["hardware"]["freq"],
|
||||
ram=self._environment["hardware"]["ram"])
|
||||
payload = {"version": get_octoprint_version_string(),
|
||||
"os": self._environment["os"]["id"],
|
||||
"python": self._environment["python"]["version"],
|
||||
"pip": self._environment["python"]["pip"],
|
||||
"cores": self._environment["hardware"]["cores"],
|
||||
"freq": self._environment["hardware"]["freq"],
|
||||
"ram": self._environment["hardware"]["ram"]}
|
||||
|
||||
if "plugins" in self._environment and "pi_support" in self._environment["plugins"]:
|
||||
payload["pi_model"] = self._environment["plugins"]["pi_support"]["model"]
|
||||
|
||||
@@ -11,7 +11,7 @@ class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.Tem
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings", custom_bindings=False)
|
||||
{"type": "settings", "custom_bindings": False}
|
||||
]
|
||||
|
||||
def get_settings_defaults(self):
|
||||
|
||||
@@ -91,7 +91,7 @@ class VirtualPrinter(object):
|
||||
self.extruderCount = self._settings.get_int(["numExtruders"])
|
||||
self.pinnedExtruders = self._settings.get(["pinnedExtruders"])
|
||||
if self.pinnedExtruders is None:
|
||||
self.pinnedExtruders = dict()
|
||||
self.pinnedExtruders = {}
|
||||
self.sharedNozzle = self._settings.get_boolean(["sharedNozzle"])
|
||||
self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount)
|
||||
|
||||
@@ -164,8 +164,8 @@ class VirtualPrinter(object):
|
||||
|
||||
self._debug_awol = False
|
||||
self._debug_sleep = 0
|
||||
self._sleepAfterNext = dict()
|
||||
self._sleepAfter = dict()
|
||||
self._sleepAfterNext = {}
|
||||
self._sleepAfter = {}
|
||||
self._rerequest_last = False
|
||||
|
||||
self._dont_answer = False
|
||||
@@ -1030,10 +1030,10 @@ class VirtualPrinter(object):
|
||||
if not entry.is_file():
|
||||
continue
|
||||
dosname = get_dos_filename(entry.name, existing_filenames=list(result.keys())).lower()
|
||||
result[dosname] = dict(name=entry.name,
|
||||
path=entry.path,
|
||||
dosname=dosname,
|
||||
size=entry.stat().st_size)
|
||||
result[dosname] = {"name": entry.name,
|
||||
"path": entry.path,
|
||||
"dosname": dosname,
|
||||
"size": entry.stat().st_size}
|
||||
return result
|
||||
|
||||
def _selectSdFile(self, filename, check_already_open=False):
|
||||
|
||||
@@ -208,36 +208,28 @@ class PrinterProfileManager(object):
|
||||
load and save printer profiles.
|
||||
"""
|
||||
|
||||
default = dict(
|
||||
id = "_default",
|
||||
name = "Default",
|
||||
model = "Generic RepRap Printer",
|
||||
color = "default",
|
||||
volume=dict(
|
||||
width = 200,
|
||||
depth = 200,
|
||||
height = 200,
|
||||
formFactor = BedFormFactor.RECTANGULAR,
|
||||
origin = BedOrigin.LOWERLEFT,
|
||||
custom_box = False
|
||||
),
|
||||
heatedBed = True,
|
||||
heatedChamber = False,
|
||||
extruder=dict(
|
||||
count = 1,
|
||||
offsets = [
|
||||
(0, 0)
|
||||
],
|
||||
nozzleDiameter = 0.4,
|
||||
sharedNozzle = False
|
||||
),
|
||||
axes=dict(
|
||||
x = dict(speed=6000, inverted=False),
|
||||
y = dict(speed=6000, inverted=False),
|
||||
z = dict(speed=200, inverted=False),
|
||||
e = dict(speed=300, inverted=False)
|
||||
)
|
||||
)
|
||||
default = {"id": "_default",
|
||||
"name": "Default",
|
||||
"model": "Generic RepRap Printer",
|
||||
"color": "default",
|
||||
"volume": {"width": 200,
|
||||
"depth": 200,
|
||||
"height": 200,
|
||||
"formFactor": BedFormFactor.RECTANGULAR,
|
||||
"origin": BedOrigin.LOWERLEFT,
|
||||
"custom_box": False},
|
||||
"heatedBed": True,
|
||||
"heatedChamber": False,
|
||||
"extruder": {"count": 1,
|
||||
"offsets": [
|
||||
(0, 0)
|
||||
],
|
||||
"nozzleDiameter": 0.4,
|
||||
"sharedNozzle": False},
|
||||
"axes": {"x": {"speed": 6000, "inverted": False},
|
||||
"y": {"speed": 6000, "inverted": False},
|
||||
"z": {"speed": 200, "inverted": False},
|
||||
"e": {"speed": 300, "inverted": False}}}
|
||||
|
||||
def __init__(self):
|
||||
self._current = None
|
||||
@@ -329,7 +321,7 @@ class PrinterProfileManager(object):
|
||||
removed = self._remove_from_path(self._get_profile_path(identifier))
|
||||
if removed and trigger_event:
|
||||
from octoprint.events import eventManager, Events
|
||||
payload = dict(identifier=identifier)
|
||||
payload = {"identifier": identifier}
|
||||
eventManager().fire(Events.PRINTER_PROFILE_DELETED, payload=payload)
|
||||
|
||||
return removed
|
||||
@@ -363,7 +355,7 @@ class PrinterProfileManager(object):
|
||||
|
||||
from octoprint.events import eventManager, Events
|
||||
if trigger_event:
|
||||
payload = dict(identifier=identifier)
|
||||
payload = {"identifier": identifier}
|
||||
event = Events.PRINTER_PROFILE_MODIFIED if is_overwrite else Events.PRINTER_PROFILE_ADDED
|
||||
eventManager().fire(event, payload=payload)
|
||||
|
||||
@@ -420,7 +412,7 @@ class PrinterProfileManager(object):
|
||||
|
||||
def _load_all(self):
|
||||
all_identifiers = self._load_all_identifiers()
|
||||
results = dict()
|
||||
results = {}
|
||||
for identifier, path in all_identifiers.items():
|
||||
try:
|
||||
profile = self._load_from_path(path)
|
||||
@@ -435,7 +427,7 @@ class PrinterProfileManager(object):
|
||||
return results
|
||||
|
||||
def _load_all_identifiers(self):
|
||||
results = dict()
|
||||
results = {}
|
||||
for entry in scandir(self._folder):
|
||||
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
|
||||
continue
|
||||
@@ -648,16 +640,16 @@ class PrinterProfileManager(object):
|
||||
if volume["origin"] == BedOrigin.CENTER:
|
||||
half_width = volume["width"] / 2.0
|
||||
half_depth = volume["depth"] / 2.0
|
||||
return dict(x_min=-half_width,
|
||||
x_max=half_width,
|
||||
y_min=-half_depth,
|
||||
y_max=half_depth,
|
||||
z_min=0.0,
|
||||
z_max=volume["height"])
|
||||
return {"x_min": -half_width,
|
||||
"x_max": half_width,
|
||||
"y_min": -half_depth,
|
||||
"y_max": half_depth,
|
||||
"z_min": 0.0,
|
||||
"z_max": volume["height"]}
|
||||
else:
|
||||
return dict(x_min=0.0,
|
||||
x_max=volume["width"],
|
||||
y_min=0.0,
|
||||
y_max=volume["depth"],
|
||||
z_min=0.0,
|
||||
z_max=volume["height"])
|
||||
return {"x_min": 0.0,
|
||||
"x_max": volume["width"],
|
||||
"y_min": 0.0,
|
||||
"y_max": volume["depth"],
|
||||
"z_min": 0.0,
|
||||
"z_max": volume["height"]}
|
||||
@@ -97,7 +97,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._estimator_factory = estimator
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing analysis queues from {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
#hook card upload
|
||||
self.sd_card_upload_hooks = plugin_manager().get_hooks("octoprint.printer.sdcardupload")
|
||||
@@ -184,7 +184,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
callback.on_printer_add_temperature(data)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while adding temperature data point to callback {}".format(callback),
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
extra={"callback": fqcn(callback)})
|
||||
|
||||
def _sendAddLogCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
@@ -192,7 +192,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
callback.on_printer_add_log(data)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while adding communication log entry to callback {}".format(callback),
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
extra={"callback": fqcn(callback)})
|
||||
|
||||
def _sendAddMessageCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
@@ -200,7 +200,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
callback.on_printer_add_message(data)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while adding printer message to callback {}".format(callback),
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
extra={"callback": fqcn(callback)})
|
||||
|
||||
def _sendCurrentDataCallbacks(self, data):
|
||||
plugin_data = self._get_additional_plugin_data(initial=False)
|
||||
@@ -212,7 +212,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
callback.on_printer_send_current_data(data_copy)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while pushing current data to callback {}".format(callback),
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
extra={"callback": fqcn(callback)})
|
||||
|
||||
def _get_additional_plugin_data(self, initial=False):
|
||||
plugin_data = {}
|
||||
@@ -265,7 +265,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
plugin.on_print_progress(storage, filename, progress)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while sending print progress to plugin %s" % plugin._identifier,
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
|
||||
thread = threading.Thread(target=call_plugins, args=(storage, filename, progress))
|
||||
thread.daemon = False
|
||||
@@ -371,7 +371,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
|
||||
|
||||
axes = dict()
|
||||
axes = {}
|
||||
axes[axis] = amount
|
||||
|
||||
if not axes:
|
||||
@@ -468,7 +468,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
def set_temperature_offset(self, offsets=None, *args, **kwargs):
|
||||
if offsets is None:
|
||||
offsets = dict()
|
||||
offsets = {}
|
||||
|
||||
if not isinstance(offsets, dict):
|
||||
raise ValueError("offsets must be a dict")
|
||||
@@ -655,7 +655,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if self._comm is not None:
|
||||
offsets = self._comm.getOffsets()
|
||||
else:
|
||||
offsets = dict()
|
||||
offsets = {}
|
||||
|
||||
result = {}
|
||||
if self._temp is not None:
|
||||
@@ -733,7 +733,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if self._comm is None or not self._comm.isSdReady():
|
||||
result = []
|
||||
else:
|
||||
result = list(map(lambda x: dict(name=x[0][1:], size=x[1], display=x[2]), self._comm.getSdFiles()))
|
||||
result = list(map(lambda x: {"name": x[0][1:], "size": x[1], "display": x[2]}, self._comm.getSdFiles()))
|
||||
return result
|
||||
|
||||
def add_sd_file(self, filename, path, on_success=None, on_failure=None, *args, **kwargs):
|
||||
@@ -745,21 +745,21 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._streamingFailedCallback = on_failure
|
||||
|
||||
def sd_upload_started(local_filename, remote_filename):
|
||||
eventManager().fire(Events.TRANSFER_STARTED, dict(local=local_filename,
|
||||
remote=remote_filename))
|
||||
eventManager().fire(Events.TRANSFER_STARTED, {"local": local_filename,
|
||||
"remote": remote_filename})
|
||||
|
||||
def sd_upload_succeeded(local_filename, remote_filename, elapsed):
|
||||
payload = dict(local=local_filename,
|
||||
remote=remote_filename,
|
||||
time=elapsed)
|
||||
payload = {"local": local_filename,
|
||||
"remote": remote_filename,
|
||||
"time": elapsed}
|
||||
eventManager().fire(Events.TRANSFER_DONE, payload)
|
||||
if callable(self._streamingFinishedCallback):
|
||||
self._streamingFinishedCallback(remote_filename, remote_filename, FileDestinations.SDCARD)
|
||||
|
||||
def sd_upload_failed(local_filename, remote_filename, elapsed):
|
||||
payload = dict(local=local_filename,
|
||||
remote=remote_filename,
|
||||
time=elapsed)
|
||||
payload = {"local": local_filename,
|
||||
"remote": remote_filename,
|
||||
"time": elapsed}
|
||||
eventManager().fire(Events.TRANSFER_FAILED, payload)
|
||||
if callable(self._streamingFailedCallback):
|
||||
self._streamingFailedCallback(remote_filename, remote_filename, FileDestinations.SDCARD)
|
||||
@@ -774,7 +774,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
except Exception:
|
||||
self._logger.exception("There was an error running the sd upload "
|
||||
"hook provided by plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
else:
|
||||
# no plugin feels responsible, use the default implementation
|
||||
@@ -852,10 +852,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._state = state
|
||||
self._stateMonitor.set_state(self._dict(text=state_string, flags=self._getStateFlags()))
|
||||
|
||||
payload = dict(
|
||||
state_id=self.get_state_id(self._state),
|
||||
state_string=self.get_state_string(self._state)
|
||||
)
|
||||
payload = {"state_id": self.get_state_id(self._state),
|
||||
"state_string": self.get_state_string(self._state)}
|
||||
eventManager().fire(Events.PRINTER_STATE_CHANGED, payload)
|
||||
|
||||
def _addLog(self, log):
|
||||
@@ -925,11 +923,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
def _addTemperatureData(self, tools=None, bed=None, chamber=None, custom=None):
|
||||
if tools is None:
|
||||
tools = dict()
|
||||
tools = {}
|
||||
if custom is None:
|
||||
custom = dict()
|
||||
custom = {}
|
||||
|
||||
data = dict(time=int(time.time()))
|
||||
data = {"time": int(time.time())}
|
||||
for tool in tools.keys():
|
||||
data["tool%d" % tool] = self._dict(actual=tools[tool][0], target=tools[tool][1])
|
||||
if bed is not None and isinstance(bed, tuple):
|
||||
@@ -1075,7 +1073,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
callback.on_printer_send_initial_data(data)
|
||||
except Exception:
|
||||
self._logger.exception(u"Error while pushing initial state update to callback {}".format(callback),
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
extra={"callback": fqcn(callback)})
|
||||
|
||||
def _getStateFlags(self):
|
||||
return self._dict(operational=self.is_operational(),
|
||||
@@ -1100,14 +1098,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
def on_comm_temperature_update(self, tools, bed, chamber, custom=None):
|
||||
if custom is None:
|
||||
custom = dict()
|
||||
custom = {}
|
||||
self._addTemperatureData(tools=copy.deepcopy(tools),
|
||||
bed=copy.deepcopy(bed),
|
||||
chamber=copy.deepcopy(chamber),
|
||||
custom=copy.deepcopy(custom))
|
||||
|
||||
def on_comm_position_update(self, position, reason=None):
|
||||
payload = dict(reason=reason)
|
||||
payload = {"reason": reason}
|
||||
payload.update(position)
|
||||
eventManager().fire(Events.POSITION_UPDATE, payload)
|
||||
|
||||
@@ -1243,7 +1241,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
if not suppress_script:
|
||||
self.script("beforePrintStarted",
|
||||
context=dict(event=payload),
|
||||
context={"event": payload},
|
||||
part_of_job=True,
|
||||
must_be_set=False)
|
||||
|
||||
@@ -1266,7 +1264,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
if not suppress_script:
|
||||
self.script("afterPrintDone",
|
||||
context=dict(event=payload),
|
||||
context={"event": payload},
|
||||
part_of_job=True,
|
||||
must_be_set=False)
|
||||
|
||||
@@ -1311,7 +1309,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
if not suppress_script:
|
||||
self.script("afterPrintCancelled",
|
||||
context=dict(event=payload),
|
||||
context={"event": payload},
|
||||
part_of_job=True,
|
||||
must_be_set=False)
|
||||
|
||||
@@ -1341,7 +1339,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
payload.get("user")))
|
||||
if not suppress_script:
|
||||
self.script("afterPrintPaused",
|
||||
context=dict(event=payload),
|
||||
context={"event": payload},
|
||||
part_of_job=True,
|
||||
must_be_set=False)
|
||||
|
||||
@@ -1356,13 +1354,13 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
if not suppress_script:
|
||||
self.script("beforePrintResumed",
|
||||
context=dict(event=payload),
|
||||
context={"event": payload},
|
||||
part_of_job=True,
|
||||
must_be_set=False)
|
||||
|
||||
def on_comm_file_transfer_started(self, local_filename, remote_filename, filesize, user=None):
|
||||
eventManager().fire(Events.TRANSFER_STARTED, dict(local=local_filename,
|
||||
remote=remote_filename))
|
||||
eventManager().fire(Events.TRANSFER_STARTED, {"local": local_filename,
|
||||
"remote": remote_filename})
|
||||
|
||||
self._sdStreaming = True
|
||||
|
||||
@@ -1373,9 +1371,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
def on_comm_file_transfer_done(self, local_filename, remote_filename, elapsed, failed=False):
|
||||
self._sdStreaming = False
|
||||
|
||||
payload = dict(local=local_filename,
|
||||
remote=remote_filename,
|
||||
time=elapsed)
|
||||
payload = {"local": local_filename,
|
||||
"remote": remote_filename,
|
||||
"time": elapsed}
|
||||
|
||||
if failed:
|
||||
eventManager().fire(Events.TRANSFER_FAILED, payload)
|
||||
@@ -1411,7 +1409,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
with self._selectedFileMutex:
|
||||
selected_file = self._selectedFile
|
||||
if not selected_file:
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
print_job_file = selected_file.get("filename", None)
|
||||
print_job_size = selected_file.get("filesize", None)
|
||||
@@ -1419,7 +1417,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL
|
||||
|
||||
if not print_job_file or not location:
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
if location == FileDestinations.SDCARD:
|
||||
full_path = print_job_file
|
||||
@@ -1434,10 +1432,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
_, name = self._fileManager.split_path(FileDestinations.LOCAL, path)
|
||||
origin = FileDestinations.LOCAL
|
||||
|
||||
result= dict(name=name,
|
||||
path=path,
|
||||
origin=origin,
|
||||
size=print_job_size)
|
||||
result= {"name": name,
|
||||
"path": path,
|
||||
"origin": origin,
|
||||
"size": print_job_size}
|
||||
|
||||
if position is not None:
|
||||
result["position"] = position
|
||||
@@ -1463,7 +1461,7 @@ class StateMonitor(object):
|
||||
self._state = None
|
||||
self._job_data = None
|
||||
self._current_z = None
|
||||
self._offsets = dict()
|
||||
self._offsets = {}
|
||||
self._progress = None
|
||||
|
||||
self._progress_dirty = False
|
||||
@@ -1527,7 +1525,7 @@ class StateMonitor(object):
|
||||
|
||||
def set_temp_offsets(self, offsets):
|
||||
if offsets is None:
|
||||
offsets = dict()
|
||||
offsets = {}
|
||||
self._offsets = offsets
|
||||
self._change_event.set()
|
||||
|
||||
|
||||
@@ -325,7 +325,7 @@ class Server(object):
|
||||
printerProfileManager = PrinterProfileManager()
|
||||
eventManager = self._event_manager
|
||||
|
||||
analysis_queue_factories = dict(gcode=octoprint.filemanager.analysis.GcodeAnalysisQueue)
|
||||
analysis_queue_factories = {"gcode": octoprint.filemanager.analysis.GcodeAnalysisQueue}
|
||||
analysis_queue_hooks = pluginManager.get_hooks("octoprint.filemanager.analysis.factory")
|
||||
for name, hook in analysis_queue_hooks.items():
|
||||
try:
|
||||
@@ -333,12 +333,12 @@ class Server(object):
|
||||
analysis_queue_factories.update(**additional_factories)
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing analysis queues from {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue(analysis_queue_factories)
|
||||
|
||||
slicingManager = octoprint.slicing.SlicingManager(self._settings.getBaseFolder("slicingProfiles"), printerProfileManager)
|
||||
|
||||
storage_managers = dict()
|
||||
storage_managers = {}
|
||||
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(self._settings.getBaseFolder("uploads"))
|
||||
|
||||
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
|
||||
@@ -351,7 +351,7 @@ class Server(object):
|
||||
|
||||
# start regular check if we are connected to the internet
|
||||
def on_connectivity_change(old_value, new_value):
|
||||
eventManager.fire(events.Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value))
|
||||
eventManager.fire(events.Events.CONNECTIVITY_CHANGED, payload={"old": old_value, "new": new_value})
|
||||
|
||||
connectivityChecker = self._connectivity_checker
|
||||
|
||||
@@ -377,20 +377,18 @@ class Server(object):
|
||||
|
||||
eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update)
|
||||
|
||||
components = dict(
|
||||
plugin_manager=pluginManager,
|
||||
printer_profile_manager=printerProfileManager,
|
||||
event_bus=eventManager,
|
||||
analysis_queue=analysisQueue,
|
||||
slicing_manager=slicingManager,
|
||||
file_manager=fileManager,
|
||||
plugin_lifecycle_manager=pluginLifecycleManager,
|
||||
preemptive_cache=preemptiveCache,
|
||||
json_encoder=jsonEncoder,
|
||||
json_decoder=jsonDecoder,
|
||||
connectivity_checker=connectivityChecker,
|
||||
environment_detector=self._environment_detector
|
||||
)
|
||||
components = {"plugin_manager": pluginManager,
|
||||
"printer_profile_manager": printerProfileManager,
|
||||
"event_bus": eventManager,
|
||||
"analysis_queue": analysisQueue,
|
||||
"slicing_manager": slicingManager,
|
||||
"file_manager": fileManager,
|
||||
"plugin_lifecycle_manager": pluginLifecycleManager,
|
||||
"preemptive_cache": preemptiveCache,
|
||||
"json_encoder": jsonEncoder,
|
||||
"json_decoder": jsonDecoder,
|
||||
"connectivity_checker": connectivityChecker,
|
||||
"environment_detector": self._environment_detector}
|
||||
|
||||
#~~ setup access control
|
||||
|
||||
@@ -416,7 +414,7 @@ class Server(object):
|
||||
self._logger.exception("Could not instantiate group manager {}, "
|
||||
"falling back to FilebasedGroupManager!".format(group_manager_name))
|
||||
groupManager = octoprint.access.groups.FilebasedGroupManager()
|
||||
components.update(dict(group_manager=groupManager))
|
||||
components.update({"group_manager": groupManager})
|
||||
|
||||
# create user manager instance
|
||||
user_manager_factories = pluginManager.get_hooks("octoprint.users.factory") # legacy, set first so that new wins
|
||||
@@ -429,7 +427,7 @@ class Server(object):
|
||||
break
|
||||
except Exception:
|
||||
self._logger.exception("Error while creating user manager instance from factory {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
user_manager_name = self._settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
@@ -441,7 +439,7 @@ class Server(object):
|
||||
userManager = octoprint.access.users.FilebasedUserManager(groupManager)
|
||||
finally:
|
||||
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
|
||||
components.update(dict(user_manager=userManager))
|
||||
components.update({"user_manager": userManager})
|
||||
|
||||
# create printer instance
|
||||
printer_factories = pluginManager.get_hooks("octoprint.printer.factory")
|
||||
@@ -453,10 +451,10 @@ class Server(object):
|
||||
break
|
||||
except Exception:
|
||||
self._logger.exception("Error while creating printer instance from factory {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
printer = Printer(fileManager, analysisQueue, printerProfileManager)
|
||||
components.update(dict(printer=printer))
|
||||
components.update({"printer": printer})
|
||||
|
||||
def octoprint_plugin_inject_factory(name, implementation):
|
||||
"""Factory for injections for all OctoPrintPlugins"""
|
||||
@@ -494,11 +492,9 @@ class Server(object):
|
||||
|
||||
components_copy["printer"] = TaggedFuncsPrinter(components["printer"])
|
||||
|
||||
props = dict()
|
||||
props = {}
|
||||
props.update(components_copy)
|
||||
props.update(dict(
|
||||
data_folder=os.path.join(self._settings.getBaseFolder("data"), name)
|
||||
))
|
||||
props.update({"data_folder": os.path.join(self._settings.getBaseFolder("data"), name)})
|
||||
return props
|
||||
|
||||
def settings_plugin_inject_factory(name, implementation):
|
||||
@@ -506,7 +502,7 @@ class Server(object):
|
||||
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
|
||||
return
|
||||
|
||||
default_settings_overlay = dict(plugins=dict())
|
||||
default_settings_overlay = {"plugins": {}}
|
||||
default_settings_overlay["plugins"][name] = implementation.get_settings_defaults()
|
||||
self._settings.add_overlay(default_settings_overlay, at_end=True)
|
||||
|
||||
@@ -514,7 +510,7 @@ class Server(object):
|
||||
if plugin_settings is None:
|
||||
return
|
||||
|
||||
return dict(settings=plugin_settings)
|
||||
return {"settings": plugin_settings}
|
||||
|
||||
def settings_plugin_config_migration_and_cleanup(identifier, implementation):
|
||||
"""Take care of migrating and cleaning up any old settings"""
|
||||
@@ -546,7 +542,7 @@ class Server(object):
|
||||
self._logger.debug("Registered event {} of plugin {} as Events.{} = \"{}\"".format(event, name, constant, value))
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving custom event list from plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory,
|
||||
settings_plugin_inject_factory]
|
||||
@@ -559,7 +555,7 @@ class Server(object):
|
||||
except Exception:
|
||||
self._logger.exception("Error while trying to migrate settings for "
|
||||
"plugin {}, ignoring it".format(implementation._identifier),
|
||||
extra=dict(plugin=implementation._identifier))
|
||||
extra={"plugin": implementation._identifier})
|
||||
|
||||
pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup]
|
||||
|
||||
@@ -606,11 +602,11 @@ class Server(object):
|
||||
|
||||
self._router = SockJSRouter(self._create_socket_connection, "/sockjs",
|
||||
session_kls=util.sockjs.ThreadSafeSession,
|
||||
user_settings=dict(websocket_allow_origin="*" if enable_cors else "",
|
||||
jsessionid=False,
|
||||
sockjs_url="../../static/js/lib/sockjs.min.js"))
|
||||
user_settings={"websocket_allow_origin": "*" if enable_cors else "",
|
||||
"jsessionid": False,
|
||||
"sockjs_url": "../../static/js/lib/sockjs.min.js"})
|
||||
|
||||
upload_suffixes = dict(name=self._settings.get(["server", "uploads", "nameSuffix"]), path=self._settings.get(["server", "uploads", "pathSuffix"]))
|
||||
upload_suffixes = {"name": self._settings.get(["server", "uploads", "nameSuffix"]), "path": self._settings.get(["server", "uploads", "pathSuffix"])}
|
||||
|
||||
def mime_type_guesser(path):
|
||||
from octoprint.filemanager import get_mime_type
|
||||
@@ -621,12 +617,10 @@ class Server(object):
|
||||
if metadata and "display" in metadata:
|
||||
return metadata["display"]
|
||||
|
||||
download_handler_kwargs = dict(
|
||||
as_attachment=True,
|
||||
allow_client_caching=False
|
||||
)
|
||||
download_handler_kwargs = {"as_attachment": True,
|
||||
"allow_client_caching": False}
|
||||
|
||||
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
|
||||
additional_mime_types={"mime_type_guesser": mime_type_guesser}
|
||||
|
||||
##~~ Permission validators
|
||||
|
||||
@@ -636,29 +630,29 @@ class Server(object):
|
||||
access_validators_from_plugins.append(util.tornado.access_validation_factory(app, hook))
|
||||
except Exception:
|
||||
self._logger.exception("Error while adding tornado access validator from plugin {}".format(plugin),
|
||||
extra=dict(plugin=plugin))
|
||||
access_validator = dict(access_validation=util.tornado.validation_chain(*access_validators_from_plugins))
|
||||
extra={"plugin": plugin})
|
||||
access_validator = {"access_validation": util.tornado.validation_chain(*access_validators_from_plugins)}
|
||||
|
||||
timelapse_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.TIMELAPSE_LIST),] + access_validators_from_plugins
|
||||
download_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.FILES_DOWNLOAD),] + access_validators_from_plugins
|
||||
log_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.PLUGIN_LOGGING_MANAGE),] + access_validators_from_plugins
|
||||
camera_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.WEBCAM),] + access_validators_from_plugins
|
||||
|
||||
timelapse_permission_validator = dict(access_validation=util.tornado.validation_chain(*timelapse_validators))
|
||||
download_permission_validator = dict(access_validation=util.tornado.validation_chain(*download_validators))
|
||||
log_permission_validator = dict(access_validation=util.tornado.validation_chain(*log_validators))
|
||||
camera_permission_validator = dict(access_validation=util.tornado.validation_chain(*camera_validators))
|
||||
timelapse_permission_validator = {"access_validation": util.tornado.validation_chain(*timelapse_validators)}
|
||||
download_permission_validator = {"access_validation": util.tornado.validation_chain(*download_validators)}
|
||||
log_permission_validator = {"access_validation": util.tornado.validation_chain(*log_validators)}
|
||||
camera_permission_validator = {"access_validation": util.tornado.validation_chain(*camera_validators)}
|
||||
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path),
|
||||
status_code=404))
|
||||
timelapse_path_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path) and octoprint.timelapse.valid_timelapse(path),
|
||||
status_code=404))
|
||||
no_hidden_files_validator = {"path_validation": util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path),
|
||||
status_code=404)}
|
||||
timelapse_path_validator = {"path_validation": util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path) and octoprint.timelapse.valid_timelapse(path),
|
||||
status_code=404)}
|
||||
|
||||
def joined_dict(*dicts):
|
||||
if not len(dicts):
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
joined = dict()
|
||||
joined = {}
|
||||
for d in dicts:
|
||||
joined.update(d)
|
||||
return joined
|
||||
@@ -669,38 +663,38 @@ class Server(object):
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
# .mpg and .mp4 timelapses:
|
||||
(r"/downloads/timelapse/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
|
||||
(r"/downloads/timelapse/(.*)", util.tornado.LargeResponseHandler, joined_dict({"path": self._settings.getBaseFolder("timelapse")},
|
||||
timelapse_permission_validator,
|
||||
download_handler_kwargs,
|
||||
timelapse_path_validator)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads"),
|
||||
as_attachment=True,
|
||||
name_generator=download_name_generator),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict({"path": self._settings.getBaseFolder("uploads"),
|
||||
"as_attachment": True,
|
||||
"name_generator": download_name_generator},
|
||||
download_permission_validator,
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator,
|
||||
additional_mime_types)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("logs"),
|
||||
mime_type_guesser=lambda *args, **kwargs: "text/plain",
|
||||
stream_body=True),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict({"path": self._settings.getBaseFolder("logs"),
|
||||
"mime_type_guesser": lambda *args, **kwargs: "text/plain",
|
||||
"stream_body": True},
|
||||
download_handler_kwargs,
|
||||
log_permission_validator)),
|
||||
# camera snapshot
|
||||
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, joined_dict(dict(url=self._settings.get(["webcam", "snapshot"]),
|
||||
as_attachment=True),
|
||||
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, joined_dict({"url": self._settings.get(["webcam", "snapshot"]),
|
||||
"as_attachment": True},
|
||||
camera_permission_validator)),
|
||||
# generated webassets
|
||||
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(self._settings.getBaseFolder("generated"), "webassets"),
|
||||
is_pre_compressed=True)),
|
||||
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, {"path": os.path.join(self._settings.getBaseFolder("generated"), "webassets"),
|
||||
"is_pre_compressed": True}),
|
||||
|
||||
# online indicators - text file with "online" as content and a transparent gif
|
||||
(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
|
||||
(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")),
|
||||
content_type="image/gif")),
|
||||
(r"/online.txt", util.tornado.StaticDataHandler, {"data": "online\n"}),
|
||||
(r"/online.gif", util.tornado.StaticDataHandler, {"data": bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")),
|
||||
"content_type": "image/gif"}),
|
||||
|
||||
# deprecated endpoints
|
||||
(r"/api/logs", util.tornado.DeprecatedEndpointHandler, dict(url="/plugin/logging/logs")),
|
||||
(r"/api/logs/(.*)", util.tornado.DeprecatedEndpointHandler, dict(url="/plugin/logging/logs/{0}")),
|
||||
(r"/api/logs", util.tornado.DeprecatedEndpointHandler, {"url": "/plugin/logging/logs"}),
|
||||
(r"/api/logs/(.*)", util.tornado.DeprecatedEndpointHandler, {"url": "/plugin/logging/logs/{0}"}),
|
||||
]
|
||||
|
||||
# fetch additional routes from plugins
|
||||
@@ -710,7 +704,7 @@ class Server(object):
|
||||
except Exception:
|
||||
self._logger.exception("There was an error while retrieving additional "
|
||||
"server routes from plugin hook {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
if isinstance(result, (list, tuple)):
|
||||
for entry in result:
|
||||
@@ -734,12 +728,12 @@ class Server(object):
|
||||
|
||||
removed_headers = ["Server"]
|
||||
|
||||
server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app,
|
||||
server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, {"fallback": util.tornado.WsgiInputContainer(app.wsgi_app,
|
||||
headers=headers,
|
||||
removed_headers=removed_headers),
|
||||
file_prefix="octoprint-file-upload-",
|
||||
file_suffix=".tmp",
|
||||
suffixes=upload_suffixes)))
|
||||
"file_prefix": "octoprint-file-upload-",
|
||||
"file_suffix": ".tmp",
|
||||
"suffixes": upload_suffixes}))
|
||||
|
||||
transforms = [util.tornado.GlobalHeaderTransform.for_headers("OctoPrintGlobalHeaderTransform",
|
||||
headers=headers,
|
||||
@@ -759,7 +753,7 @@ class Server(object):
|
||||
except Exception:
|
||||
self._logger.exception("There was an error while retrieving additional "
|
||||
"upload sizes from plugin hook {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
if isinstance(result, (list, tuple)):
|
||||
for entry in result:
|
||||
@@ -784,13 +778,13 @@ class Server(object):
|
||||
self._logger.warning("server.reverseProxy.trustedDownstream is not a list, skipping")
|
||||
trusted_downstreams = []
|
||||
|
||||
server_kwargs = dict(max_body_sizes=max_body_sizes,
|
||||
default_max_body_size=self._settings.getInt(["server", "maxSize"]),
|
||||
xheaders=True,
|
||||
trusted_downstream=trusted_downstream)
|
||||
server_kwargs = {"max_body_sizes": max_body_sizes,
|
||||
"default_max_body_size": self._settings.getInt(["server", "maxSize"]),
|
||||
"xheaders": True,
|
||||
"trusted_downstream": trusted_downstream}
|
||||
if sys.platform == "win32":
|
||||
# set 10min idle timeout under windows to hopefully make #2916 less likely
|
||||
server_kwargs.update(dict(idle_connection_timeout=600))
|
||||
server_kwargs.update({"idle_connection_timeout": 600})
|
||||
|
||||
self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs)
|
||||
|
||||
@@ -1245,7 +1239,7 @@ class Server(object):
|
||||
logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry")
|
||||
continue
|
||||
|
||||
additional_request_data = kwargs.get("_additional_request_data", dict())
|
||||
additional_request_data = kwargs.get("_additional_request_data", {})
|
||||
kwargs = dict((k, v) for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin")
|
||||
kwargs.update(additional_request_data)
|
||||
|
||||
@@ -1256,7 +1250,7 @@ class Server(object):
|
||||
else:
|
||||
logger.info("Preemptively caching {} (ui _default) for {!r}".format(route, kwargs))
|
||||
|
||||
headers = kwargs.get("headers", dict())
|
||||
headers = kwargs.get("headers", {})
|
||||
headers["X-Force-View"] = plugin if plugin else "_default"
|
||||
headers["X-Preemptive-Recording"] = "yes"
|
||||
kwargs["headers"] = headers
|
||||
@@ -1323,7 +1317,7 @@ class Server(object):
|
||||
except Exception:
|
||||
self._logger.exception("Error while registering blueprint of "
|
||||
"plugin {}, ignoring it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
continue
|
||||
|
||||
return blueprints
|
||||
@@ -1341,7 +1335,7 @@ class Server(object):
|
||||
except Exception:
|
||||
self._logger.exception("Error while registering assets of plugin "
|
||||
"{}, ignoring it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
continue
|
||||
|
||||
return blueprints
|
||||
@@ -1393,7 +1387,7 @@ class Server(object):
|
||||
blueprint.before_request(h)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing before_request hooks from plugin {}".format(plugin),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
for name, hook in after_hooks.items():
|
||||
plugin = octoprint.plugin.plugin_manager().get_plugin(name)
|
||||
@@ -1405,7 +1399,7 @@ class Server(object):
|
||||
blueprint.after_request(h)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing after_request hooks from plugin {}".format(plugin),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
def _setup_mimetypes(self):
|
||||
# Safety measures for Windows... apparently the mimetypes module takes its translation from the windows
|
||||
@@ -1490,7 +1484,7 @@ class Server(object):
|
||||
|
||||
AdjustedEnvironment = type(Environment)(Environment.__name__,
|
||||
(Environment,),
|
||||
dict(resolver_class=util.flask.PluginAssetResolver))
|
||||
{"resolver_class": util.flask.PluginAssetResolver})
|
||||
class CustomDirectoryEnvironment(AdjustedEnvironment):
|
||||
@property
|
||||
def directory(self):
|
||||
@@ -1501,7 +1495,7 @@ class Server(object):
|
||||
|
||||
UpdaterType = type(util.flask.SettingsCheckUpdater)(util.flask.SettingsCheckUpdater.__name__,
|
||||
(util.flask.SettingsCheckUpdater,),
|
||||
dict(updater=assets.updater))
|
||||
{"updater": assets.updater})
|
||||
assets.updater = UpdaterType
|
||||
|
||||
preferred_stylesheet = self._settings.get(["devel", "stylesheet"])
|
||||
|
||||
@@ -77,7 +77,7 @@ def pluginData(name):
|
||||
raise
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error calling SimpleApiPlugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
return abort(500)
|
||||
|
||||
#~~ commands for plugins
|
||||
@@ -114,7 +114,7 @@ def pluginCommand(name):
|
||||
raise
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error while executing SimpleApiPlugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
return abort(500)
|
||||
|
||||
#~~ first run setup
|
||||
@@ -126,7 +126,7 @@ def wizardState():
|
||||
|
||||
seen_wizards = s().get(["server", "seenWizards"])
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
wizard_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.WizardPlugin)
|
||||
for implementation in wizard_plugins:
|
||||
name = implementation._identifier
|
||||
@@ -138,9 +138,9 @@ def wizardState():
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("There was an error fetching wizard "
|
||||
"details for {}, ignoring".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
result[name] = dict(required=required, details=details, version=version, ignored=ignored)
|
||||
result[name] = {"required": required, "details": details, "version": version, "ignored": ignored}
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
@@ -150,7 +150,7 @@ def wizardFinish():
|
||||
if not s().getBoolean(["server", "firstRun"]) and not Permissions.ADMIN.can():
|
||||
abort(403)
|
||||
|
||||
data = dict()
|
||||
data = {}
|
||||
try:
|
||||
data = request.get_json()
|
||||
except Exception:
|
||||
@@ -178,7 +178,7 @@ def wizardFinish():
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("There was an error finishing the "
|
||||
"wizard for {}, ignoring".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
s().set(["server", "seenWizards"], seen_wizards)
|
||||
s().save()
|
||||
@@ -256,7 +256,7 @@ def login():
|
||||
r = make_response(jsonify(response))
|
||||
r.delete_cookie("active_logout")
|
||||
|
||||
eventManager().fire(Events.USER_LOGGED_IN, payload=dict(username=user.get_id()))
|
||||
eventManager().fire(Events.USER_LOGGED_IN, payload={"username": user.get_id()})
|
||||
|
||||
return r
|
||||
|
||||
@@ -285,7 +285,7 @@ def logout():
|
||||
r.set_cookie("active_logout", "true")
|
||||
|
||||
if username:
|
||||
eventManager().fire(Events.USER_LOGGED_OUT, payload=dict(username=username))
|
||||
eventManager().fire(Events.USER_LOGGED_OUT, payload={"username": username})
|
||||
|
||||
return r
|
||||
|
||||
@@ -312,12 +312,10 @@ def get_current_user():
|
||||
@no_firstrun_access
|
||||
@Permissions.ADMIN.require(403)
|
||||
def utilTest():
|
||||
valid_commands = dict(
|
||||
path=["path"],
|
||||
url=["url"],
|
||||
server=["host", "port"],
|
||||
resolution=["name"]
|
||||
)
|
||||
valid_commands = {"path": ["path"],
|
||||
"url": ["url"],
|
||||
"server": ["host", "port"],
|
||||
"resolution": ["name"]}
|
||||
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
@@ -379,14 +377,14 @@ def _test_path(data):
|
||||
exists = True
|
||||
|
||||
# check path type
|
||||
type_mapping = dict(file=os.path.isfile, dir=os.path.isdir)
|
||||
type_mapping = {"file": os.path.isfile, "dir": os.path.isdir}
|
||||
if check_type:
|
||||
typeok = type_mapping[check_type](path)
|
||||
else:
|
||||
typeok = exists
|
||||
|
||||
# check if path allows requested access
|
||||
access_mapping = dict(r=os.R_OK, w=os.W_OK, x=os.X_OK)
|
||||
access_mapping = {"r": os.R_OK, "w": os.W_OK, "x": os.X_OK}
|
||||
if check_access:
|
||||
mode = 0
|
||||
for a in map(lambda x: access_mapping[x], check_access):
|
||||
@@ -430,22 +428,18 @@ def _test_url(data):
|
||||
return False
|
||||
|
||||
def as_dict(self):
|
||||
return dict(
|
||||
start=self.start,
|
||||
end=self.end
|
||||
)
|
||||
return {"start": self.start,
|
||||
"end": self.end}
|
||||
|
||||
status_ranges = dict(
|
||||
informational=StatusCodeRange(start=100, end=200),
|
||||
success=StatusCodeRange(start=200, end=300),
|
||||
redirection=StatusCodeRange(start=300, end=400),
|
||||
client_error=StatusCodeRange(start=400, end=500),
|
||||
server_error=StatusCodeRange(start=500, end=600),
|
||||
normal=StatusCodeRange(end=400),
|
||||
error=StatusCodeRange(start=400, end=600),
|
||||
any=StatusCodeRange(start=100),
|
||||
timeout=StatusCodeRange(start=0, end=1)
|
||||
)
|
||||
status_ranges = {"informational": StatusCodeRange(start=100, end=200),
|
||||
"success": StatusCodeRange(start=200, end=300),
|
||||
"redirection": StatusCodeRange(start=300, end=400),
|
||||
"client_error": StatusCodeRange(start=400, end=500),
|
||||
"server_error": StatusCodeRange(start=500, end=600),
|
||||
"normal": StatusCodeRange(end=400),
|
||||
"error": StatusCodeRange(start=400, end=600),
|
||||
"any": StatusCodeRange(start=100),
|
||||
"timeout": StatusCodeRange(start=0, end=1)}
|
||||
|
||||
url = data["url"]
|
||||
method = data.get("method", "HEAD")
|
||||
@@ -500,8 +494,8 @@ def _test_url(data):
|
||||
outcome = outcome and any(map(lambda x: status in x, check_status))
|
||||
content_type = response.headers.get("content-type")
|
||||
|
||||
response_result = dict(headers=dict(response.headers),
|
||||
content_type=content_type)
|
||||
response_result = {"headers": dict(response.headers),
|
||||
"content_type": content_type}
|
||||
|
||||
if not content_type and data.get("content_type_guess") in valid_boolean_trues:
|
||||
content = response.content
|
||||
@@ -510,7 +504,7 @@ def _test_url(data):
|
||||
if not content_type:
|
||||
content_type = "application/octet-stream"
|
||||
|
||||
response_result = dict(assumed_content_type=content_type)
|
||||
response_result = {"assumed_content_type": content_type}
|
||||
|
||||
parsed_content_type = util.parse_mime_type(content_type)
|
||||
|
||||
@@ -538,11 +532,9 @@ def _test_url(data):
|
||||
logging.getLogger(__name__).exception("Error while running a test {} request on {}".format(method, url))
|
||||
outcome = False
|
||||
|
||||
result = dict(
|
||||
url=url,
|
||||
status=status,
|
||||
result=outcome
|
||||
)
|
||||
result = {"url": url,
|
||||
"status": status,
|
||||
"result": outcome}
|
||||
if response_result:
|
||||
result["response"] = response_result
|
||||
|
||||
@@ -570,10 +562,10 @@ def _test_server(data):
|
||||
from octoprint.util import server_reachable
|
||||
reachable = server_reachable(host, port, timeout=timeout, proto=protocol)
|
||||
|
||||
result = dict(host=host,
|
||||
port=port,
|
||||
protocol=protocol,
|
||||
result=reachable)
|
||||
result = {"host": host,
|
||||
"port": port,
|
||||
"protocol": protocol,
|
||||
"result": reachable}
|
||||
|
||||
return jsonify(**result)
|
||||
|
||||
@@ -583,7 +575,7 @@ def _test_resolution(data):
|
||||
from octoprint.util.net import resolve_host
|
||||
resolvable = len(resolve_host(name)) > 0
|
||||
|
||||
result = dict(name=name,
|
||||
result=resolvable)
|
||||
result = {"name": name,
|
||||
"result": resolvable}
|
||||
|
||||
return jsonify(**result)
|
||||
@@ -89,7 +89,7 @@ def update_group(key):
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
try:
|
||||
kwargs = dict()
|
||||
kwargs = {}
|
||||
|
||||
if "permissions" in data:
|
||||
kwargs["permissions"] = data["permissions"]
|
||||
|
||||
@@ -79,13 +79,11 @@ def _get_options():
|
||||
profile_options = printerProfileManager.get_all()
|
||||
default_profile = printerProfileManager.get_default()
|
||||
|
||||
options = dict(
|
||||
ports=connection_options["ports"],
|
||||
baudrates=connection_options["baudrates"],
|
||||
printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile],
|
||||
portPreference=connection_options["portPreference"],
|
||||
baudratePreference=connection_options["baudratePreference"],
|
||||
printerProfilePreference=default_profile["id"] if "id" in default_profile else None
|
||||
)
|
||||
options = {"ports": connection_options["ports"],
|
||||
"baudrates": connection_options["baudrates"],
|
||||
"printerProfiles": [{"id": printer_profile["id"], "name": printer_profile["name"] if "name" in printer_profile else printer_profile["id"]} for printer_profile in profile_options.values() if "id" in printer_profile],
|
||||
"portPreference": connection_options["portPreference"],
|
||||
"baudratePreference": connection_options["baudratePreference"],
|
||||
"printerProfilePreference": default_profile["id"] if "id" in default_profile else None}
|
||||
|
||||
return options
|
||||
@@ -31,7 +31,7 @@ import threading
|
||||
|
||||
#~~ GCODE file handling
|
||||
|
||||
_file_cache = dict()
|
||||
_file_cache = {}
|
||||
_file_cache_mutex = threading.RLock()
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
@@ -252,7 +252,7 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac
|
||||
if "children" in file_or_folder:
|
||||
file_or_folder["children"] = analyse_recursively(file_or_folder["children"].values(), path + file_or_folder["name"] + "/")
|
||||
|
||||
file_or_folder["refs"] = dict(resource=url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=path + file_or_folder["name"], _external=True))
|
||||
file_or_folder["refs"] = {"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=path + file_or_folder["name"], _external=True)}
|
||||
else:
|
||||
if "analysis" in file_or_folder and octoprint.filemanager.valid_file_type(file_or_folder["name"], type="gcode"):
|
||||
file_or_folder["gcodeAnalysis"] = file_or_folder["analysis"]
|
||||
@@ -271,20 +271,16 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac
|
||||
if not last or ("timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"]):
|
||||
last = entry
|
||||
if last:
|
||||
prints = dict(
|
||||
success=success,
|
||||
failure=failure,
|
||||
last=dict(
|
||||
success=last["success"],
|
||||
date=last["timestamp"]
|
||||
)
|
||||
)
|
||||
prints = {"success": success,
|
||||
"failure": failure,
|
||||
"last": {"success": last["success"],
|
||||
"date": last["timestamp"]}}
|
||||
if "printTime" in last:
|
||||
prints["last"]["printTime"] = last["printTime"]
|
||||
file_or_folder["prints"] = prints
|
||||
|
||||
file_or_folder["refs"] = dict(resource=url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file_or_folder["path"], _external=True),
|
||||
download=url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + file_or_folder["path"])
|
||||
file_or_folder["refs"] = {"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file_or_folder["path"], _external=True),
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + file_or_folder["path"]}
|
||||
|
||||
result.append(file_or_folder)
|
||||
|
||||
@@ -434,11 +430,11 @@ def uploadGcodeFile(target):
|
||||
if isinstance(filename, tuple):
|
||||
filename, sdFilename = filename
|
||||
|
||||
payload = dict(name=futureFilename,
|
||||
path=filename,
|
||||
target=target,
|
||||
select=selectAfterUpload,
|
||||
print=printAfterSelect)
|
||||
payload = {"name": futureFilename,
|
||||
"path": filename,
|
||||
"target": target,
|
||||
"select": selectAfterUpload,
|
||||
"print": printAfterSelect}
|
||||
if userdata is not None:
|
||||
payload["userdata"] = userdata
|
||||
eventManager.fire(Events.UPLOAD, payload)
|
||||
@@ -506,10 +502,10 @@ def uploadGcodeFile(target):
|
||||
target=FileDestinations.LOCAL,
|
||||
filename=added_folder,
|
||||
_external=True)
|
||||
folder = dict(name=futureName,
|
||||
path=added_folder,
|
||||
origin=target,
|
||||
refs=dict(resource=location))
|
||||
folder = {"name": futureName,
|
||||
"path": added_folder,
|
||||
"origin": target,
|
||||
"refs": {"resource": location}}
|
||||
|
||||
r = make_response(jsonify(folder=folder, done=True), 201)
|
||||
r.headers["Location"] = location
|
||||
@@ -658,7 +654,7 @@ def gcodeFileCommand(filename, target):
|
||||
select_after_slicing = print_after_slicing = True
|
||||
|
||||
override_keys = [k for k in data if k.startswith("profile.") and data[k] is not None]
|
||||
overrides = dict()
|
||||
overrides = {}
|
||||
for key in override_keys:
|
||||
overrides[key[len("profile."):]] = data[key]
|
||||
|
||||
|
||||
@@ -36,16 +36,16 @@ from flask_babel import Locale
|
||||
def getInstalledLanguagePacks():
|
||||
translation_folder = settings().getBaseFolder("translations", check_writable=False)
|
||||
if not os.path.exists(translation_folder):
|
||||
return jsonify(language_packs=dict(_core=[]))
|
||||
return jsonify(language_packs={"_core": []})
|
||||
|
||||
core_packs = []
|
||||
plugin_packs = defaultdict(lambda: dict(identifier=None, display=None, languages=[]))
|
||||
plugin_packs = defaultdict(lambda: {"identifier": None, "display": None, "languages": []})
|
||||
for entry in scandir(translation_folder):
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
|
||||
def load_meta(path, locale):
|
||||
meta = dict()
|
||||
meta = {}
|
||||
|
||||
meta_path = os.path.join(path, "meta.yaml")
|
||||
if os.path.isfile(meta_path):
|
||||
@@ -97,7 +97,7 @@ def getInstalledLanguagePacks():
|
||||
logging.getLogger(__name__).exception("Error while parsing metadata for core language pack {} from {}".format(entry.name,
|
||||
entry.path))
|
||||
|
||||
result = dict(_core=dict(identifier="_core", display="Core", languages=core_packs))
|
||||
result = {"_core": {"identifier": "_core", "display": "Core", "languages": core_packs}}
|
||||
result.update(plugin_packs)
|
||||
return jsonify(language_packs=result)
|
||||
|
||||
|
||||
@@ -438,7 +438,7 @@ def printerCommand():
|
||||
elif not ("command" in data or "commands" in data or "script" in data):
|
||||
return make_response("Need one of 'command', 'commands' or 'script'", 400)
|
||||
|
||||
parameters = dict()
|
||||
parameters = {}
|
||||
if "parameters" in data:
|
||||
parameters = data["parameters"]
|
||||
|
||||
@@ -463,7 +463,7 @@ def printerCommand():
|
||||
|
||||
elif "script" in data:
|
||||
script_name = data["script"]
|
||||
context = dict(parameters=parameters)
|
||||
context = {"parameters": parameters}
|
||||
if "context" in data:
|
||||
context["context"] = data["context"]
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ def _etag(lm=None):
|
||||
@Permissions.CONNECTION.require(403)
|
||||
def printerProfilesList():
|
||||
all_profiles = printerProfileManager.get_all()
|
||||
return jsonify(dict(profiles=_convert_profiles(all_profiles)))
|
||||
return jsonify({"profiles": _convert_profiles(all_profiles)})
|
||||
|
||||
@api.route("/printerprofiles", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@@ -103,7 +103,7 @@ def printerProfilesAdd():
|
||||
except Exception as e:
|
||||
return make_response("Could not save profile: %s" % str(e), 500)
|
||||
else:
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
return jsonify({"profile": _convert_profile(saved_profile)})
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@@ -172,10 +172,10 @@ def printerProfilesUpdate(identifier):
|
||||
except Exception as e:
|
||||
return make_response("Could not save profile: %s" % str(e), 500)
|
||||
else:
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
return jsonify({"profile": _convert_profile(saved_profile)})
|
||||
|
||||
def _convert_profiles(profiles):
|
||||
result = dict()
|
||||
result = {}
|
||||
for identifier, profile in profiles.items():
|
||||
result[identifier] = _convert_profile(profile)
|
||||
return result
|
||||
|
||||
@@ -38,7 +38,7 @@ def _etag(lm=None):
|
||||
from collections import OrderedDict
|
||||
sorted_plugin_settings = OrderedDict()
|
||||
for key in sorted(plugin_settings.keys()):
|
||||
sorted_plugin_settings[key] = plugin_settings.get(key, dict())
|
||||
sorted_plugin_settings[key] = plugin_settings.get(key, {})
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous:
|
||||
roles = sorted(current_user.permissions, key=lambda x: x.key)
|
||||
@@ -227,7 +227,7 @@ def getSettings():
|
||||
"afterPrintResumed": None,
|
||||
"beforeToolChange": None,
|
||||
"afterToolChange": None,
|
||||
"snippets": dict()
|
||||
"snippets": {}
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
@@ -261,7 +261,7 @@ def getSettings():
|
||||
|
||||
gcode_scripts = s.listScripts("gcode")
|
||||
if gcode_scripts:
|
||||
data["scripts"] = dict(gcode=dict())
|
||||
data["scripts"] = {"gcode": {}}
|
||||
for name in gcode_scripts:
|
||||
data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True)
|
||||
|
||||
@@ -275,7 +275,7 @@ def getSettings():
|
||||
def _get_plugin_settings():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
data = dict()
|
||||
data = {}
|
||||
|
||||
def process_plugin_result(name, result):
|
||||
if result:
|
||||
@@ -296,7 +296,7 @@ def _get_plugin_settings():
|
||||
except Exception:
|
||||
logger.exception("Could not load settings for plugin {name} ({version})".format(version=plugin._plugin_version,
|
||||
name=plugin._plugin_name),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
|
||||
return data
|
||||
|
||||
@@ -350,7 +350,7 @@ def fetchTemplateData():
|
||||
refresh = request.values.get("refresh", "false") in valid_boolean_trues
|
||||
templates, _, _ = fetch_template_data(refresh=refresh)
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
for tt in templates:
|
||||
result[tt] = []
|
||||
for key in templates[tt]["order"]:
|
||||
@@ -363,7 +363,7 @@ def fetchTemplateData():
|
||||
else:
|
||||
name, entry = entry
|
||||
|
||||
data = dict(id=key, name=name)
|
||||
data = {"id": key, "name": name}
|
||||
|
||||
if entry and "_plugin" in entry:
|
||||
plugin = pluginManager.get_plugin_info(entry["_plugin"], require_enabled=False)
|
||||
@@ -607,6 +607,6 @@ def _saveSettings(data):
|
||||
except Exception:
|
||||
logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version,
|
||||
name=plugin._plugin_name),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
|
||||
s.save(trigger_event=True)
|
||||
@@ -78,7 +78,7 @@ def slicingListAll():
|
||||
else:
|
||||
slicers = slicingManager.registered_slicers
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
for slicer in slicers:
|
||||
try:
|
||||
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
|
||||
@@ -87,18 +87,14 @@ def slicingListAll():
|
||||
for source_file_type in slicer_impl.get_slicer_properties().get("source_file_types", ["model"]):
|
||||
extensions = extensions.union(get_extensions(source_file_type))
|
||||
|
||||
result[slicer] = dict(
|
||||
key=slicer,
|
||||
displayName=slicer_impl.get_slicer_properties().get("name", "n/a"),
|
||||
sameDevice=slicer_impl.get_slicer_properties().get("same_device", True),
|
||||
default=default_slicer == slicer,
|
||||
configured=slicer_impl.is_slicer_configured(),
|
||||
profiles=_getSlicingProfilesData(slicer),
|
||||
extensions=dict(
|
||||
source=list(extensions),
|
||||
destination=slicer_impl.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])
|
||||
)
|
||||
)
|
||||
result[slicer] = {"key": slicer,
|
||||
"displayName": slicer_impl.get_slicer_properties().get("name", "n/a"),
|
||||
"sameDevice": slicer_impl.get_slicer_properties().get("same_device", True),
|
||||
"default": default_slicer == slicer,
|
||||
"configured": slicer_impl.is_slicer_configured(),
|
||||
"profiles": _getSlicingProfilesData(slicer),
|
||||
"extensions": {"source": list(extensions),
|
||||
"destination": slicer_impl.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])}}
|
||||
except (UnknownSlicer, SlicerNotConfigured):
|
||||
# this should never happen
|
||||
pass
|
||||
@@ -148,7 +144,7 @@ def slicingAddSlicerProfile(slicer, name):
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
data = dict()
|
||||
data = {}
|
||||
display_name = None
|
||||
description = None
|
||||
if "data" in json_data:
|
||||
@@ -191,7 +187,7 @@ def slicingPatchSlicerProfile(slicer, name):
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
data = dict()
|
||||
data = {}
|
||||
display_name = None
|
||||
description = None
|
||||
if "data" in json_data:
|
||||
@@ -229,18 +225,16 @@ def slicingDelSlicerProfile(slicer, name):
|
||||
def _getSlicingProfilesData(slicer, require_configured=False):
|
||||
profiles = slicingManager.all_profiles(slicer, require_configured=require_configured)
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
for name, profile in profiles.items():
|
||||
result[name] = _getSlicingProfileData(slicer, name, profile)
|
||||
return result
|
||||
|
||||
def _getSlicingProfileData(slicer, name, profile):
|
||||
defaultProfiles = s().get(["slicing", "defaultProfiles"])
|
||||
result = dict(
|
||||
key=name,
|
||||
default=defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name,
|
||||
resource=url_for(".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True)
|
||||
)
|
||||
result = {"key": name,
|
||||
"default": defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name,
|
||||
"resource": url_for(".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True)}
|
||||
if profile.display_name is not None:
|
||||
result["displayName"] = profile.display_name
|
||||
if profile.description is not None:
|
||||
|
||||
@@ -182,23 +182,19 @@ def _get_core_command_specs():
|
||||
s().save()
|
||||
|
||||
commands = collections.OrderedDict(
|
||||
shutdown=dict(
|
||||
command=s().get(["server", "commands", "systemShutdownCommand"]),
|
||||
name=gettext("Shutdown system"),
|
||||
confirm=gettext(u"<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
|
||||
reboot=dict(
|
||||
command=s().get(["server", "commands", "systemRestartCommand"]),
|
||||
name=gettext("Reboot system"),
|
||||
confirm=gettext(u"<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
|
||||
restart=dict(
|
||||
command=s().get(["server", "commands", "serverRestartCommand"]),
|
||||
name=gettext("Restart OctoPrint"),
|
||||
confirm=gettext(u"<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
|
||||
restart_safe=dict(
|
||||
command=s().get(["server", "commands", "serverRestartCommand"]),
|
||||
name=gettext("Restart OctoPrint in safe mode"),
|
||||
confirm=gettext(u"<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
|
||||
before=enable_safe_mode)
|
||||
shutdown={"command": s().get(["server", "commands", "systemShutdownCommand"]),
|
||||
"name": gettext("Shutdown system"),
|
||||
"confirm": gettext(u"<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")},
|
||||
reboot={"command": s().get(["server", "commands", "systemRestartCommand"]),
|
||||
"name": gettext("Reboot system"),
|
||||
"confirm": gettext(u"<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")},
|
||||
restart={"command": s().get(["server", "commands", "serverRestartCommand"]),
|
||||
"name": gettext("Restart OctoPrint"),
|
||||
"confirm": gettext(u"<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")},
|
||||
restart_safe={"command": s().get(["server", "commands", "serverRestartCommand"]),
|
||||
"name": gettext("Restart OctoPrint in safe mode"),
|
||||
"confirm": gettext(u"<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
|
||||
"before": enable_safe_mode}
|
||||
)
|
||||
|
||||
available_commands = collections.OrderedDict()
|
||||
|
||||
@@ -34,18 +34,18 @@ _timelapse_cache_mutex = threading.RLock()
|
||||
|
||||
def _config_for_timelapse(timelapse):
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
return dict(type="zchange",
|
||||
postRoll=timelapse.post_roll,
|
||||
fps=timelapse.fps,
|
||||
retractionZHop=timelapse.retraction_zhop,
|
||||
minDelay=timelapse.min_delay)
|
||||
return {"type": "zchange",
|
||||
"postRoll": timelapse.post_roll,
|
||||
"fps": timelapse.fps,
|
||||
"retractionZHop": timelapse.retraction_zhop,
|
||||
"minDelay": timelapse.min_delay}
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
return dict(type="timed",
|
||||
postRoll=timelapse.post_roll,
|
||||
fps=timelapse.fps,
|
||||
interval=timelapse.interval)
|
||||
return {"type": "timed",
|
||||
"postRoll": timelapse.post_roll,
|
||||
"fps": timelapse.fps,
|
||||
"interval": timelapse.interval}
|
||||
else:
|
||||
return dict(type="off")
|
||||
return {"type": "off"}
|
||||
|
||||
def _lastmodified(unrendered):
|
||||
lm_finished = octoprint.timelapse.last_modified_finished()
|
||||
@@ -115,9 +115,9 @@ def getTimelapseData():
|
||||
output["url"] = url_for("index") + "downloads/timelapse/" + f["name"]
|
||||
finished_list.append(output)
|
||||
|
||||
result = dict(config=config,
|
||||
enabled=settings().getBoolean(["webcam", "timelapseEnabled"]),
|
||||
files=finished_list)
|
||||
result = {"config": config,
|
||||
"enabled": settings().getBoolean(["webcam", "timelapseEnabled"]),
|
||||
"files": finished_list}
|
||||
|
||||
if unrendered:
|
||||
result.update(unrendered=unrendered_files)
|
||||
|
||||
@@ -206,7 +206,7 @@ def get_user_for_apikey(apikey):
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error running api key validator "
|
||||
"for plugin {} and key {}".format(name, apikey),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -465,8 +465,8 @@ class OctoPrintFlaskRequest(flask.Request):
|
||||
# strip cookie_suffix from all cookies in the request, return result
|
||||
cookies = flask.Request.cookies.__get__(self)
|
||||
|
||||
result = dict()
|
||||
desuffixed = dict()
|
||||
result = {}
|
||||
desuffixed = {}
|
||||
for key, value in cookies.items():
|
||||
if key.endswith(self.cookie_suffix):
|
||||
desuffixed[key[:-len(self.cookie_suffix)]] = value
|
||||
@@ -589,7 +589,7 @@ def passive_login():
|
||||
flask.session["usersession.id"] = u.session
|
||||
flask.g.user = u
|
||||
|
||||
eventManager().fire(Events.USER_LOGGED_IN, payload=dict(username=u.get_id()))
|
||||
eventManager().fire(Events.USER_LOGGED_IN, payload={"username": u.get_id()})
|
||||
|
||||
return u
|
||||
|
||||
@@ -895,11 +895,11 @@ class PreemptiveCache(object):
|
||||
self._logger.exception("Error while reading {}".format(self.cachefile))
|
||||
|
||||
if cache_data is None:
|
||||
cache_data = dict()
|
||||
cache_data = {}
|
||||
|
||||
if not self._validate_data(cache_data):
|
||||
self._logger.warning("Preemptive cache data was invalid, ignoring it")
|
||||
cache_data = dict()
|
||||
cache_data = {}
|
||||
|
||||
return cache_data
|
||||
|
||||
@@ -1438,12 +1438,10 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
|
||||
|
||||
##~~ core assets collector
|
||||
def collect_core_assets(preferred_stylesheet="css"):
|
||||
assets = dict(
|
||||
js=[],
|
||||
clientjs=[],
|
||||
css=[],
|
||||
less=[]
|
||||
)
|
||||
assets = {"js": [],
|
||||
"clientjs": [],
|
||||
"css": [],
|
||||
"less": []}
|
||||
assets["js"] = [
|
||||
'js/app/bindings/allowbindings.js',
|
||||
'js/app/bindings/contextmenu.js',
|
||||
@@ -1512,14 +1510,14 @@ def collect_plugin_assets(preferred_stylesheet="css"):
|
||||
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
|
||||
|
||||
supported_stylesheets = ("css", "less")
|
||||
assets = dict(bundled=dict(js=DefaultOrderedDict(list),
|
||||
clientjs=DefaultOrderedDict(list),
|
||||
css=DefaultOrderedDict(list),
|
||||
less=DefaultOrderedDict(list)),
|
||||
external=dict(js=DefaultOrderedDict(list),
|
||||
clientjs=DefaultOrderedDict(list),
|
||||
css=DefaultOrderedDict(list),
|
||||
less=DefaultOrderedDict(list)))
|
||||
assets = {"bundled": {"js": DefaultOrderedDict(list),
|
||||
"clientjs": DefaultOrderedDict(list),
|
||||
"css": DefaultOrderedDict(list),
|
||||
"less": DefaultOrderedDict(list)},
|
||||
"external": {"js": DefaultOrderedDict(list),
|
||||
"clientjs": DefaultOrderedDict(list),
|
||||
"css": DefaultOrderedDict(list),
|
||||
"less": DefaultOrderedDict(list)}}
|
||||
|
||||
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
|
||||
for implementation in asset_plugins:
|
||||
@@ -1533,7 +1531,7 @@ def collect_plugin_assets(preferred_stylesheet="css"):
|
||||
basefolder = implementation.get_asset_folder()
|
||||
except Exception:
|
||||
logger.exception("Got an error while trying to collect assets from {}, ignoring assets from the plugin".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
continue
|
||||
|
||||
def asset_exists(category, asset):
|
||||
|
||||
@@ -77,8 +77,8 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
Events.USER_LOGGED_OUT: [Permissions.ADMIN],
|
||||
"*": []}
|
||||
|
||||
_event_payload_processors = {Events.CLIENT_OPENED: [lambda user, payload: payload if user.has_permission(Permissions.ADMIN) else dict()],
|
||||
Events.CLIENT_AUTHED: [lambda user, payload: payload if user.has_permission(Permissions.ADMIN) else dict()],
|
||||
_event_payload_processors = {Events.CLIENT_OPENED: [lambda user, payload: payload if user.has_permission(Permissions.ADMIN) else {}],
|
||||
Events.CLIENT_AUTHED: [lambda user, payload: payload if user.has_permission(Permissions.ADMIN) else {}],
|
||||
"*": []}
|
||||
|
||||
_emit_permissions = {"connected": [],
|
||||
@@ -164,14 +164,14 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
config_hash = settings().config_hash
|
||||
|
||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||
self._emit("connected", dict(version=octoprint.server.VERSION,
|
||||
display_version=octoprint.server.DISPLAY_VERSION,
|
||||
branch=octoprint.server.BRANCH,
|
||||
plugin_hash=plugin_hash.hexdigest(),
|
||||
config_hash=config_hash,
|
||||
debug=octoprint.server.debug,
|
||||
safe_mode=octoprint.server.safe_mode,
|
||||
permissions=[permission.as_dict() for permission in Permissions.all()]))
|
||||
self._emit("connected", {"version": octoprint.server.VERSION,
|
||||
"display_version": octoprint.server.DISPLAY_VERSION,
|
||||
"branch": octoprint.server.BRANCH,
|
||||
"plugin_hash": plugin_hash.hexdigest(),
|
||||
"config_hash": config_hash,
|
||||
"debug": octoprint.server.debug,
|
||||
"safe_mode": octoprint.server.safe_mode,
|
||||
"permissions": [permission.as_dict() for permission in Permissions.all()]})
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
|
||||
self._register()
|
||||
@@ -260,12 +260,12 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
messages = self._messageBacklog
|
||||
self._messageBacklog = []
|
||||
|
||||
busy_files = [dict(origin=v[0], path=v[1]) for v in self._fileManager.get_busy_files()]
|
||||
busy_files = [{"origin": v[0], "path": v[1]} for v in self._fileManager.get_busy_files()]
|
||||
if "job" in data and data["job"] is not None \
|
||||
and "file" in data["job"] and "path" in data["job"]["file"] and "origin" in data["job"]["file"] \
|
||||
and data["job"]["file"]["path"] is not None and data["job"]["file"]["origin"] is not None \
|
||||
and (self._printer.is_printing() or self._printer.is_paused()):
|
||||
busy_files.append(dict(origin=data["job"]["file"]["origin"], path=data["job"]["file"]["path"]))
|
||||
busy_files.append({"origin": data["job"]["file"]["origin"], "path": data["job"]["file"]["path"]})
|
||||
|
||||
data.update({
|
||||
"serverTime": time.time(),
|
||||
@@ -291,26 +291,26 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
for processor in processors:
|
||||
payload = processor(self._user, payload)
|
||||
|
||||
self._emit("event", payload=dict(type=type, payload=payload))
|
||||
self._emit("event", payload={"type": type, "payload": payload})
|
||||
|
||||
def sendTimelapseConfig(self, timelapseConfig):
|
||||
self._emit("timelapse", payload=timelapseConfig)
|
||||
|
||||
def sendSlicingProgress(self, slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
self._emit("slicingProgress", payload=dict(slicer=slicer,
|
||||
source_location=source_location,
|
||||
source_path=source_path,
|
||||
dest_location=dest_location,
|
||||
dest_path=dest_path,
|
||||
progress=progress))
|
||||
self._emit("slicingProgress", payload={"slicer": slicer,
|
||||
"source_location": source_location,
|
||||
"source_path": source_path,
|
||||
"dest_location": dest_location,
|
||||
"dest_path": dest_path,
|
||||
"progress": progress})
|
||||
|
||||
def sendRenderProgress(self, progress):
|
||||
self._emit("renderProgress",
|
||||
dict(progress=progress)
|
||||
{"progress": progress}
|
||||
)
|
||||
|
||||
def on_plugin_message(self, plugin, data, permissions=None):
|
||||
self._emit("plugin", payload=dict(plugin=plugin, data=data), permissions=permissions)
|
||||
self._emit("plugin", payload={"plugin": plugin, "data": data}, permissions=permissions)
|
||||
|
||||
def on_printer_add_log(self, data):
|
||||
with self._logBacklogMutex:
|
||||
@@ -364,7 +364,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
proceed = proceed and hook(self, self._user)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing register hook handler for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
if not proceed:
|
||||
return
|
||||
@@ -416,7 +416,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
self._register()
|
||||
|
||||
def _sendReauthRequired(self, reason):
|
||||
self._emit("reauthRequired", payload=dict(reason=reason))
|
||||
self._emit("reauthRequired", payload={"reason": reason})
|
||||
|
||||
def _emit(self, type, payload=None, permissions=None):
|
||||
proceed = True
|
||||
@@ -425,7 +425,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
proceed = proceed and hook(self, self._user, type, payload)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing emit hook handler from plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
if not proceed:
|
||||
return
|
||||
@@ -466,7 +466,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
hook(self, self._user)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing authed hook handler for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
# if we have a backlog from being unauthed, process that now
|
||||
with self._unauthed_backlog_mutex:
|
||||
@@ -480,8 +480,8 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
|
||||
# trigger ClientAuthed event
|
||||
octoprint.events.eventManager().fire(octoprint.events.Events.CLIENT_AUTHED,
|
||||
payload=dict(username=user.get_name(),
|
||||
remoteAddress=self._remoteAddress))
|
||||
payload={"username": user.get_name(),
|
||||
"remoteAddress": self._remoteAddress})
|
||||
|
||||
def _on_logout(self):
|
||||
self._user = self._userManager.anonymous_user_factory()
|
||||
@@ -492,5 +492,5 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
hook(self, self._user)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing authed hook handler for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
@@ -56,8 +56,8 @@ def fix_websocket_check_origin():
|
||||
header case-insensitively, as defined in RFC6454, Section 4, item 5.
|
||||
"""
|
||||
|
||||
scheme_translation = dict(wss='https',
|
||||
ws='http')
|
||||
scheme_translation = {"wss": 'https',
|
||||
"ws": 'http'}
|
||||
|
||||
def patched_check_origin(self, origin):
|
||||
def get_check_tuple(urlstring):
|
||||
@@ -212,7 +212,7 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin,
|
||||
|
||||
def initialize(self, fallback, file_prefix="tmp", file_suffix="", path=None, suffixes=None):
|
||||
if not suffixes:
|
||||
suffixes = dict()
|
||||
suffixes = {}
|
||||
|
||||
self._fallback = fallback
|
||||
self._file_prefix = file_prefix
|
||||
@@ -228,7 +228,7 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin,
|
||||
self._multipart_boundary = None
|
||||
|
||||
# Parts, files and values will be stored here
|
||||
self._parts = dict()
|
||||
self._parts = {}
|
||||
self._files = []
|
||||
|
||||
# Part currently being processed
|
||||
@@ -433,14 +433,14 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin,
|
||||
# this is a file
|
||||
import tempfile
|
||||
handle = tempfile.NamedTemporaryFile(mode="wb", prefix=self._file_prefix, suffix=self._file_suffix, dir=self._path, delete=False)
|
||||
return dict(name=tornado.escape.utf8(name),
|
||||
filename=tornado.escape.utf8(filename),
|
||||
path=tornado.escape.utf8(handle.name),
|
||||
content_type=tornado.escape.utf8(content_type),
|
||||
file=handle)
|
||||
return {"name": tornado.escape.utf8(name),
|
||||
"filename": tornado.escape.utf8(filename),
|
||||
"path": tornado.escape.utf8(handle.name),
|
||||
"content_type": tornado.escape.utf8(content_type),
|
||||
"file": handle}
|
||||
|
||||
else:
|
||||
return dict(name=tornado.escape.utf8(name), content_type=tornado.escape.utf8(content_type), data=b"")
|
||||
return {"name": tornado.escape.utf8(name), "content_type": tornado.escape.utf8(content_type), "data": b""}
|
||||
|
||||
def _on_part_data(self, part, data):
|
||||
"""
|
||||
@@ -481,11 +481,9 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin,
|
||||
if not "path" in part:
|
||||
continue
|
||||
|
||||
parameters = dict(
|
||||
name=part["filename"],
|
||||
path=part["path"],
|
||||
size=str(os.stat(part["path"]).st_size)
|
||||
)
|
||||
parameters = {"name": part["filename"],
|
||||
"path": part["path"],
|
||||
"size": str(os.stat(part["path"]).st_size)}
|
||||
if "content_type" in part:
|
||||
parameters["content_type"] = part["content_type"]
|
||||
|
||||
@@ -621,9 +619,9 @@ class WsgiInputContainer(object):
|
||||
self.wsgi_application = wsgi_application
|
||||
|
||||
if headers is None:
|
||||
headers = dict()
|
||||
headers = {}
|
||||
if forced_headers is None:
|
||||
forced_headers = dict()
|
||||
forced_headers = {}
|
||||
if removed_headers is None:
|
||||
removed_headers = []
|
||||
|
||||
@@ -783,8 +781,8 @@ class CustomHTTPServer(tornado.httpserver.HTTPServer):
|
||||
|
||||
tornado.httpserver.HTTPServer.initialize(self, *args, **kwargs)
|
||||
|
||||
additional = dict(default_max_body_size=default_max_body_size,
|
||||
max_body_sizes=max_body_sizes)
|
||||
additional = {"default_max_body_size": default_max_body_size,
|
||||
"max_body_sizes": max_body_sizes}
|
||||
self.conn_params = CustomHTTP1ConnectionParameters.from_stock_params(self.conn_params, **additional)
|
||||
|
||||
|
||||
@@ -1269,23 +1267,23 @@ class DeprecatedEndpointHandler(CorsSupportMixin,
|
||||
|
||||
class GlobalHeaderTransform(tornado.web.OutputTransform):
|
||||
|
||||
HEADERS = dict()
|
||||
FORCED_HEADERS = dict()
|
||||
HEADERS = {}
|
||||
FORCED_HEADERS = {}
|
||||
REMOVED_HEADERS = []
|
||||
|
||||
@classmethod
|
||||
def for_headers(cls, name, headers=None, forced_headers=None, removed_headers=None):
|
||||
if headers is None:
|
||||
headers = dict()
|
||||
headers = {}
|
||||
if forced_headers is None:
|
||||
forced_headers = dict()
|
||||
forced_headers = {}
|
||||
if removed_headers is None:
|
||||
removed_headers = []
|
||||
|
||||
return type(octoprint.util.to_native_str(name), (GlobalHeaderTransform,),
|
||||
dict(HEADERS=headers,
|
||||
FORCED_HEADERS=forced_headers,
|
||||
REMOVED_HEADERS=removed_headers))
|
||||
{"HEADERS": headers,
|
||||
"FORCED_HEADERS": forced_headers,
|
||||
"REMOVED_HEADERS": removed_headers})
|
||||
|
||||
def __init__(self, request):
|
||||
tornado.web.OutputTransform.__init__(self, request)
|
||||
|
||||
+218
-136
@@ -33,7 +33,7 @@ from . import util
|
||||
import logging
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_templates = dict()
|
||||
_templates = {}
|
||||
_plugin_names = None
|
||||
_plugin_vars = None
|
||||
|
||||
@@ -61,9 +61,9 @@ def _preemptive_data(key, path=None, base_url=None, data=None, additional_reques
|
||||
if base_url is None:
|
||||
base_url = request.url_root
|
||||
|
||||
d = dict(path=path,
|
||||
base_url=base_url,
|
||||
query_string="l10n={}".format(g.locale.language if g.locale else "en"))
|
||||
d = {"path": path,
|
||||
"base_url": base_url,
|
||||
"query_string": "l10n={}".format(g.locale.language if g.locale else "en")}
|
||||
|
||||
if key != "_default":
|
||||
d["plugin"] = key
|
||||
@@ -85,9 +85,7 @@ def _preemptive_data(key, path=None, base_url=None, data=None, additional_reques
|
||||
try:
|
||||
ard = additional_request_data()
|
||||
if ard:
|
||||
d.update(dict(
|
||||
_additional_request_data=ard
|
||||
))
|
||||
d.update({"_additional_request_data": ard})
|
||||
except Exception:
|
||||
_logger.exception("Error retrieving additional data for preemptive cache from plugin {}".format(key))
|
||||
|
||||
@@ -124,7 +122,7 @@ def _add_additional_assets(hook):
|
||||
result += assets
|
||||
except:
|
||||
_logger.exception("Error fetching theming CSS to include from plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
return result
|
||||
|
||||
def _has_permissions(*permissions):
|
||||
@@ -158,10 +156,10 @@ def login():
|
||||
if _has_permissions(*permissions):
|
||||
return redirect(redirect_url)
|
||||
|
||||
render_kwargs = dict(theming=[],
|
||||
redirect_url=redirect_url,
|
||||
permission_names=map(lambda x: x.get_name(), permissions),
|
||||
logged_in=not current_user.is_anonymous)
|
||||
render_kwargs = {"theming": [],
|
||||
"redirect_url": redirect_url,
|
||||
"permission_names": map(lambda x: x.get_name(), permissions),
|
||||
"logged_in": not current_user.is_anonymous}
|
||||
|
||||
try:
|
||||
additional_assets = _add_additional_assets("octoprint.theming.login")
|
||||
@@ -170,7 +168,7 @@ def login():
|
||||
additional_assets += _add_additional_assets("octoprint.plugin.forcelogin.theming")
|
||||
additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming")
|
||||
|
||||
render_kwargs.update(dict(theming=additional_assets))
|
||||
render_kwargs.update({"theming": additional_assets})
|
||||
except:
|
||||
_logger.exception("Error processing theming CSS, ignoring")
|
||||
|
||||
@@ -184,11 +182,11 @@ def recovery():
|
||||
redirect=request.script_root + request.full_path,
|
||||
permissions=Permissions.ADMIN.key))
|
||||
|
||||
render_kwargs = dict(theming=[])
|
||||
render_kwargs = {"theming": []}
|
||||
|
||||
try:
|
||||
additional_assets = _add_additional_assets("octoprint.theming.recovery")
|
||||
render_kwargs.update(dict(theming=additional_assets))
|
||||
render_kwargs.update({"theming": additional_assets})
|
||||
except:
|
||||
_logger.exception("Error processing theming CSS, ignoring")
|
||||
|
||||
@@ -219,7 +217,7 @@ def in_cache():
|
||||
break
|
||||
except Exception:
|
||||
_logger.exception("Error while calling plugin {}, skipping it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
else:
|
||||
ui = "_default"
|
||||
key = _cache_key("_default", url=url)
|
||||
@@ -464,17 +462,15 @@ def index():
|
||||
_plugin_names,
|
||||
_plugin_vars,
|
||||
now)
|
||||
render_kwargs.update(dict(
|
||||
enableWebcam=enable_webcam,
|
||||
enableTemperatureGraph=enable_temperature_graph,
|
||||
enableAccessControl=enable_accesscontrol,
|
||||
accessControlActive=accesscontrol_active,
|
||||
enableLoadingAnimation=enable_loading_animation,
|
||||
enableSdSupport=enable_sd_support,
|
||||
sockJsConnectTimeout=sockjs_connect_timeout * 1000,
|
||||
wizard=wizard,
|
||||
now=now,
|
||||
))
|
||||
render_kwargs.update({"enableWebcam": enable_webcam,
|
||||
"enableTemperatureGraph": enable_temperature_graph,
|
||||
"enableAccessControl": enable_accesscontrol,
|
||||
"accessControlActive": accesscontrol_active,
|
||||
"enableLoadingAnimation": enable_loading_animation,
|
||||
"enableSdSupport": enable_sd_support,
|
||||
"sockJsConnectTimeout": sockjs_connect_timeout * 1000,
|
||||
"wizard": wizard,
|
||||
"now": now,})
|
||||
|
||||
# no plugin took an interest, we'll use the default UI
|
||||
def make_default_ui():
|
||||
@@ -489,8 +485,8 @@ def index():
|
||||
additional_etag=default_additional_etag)
|
||||
preemptively_cached = get_preemptively_cached_view("_default",
|
||||
cached,
|
||||
dict(),
|
||||
dict())
|
||||
{},
|
||||
{})
|
||||
return preemptively_cached()
|
||||
|
||||
response = None
|
||||
@@ -527,7 +523,7 @@ def index():
|
||||
_logger.warning("UiPlugin {} returned an empty response".format(plugin._identifier))
|
||||
except Exception:
|
||||
_logger.exception("Error while calling plugin {}, skipping it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
else:
|
||||
response = default_view()
|
||||
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
|
||||
@@ -545,10 +541,10 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
|
||||
first_run = settings().getBoolean(["server", "firstRun"])
|
||||
|
||||
locales = dict()
|
||||
locales = {}
|
||||
for l in LOCALES:
|
||||
try:
|
||||
locales[l.language] = dict(language=l.language, display=l.display_name, english=l.english_name)
|
||||
locales[l.language] = {"language": l.language, "display": l.display_name, "english": l.english_name}
|
||||
except Exception:
|
||||
_logger.exception("Error while collecting available locales")
|
||||
|
||||
@@ -558,18 +554,16 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
|
||||
#~~ prepare full set of template vars for rendering
|
||||
|
||||
render_kwargs = dict(
|
||||
debug=debug,
|
||||
firstRun=first_run,
|
||||
version=dict(number=VERSION, display=DISPLAY_VERSION, branch=BRANCH),
|
||||
python_version=get_python_version_string(),
|
||||
templates=templates,
|
||||
pluginNames=plugin_names,
|
||||
locales=locales,
|
||||
permissions=permissions,
|
||||
supportedFiletypes=filetypes,
|
||||
supportedExtensions=extensions
|
||||
)
|
||||
render_kwargs = {"debug": debug,
|
||||
"firstRun": first_run,
|
||||
"version": {"number": VERSION, "display": DISPLAY_VERSION, "branch": BRANCH},
|
||||
"python_version": get_python_version_string(),
|
||||
"templates": templates,
|
||||
"pluginNames": plugin_names,
|
||||
"locales": locales,
|
||||
"permissions": permissions,
|
||||
"supportedFiletypes": filetypes,
|
||||
"supportedExtensions": extensions}
|
||||
render_kwargs.update(plugin_vars)
|
||||
|
||||
return render_kwargs
|
||||
@@ -587,19 +581,17 @@ def fetch_template_data(refresh=False):
|
||||
|
||||
##~~ prepare templates
|
||||
|
||||
templates = defaultdict(lambda: dict(order=[], entries=dict()))
|
||||
templates = defaultdict(lambda: {"order": [], "entries": {}})
|
||||
|
||||
# rules for transforming template configs to template entries
|
||||
template_rules = dict(
|
||||
navbar=dict(div=lambda x: "navbar_plugin_" + x, template=lambda x: x + "_navbar.jinja2", to_entry=lambda data: data),
|
||||
sidebar=dict(div=lambda x: "sidebar_plugin_" + x, template=lambda x: x + "_sidebar.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
tab=dict(div=lambda x: "tab_plugin_" + x, template=lambda x: x + "_tab.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
settings=dict(div=lambda x: "settings_plugin_" + x, template=lambda x: x + "_settings.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
usersettings=dict(div=lambda x: "usersettings_plugin_" + x, template=lambda x: x + "_usersettings.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
wizard=dict(div=lambda x: "wizard_plugin_" + x, template=lambda x: x + "_wizard.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
about=dict(div=lambda x: "about_plugin_" + x, template=lambda x: x + "_about.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
generic=dict(template=lambda x: x + ".jinja2", to_entry=lambda data: data)
|
||||
)
|
||||
template_rules = {"navbar": {"div": lambda x: "navbar_plugin_" + x, "template": lambda x: x + "_navbar.jinja2", "to_entry": lambda data: data},
|
||||
"sidebar": {"div": lambda x: "sidebar_plugin_" + x, "template": lambda x: x + "_sidebar.jinja2", "to_entry": lambda data: (data["name"], data)},
|
||||
"tab": {"div": lambda x: "tab_plugin_" + x, "template": lambda x: x + "_tab.jinja2", "to_entry": lambda data: (data["name"], data)},
|
||||
"settings": {"div": lambda x: "settings_plugin_" + x, "template": lambda x: x + "_settings.jinja2", "to_entry": lambda data: (data["name"], data)},
|
||||
"usersettings": {"div": lambda x: "usersettings_plugin_" + x, "template": lambda x: x + "_usersettings.jinja2", "to_entry": lambda data: (data["name"], data)},
|
||||
"wizard": {"div": lambda x: "wizard_plugin_" + x, "template": lambda x: x + "_wizard.jinja2", "to_entry": lambda data: (data["name"], data)},
|
||||
"about": {"div": lambda x: "about_plugin_" + x, "template": lambda x: x + "_about.jinja2", "to_entry": lambda data: (data["name"], data)},
|
||||
"generic": {"template": lambda x: x + ".jinja2", "to_entry": lambda data: data}}
|
||||
|
||||
# sorting orders
|
||||
def wizard_key_extractor(d, k):
|
||||
@@ -615,16 +607,14 @@ def fetch_template_data(refresh=False):
|
||||
# Finally everything else
|
||||
return "2:{}".format(to_unicode(d[0]))
|
||||
|
||||
template_sorting = dict(
|
||||
navbar=dict(add="prepend", key=None),
|
||||
sidebar=dict(add="append", key="name"),
|
||||
tab=dict(add="append", key="name"),
|
||||
settings=dict(add="custom_append", key="name", custom_add_entries=lambda missing: dict(section_plugins=(gettext("Plugins"), None)), custom_add_order=lambda missing: ["section_plugins"] + missing),
|
||||
usersettings=dict(add="append", key="name"),
|
||||
wizard=dict(add="append", key="name", key_extractor=wizard_key_extractor),
|
||||
about=dict(add="append", key="name"),
|
||||
generic=dict(add="append", key=None)
|
||||
)
|
||||
template_sorting = {"navbar": {"add": "prepend", "key": None},
|
||||
"sidebar": {"add": "append", "key": "name"},
|
||||
"tab": {"add": "append", "key": "name"},
|
||||
"settings": {"add": "custom_append", "key": "name", "custom_add_entries": lambda missing: {"section_plugins": (gettext("Plugins"), None)}, "custom_add_order": lambda missing: ["section_plugins"] + missing},
|
||||
"usersettings": {"add": "append", "key": "name"},
|
||||
"wizard": {"add": "append", "key": "name", "key_extractor": wizard_key_extractor},
|
||||
"about": {"add": "append", "key": "name"},
|
||||
"generic": {"add": "append", "key": None}}
|
||||
|
||||
hooks = pluginManager.get_hooks("octoprint.ui.web.templatetypes")
|
||||
for name, hook in hooks.items():
|
||||
@@ -633,7 +623,7 @@ def fetch_template_data(refresh=False):
|
||||
except Exception:
|
||||
_logger.exception("Error while retrieving custom template type "
|
||||
"definitions from plugin {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
if not isinstance(result, list):
|
||||
continue
|
||||
@@ -669,60 +659,137 @@ def fetch_template_data(refresh=False):
|
||||
|
||||
# navbar
|
||||
|
||||
templates["navbar"]["entries"] = dict(
|
||||
settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.SETTINGS)"),
|
||||
systemmenu=dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", classes=["dropdown"], styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", custom_bindings=False),
|
||||
login=dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False),
|
||||
)
|
||||
templates["navbar"]["entries"] = {"settings": {"template": "navbar/settings.jinja2",
|
||||
"_div": "navbar_settings",
|
||||
"styles": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.SETTINGS)"},
|
||||
"systemmenu": {"template": "navbar/systemmenu.jinja2",
|
||||
"_div": "navbar_systemmenu",
|
||||
"classes": ["dropdown"],
|
||||
"styles": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)",
|
||||
"custom_bindings": False},
|
||||
"login": {"template": "navbar/login.jinja2",
|
||||
"_div": "navbar_login",
|
||||
"classes": ["dropdown"],
|
||||
"custom_bindings": False}}
|
||||
|
||||
# sidebar
|
||||
|
||||
templates["sidebar"]["entries"]= dict(
|
||||
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.CONNECTION)", template_header="sidebar/connection_header.jinja2")),
|
||||
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-circle", styles_wrapper=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.STATUS)")),
|
||||
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2", styles_wrapper=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.FILES_LIST)"))
|
||||
)
|
||||
templates["sidebar"]["entries"]= {"connection": (gettext("Connection"),
|
||||
{"template": "sidebar/connection.jinja2",
|
||||
"_div": "connection",
|
||||
"icon": "signal",
|
||||
"styles_wrapper": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.CONNECTION)",
|
||||
"template_header": "sidebar/connection_header.jinja2"}),
|
||||
"state": (gettext("State"),
|
||||
{"template": "sidebar/state.jinja2",
|
||||
"_div": "state",
|
||||
"icon": "info-circle",
|
||||
"styles_wrapper": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.STATUS)"}),
|
||||
"files": (gettext("Files"),
|
||||
{"template": "sidebar/files.jinja2",
|
||||
"_div": "files",
|
||||
"icon": "list",
|
||||
"classes_content": ["overflow_visible"],
|
||||
"template_header": "sidebar/files_header.jinja2",
|
||||
"styles_wrapper": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.FILES_LIST)"})}
|
||||
|
||||
# tabs
|
||||
|
||||
templates["tab"]["entries"] = dict(
|
||||
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp", styles=["display: none;"], data_bind="visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)() && visible()")),
|
||||
control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control", styles=["display: none;"], data_bind="visible: loginState.hasAnyPermissionKo(access.permissions.WEBCAM, access.permissions.CONTROL)")),
|
||||
terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.MONITOR_TERMINAL)")),
|
||||
timelapse=(gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.TIMELAPSE_LIST)"))
|
||||
)
|
||||
templates["tab"]["entries"] = {"temperature": (gettext("Temperature"),
|
||||
{"template": "tabs/temperature.jinja2",
|
||||
"_div": "temp",
|
||||
"styles": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)() && visible()"}),
|
||||
"control": (gettext("Control"),
|
||||
{"template": "tabs/control.jinja2",
|
||||
"_div": "control",
|
||||
"styles": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.WEBCAM, access.permissions.CONTROL)"}),
|
||||
"terminal": (gettext("Terminal"),
|
||||
{"template": "tabs/terminal.jinja2",
|
||||
"_div": "term",
|
||||
"styles": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.MONITOR_TERMINAL)"}),
|
||||
"timelapse": (gettext("Timelapse"),
|
||||
{"template": "tabs/timelapse.jinja2",
|
||||
"_div": "timelapse",
|
||||
"styles": ["display: none;"],
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.TIMELAPSE_LIST)"})}
|
||||
|
||||
# settings dialog
|
||||
|
||||
templates["settings"]["entries"] = dict(
|
||||
section_printer=(gettext("Printer"), None),
|
||||
templates["settings"]["entries"] = {"section_printer": (gettext("Printer"), None),
|
||||
|
||||
serial=(gettext("Serial Connection"), dict(template="dialogs/settings/serialconnection.jinja2", _div="settings_serialConnection", custom_bindings=False)),
|
||||
printerprofiles=(gettext("Printer Profiles"), dict(template="dialogs/settings/printerprofiles.jinja2", _div="settings_printerProfiles", custom_bindings=False)),
|
||||
temperatures=(gettext("Temperatures"), dict(template="dialogs/settings/temperatures.jinja2", _div="settings_temperature", custom_bindings=False)),
|
||||
terminalfilters=(gettext("Terminal Filters"), dict(template="dialogs/settings/terminalfilters.jinja2", _div="settings_terminalFilters", custom_bindings=False)),
|
||||
gcodescripts=(gettext("GCODE Scripts"), dict(template="dialogs/settings/gcodescripts.jinja2", _div="settings_gcodeScripts", custom_bindings=False)),
|
||||
"serial": (gettext("Serial Connection"),
|
||||
{"template": "dialogs/settings/serialconnection.jinja2",
|
||||
"_div": "settings_serialConnection",
|
||||
"custom_bindings": False}),
|
||||
"printerprofiles": (gettext("Printer Profiles"),
|
||||
{"template": "dialogs/settings/printerprofiles.jinja2",
|
||||
"_div": "settings_printerProfiles",
|
||||
"custom_bindings": False}),
|
||||
"temperatures": (gettext("Temperatures"),
|
||||
{"template": "dialogs/settings/temperatures.jinja2",
|
||||
"_div": "settings_temperature",
|
||||
"custom_bindings": False}),
|
||||
"terminalfilters": (gettext("Terminal Filters"),
|
||||
{"template": "dialogs/settings/terminalfilters.jinja2",
|
||||
"_div": "settings_terminalFilters",
|
||||
"custom_bindings": False}),
|
||||
"gcodescripts": (gettext("GCODE Scripts"),
|
||||
{"template": "dialogs/settings/gcodescripts.jinja2",
|
||||
"_div": "settings_gcodeScripts",
|
||||
"custom_bindings": False}),
|
||||
|
||||
section_features=(gettext("Features"), None),
|
||||
"section_features": (gettext("Features"), None),
|
||||
|
||||
features=(gettext("Features"), dict(template="dialogs/settings/features.jinja2", _div="settings_features", custom_bindings=False)),
|
||||
webcam=(gettext("Webcam & Timelapse"), dict(template="dialogs/settings/webcam.jinja2", _div="settings_webcam", custom_bindings=False)),
|
||||
api=(gettext("API"), dict(template="dialogs/settings/api.jinja2", _div="settings_api", custom_bindings=False)),
|
||||
"features": (gettext("Features"),
|
||||
{"template": "dialogs/settings/features.jinja2",
|
||||
"_div": "settings_features",
|
||||
"custom_bindings": False}),
|
||||
"webcam": (gettext("Webcam & Timelapse"),
|
||||
{"template": "dialogs/settings/webcam.jinja2",
|
||||
"_div": "settings_webcam",
|
||||
"custom_bindings": False}),
|
||||
"api": (gettext("API"),
|
||||
{"template": "dialogs/settings/api.jinja2",
|
||||
"_div": "settings_api",
|
||||
"custom_bindings": False}),
|
||||
|
||||
section_octoprint=(gettext("OctoPrint"), None),
|
||||
"section_octoprint": (gettext("OctoPrint"), None),
|
||||
|
||||
accesscontrol=(gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False)),
|
||||
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
|
||||
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
|
||||
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
|
||||
)
|
||||
"accesscontrol": (gettext("Access Control"),
|
||||
{"template": "dialogs/settings/accesscontrol.jinja2",
|
||||
"_div": "settings_users",
|
||||
"custom_bindings": False}),
|
||||
"folders": (gettext("Folders"),
|
||||
{"template": "dialogs/settings/folders.jinja2",
|
||||
"_div": "settings_folders",
|
||||
"custom_bindings": False}),
|
||||
"appearance": (gettext("Appearance"),
|
||||
{"template": "dialogs/settings/appearance.jinja2",
|
||||
"_div": "settings_appearance",
|
||||
"custom_bindings": False}),
|
||||
"server": (gettext("Server"),
|
||||
{"template": "dialogs/settings/server.jinja2",
|
||||
"_div": "settings_server",
|
||||
"custom_bindings": False})}
|
||||
|
||||
# user settings dialog
|
||||
|
||||
templates["usersettings"]["entries"] = dict(
|
||||
access=(gettext("Access"), dict(template="dialogs/usersettings/access.jinja2", _div="usersettings_access", custom_bindings=False)),
|
||||
interface=(gettext("Interface"), dict(template="dialogs/usersettings/interface.jinja2", _div="usersettings_interface", custom_bindings=False)),
|
||||
)
|
||||
templates["usersettings"]["entries"] = {"access": (gettext("Access"),
|
||||
{"template": "dialogs/usersettings/access.jinja2",
|
||||
"_div": "usersettings_access",
|
||||
"custom_bindings": False}),
|
||||
"interface": (gettext("Interface"),
|
||||
{"template": "dialogs/usersettings/interface.jinja2",
|
||||
"_div": "usersettings_interface",
|
||||
"custom_bindings": False})}
|
||||
|
||||
# wizard
|
||||
|
||||
@@ -735,30 +802,47 @@ def fetch_template_data(refresh=False):
|
||||
|
||||
return ["firstrunstart"] + existing + missing + ["firstrunend"]
|
||||
|
||||
template_sorting["wizard"].update(dict(add="custom_insert", custom_insert_entries=lambda missing: dict(), custom_insert_order=custom_insert_order))
|
||||
templates["wizard"]["entries"] = dict(
|
||||
firstrunstart=(gettext("Start"), dict(template="dialogs/wizard/firstrun_start.jinja2", _div="wizard_firstrun_start")),
|
||||
firstrunend=(gettext("Finish"), dict(template="dialogs/wizard/firstrun_end.jinja2", _div="wizard_firstrun_end")),
|
||||
)
|
||||
template_sorting["wizard"].update({"add": "custom_insert",
|
||||
"custom_insert_entries": lambda missing: {},
|
||||
"custom_insert_order": custom_insert_order})
|
||||
templates["wizard"]["entries"] = {"firstrunstart": (gettext("Start"),
|
||||
{"template": "dialogs/wizard/firstrun_start.jinja2",
|
||||
"_div": "wizard_firstrun_start"}),
|
||||
"firstrunend": (gettext("Finish"),
|
||||
{"template": "dialogs/wizard/firstrun_end.jinja2",
|
||||
"_div": "wizard_firstrun_end"})}
|
||||
|
||||
# about dialog
|
||||
|
||||
templates["about"]["entries"] = dict(
|
||||
about=("About OctoPrint", dict(template="dialogs/about/about.jinja2", _div="about_about", custom_bindings=False)),
|
||||
license=("OctoPrint License", dict(template="dialogs/about/license.jinja2", _div="about_license", custom_bindings=False)),
|
||||
thirdparty=("Third Party Licenses", dict(template="dialogs/about/thirdparty.jinja2", _div="about_thirdparty", custom_bindings=False)),
|
||||
authors=("Authors", dict(template="dialogs/about/authors.jinja2", _div="about_authors", custom_bindings=False)),
|
||||
supporters=("Supporters", dict(template="dialogs/about/supporters.jinja2", _div="about_sponsors", custom_bindings=False))
|
||||
)
|
||||
templates["about"]["entries"] = {"about": ("About OctoPrint",
|
||||
{"template": "dialogs/about/about.jinja2",
|
||||
"_div": "about_about",
|
||||
"custom_bindings": False}),
|
||||
"license": ("OctoPrint License",
|
||||
{"template": "dialogs/about/license.jinja2",
|
||||
"_div": "about_license",
|
||||
"custom_bindings": False}),
|
||||
"thirdparty": ("Third Party Licenses",
|
||||
{"template": "dialogs/about/thirdparty.jinja2",
|
||||
"_div": "about_thirdparty",
|
||||
"custom_bindings": False}),
|
||||
"authors": ("Authors",
|
||||
{"template": "dialogs/about/authors.jinja2",
|
||||
"_div": "about_authors",
|
||||
"custom_bindings": False}),
|
||||
"supporters": ("Supporters",
|
||||
{"template": "dialogs/about/supporters.jinja2",
|
||||
"_div": "about_sponsors",
|
||||
"custom_bindings": False})}
|
||||
|
||||
# extract data from template plugins
|
||||
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
|
||||
plugin_vars = dict()
|
||||
plugin_vars = {}
|
||||
plugin_names = set()
|
||||
plugin_aliases = dict()
|
||||
seen_wizards = settings().get(["server", "seenWizards"]) if not first_run else dict()
|
||||
plugin_aliases = {}
|
||||
seen_wizards = settings().get(["server", "seenWizards"]) if not first_run else {}
|
||||
for implementation in template_plugins:
|
||||
name = implementation._identifier
|
||||
plugin_names.add(name)
|
||||
@@ -773,11 +857,11 @@ def fetch_template_data(refresh=False):
|
||||
wizard_ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored(seen_wizards, implementation)
|
||||
except Exception:
|
||||
_logger.exception("Error while retrieving template data for plugin {}, ignoring it".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
continue
|
||||
|
||||
if not isinstance(vars, dict):
|
||||
vars = dict()
|
||||
vars = {}
|
||||
if not isinstance(configs, (list, tuple)):
|
||||
configs = []
|
||||
|
||||
@@ -790,7 +874,7 @@ def fetch_template_data(refresh=False):
|
||||
includes["wizard"] = list()
|
||||
|
||||
for t in template_types:
|
||||
plugin_aliases[t] = dict()
|
||||
plugin_aliases[t] = {}
|
||||
for include in includes[t]:
|
||||
if t == "navbar" or t == "generic":
|
||||
data = include
|
||||
@@ -810,7 +894,7 @@ def fetch_template_data(refresh=False):
|
||||
# 2) we have all entries located somewhere within the order
|
||||
|
||||
for t in template_types:
|
||||
default_order = settings().get(["appearance", "components", "order", t], merged=True, config=dict()) or []
|
||||
default_order = settings().get(["appearance", "components", "order", t], merged=True, config={}) or []
|
||||
configured_order = settings().get(["appearance", "components", "order", t], merged=True) or []
|
||||
configured_disabled = settings().get(["appearance", "components", "disabled", t]) or []
|
||||
|
||||
@@ -949,7 +1033,7 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
return None
|
||||
|
||||
if config is None:
|
||||
config = dict()
|
||||
config = {}
|
||||
data = dict(config)
|
||||
|
||||
if not "suffix" in data and counter > 1:
|
||||
@@ -988,15 +1072,15 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
|
||||
|
||||
def _filter_templates(templates, template_filter):
|
||||
filtered_templates = dict()
|
||||
filtered_templates = {}
|
||||
for template_type, template_collection in templates.items():
|
||||
filtered_entries = dict()
|
||||
filtered_entries = {}
|
||||
for template_key, template_entry in template_collection["entries"].items():
|
||||
if template_filter(template_type, template_key):
|
||||
filtered_entries[template_key] = template_entry
|
||||
filtered_templates[template_type] = dict(order=list(filter(lambda x: x in filtered_entries,
|
||||
filtered_templates[template_type] = {"order": list(filter(lambda x: x in filtered_entries,
|
||||
template_collection["order"])),
|
||||
entries=filtered_entries)
|
||||
"entries": filtered_entries}
|
||||
return filtered_templates
|
||||
|
||||
|
||||
@@ -1010,18 +1094,16 @@ def robotsTxt():
|
||||
@util.flask.etagged(lambda _: _compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]))
|
||||
@util.flask.lastmodified(lambda _: _compute_date_for_i18n(request.view_args["locale"], request.view_args["domain"]))
|
||||
def localeJs(locale, domain):
|
||||
messages = dict()
|
||||
messages = {}
|
||||
plural_expr = None
|
||||
|
||||
if locale != "en":
|
||||
messages, plural_expr = _get_translations(locale, domain)
|
||||
|
||||
catalog = dict(
|
||||
messages=messages,
|
||||
plural_expr=plural_expr,
|
||||
locale=locale,
|
||||
domain=domain
|
||||
)
|
||||
catalog = {"messages": messages,
|
||||
"plural_expr": plural_expr,
|
||||
"locale": locale,
|
||||
"domain": domain}
|
||||
|
||||
from flask import Response
|
||||
return Response(render_template("i18n.js.jinja2", catalog=catalog), content_type="application/x-javascript; charset=utf-8")
|
||||
@@ -1132,11 +1214,11 @@ def _get_translations(locale, domain):
|
||||
from babel.messages.pofile import read_po
|
||||
from octoprint.util import dict_merge
|
||||
|
||||
messages = dict()
|
||||
messages = {}
|
||||
plural_expr = None
|
||||
|
||||
def messages_from_po(path, locale, domain):
|
||||
messages = dict()
|
||||
messages = {}
|
||||
with io.open(path, mode="rt", encoding="utf-8") as f:
|
||||
catalog = read_po(f, locale=locale, domain=domain)
|
||||
|
||||
|
||||
+31
-35
@@ -449,7 +449,7 @@ class HierarchicalChainMap(ChainMap):
|
||||
if root is None:
|
||||
root = self
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
for key, value in root.items():
|
||||
if isinstance(value, dict):
|
||||
result[key] = self.deep_dict(root=self.__class__._get_next(key, root))
|
||||
@@ -500,7 +500,7 @@ class HierarchicalChainMap(ChainMap):
|
||||
|
||||
for key in path[:-1]:
|
||||
if key not in current.maps[0]:
|
||||
current.maps[0][key] = dict()
|
||||
current.maps[0][key] = {}
|
||||
if not isinstance(current[key], dict):
|
||||
raise KeyError(key)
|
||||
current = self.__class__._hierarchy_for_key(key, current)
|
||||
@@ -528,7 +528,7 @@ class HierarchicalChainMap(ChainMap):
|
||||
if key in mapping and mapping[key] is not None:
|
||||
wrapped_mappings.append(mapping[key])
|
||||
else:
|
||||
wrapped_mappings.append(dict())
|
||||
wrapped_mappings.append({})
|
||||
return HierarchicalChainMap(*wrapped_mappings)
|
||||
|
||||
@classmethod
|
||||
@@ -602,7 +602,7 @@ class Settings(object):
|
||||
|
||||
assert(isinstance(default_settings, dict))
|
||||
|
||||
self._map = HierarchicalChainMap(dict(), default_settings)
|
||||
self._map = HierarchicalChainMap({}, default_settings)
|
||||
|
||||
self._config = None
|
||||
self._dirty = False
|
||||
@@ -611,10 +611,8 @@ class Settings(object):
|
||||
self._last_effective_hash = None
|
||||
self._mtime = None
|
||||
|
||||
self._get_preprocessors = dict(
|
||||
controls=self._process_custom_controls
|
||||
)
|
||||
self._set_preprocessors = dict()
|
||||
self._get_preprocessors = {"controls": self._process_custom_controls}
|
||||
self._set_preprocessors = {}
|
||||
|
||||
self._init_basedir(basedir)
|
||||
|
||||
@@ -759,8 +757,8 @@ class Settings(object):
|
||||
settings_loader = SettingsScriptLoader(self)
|
||||
choice_loader = ChoiceLoader([file_system_loader, settings_loader])
|
||||
select_loader = SelectLoader(choice_loader,
|
||||
dict(bundled=settings_loader,
|
||||
file=file_system_loader))
|
||||
{"bundled": settings_loader,
|
||||
"file": file_system_loader})
|
||||
return RelEnvironment(loader=select_loader, extensions=[SnippetExtension])
|
||||
|
||||
def _get_script_template(self, script_type, name, source=False):
|
||||
@@ -909,7 +907,7 @@ class Settings(object):
|
||||
|
||||
# changed from else to handle cases where the file exists, but is empty / 0 bytes
|
||||
if not self._config or not isinstance(self._config, dict):
|
||||
self._config = dict()
|
||||
self._config = {}
|
||||
|
||||
if migrate:
|
||||
self._migrate_config()
|
||||
@@ -1011,12 +1009,10 @@ class Settings(object):
|
||||
if "templates" in config["scripts"]["gcode"]:
|
||||
del config["scripts"]["gcode"]["templates"]
|
||||
|
||||
replacements = dict(
|
||||
disable_steppers="M84",
|
||||
disable_hotends="{% snippet 'disable_hotends' %}",
|
||||
disable_bed="M140 S0",
|
||||
disable_fan="M106 S0"
|
||||
)
|
||||
replacements = {"disable_steppers": "M84",
|
||||
"disable_hotends": "{% snippet 'disable_hotends' %}",
|
||||
"disable_bed": "M140 S0",
|
||||
"disable_fan": "M106 S0"}
|
||||
|
||||
for name, script in config["scripts"]["gcode"].items():
|
||||
self.saveScript("gcode", name, script.format(**replacements))
|
||||
@@ -1030,7 +1026,7 @@ class Settings(object):
|
||||
|
||||
Added in 1.2.0
|
||||
"""
|
||||
default_profile = config["printerProfiles"]["defaultProfile"] if "printerProfiles" in config and "defaultProfile" in config["printerProfiles"] else dict()
|
||||
default_profile = config["printerProfiles"]["defaultProfile"] if "printerProfiles" in config and "defaultProfile" in config["printerProfiles"] else {}
|
||||
dirty = False
|
||||
|
||||
if "printerParameters" in config:
|
||||
@@ -1038,7 +1034,7 @@ class Settings(object):
|
||||
|
||||
if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters:
|
||||
dirty = True
|
||||
default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict())
|
||||
default_profile["axes"] = {"x": {}, "y": {}, "z": {}, "e": {}}
|
||||
if "movementSpeed" in printer_parameters:
|
||||
for axis in ("x", "y", "z", "e"):
|
||||
if axis in printer_parameters["movementSpeed"]:
|
||||
@@ -1053,7 +1049,7 @@ class Settings(object):
|
||||
if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters:
|
||||
dirty = True
|
||||
if not "extruder" in default_profile:
|
||||
default_profile["extruder"] = dict()
|
||||
default_profile["extruder"] = {}
|
||||
|
||||
if "numExtruders" in printer_parameters:
|
||||
default_profile["extruder"]["count"] = printer_parameters["numExtruders"]
|
||||
@@ -1070,7 +1066,7 @@ class Settings(object):
|
||||
dirty = True
|
||||
bed_dimensions = printer_parameters["bedDimensions"]
|
||||
if not "volume" in default_profile:
|
||||
default_profile["volume"] = dict()
|
||||
default_profile["volume"] = {}
|
||||
|
||||
if "circular" in bed_dimensions and "r" in bed_dimensions and bed_dimensions["circular"]:
|
||||
default_profile["volume"]["formFactor"] = "circular"
|
||||
@@ -1086,7 +1082,7 @@ class Settings(object):
|
||||
|
||||
if dirty:
|
||||
if not "printerProfiles" in config:
|
||||
config["printerProfiles"] = dict()
|
||||
config["printerProfiles"] = {}
|
||||
config["printerProfiles"]["defaultProfile"] = default_profile
|
||||
return dirty
|
||||
|
||||
@@ -1109,7 +1105,7 @@ class Settings(object):
|
||||
del config["server"]["scheme"]
|
||||
|
||||
if not "reverseProxy" in config["server"] or not isinstance(config["server"]["reverseProxy"], dict):
|
||||
config["server"]["reverseProxy"] = dict()
|
||||
config["server"]["reverseProxy"] = {}
|
||||
if prefix:
|
||||
config["server"]["reverseProxy"]["prefixFallback"] = prefix
|
||||
if scheme:
|
||||
@@ -1225,9 +1221,9 @@ class Settings(object):
|
||||
"""
|
||||
changed = False
|
||||
|
||||
migration_map = dict(shutdown="systemShutdownCommand",
|
||||
reboot="systemRestartCommand",
|
||||
restart="serverRestartCommand")
|
||||
migration_map = {"shutdown": "systemShutdownCommand",
|
||||
"reboot": "systemRestartCommand",
|
||||
"restart": "serverRestartCommand"}
|
||||
|
||||
if "system" in config and "actions" in config["system"] and isinstance(config["system"]["actions"], (list, tuple)):
|
||||
actions = config["system"]["actions"]
|
||||
@@ -1242,9 +1238,9 @@ class Settings(object):
|
||||
if migrate_to is not None:
|
||||
if not "server" in config or not "commands" in config["server"] or not migrate_to in config["server"]["commands"]:
|
||||
if not "server" in config:
|
||||
config["server"] = dict()
|
||||
config["server"] = {}
|
||||
if not "commands" in config["server"]:
|
||||
config["server"]["commands"] = dict()
|
||||
config["server"]["commands"] = {}
|
||||
config["server"]["commands"][migrate_to] = command
|
||||
self._logger.info("Migrated {} action to server.commands.{}".format(action, migrate_to))
|
||||
|
||||
@@ -1285,7 +1281,7 @@ class Settings(object):
|
||||
if source in config and key in config[source]:
|
||||
if config.get(target) is None:
|
||||
# make sure we have a serial tree
|
||||
config[target] = dict()
|
||||
config[target] = {}
|
||||
if key not in config[target]:
|
||||
# only copy over if it's not there yet
|
||||
config[target][key] = config[source][key]
|
||||
@@ -1366,7 +1362,7 @@ class Settings(object):
|
||||
def _migrate_gcodeviewer_enabled(self, config):
|
||||
if "gcodeViewer" in config and "enabled" in config["gcodeViewer"] and not config["gcodeViewer"]["enabled"]:
|
||||
if not "plugins" in config:
|
||||
config["plugins"] = dict()
|
||||
config["plugins"] = {}
|
||||
if not "_disabled" in config["plugins"]:
|
||||
config["plugins"]["_disabled"] = []
|
||||
config["plugins"]["_disabled"].append("gcodeviewer")
|
||||
@@ -1413,8 +1409,8 @@ class Settings(object):
|
||||
self.load()
|
||||
|
||||
if trigger_event:
|
||||
payload = dict(config_hash=self.config_hash,
|
||||
effective_hash=self.effective_hash)
|
||||
payload = {"config_hash": self.config_hash,
|
||||
"effective_hash": self.effective_hash}
|
||||
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
|
||||
|
||||
return True
|
||||
@@ -1464,7 +1460,7 @@ class Settings(object):
|
||||
keys = last
|
||||
|
||||
if asdict:
|
||||
results = dict()
|
||||
results = {}
|
||||
else:
|
||||
results = list()
|
||||
|
||||
@@ -1635,8 +1631,8 @@ class Settings(object):
|
||||
|
||||
def loadScript(self, script_type, name, context=None, source=False):
|
||||
if context is None:
|
||||
context = dict()
|
||||
context.update(dict(script=dict(type=script_type, name=name)))
|
||||
context = {}
|
||||
context.update({"script": {"type": script_type, "name": name}})
|
||||
|
||||
template = self._get_script_template(script_type, name, source=source)
|
||||
if template is None:
|
||||
|
||||
@@ -119,8 +119,8 @@ class SlicingManager(object):
|
||||
self._profile_path = profile_path
|
||||
self._printer_profile_manager = printer_profile_manager
|
||||
|
||||
self._slicers = dict()
|
||||
self._slicer_names = dict()
|
||||
self._slicers = {}
|
||||
self._slicer_names = {}
|
||||
|
||||
def initialize(self):
|
||||
"""
|
||||
@@ -135,13 +135,13 @@ class SlicingManager(object):
|
||||
available slicers.
|
||||
"""
|
||||
plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
|
||||
slicers = dict()
|
||||
slicers = {}
|
||||
for plugin in plugins:
|
||||
try:
|
||||
slicers[plugin.get_slicer_properties()["type"]] = plugin
|
||||
except Exception:
|
||||
self._logger.exception("Error while getting properties from slicer {}, ignoring it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
extra={"plugin": plugin._identifier})
|
||||
continue
|
||||
self._slicers = slicers
|
||||
|
||||
@@ -272,7 +272,7 @@ class SlicingManager(object):
|
||||
if callback_args is None:
|
||||
callback_args = ()
|
||||
if callback_kwargs is None:
|
||||
callback_kwargs = dict()
|
||||
callback_kwargs = {}
|
||||
|
||||
if not slicer_name in self.configured_slicers:
|
||||
if not slicer_name in self.registered_slicers:
|
||||
@@ -281,7 +281,7 @@ class SlicingManager(object):
|
||||
else:
|
||||
error = "Slicer not configured: {slicer_name}".format(**locals())
|
||||
exc = SlicerNotConfigured(slicer_name)
|
||||
callback_kwargs.update(dict(_error=error, _exc=exc))
|
||||
callback_kwargs.update({"_error": error, "_exc": exc})
|
||||
callback(*callback_args, **callback_kwargs)
|
||||
raise exc
|
||||
|
||||
@@ -310,11 +310,11 @@ class SlicingManager(object):
|
||||
)
|
||||
|
||||
if not ok:
|
||||
callback_kwargs.update(dict(_error=result))
|
||||
callback_kwargs.update({"_error": result})
|
||||
elif result is not None and isinstance(result, dict) and "analysis" in result:
|
||||
callback_kwargs.update(dict(_analysis=result["analysis"]))
|
||||
callback_kwargs.update({"_analysis": result["analysis"]})
|
||||
except SlicingCancelled:
|
||||
callback_kwargs.update(dict(_cancelled=True))
|
||||
callback_kwargs.update({"_cancelled": True})
|
||||
finally:
|
||||
callback(*callback_args, **callback_kwargs)
|
||||
|
||||
@@ -430,8 +430,8 @@ class SlicingManager(object):
|
||||
|
||||
self._save_profile_to_path(slicer, path, profile, overrides=overrides, allow_overwrite=allow_overwrite)
|
||||
|
||||
payload = dict(slicer=slicer,
|
||||
profile=name)
|
||||
payload = {"slicer": slicer,
|
||||
"profile": name}
|
||||
event = octoprint.events.Events.SLICING_PROFILE_MODIFIED if is_overwrite else octoprint.events.Events.SLICING_PROFILE_ADDED
|
||||
octoprint.events.eventManager().fire(event, payload)
|
||||
|
||||
@@ -487,7 +487,7 @@ class SlicingManager(object):
|
||||
except Exception as e:
|
||||
raise CouldNotDeleteProfile(slicer, name, cause=e)
|
||||
else:
|
||||
octoprint.events.eventManager().fire(octoprint.events.Events.SLICING_PROFILE_DELETED, dict(slicer=slicer, profile=name))
|
||||
octoprint.events.eventManager().fire(octoprint.events.Events.SLICING_PROFILE_DELETED, {"slicer": slicer, "profile": name})
|
||||
|
||||
def set_default_profile(self, slicer, name, require_configured=False,
|
||||
require_exists=True):
|
||||
@@ -528,7 +528,7 @@ class SlicingManager(object):
|
||||
|
||||
default_profiles = settings().get(["slicing", "defaultProfiles"])
|
||||
if not default_profiles:
|
||||
default_profiles = dict()
|
||||
default_profiles = {}
|
||||
default_profiles[slicer] = name
|
||||
settings().set(["slicing", "defaultProfiles"], default_profiles)
|
||||
settings().save(force=True)
|
||||
|
||||
+34
-34
@@ -92,7 +92,7 @@ def valid_timelapse(path):
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional timelapse "
|
||||
"extensions from hook {name}".format(name=name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
_extensions = list(set(extensions))
|
||||
|
||||
@@ -142,7 +142,7 @@ def get_unrendered_timelapses():
|
||||
delete_old_unrendered_timelapses()
|
||||
|
||||
basedir = settings().getBaseFolder("timelapse_tmp", check_writable=False)
|
||||
jobs = collections.defaultdict(lambda: dict(count=0, size=None, bytes=0, date=None, timestamp=None))
|
||||
jobs = collections.defaultdict(lambda: {"count": 0, "size": None, "bytes": 0, "date": None, "timestamp": None})
|
||||
|
||||
for entry in scandir(basedir):
|
||||
if not fnmatch.fnmatch(entry.name, "*.jpg"):
|
||||
@@ -173,7 +173,7 @@ def get_unrendered_timelapses():
|
||||
|
||||
return job
|
||||
|
||||
return sorted([util.dict_merge(dict(name=key), finalize_fields(key, value))
|
||||
return sorted([util.dict_merge({"name": key}, finalize_fields(key, value))
|
||||
for key, value in jobs.items()],
|
||||
key=lambda x: sv(x["name"]))
|
||||
|
||||
@@ -256,11 +256,11 @@ def _create_render_start_handler(name, gcode=None):
|
||||
|
||||
with _job_lock:
|
||||
global current_render_job
|
||||
payload = dict(gcode=gcode if gcode is not None else "unknown",
|
||||
movie=movie,
|
||||
movie_basename=os.path.basename(movie),
|
||||
movie_prefix=name)
|
||||
current_render_job = dict(prefix=name)
|
||||
payload = {"gcode": gcode if gcode is not None else "unknown",
|
||||
"movie": movie,
|
||||
"movie_basename": os.path.basename(movie),
|
||||
"movie_prefix": name}
|
||||
current_render_job = {"prefix": name}
|
||||
current_render_job.update(payload)
|
||||
eventManager().fire(Events.MOVIE_RENDERING, payload)
|
||||
return f
|
||||
@@ -269,24 +269,24 @@ def _create_render_start_handler(name, gcode=None):
|
||||
def _create_render_success_handler(name, gcode=None):
|
||||
def f(movie):
|
||||
delete_unrendered_timelapse(name)
|
||||
payload = dict(gcode=gcode if gcode is not None else "unknown",
|
||||
movie=movie,
|
||||
movie_basename=os.path.basename(movie),
|
||||
movie_prefix=name)
|
||||
payload = {"gcode": gcode if gcode is not None else "unknown",
|
||||
"movie": movie,
|
||||
"movie_basename": os.path.basename(movie),
|
||||
"movie_prefix": name}
|
||||
eventManager().fire(Events.MOVIE_DONE, payload)
|
||||
return f
|
||||
|
||||
|
||||
def _create_render_fail_handler(name, gcode=None):
|
||||
def f(movie, returncode=255, stdout="Unknown error", stderr="Unknown error", reason="unknown"):
|
||||
payload = dict(gcode=gcode if gcode is not None else "unknown",
|
||||
movie=movie,
|
||||
movie_basename=os.path.basename(movie),
|
||||
movie_prefix=name,
|
||||
returncode=returncode,
|
||||
out=stdout,
|
||||
error=stderr,
|
||||
reason=reason)
|
||||
payload = {"gcode": gcode if gcode is not None else "unknown",
|
||||
"movie": movie,
|
||||
"movie_basename": os.path.basename(movie),
|
||||
"movie_prefix": name,
|
||||
"returncode": returncode,
|
||||
"out": stdout,
|
||||
"error": stderr,
|
||||
"reason": reason}
|
||||
eventManager().fire(Events.MOVIE_FAILED, payload)
|
||||
return f
|
||||
|
||||
@@ -331,7 +331,7 @@ def notify_callback(callback, config=None, timelapse=None):
|
||||
callback.sendTimelapseConfig(config)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while pushing timelapse configuration",
|
||||
extra=dict(callback=fqcn(callback)))
|
||||
extra={"callback": fqcn(callback)})
|
||||
|
||||
|
||||
def configure_timelapse(config=None, persist=False):
|
||||
@@ -531,7 +531,7 @@ class Timelapse(object):
|
||||
create_movie()
|
||||
|
||||
def wait_for_captures(callback):
|
||||
self._capture_queue.put(dict(type=self.__class__.QUEUE_ENTRY_TYPE_CALLBACK, callback=callback))
|
||||
self._capture_queue.put({"type": self.__class__.QUEUE_ENTRY_TYPE_CALLBACK, "callback": callback})
|
||||
|
||||
def create_wait_for_captures(callback):
|
||||
def f():
|
||||
@@ -558,9 +558,9 @@ class Timelapse(object):
|
||||
if self._post_roll > 0:
|
||||
# capture post roll, wait for THAT to finish, THEN render
|
||||
eventManager().fire(Events.POSTROLL_START,
|
||||
dict(postroll_duration=self.calculate_post_roll(),
|
||||
postroll_length=self.post_roll,
|
||||
postroll_fps=self.fps))
|
||||
{"postroll_duration": self.calculate_post_roll(),
|
||||
"postroll_length": self.post_roll,
|
||||
"postroll_fps": self.fps})
|
||||
if do_create_movie:
|
||||
self._on_post_roll_done = create_wait_for_captures(reset_and_create)
|
||||
else:
|
||||
@@ -602,9 +602,9 @@ class Timelapse(object):
|
||||
self._image_number += 1
|
||||
|
||||
self._logger.debug("Capturing image to {}".format(filename))
|
||||
entry = dict(type=self.__class__.QUEUE_ENTRY_TYPE_CAPTURE,
|
||||
filename=filename,
|
||||
onerror=self._on_capture_error)
|
||||
entry = {"type": self.__class__.QUEUE_ENTRY_TYPE_CAPTURE,
|
||||
"filename": filename,
|
||||
"onerror": self._on_capture_error}
|
||||
self._capture_queue.put(entry)
|
||||
return filename
|
||||
|
||||
@@ -624,7 +624,7 @@ class Timelapse(object):
|
||||
|
||||
elif entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CALLBACK and "callback" in entry:
|
||||
args = entry.pop("args", [])
|
||||
kwargs = entry.pop("kwargs", dict())
|
||||
kwargs = entry.pop("kwargs", {})
|
||||
entry["callback"](*args, **kwargs)
|
||||
|
||||
def _perform_capture(self, filename, onerror=None):
|
||||
@@ -635,7 +635,7 @@ class Timelapse(object):
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing hook {name}.".format(**locals()))
|
||||
|
||||
eventManager().fire(Events.CAPTURE_START, dict(file=filename))
|
||||
eventManager().fire(Events.CAPTURE_START, {"file": filename})
|
||||
try:
|
||||
self._logger.debug("Going to capture {} from {}".format(filename, self._snapshot_url))
|
||||
r = requests.get(self._snapshot_url,
|
||||
@@ -668,14 +668,14 @@ class Timelapse(object):
|
||||
|
||||
# handle events and onerror call
|
||||
if err is None:
|
||||
eventManager().fire(Events.CAPTURE_DONE, dict(file=filename))
|
||||
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
|
||||
return True
|
||||
else:
|
||||
if callable(onerror):
|
||||
onerror()
|
||||
eventManager().fire(Events.CAPTURE_FAILED, dict(file=filename,
|
||||
error=str(err),
|
||||
url=self._snapshot_url))
|
||||
eventManager().fire(Events.CAPTURE_FAILED, {"file": filename,
|
||||
"error": str(err),
|
||||
"url": self._snapshot_url})
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@@ -721,9 +721,9 @@ def dict_merge(a, b, leaf_merger=None, in_place=False):
|
||||
from copy import deepcopy
|
||||
|
||||
if a is None:
|
||||
a = dict()
|
||||
a = {}
|
||||
if b is None:
|
||||
b = dict()
|
||||
b = {}
|
||||
|
||||
if not isinstance(b, dict):
|
||||
return b
|
||||
@@ -821,12 +821,12 @@ def dict_minimal_mergediff(source, target):
|
||||
|
||||
if source == target:
|
||||
# shortcut: if both are equal, we return an empty dict as result
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
all_keys = set(list(source.keys()) + list(target.keys()))
|
||||
result = dict()
|
||||
result = {}
|
||||
for k in all_keys:
|
||||
if k not in target:
|
||||
# key not contained in b => not contained in result
|
||||
@@ -1167,7 +1167,7 @@ def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs):
|
||||
encoding = codec.name
|
||||
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
kwargs = {}
|
||||
|
||||
potential_bom_attribute = "BOM_" + codec.name.replace("utf-", "utf").upper()
|
||||
if "r" in mode and hasattr(codecs, potential_bom_attribute):
|
||||
@@ -1249,7 +1249,7 @@ def thaw_frozendict(obj):
|
||||
raise ValueError("obj must be a dict or frozendict instance")
|
||||
|
||||
# only true love can thaw a frozen dict
|
||||
letitgo = dict()
|
||||
letitgo = {}
|
||||
for key, value in obj.items():
|
||||
if isinstance(value, (dict, frozendict.frozendict)):
|
||||
letitgo[key] = thaw_frozendict(value)
|
||||
@@ -1366,7 +1366,7 @@ class RepeatedTimer(threading.Thread):
|
||||
if args is None:
|
||||
args = []
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
kwargs = {}
|
||||
if condition is None:
|
||||
condition = lambda: True
|
||||
|
||||
@@ -1465,7 +1465,7 @@ class ResettableTimer(threading.Thread):
|
||||
if args is None:
|
||||
args = []
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
kwargs = {}
|
||||
|
||||
self.interval = interval
|
||||
self.function = function
|
||||
|
||||
+87
-94
@@ -66,19 +66,17 @@ regex_command = re.compile(r"^\s*((?P<codeGM>[GM]\d+)(\.(?P<subcode>\d+))?|(?P<c
|
||||
regex_float = re.compile(regex_float_pattern)
|
||||
"""Regex for a float value."""
|
||||
|
||||
regexes_parameters = dict(
|
||||
floatE=re.compile(r"(^|[^A-Za-z])[Ee](?P<value>%s)" % regex_float_pattern),
|
||||
floatF=re.compile(r"(^|[^A-Za-z])[Ff](?P<value>%s)" % regex_float_pattern),
|
||||
floatP=re.compile(r"(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
|
||||
floatR=re.compile(r"(^|[^A-Za-z])[Rr](?P<value>%s)" % regex_float_pattern),
|
||||
floatS=re.compile(r"(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
|
||||
floatX=re.compile(r"(^|[^A-Za-z])[Xx](?P<value>%s)" % regex_float_pattern),
|
||||
floatY=re.compile(r"(^|[^A-Za-z])[Yy](?P<value>%s)" % regex_float_pattern),
|
||||
floatZ=re.compile(r"(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
|
||||
intN=re.compile(r"(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
|
||||
intS=re.compile(r"(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_int_pattern),
|
||||
intT=re.compile(r"(^|[^A-Za-z])[Tt](?P<value>%s)" % regex_int_pattern)
|
||||
)
|
||||
regexes_parameters = {"floatE": re.compile(r"(^|[^A-Za-z])[Ee](?P<value>%s)" % regex_float_pattern),
|
||||
"floatF": re.compile(r"(^|[^A-Za-z])[Ff](?P<value>%s)" % regex_float_pattern),
|
||||
"floatP": re.compile(r"(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
|
||||
"floatR": re.compile(r"(^|[^A-Za-z])[Rr](?P<value>%s)" % regex_float_pattern),
|
||||
"floatS": re.compile(r"(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
|
||||
"floatX": re.compile(r"(^|[^A-Za-z])[Xx](?P<value>%s)" % regex_float_pattern),
|
||||
"floatY": re.compile(r"(^|[^A-Za-z])[Yy](?P<value>%s)" % regex_float_pattern),
|
||||
"floatZ": re.compile(r"(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
|
||||
"intN": re.compile(r"(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
|
||||
"intS": re.compile(r"(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_int_pattern),
|
||||
"intT": re.compile(r"(^|[^A-Za-z])[Tt](?P<value>%s)" % regex_int_pattern)}
|
||||
"""Regexes for parsing various GCODE command parameters."""
|
||||
|
||||
regex_minMaxError = re.compile(r"Error:[0-9]\n")
|
||||
@@ -307,10 +305,10 @@ class TemperatureRecord(object):
|
||||
RESERVED_IDENTIFIER_REGEX = re.compile("[0-9]+|[bc]")
|
||||
|
||||
def __init__(self):
|
||||
self._tools = dict()
|
||||
self._tools = {}
|
||||
self._bed = (None, None)
|
||||
self._chamber = (None, None)
|
||||
self._custom = dict()
|
||||
self._custom = {}
|
||||
|
||||
def copy_from(self, other):
|
||||
self._tools = other.tools
|
||||
@@ -351,25 +349,25 @@ class TemperatureRecord(object):
|
||||
return dict(self._custom)
|
||||
|
||||
def as_script_dict(self):
|
||||
result = dict()
|
||||
result = {}
|
||||
|
||||
tools = self.tools
|
||||
for tool, data in tools.items():
|
||||
result[tool] = dict(actual=data[0],
|
||||
target=data[1])
|
||||
result[tool] = {"actual": data[0],
|
||||
"target": data[1]}
|
||||
|
||||
bed = self.bed
|
||||
result["b"] = dict(actual=bed[0],
|
||||
target=bed[1])
|
||||
result["b"] = {"actual": bed[0],
|
||||
"target": bed[1]}
|
||||
|
||||
chamber = self.chamber
|
||||
result["c"] = dict(actual=chamber[0],
|
||||
target=chamber[1])
|
||||
result["c"] = {"actual": chamber[0],
|
||||
"target": chamber[1]}
|
||||
|
||||
custom = self.custom
|
||||
for identifier, data in custom.items():
|
||||
result[identifier] = dict(actual=data[0],
|
||||
target=data[1])
|
||||
result[identifier] = {"actual": data[0],
|
||||
"target": data[1]}
|
||||
|
||||
return result
|
||||
|
||||
@@ -454,7 +452,7 @@ class MachineCom(object):
|
||||
self._detection_retry = self.DETECTION_RETRIES
|
||||
|
||||
self._temperatureTargetSetThreshold = 25
|
||||
self._tempOffsets = dict()
|
||||
self._tempOffsets = {}
|
||||
self._command_queue = CommandQueue()
|
||||
self._currentZ = None
|
||||
self._currentF = None
|
||||
@@ -474,7 +472,7 @@ class MachineCom(object):
|
||||
|
||||
self._timeout = None
|
||||
self._ok_timeout = None
|
||||
self._timeout_intervals = dict()
|
||||
self._timeout_intervals = {}
|
||||
for key, value in settings().get(["serial", "timeout"], merged=True, asdict=True).items():
|
||||
try:
|
||||
self._timeout_intervals[key] = float(value)
|
||||
@@ -482,7 +480,7 @@ class MachineCom(object):
|
||||
pass
|
||||
|
||||
self._consecutive_timeouts = 0
|
||||
self._consecutive_timeout_maximums = dict()
|
||||
self._consecutive_timeout_maximums = {}
|
||||
for key, value in settings().get(["serial", "maxCommunicationTimeouts"], merged=True, asdict=True).items():
|
||||
try:
|
||||
self._consecutive_timeout_maximums[key] = int(value)
|
||||
@@ -529,8 +527,8 @@ class MachineCom(object):
|
||||
|
||||
self._firmware_detection = settings().getBoolean(["serial", "firmwareDetection"])
|
||||
self._firmware_info_received = False
|
||||
self._firmware_info = dict()
|
||||
self._firmware_capabilities = dict()
|
||||
self._firmware_info = {}
|
||||
self._firmware_capabilities = {}
|
||||
|
||||
self._temperature_autoreporting = False
|
||||
self._sdstatus_autoreporting = False
|
||||
@@ -577,22 +575,16 @@ class MachineCom(object):
|
||||
# hooks
|
||||
self._pluginManager = octoprint.plugin.plugin_manager()
|
||||
|
||||
self._gcode_hooks = dict(
|
||||
queuing=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.queuing"),
|
||||
queued=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.queued"),
|
||||
sending=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sending"),
|
||||
sent=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sent")
|
||||
)
|
||||
self._gcode_hooks = {"queuing": self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.queuing"),
|
||||
"queued": self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.queued"),
|
||||
"sending": self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sending"),
|
||||
"sent": self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sent")}
|
||||
self._received_message_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.received")
|
||||
self._error_message_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.error")
|
||||
self._atcommand_hooks = dict(
|
||||
queuing=self._pluginManager.get_hooks("octoprint.comm.protocol.atcommand.queuing"),
|
||||
sending=self._pluginManager.get_hooks("octoprint.comm.protocol.atcommand.sending")
|
||||
)
|
||||
self._firmware_info_hooks = dict(
|
||||
info=self._pluginManager.get_hooks("octoprint.comm.protocol.firmware.info"),
|
||||
capabilities=self._pluginManager.get_hooks("octoprint.comm.protocol.firmware.capabilities")
|
||||
)
|
||||
self._atcommand_hooks = {"queuing": self._pluginManager.get_hooks("octoprint.comm.protocol.atcommand.queuing"),
|
||||
"sending": self._pluginManager.get_hooks("octoprint.comm.protocol.atcommand.sending")}
|
||||
self._firmware_info_hooks = {"info": self._pluginManager.get_hooks("octoprint.comm.protocol.firmware.info"),
|
||||
"capabilities": self._pluginManager.get_hooks("octoprint.comm.protocol.firmware.capabilities")}
|
||||
|
||||
self._printer_action_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.action")
|
||||
self._gcodescript_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts")
|
||||
@@ -606,7 +598,7 @@ class MachineCom(object):
|
||||
self._sdFileList = False
|
||||
self._sdFileLongName = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = dict()
|
||||
self._sdFilesMap = {}
|
||||
self._sdFileToSelect = None
|
||||
self._sdFileToSelectUser = None
|
||||
self._ignore_select = False
|
||||
@@ -626,7 +618,7 @@ class MachineCom(object):
|
||||
self._suppress_scripts = set()
|
||||
self._suppress_scripts_mutex = threading.RLock()
|
||||
|
||||
self._action_users = dict()
|
||||
self._action_users = {}
|
||||
self._action_users_mutex = threading.RLock()
|
||||
|
||||
self._pause_position_timer = None
|
||||
@@ -683,7 +675,7 @@ class MachineCom(object):
|
||||
if settings().getBoolean(["feature", "sdSupport"]):
|
||||
self._sdFileList = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = dict()
|
||||
self._sdFilesMap = {}
|
||||
self._callback.on_comm_sd_files([])
|
||||
|
||||
if self._currentFile is not None:
|
||||
@@ -1046,22 +1038,20 @@ class MachineCom(object):
|
||||
return self._sendCommand(cmd, cmd_type=cmd_type, on_sent=on_sent, tags=tags)
|
||||
|
||||
def _getGcodeScript(self, scriptName, replacements=None):
|
||||
context = dict()
|
||||
context = {}
|
||||
if replacements is not None and isinstance(replacements, dict):
|
||||
context.update(replacements)
|
||||
|
||||
context.update(dict(
|
||||
printer_profile=self._printerProfileManager.get_current_or_default(),
|
||||
last_position=self.last_position,
|
||||
last_temperature=self.last_temperature.as_script_dict()
|
||||
))
|
||||
context.update({"printer_profile": self._printerProfileManager.get_current_or_default(),
|
||||
"last_position": self.last_position,
|
||||
"last_temperature": self.last_temperature.as_script_dict()})
|
||||
|
||||
if scriptName == "afterPrintPaused" or scriptName == "beforePrintResumed":
|
||||
context.update(dict(pause_position=self.pause_position,
|
||||
pause_temperature=self.pause_temperature.as_script_dict()))
|
||||
context.update({"pause_position": self.pause_position,
|
||||
"pause_temperature": self.pause_temperature.as_script_dict()})
|
||||
elif scriptName == "afterPrintCancelled":
|
||||
context.update(dict(cancel_position=self.cancel_position,
|
||||
cancel_temperature=self.cancel_temperature.as_script_dict()))
|
||||
context.update({"cancel_position": self.cancel_position,
|
||||
"cancel_temperature": self.cancel_temperature.as_script_dict()})
|
||||
|
||||
scriptLinesPrefix = []
|
||||
scriptLinesSuffix = []
|
||||
@@ -1071,7 +1061,7 @@ class MachineCom(object):
|
||||
retval = hook(self, "gcode", scriptName)
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing hook {name}.".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
if retval is None:
|
||||
continue
|
||||
@@ -1099,7 +1089,7 @@ class MachineCom(object):
|
||||
|
||||
if len(retval) == 3:
|
||||
variables = retval[2]
|
||||
context.update(dict(plugins={name:variables}))
|
||||
context.update({"plugins": {name:variables}})
|
||||
|
||||
template = settings().loadScript("gcode", scriptName, context=context)
|
||||
if template is None:
|
||||
@@ -1568,7 +1558,7 @@ class MachineCom(object):
|
||||
self.sendCommand("M22", tags=tags | {"trigger:comm.release_sd_card",})
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = dict()
|
||||
self._sdFilesMap = {}
|
||||
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
self._callback.on_comm_sd_files(self.getSdFiles())
|
||||
@@ -1602,9 +1592,9 @@ class MachineCom(object):
|
||||
filename = self._currentFile.getFilename()
|
||||
pos = self._currentFile.getFilepos()
|
||||
|
||||
return dict(origin=origin,
|
||||
filename=filename,
|
||||
pos=pos)
|
||||
return {"origin": origin,
|
||||
"filename": filename,
|
||||
"pos": pos}
|
||||
|
||||
def _recordFilePosition(self):
|
||||
if self._currentFile is None:
|
||||
@@ -1628,7 +1618,7 @@ class MachineCom(object):
|
||||
return
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing temperatures in {}, skipping".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
if current_tool_key in parsedTemps or "T0" in parsedTemps:
|
||||
shared_nozzle = self._printerProfileManager.get_current_or_default()["extruder"]["sharedNozzle"]
|
||||
@@ -1797,7 +1787,7 @@ class MachineCom(object):
|
||||
except Exception:
|
||||
self._logger.exception("Error while calling hook from plugin "
|
||||
"{} with action command {}".format(name, action_command),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
continue
|
||||
|
||||
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
|
||||
@@ -2019,7 +2009,7 @@ class MachineCom(object):
|
||||
if name and "malyan" in name.lower() and ver:
|
||||
firmware_name = name.strip() + " " + ver.strip()
|
||||
|
||||
eventManager().fire(Events.FIRMWARE_DATA, dict(name=firmware_name, data=data))
|
||||
eventManager().fire(Events.FIRMWARE_DATA, {"name": firmware_name, "data": data})
|
||||
|
||||
if not self._firmware_info_received and firmware_name:
|
||||
firmware_name = firmware_name.strip()
|
||||
@@ -2079,7 +2069,7 @@ class MachineCom(object):
|
||||
hook(self, firmware_name, copy.copy(data))
|
||||
except Exception:
|
||||
self._logger.exception("Error processing firmware info hook {}:".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
##~~ Firmware capability report triggered by M115
|
||||
elif lower_line.startswith("cap:"):
|
||||
@@ -2104,7 +2094,7 @@ class MachineCom(object):
|
||||
hook(self, capability, enabled, copy.copy(self._firmware_capabilities))
|
||||
except Exception:
|
||||
self._logger.exception("Error processing firmware capability hook {}:".format(name),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
##~~ invalid extruder
|
||||
elif 'invalid extruder' in lower_line:
|
||||
@@ -2326,7 +2316,7 @@ class MachineCom(object):
|
||||
self._on_external_reset()
|
||||
self.cancelPrint(disable_log_position=True)
|
||||
|
||||
eventManager().fire(Events.PRINTER_RESET, payload=dict(idle=idle))
|
||||
eventManager().fire(Events.PRINTER_RESET, payload={"idle": idle})
|
||||
|
||||
except Exception:
|
||||
self._logger.exception("Something crashed inside the serial connection loop, please report this in OctoPrint's bug tracker:")
|
||||
@@ -2564,7 +2554,7 @@ class MachineCom(object):
|
||||
if match is None:
|
||||
continue
|
||||
|
||||
outputs = dict()
|
||||
outputs = {}
|
||||
for template_key, template in feedback_controls[feedback_key]["templates"].items():
|
||||
try:
|
||||
output = template.format(*match.groups())
|
||||
@@ -2578,7 +2568,10 @@ class MachineCom(object):
|
||||
|
||||
if output is not None:
|
||||
outputs[template_key] = output
|
||||
eventManager().fire(Events.REGISTERED_MESSAGE_RECEIVED, dict(key=feedback_key, matched=matched_part, outputs=outputs))
|
||||
eventManager().fire(Events.REGISTERED_MESSAGE_RECEIVED,
|
||||
{"key": feedback_key,
|
||||
"matched": matched_part,
|
||||
"outputs": outputs})
|
||||
except Exception:
|
||||
self._logger.exception("Error while trying to match feedback control output, disabling key {key}".format(key=match_key))
|
||||
feedback_errors.append(match_key)
|
||||
@@ -2662,9 +2655,9 @@ class MachineCom(object):
|
||||
else:
|
||||
self.initSdCard(tags={"trigger:comm.on_connected"})
|
||||
|
||||
payload = dict(port=self._port, baudrate=self._baudrate)
|
||||
payload = {"port": self._port, "baudrate": self._baudrate}
|
||||
eventManager().fire(Events.CONNECTED, payload)
|
||||
self.sendGcodeScript("afterPrinterConnected", replacements=dict(event=payload))
|
||||
self.sendGcodeScript("afterPrinterConnected", replacements={"event": payload})
|
||||
|
||||
def _on_external_reset(self):
|
||||
# hold queue processing, clear queues and acknowledgements, reset line number and last lines
|
||||
@@ -2922,7 +2915,7 @@ class MachineCom(object):
|
||||
ret = hook(self, stripped_error)
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing hook {name}:".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
if ret:
|
||||
return line
|
||||
@@ -2999,7 +2992,7 @@ class MachineCom(object):
|
||||
ret = hook(self, ret)
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing hook {name}:".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
if ret is None:
|
||||
return ""
|
||||
@@ -3486,7 +3479,7 @@ class MachineCom(object):
|
||||
phase=phase,
|
||||
command=to_unicode(command,
|
||||
errors="replace")),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
else:
|
||||
normalized = _normalize_command_handler_result(command, command_type, gcode, subcode, tags,
|
||||
hook_results,
|
||||
@@ -3503,7 +3496,7 @@ class MachineCom(object):
|
||||
u"command as-is.".format(name=name,
|
||||
phase=phase,
|
||||
command=to_unicode(command, errors="replace")),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
new_results.append((command, command_type, gcode, subcode, tags))
|
||||
else:
|
||||
new_results += normalized
|
||||
@@ -3576,7 +3569,7 @@ class MachineCom(object):
|
||||
except Exception:
|
||||
self._logger.exception(u"Error while processing hook {} for "
|
||||
u"phase {} and command {}:".format(name, phase, to_unicode(atcommand, errors="replace")),
|
||||
extra=dict(plugin=name))
|
||||
extra={"plugin": name})
|
||||
|
||||
# trigger built-in handler if available
|
||||
handler = getattr(self, "_atcommand_{}_{}".format(atcommand, phase), None)
|
||||
@@ -3705,8 +3698,8 @@ class MachineCom(object):
|
||||
"was reported as invalid by the firmware".format(new_tool))
|
||||
return None,
|
||||
|
||||
before = self._getGcodeScript("beforeToolChange", replacements=dict(tool=dict(old=current_tool, new=new_tool)))
|
||||
after = self._getGcodeScript("afterToolChange", replacements=dict(tool=dict(old=current_tool, new=new_tool)))
|
||||
before = self._getGcodeScript("beforeToolChange", replacements={"tool": {"old": current_tool, "new": new_tool}})
|
||||
after = self._getGcodeScript("afterToolChange", replacements={"tool": {"old": current_tool, "new": new_tool}})
|
||||
|
||||
def convert(data):
|
||||
result = []
|
||||
@@ -3735,7 +3728,7 @@ class MachineCom(object):
|
||||
new_tool = int(toolMatch.group("value"))
|
||||
self._toolBeforeChange = self._currentTool
|
||||
self._currentTool = new_tool
|
||||
eventManager().fire(Events.TOOL_CHANGE, dict(old=self._toolBeforeChange, new=self._currentTool))
|
||||
eventManager().fire(Events.TOOL_CHANGE, {"old": self._toolBeforeChange, "new": self._currentTool})
|
||||
|
||||
def _gcode_G0_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if "Z" in cmd or "F" in cmd:
|
||||
@@ -4335,10 +4328,10 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
|
||||
duration = monotonic_time() - self._start_time
|
||||
read_lines = self._read_lines
|
||||
if duration > 0 and read_lines > 0:
|
||||
stats = dict(lines=read_lines,
|
||||
rate=float(read_lines) / duration,
|
||||
time_per_line=duration * 1000.0 / float(read_lines),
|
||||
duration=duration)
|
||||
stats = {"lines": read_lines,
|
||||
"rate": float(read_lines) / duration,
|
||||
"time_per_line": duration * 1000.0 / float(read_lines),
|
||||
"duration": duration}
|
||||
self._logger.info("Finished in {duration:.3f} s. Approx. transfer rate of {rate:.3f} lines/s or {time_per_line:.3f} ms per line".format(**stats))
|
||||
|
||||
|
||||
@@ -4573,7 +4566,7 @@ def process_gcode_line(line, offsets=None, current_tool=None):
|
||||
|
||||
def convert_pause_triggers(configured_triggers):
|
||||
if not configured_triggers:
|
||||
return dict()
|
||||
return {}
|
||||
|
||||
triggers = {
|
||||
"enable": [],
|
||||
@@ -4596,7 +4589,7 @@ def convert_pause_triggers(configured_triggers):
|
||||
# invalid regex or something like this
|
||||
_logger.debug("Problem with trigger %r: %s", trigger, str(exc))
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
for t in triggers.keys():
|
||||
if len(triggers[t]) > 0:
|
||||
result[t] = re.compile("|".join(map(lambda pattern: "({pattern})".format(pattern=pattern), triggers[t])))
|
||||
@@ -4605,7 +4598,7 @@ def convert_pause_triggers(configured_triggers):
|
||||
|
||||
def convert_feedback_controls(configured_controls):
|
||||
if not configured_controls:
|
||||
return dict(), None
|
||||
return {}, None
|
||||
|
||||
def preprocess_feedback_control(control, result):
|
||||
if "key" in control and "regex" in control and "template" in control:
|
||||
@@ -4627,7 +4620,7 @@ def convert_feedback_controls(configured_controls):
|
||||
preprocess_feedback_control(c, result)
|
||||
|
||||
def prepare_result_entry():
|
||||
return dict(pattern=None, matcher=None, templates=dict())
|
||||
return {"pattern": None, "matcher": None, "templates": {}}
|
||||
|
||||
from collections import defaultdict
|
||||
feedback_controls = defaultdict(prepare_result_entry)
|
||||
@@ -4792,7 +4785,7 @@ def parse_firmware_line(line):
|
||||
line[4] = ":"
|
||||
line = "".join(line)
|
||||
|
||||
result = dict()
|
||||
result = {}
|
||||
split_line = regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
|
||||
for key, value in chunks(split_line, 2):
|
||||
result[key] = value.strip()
|
||||
@@ -4866,9 +4859,9 @@ def parse_position_line(line):
|
||||
|
||||
match = regex_position.search(line)
|
||||
if match is not None:
|
||||
result = dict(x=float(match.group("x")),
|
||||
y=float(match.group("y")),
|
||||
z=float(match.group("z")))
|
||||
result = {"x": float(match.group("x")),
|
||||
"y": float(match.group("y")),
|
||||
"z": float(match.group("z"))}
|
||||
if match.group("e") is not None:
|
||||
# report contains only one E
|
||||
result["e"] = float(match.group("e"))
|
||||
@@ -5212,8 +5205,8 @@ def upload_cli():
|
||||
callback = MyMachineComCallback(path, target)
|
||||
|
||||
# mock printer profile manager
|
||||
profile = dict(heatedBed=False,
|
||||
extruder=dict(count=1, sharedNozzle=False))
|
||||
profile = {"heatedBed": False,
|
||||
"extruder": {"count": 1, "sharedNozzle": False}}
|
||||
printer_profile_manager = Object()
|
||||
printer_profile_manager.get_current_or_default = lambda: profile
|
||||
|
||||
|
||||
@@ -188,10 +188,10 @@ class CommandlineCaller(object):
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
kwargs.update(dict(close_fds=CLOSE_FDS,
|
||||
async_=True,
|
||||
stdout=DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
|
||||
stderr=DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size)))
|
||||
kwargs.update({"close_fds": CLOSE_FDS,
|
||||
"async_": True,
|
||||
"stdout": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
|
||||
"stderr": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size)})
|
||||
|
||||
p = sarge.run(command, **kwargs)
|
||||
while len(p.commands) == 0:
|
||||
|
||||
@@ -203,18 +203,18 @@ class gcode(object):
|
||||
@property
|
||||
def dimensions(self):
|
||||
size = self._minMax.size
|
||||
return dict(width=size.x,
|
||||
depth=size.y,
|
||||
height=size.z)
|
||||
return {"width": size.x,
|
||||
"depth": size.y,
|
||||
"height": size.z}
|
||||
|
||||
@property
|
||||
def printing_area(self):
|
||||
return dict(minX=None if math.isinf(self._minMax.min.x) else self._minMax.min.x,
|
||||
minY=None if math.isinf(self._minMax.min.y) else self._minMax.min.y,
|
||||
minZ=None if math.isinf(self._minMax.min.z) else self._minMax.min.z,
|
||||
maxX=None if math.isinf(self._minMax.max.x) else self._minMax.max.x,
|
||||
maxY=None if math.isinf(self._minMax.max.y) else self._minMax.max.y,
|
||||
maxZ=None if math.isinf(self._minMax.max.z) else self._minMax.max.z)
|
||||
return {"minX": None if math.isinf(self._minMax.min.x) else self._minMax.min.x,
|
||||
"minY": None if math.isinf(self._minMax.min.y) else self._minMax.min.y,
|
||||
"minZ": None if math.isinf(self._minMax.min.z) else self._minMax.min.z,
|
||||
"maxX": None if math.isinf(self._minMax.max.x) else self._minMax.max.x,
|
||||
"maxY": None if math.isinf(self._minMax.max.y) else self._minMax.max.y,
|
||||
"maxZ": None if math.isinf(self._minMax.max.z) else self._minMax.max.z}
|
||||
|
||||
def load(self, filename, throttle=None, speedx=6000, speedy=6000, offsets=None, max_extruders=10, g90_extruder=False):
|
||||
if os.path.isfile(filename):
|
||||
@@ -459,8 +459,8 @@ class gcode(object):
|
||||
s = getCodeInt(line, 'S')
|
||||
if s in [2, 4, 5, 6]:
|
||||
# Duplication / Mirroring mode selected. Printer firmware copies extrusion commands
|
||||
# from first extruder to all other extruders
|
||||
duplicationMode = True
|
||||
# from first extruder to all other extruders
|
||||
duplicationMode = True
|
||||
else:
|
||||
duplicationMode = False
|
||||
|
||||
@@ -504,11 +504,11 @@ class gcode(object):
|
||||
return {key: value for (key, value) in map(lambda x: x.split(b"=", 1), zlib.decompress(base64.b64decode(comment[len(prefix):])).split(b"\b"))}
|
||||
|
||||
def get_result(self):
|
||||
return dict(total_time=self.totalMoveTimeMinute,
|
||||
extrusion_length=self.extrusionAmount,
|
||||
extrusion_volume=self.extrusionVolume,
|
||||
dimensions=self.dimensions,
|
||||
printing_area=self.printing_area)
|
||||
return {"total_time": self.totalMoveTimeMinute,
|
||||
"extrusion_length": self.extrusionAmount,
|
||||
"extrusion_volume": self.extrusionVolume,
|
||||
"dimensions": self.dimensions,
|
||||
"printing_area": self.printing_area}
|
||||
|
||||
def getCodeInt(line, code):
|
||||
return getCode(line, code, int)
|
||||
|
||||
@@ -20,7 +20,7 @@ from .commandline import CommandlineCaller, clean_ansi
|
||||
from octoprint.util import to_unicode, to_native_str
|
||||
from octoprint.util.platform import CLOSE_FDS
|
||||
|
||||
_cache = dict(version=dict(), setup=dict())
|
||||
_cache = {"version": {}, "setup": {}}
|
||||
_cache_mutex = threading.RLock()
|
||||
|
||||
class UnknownPip(Exception):
|
||||
@@ -372,12 +372,12 @@ class PipCaller(CommandlineCaller):
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture(),
|
||||
cwd=testballoon,
|
||||
env=dict(TESTBALLOON_OUTPUT=to_native_str(testballoon_output_file)))
|
||||
env={"TESTBALLOON_OUTPUT": to_native_str(testballoon_output_file)})
|
||||
except Exception:
|
||||
self._logger.exception("Error while trying to install testballoon to figure out pip setup")
|
||||
return False, False, False, None
|
||||
|
||||
data = dict()
|
||||
data = {}
|
||||
with io.open(testballoon_output_file, 'rt', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
key, value = line.split("=", 2)
|
||||
|
||||
@@ -64,10 +64,10 @@ if sys.platform == "win32" and sys.version_info < (3, 7):
|
||||
|
||||
# current os
|
||||
|
||||
_OPERATING_SYSTEMS = dict(windows=["win32"],
|
||||
linux=lambda x: x.startswith("linux"),
|
||||
macos=["darwin"],
|
||||
freebsd=lambda x: x.startswith("freebsd"))
|
||||
_OPERATING_SYSTEMS = {"windows": ["win32"],
|
||||
"linux": lambda x: x.startswith("linux"),
|
||||
"macos": ["darwin"],
|
||||
"freebsd": lambda x: x.startswith("freebsd")}
|
||||
OPERATING_SYSTEM_UNMAPPED = "unmapped"
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user