Merge remote-tracking branch 'origin/maintenance' into py23

This commit is contained in:
Matthias Urlichs committed 2019-01-27 17:28:46 +01:00
commit 670ca15997
61 files changed
+1293 -440

No files matched your search

+2
View File
@@ -96,6 +96,8 @@ date of first contribution):
* [Gaston Dombiak](https://github.com/gdombiak)
* [Brad Fisher](https://github.com/bradcfisher)
* [Aldo Hoeben](https://github.com/fieldofview)
* [Henning Groß](https://github.com/hgross)
* [Jubaleth](https://github.com/jubaleth)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+4
View File
@@ -11,6 +11,10 @@ Apps
Session Keys
============
.. deprecated:: 1.3.11
This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` instead.
OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based
validity and are generated by OctoPrint for requesting apps.
+39
View File
@@ -82,6 +82,45 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
- hidden
- plugins
.. _sec-bundledplugins-pluginmanager-events:
Events
------
plugin_pluginmanager_install_plugin
A plugin was installed.
Payload:
* ``id``: the identifier of the installed plugin
* ``version``: the version of the installed plugin
* ``source``: source from which the plugin was installed, can be an URL or a path in the local file system
* ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path``
plugin_pluginmanager_uninstall_plugin
A plugin was uninstalled.
Payload:
* ``id``: the identifier of the uninstalled plugin
* ``version``: the version of the uninstalled plugin
plugin_pluginmanager_enable_plugin
A plugin was enabled.
Payload:
* ``id``: the identifier of the enabled plugin
* ``version``: the version of the enabled plugin
plugin_pluginmanager_disabled_plugin
A plugin was disabled.
Payload:
* ``id``: the identifier of the disabled plugin
* ``version``: the version of the disabled plugin
.. _sec-bundledplugins-pluginmanager-hooks:
Hooks
@@ -29,6 +29,20 @@ If you know of further printers/printer firmwares that need to be added here, pl
unexpectedly and with `catastrophic <https://www.thissmarthouse.net/dont-burn-your-house-down-3d-printing-a-cautionary-tale/>`_
`results <https://www.reddit.com/r/3Dprinting/comments/6cekgk/house_fire_thanks_to_cheap_printer_from_china/>`_.
.. _sec-bundledplugins-printer_safety_check-events:
Events
------
warning
A printer safety warning was triggered.
Payload:
* ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``)
* ``check_name``: name of check that was triggered (e.g. ``aneta8``)
* ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``)
.. _sec-bundledplugins-printer_safety_check-source:
Source Code
+23
View File
@@ -325,6 +325,29 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing
branch: devel
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
.. _sec-bundledplugins-softwareupdate-events:
Events
------
plugin_softwareupdate_update_succeeded
An update succeeded.
Payload:
* ``target``: update target
* ``from_version``: version from which was updated
* ``to_version``: version to which was updated
plugin_softwareupdate_update_failed
An update failed.
Payload:
* ``target``: update target
* ``from_version``: version from which was updated
* ``to_version``: version to which was updated
.. _sec-bundledplugins-softwareupdate-hooks:
Hooks
+2 -1
View File
@@ -81,7 +81,8 @@ Settings for the REST API:
# Whether to allow cross origin access to the API or not
allowCrossOrigin: false
# Additional app api keys, see REST API > Apps in the docs
# Additional app api keys, see REST API > Apps in the docs.
# Deprecated since 1.3.11, to be removed in 1.4.0!
apps:
"some.app.identifier:some_version":
pubkey: <RSA pubkey>
+26 -11
View File
@@ -6,15 +6,6 @@ Events
.. contents::
.. note::
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
to indicate what to do with the command contained.
.. _sec-events-configuration:
Configuration
@@ -85,6 +76,10 @@ and its origin via the placeholder ``{origin}``.
Available Events
================
.. note::
Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook <sec-plugins-hook-events-register_custom_events>`.
Server
------
@@ -323,6 +318,9 @@ PrintStarted
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who started the print job (if available)
.. deprecated:: 1.3.0
@@ -339,6 +337,8 @@ PrintFailed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the elapsed time of the print when it failed, in seconds (float)
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
@@ -357,6 +357,8 @@ PrintDone
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the time needed for the print, in seconds (float)
.. deprecated:: 1.3.0
@@ -374,6 +376,9 @@ PrintCancelling
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who cancelled the print job (if available)
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
PrintCancelled
@@ -384,7 +389,11 @@ PrintCancelled
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of cancelling, if available
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the elapsed time of the print when it was cancelled, in seconds (float)
* ``user``: the user who cancelled the print job (if available)
* ``position``: the print head position at the time of cancelling (if available)
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
@@ -411,7 +420,10 @@ PrintPaused
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of pausing, if available
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who paused the print job (if available)
* ``position``: the print head position at the time of pausing (if available)
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
@@ -438,6 +450,9 @@ PrintResumed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who resumed the print job (if available)
.. deprecated:: 1.3.0
+117
View File
@@ -208,6 +208,10 @@ octoprint.accesscontrol.appkey
.. py:function:: acl_appkey_hook(*args, **kwargs)
.. deprecated:: 1.3.11
This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` instead.
By handling this hook plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
within the system.
@@ -903,6 +907,34 @@ octoprint.comm.transport.serial.factory
:rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and
optionally ``baudrate`` and ``timeout`` attributes as described above.
.. _sec-plugins-hook-events-register_custom_events:
octoprint.events.register_custom_events
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: register_custom_events_hook(*args, **kwargs)
Return a list of custom :ref:`events <sec-events>` to register in the system for your plugin.
Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object
will be the returned value transformed into upper case ``CAMEL_CASE`` and prefixed with ``PLUGIN_<IDENTIFIER>``. Their
value will be prefixed with ``plugin_<identifier>_``.
Example:
Consider the following hook part of a plugin with the identifier ``myplugin``. It will register two custom events
in the system, ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_CUSTOM_EVENT`` with value ``plugin_myplugin_my_custom_event``
and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``.
.. code-block:: python
:linenos:
def register_custom_events(*args, **kwargs):
return ["my_custom_event", "my_other_custom_event"]
:return: A list of custom events to register
:rtype: list
.. _sec-plugins-hook-filemanager-analysis-factory:
octoprint.filemanager.analysis.factory
@@ -1089,6 +1121,91 @@ octoprint.printer.estimation.factory
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
:rtype: class or function
.. _sec-plugins-hook-octoprint-printer-sdcardupload:
octoprint.printer.sdcardupload
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs)
Via this hook plugins can change the way files are being uploaded to the sd card of the printer.
Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback``
or ``failure_callback`` on the end of the file transfer, depending on whether it was successful or not.
The ``start_callback`` has the following signature:
.. code-block:: python
def start_callback(local_filename, remote_filename):
# ...
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
to be created on the ``sdcard`` storage.
``success_callback`` and ``failure_callback`` both have the following signature:
.. code-block:: python
def success_or_failure_callback(local_filename, remote_filename, elapsed):
# ...
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
to be created on the ``sdcard`` storage. ``elapsed`` is the elapsed time in seconds.
If the hook is going to handle the upload, it must return the (future) remote filename of the file on the ``sdcard``
storage. If it returns ``None`` (or an otherwise falsy value), OctoPrint will interpret this as the hook not going to
handle the file upload, in which case the next hook or - if no other hook is registered - the default implementation
will be called.
**Example**
The following example creates a dummy SD card uploader that does nothing but sleep for ten seconds when a file
is supposed to be uploaded. Note that the long running process of sleeping for ten seconds is extracted into its
own thread, which is important in order to not block the main application!
.. code-block:: python
import threading
import logging
import time
def nop_upload_to_sd(printer, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs):
logger = logging.getLogger(__name__)
remote_name = printer._get_free_remote_name(filename)
logger.info("Starting dummy SDCard upload from {} to {}".format(filename, remote_name))
sd_upload_started(filename, remote_name)
def process():
logger.info("Sleeping 10s...")
time.sleep(10)
logger.info("And done!")
sd_upload_succeeded(filename, remote_name, 10)
thread = threading.Thread(target=process)
thread.daemon = True
thread.start()
return remote_name
__plugin_name__ = "No-op SDCard Upload Test"
__plugin_hooks__ = {
"octoprint.printer.sdcardupload": nop_upload_to_sd
}
.. versionadded:: 1.3.11
:param object printer: the :py:class:`~octoprint.printer.PrinterInterface` instance the hook was called from
:param str filename: filename on the ``local`` storage
:param str path: path of the file in the local file system
:param function sd_upload_started: callback for when the upload started
:param function sd_upload_success: callback for successful finish of upload
:param function sd_upload_failure: callback for failure of upload
:return: the name of the file on the ``sdcard`` storage or ``None``
:rtype: string or ``None``
.. _sec-plugins-hook-server-http-after_request:
octoprint.server.api.after_request
+44 -9
View File
@@ -68,11 +68,14 @@ calls are done is as follows:
* Plugins with a return value that is not ``None`` for :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`
for the provided sorting context will be ordered among each other first. If the returned order number is equal for
two or more implementations, the plugin's identifier will be the next sorting criteria.
* After that follow plugins which returned ``None`` (the default). They are sorted by their identifier.
two or more implementations, they will be sorted first by whether they come bundled with OctoPrint or not, then by
their identifier.
* After that follow plugins which returned ``None`` (the default). They are first sorted by whether they come bundled
with OctoPrint or not, then by their identifier.
Example: Consider three plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
``plugin_a``, ``plugin_b`` and ``plugin_c``. ``plugin_a`` doesn't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
Example: Consider four plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
``plugin_a``, ``plugin_b``, ``plugin_c`` and ``plugin_d``, the latter coming bundled with OctoPrint. ``plugin_a``
and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
``plugin_b`` and ``plugin_c`` both return ``1`` for the sorting context ``StartupPlugin.on_startup``, ``None`` otherwise:
.. code-block:: python
@@ -99,7 +102,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
class PluginB(octoprint.plugin.StartupPlugin):
def get_sorting_key(context):
def get_sorting_key(self, context):
if context == "StartupPlugin.on_startup":
return 1
return None
@@ -120,7 +123,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
class PluginC(octoprint.plugin.StartupPlugin):
def get_sorting_key(context):
def get_sorting_key(self, context):
if context == "StartupPlugin.on_startup":
return 1
return None
@@ -134,13 +137,45 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
__plugin_implementation__ = PluginC()
.. code-block:: python
:linenos:
:caption: plugin_d.py
# in this example this is bundled with OctoPrint
import octoprint.plugin
class PluginD(octoprint.plugin.StartupPlugin):
def on_startup(self, *args, **kwargs):
self._logger.info("PluginD starting up")
def on_after_startup(self, *args, **kwargs):
self._logger.info("PluginD started up")
__plugin_implementation__ = PluginD()
OctoPrint will detect that ``plugin_b`` and ``plugin_c`` define a order number, and since it's identical for both (``1``)
will order both plugins based on their plugin identifier. ``plugin_a`` doesn't define a sort key and hence will be
put after the other two. The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_a``.
will order both plugins based first on their bundling status and then on their plugin identifier.
``plugin_a`` and ``plugin_d`` don't define a sort key and hence will be
put after the other two, with ``plugin_d`` coming *before* ``plugin_a`` since it comes bundled with OctoPrint.
The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_d``, ``plugin_a``.
Now, the execution order of the ``on_after_startup`` method will be determined based on another sorting context,
``StartupPlugin.on_after_startup`` for which all of the plugins return ``None``. Hence, the execution order of the
``on_after_startup`` method will be purely ordered by plugin identifier, ``plugin_a``, ``plugin_b``, ``plugin_c``.
``on_after_startup`` method will be ordered first by bundle status, then by plugin identifier: ``plugin_d``, ``plugin_a``, ``plugin_b``, ``plugin_c``.
This will result in the following messages to be generated:
.. code-block:: plain
Plugin B starting up
Plugin C starting up
Plugin D starting up
Plugin A starting up
Plugin D started up
Plugin A started up
Plugin B started up
Plugin C started up
.. _sec-plugins-mixins-injectedproperties:
+17
View File
@@ -0,0 +1,17 @@
# init/systemd files for OctoPrint.
Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octoprint. If you have a different
setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly.
## init
```
octoprint.default => /etc/default/octoprint
octoprint.init => /etc/init.d/octoprint
```
## systemd
```
octoprint.service => /etc/systemd/service/octoprint.service
```
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=The snappy web interface for your 3D printer
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=pi
ExecStart=/home/pi/OctoPrint/venv/bin/octoprint
[Install]
WantedBy=multi-user.target
+1 -1
View File
@@ -143,7 +143,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
ignore_blacklist=ignore_blacklist,
connectivity_checker=connectivity_checker)
except Exception as ex:
raise FatalStartupError("Could not initialize settings manager", cause=ex)
raise FatalStartupError("Could not initialize plugin manager", cause=ex)
kwargs["plugin_manager"] = plugin_manager
if callable(after_plugin_manager):
+26 -6
View File
@@ -14,6 +14,7 @@ except ImportError:
import Queue as queue
import threading
import collections
import re
from octoprint.settings import settings
import octoprint.plugin
@@ -23,7 +24,7 @@ _instance = None
def all_events():
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")]
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)]
class Events(object):
@@ -119,6 +120,23 @@ class Events(object):
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
@classmethod
def register_event(cls, event, prefix=None):
name = cls._to_identifier(event)
if prefix:
event = prefix + event
name = cls._to_identifier(prefix) + name
setattr(cls, name, event)
return name, event
# based on https://stackoverflow.com/a/1176023
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
@classmethod
def _to_identifier(cls, name):
s1 = cls._first_cap_re.sub(r'\1_\2', name)
return cls._all_cap_re.sub(r'\1_\2', s1).upper()
def eventManager():
global _instance
@@ -135,6 +153,7 @@ class EventManager(object):
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
self._startup_signaled = False
self._shutdown_signaled = False
@@ -156,14 +175,14 @@ class EventManager(object):
self._shutdown_signaled = True
eventListeners = self._registeredListeners[event]
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
for listener in eventListeners:
self._logger.debug("Sending action to %r" % listener)
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except:
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
@@ -227,7 +246,7 @@ class EventManager(object):
return
self._registeredListeners[event].append(callback)
self._logger.debug("Subscribed listener %r for event %s" % (callback, event))
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
def unsubscribe (self, event, callback):
"""
@@ -236,10 +255,11 @@ class EventManager(object):
try:
self._registeredListeners[event].remove(callback)
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
except ValueError:
# not registered
pass
else:
self._logger.debug("Unsubscribed listener %r for event %s", callback, event)
def join(self, timeout=None):
self._worker.join(timeout)
-10
View File
@@ -33,16 +33,6 @@ from octoprint.util import deprecated
_instance = None
def _validate_plugin(phase, plugin_info):
if phase == "after_load":
if plugin_info.implementation is not None and isinstance(plugin_info.implementation, AppPlugin):
# transform app plugin into hook
import warnings
warnings.warn("{name} uses deprecated plugin mixin AppPlugin, use octoprint.accesscontrol.appkey hook instead".format(name=plugin_info.key), DeprecationWarning)
hooks = plugin_info.hooks
if not "octoprint.accesscontrol.appkey" in hooks:
hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
return True
def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None,
+9 -5
View File
@@ -840,12 +840,15 @@ class PluginManager(object):
# ... then create and return the real one
return self._import_plugin(key, *module,
name=name, version=version, summary=summary, author=author, url=url,
module_name=module_name, name=name, version=version, summary=summary, author=author, url=url,
license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata)
def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
def _import_plugin(self, key, f, filename, description, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
try:
instance = imp.load_module(key, f, filename, description)
if module_name:
instance = imp.load_module(module_name, f, filename, description)
else:
instance = imp.load_module(key, f, filename, description)
plugin = PluginInfo(key, filename, instance,
name=name,
version=version,
@@ -1479,12 +1482,13 @@ class PluginManager(object):
if sorting_value is not None:
try:
int(sorting_value)
sorting_value = int(sorting_value)
except ValueError:
self.logger.warning("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
sorting_value = None
return sorting_value is None, sorting_value, impl[0]
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
return sorting_value is None, sorting_value, not plugin_info.bundled, impl[0]
return [impl[1] for impl in sorted(result, key=sort_func)]
-17
View File
@@ -2061,20 +2061,3 @@ class ProgressPlugin(OctoPrintPlugin):
:param int progress: Current progress as a value between 0 and 100
"""
pass
class AppPlugin(OctoPrintPlugin):
"""
Using the :class:`AppPlugin mixin` plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
within the system.
.. deprecated:: 1.2.0
Refer to the :ref:`octoprint.accesscontrol.appkey hook <sec-plugins-hook-accesscontrol-appkey>` instead.
"""
# noinspection PyMethodMayBeStatic
def get_additional_apps(self):
return []
+4 -4
View File
@@ -698,7 +698,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
os.rename(temporary_path, final_path)
shutil.move(temporary_path, final_path)
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
@@ -848,18 +848,18 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
if callable(on_log_progress):
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
os.rename(basedir, basedir_backup)
shutil.move(basedir, basedir_backup)
try:
if callable(on_log_progress):
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
os.rename(basedir_extracted, basedir)
shutil.move(basedir_extracted, basedir)
except:
if callable(on_log_error):
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
on_log_error(u"Rolling back old config data")
os.rename(basedir_backup, basedir)
shutil.move(basedir_backup, basedir)
if callable(on_restore_failed):
on_restore_failed(path)
+23 -1
View File
@@ -34,14 +34,28 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
# ACL hasn't been configured yet, make an exception
return False
from octoprint.server.util import loginUserFromApiKey, loginUserFromAuthorizationHeader, InvalidApiKeyException
from octoprint.server.util.flask import passive_login
# first try to login via api key & authorization header, just in case that's set
try:
if loginUserFromApiKey():
# successful? No need for handling the UI
return False
except InvalidApiKeyException:
pass # ignored
if loginUserFromAuthorizationHeader():
# successful? No need for handling the UI
return False
# then try a passive login
result = passive_login()
if hasattr(result, "status_code") and result.status_code == 200:
try:
data = json.loads(result.data)
if "name" in data:
# passive login successful, no need to handle that
# successful? No need for handling the UI
return False
except:
self._logger.exception("Error while trying to decode passive login response")
@@ -95,6 +109,14 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
def get_ui_preemptive_caching_enabled(self):
return False
def get_sorting_key(self, context=None):
if context == "UiPlugin.on_ui_render":
# If a plugin *really* wants to come before this plugin, it'll have to turn to negative numbers.
#
# This is obviously discouraged for security reasons, but very specific setups might make it necessary,
# so we make it possible. If this should get abused long term we can always turn this into -inf.
return 0
def get_before_request_handlers(self):
def check_login_required():
if self._user_manager.enabled and not self._user_manager.has_been_customized():
@@ -17,7 +17,7 @@ $(function() {
var username = usernameElement.val();
var password = passwordElement.val();
var remember = rememberElement.checked;
var remember = rememberElement.prop("checked");
overlayElement.addClass("in");
errorElement.removeClass("in");
@@ -1,5 +1,6 @@
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OctoPrint Login</title>
{% include "parts/forcelogin_css.jinja2" %}
@@ -1 +1 @@
table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
table td.settings_logs_checkbox,table th.settings_logs_checkbox{text-align:center;width:10px}table td.settings_logs_checkbox input[type=checkbox],table th.settings_logs_checkbox input[type=checkbox]{margin-top:0}table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
@@ -9,6 +9,8 @@ $(function() {
self.configuredLoggers = ko.observableArray();
self.configuredLoggersChanged = false;
self.markedForDeletion = ko.observableArray([]);
self.availableLoggersSorted = ko.computed(function() {
return _.sortBy(self.availableLoggers());
});
@@ -114,8 +116,37 @@ $(function() {
};
self.removeFile = function(filename) {
OctoPrint.plugins.logging.deleteLog(filename)
.done(self.requestData);
var perform = function() {
OctoPrint.plugins.logging.deleteLog(filename)
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: filename}),
perform);
};
self.markFilesOnPage = function() {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.listHelper.paginatedItems(), "name"))));
};
self.markAllFiles = function() {
self.markedForDeletion(_.map(self.listHelper.allItems, "name"));
};
self.clearMarkedFiles = function() {
self.markedForDeletion.removeAll();
};
self.removeMarkedFiles = function() {
var perform = function() {
self._bulkRemove(self.markedForDeletion(), "files")
.done(function() {
self.markedForDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d log files."), {count: self.markedForDeletion().length}),
perform);
};
self.onSettingsShown = function() {
@@ -134,6 +165,47 @@ $(function() {
console.log("ConfiguredLoggers has not changed. Not saving.");
}
};
self._bulkRemove = function(files) {
var title = gettext("Deleting log files");
var message = _.sprintf(gettext("Deleting %(count)d log files..."), {count: files.length});
var handler = function(filename) {
return OctoPrint.plugins.logging.deleteLog(filename)
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
deferred.notify(short, long, false);
});
};
var deferred = $.Deferred();
var promise = deferred.promise();
var options = {
title: title,
message: message,
max: files.length,
output: true
};
showProgressModal(options, promise);
var requests = [];
_.each(files, function(filename) {
var request = handler(filename);
requests.push(request)
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -1,5 +1,14 @@
table {
th, td {
&.settings_logs_checkbox {
text-align: center;
width: 10px;
input[type="checkbox"] {
margin-top: 0;
}
}
&.settings_logs_name {
text-overflow: ellipsis;
text-align: left;
@@ -1,13 +1,31 @@
<h3>{{ _('Logs') }}</h3>
<div class="pull-right">
<small>
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
</small>
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-wrench"></i> <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('name'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> {{ _('Sort by name') }} ({{ _('ascending') }})</a></li>
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('modification'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'modification' ? 'visible' : 'hidden'}"></i> {{ _('Sort by modification date') }} ({{ _('descending') }})</a></li>
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('size'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> {{ _('Sort by file size') }} ({{ _('descending') }})</a></li>
</ul>
</div>
</div>
<div class="pull-left">
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
<li class="divider"></li>
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
</ul>
</div>
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForDeletion().length > 0">{{ _('Delete selected') }}</button>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
<thead>
<tr>
<th class="settings_logs_checkbox"></th>
<th class="settings_logs_name">{{ _('Name') }}</th>
<th class="settings_logs_size">{{ _('Size') }}</th>
<th class="settings_logs_date">{{ _('Date') }}</th>
@@ -16,6 +34,7 @@
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_logs_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForDeletion"></td>
<td class="settings_logs_name" data-bind="text: name"></td>
<td class="settings_logs_size" data-bind="text: formatSize(size)"></td>
<td class="settings_logs_date" data-bind="text: formatDate(date)"></td>
+13 -1
View File
@@ -13,6 +13,7 @@ from flask_babel import gettext
from octoprint.util import RepeatedTimer
import octoprint.plugin
import octoprint.events
_PROC_DT_MODEL_PATH = "/proc/device-tree/model"
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
@@ -291,7 +292,13 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
state=self._throttle_state.as_dict()))
self._event_bus.fire("plugin_pi_support_throttle_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())
def register_custom_events(*args, **kwargs):
return ["throttle_state",]
__plugin_name__ = "Pi Support Plugin"
@@ -317,5 +324,10 @@ def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.events.register_custom_events": register_custom_events
}
global __plugin_helpers__
__plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state)
+22 -12
View File
@@ -16,6 +16,7 @@ from octoprint.access.permissions import Permissions
from octoprint.util.pip import LocalPipCaller
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
from octoprint.util.platform import get_os, is_os_compatible
from octoprint.events import Events
from flask import jsonify, make_response
from flask_babel import gettext
@@ -382,7 +383,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
raise ValueError("Either URL or path must be provided")
self._logger.info("Installing plugin from {}".format(source))
pip_args = ["install", sarge.shell_quote(source), '--no-cache-dir']
pip_args = ["--disable-pip-version-check", "install", sarge.shell_quote(source), "--no-cache-dir"]
if dependency_links or self._settings.get_boolean(["dependency_links"]):
pip_args.append("--process-dependency-links")
@@ -504,10 +505,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._plugin_manager.log_all_plugins()
self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version))
self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key,
version=new_plugin.version,
source=source,
source_type=source_type))
# 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))
result = dict(result=True,
source=source,
@@ -540,7 +543,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if origin is None:
origin = plugin.origin[2]
pip_args = ["uninstall", "--yes", origin]
pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin]
try:
self._call_pip(pip_args)
except:
@@ -599,8 +602,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._plugin_manager.reload_plugins()
self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key,
version=plugin.version))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, dict(id=plugin.key,
version=plugin.version))
result = dict(result=True,
needs_restart=needs_restart,
@@ -742,8 +746,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
elif not plugin.enabled and plugin.key not in self._pending_enable:
self._pending_enable.add(plugin.key)
self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key,
version=plugin.version))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, dict(id=plugin.key,
version=plugin.version))
def _mark_plugin_disabled(self, plugin, needs_restart=False):
disabled_list = list(self._settings.global_get(["plugins", "_disabled"],
@@ -762,8 +767,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable:
self._pending_disable.add(plugin.key)
self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key,
version=plugin.version))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, dict(id=plugin.key,
version=plugin.version))
def _fetch_all_data(self, do_async=False):
def run():
@@ -981,6 +987,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
important=notification.get("important", False))
def _register_custom_events(*args, **kwargs):
return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"]
__plugin_name__ = "Plugin Manager"
__plugin_author__ = "Gina Häußge"
@@ -997,4 +1006,5 @@ def __plugin_load__():
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.events.register_custom_events": _register_custom_events
}
@@ -162,9 +162,12 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
for check_name, check in checks:
if check(*args, **kwargs):
self._register_warning(warning_type, message)
self._event_bus.fire("plugin_printer_safety_check_warning", dict(check_type=check_type,
check_name=check_name,
warning_type=warning_type))
# noinspection PyUnresolvedReferences
self._event_bus.fire(Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING, dict(check_type=check_type,
check_name=check_name,
warning_type=warning_type))
changes = True
break
@@ -188,6 +191,11 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
def _ping_clients(self):
self._plugin_manager.send_plugin_message(self._identifier, dict(type="update"))
def register_custom_events(*args, **kwargs):
return ["warning",]
__plugin_name__ = "Printer Safety Check"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html"
@@ -202,5 +210,6 @@ __plugin_hooks__ = {
"octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.events.register_custom_events": register_custom_events
}
@@ -965,17 +965,21 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
target_result = None
def trigger_event(success, **additional_payload):
from octoprint.events import Events
if success:
event = "update_succeeded"
# noinspection PyUnresolvedReferences
event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED
else:
event = "update_failed"
# noinspection PyUnresolvedReferences
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))
self._event_bus.fire("plugin_softwareupdate_{}".format(event), payload=payload)
self._event_bus.fire(event, payload=payload)
### The actual update procedure starts here...
@@ -1218,6 +1222,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
return None
def _register_custom_events(*args, **kwargs):
return ["update_succeeded", "update_failed"]
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
@@ -1242,4 +1250,5 @@ def __plugin_load__():
__plugin_hooks__ = {
"octoprint.cli.commands": cli.commands,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.events.register_custom_events": _register_custom_events
}
@@ -86,7 +86,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
install_arg = check["pip"].format(target_version=target_version, target=target_version)
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
pip_args = ["install", install_arg, "--no-cache-dir"]
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
pip_kwargs = dict()
if pip_working_directory is not None:
pip_kwargs.update(cwd=pip_working_directory)
+75 -66
View File
@@ -51,7 +51,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._startup_time = monotonic_time()
def initialize(self):
self._init_tracking()
self._init_id()
##~~ SettingsPlugin
@@ -79,9 +79,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
if enabled is None and self._settings.get([b"enabled"]):
# tracking was just enabled, let's init it and send a startup event
self._init_tracking()
self._track_startup()
# tracking was just enabled, let's start up tracking
self._start_tracking()
##~~ EnvironmentDetectionPlugin
@@ -91,48 +90,53 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
##~~ StartupPlugin
def on_after_startup(self):
ping = self._settings.get_int(["ping"])
if ping:
self._ping_worker = RepeatedTimer(ping, self._track_ping, run_first=True)
self._ping_worker.start()
# cautiously look for the get_throttled helper from pi_support
pi_helper = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if pi_helper and 'get_throttled' in pi_helper:
self._helpers_get_throttle_state = pi_helper['get_throttled']
# now that we have everything set up, phone home.
self._track_startup()
self._start_tracking()
##~~ ShutdownPlugin
def on_shutdown(self):
if not self._settings.get_boolean([b"enabled"]):
return
self._track_shutdown()
##~~ EventHandlerPlugin
# noinspection PyUnresolvedReferences
def on_event(self, event, payload):
if event.startswith("plugin_pluginmanager_"):
self._track_plugin_event(event, payload)
elif event.startswith("plugin_softwareupdate_"):
self._track_update_event(event, payload)
elif event in ("plugin_pi_support_throttle_state",):
self._throttle_state = payload
self._track_throttle_event(event, payload)
elif event in ("plugin_printer_safety_check_warning",):
self._track_printer_safety_event(event, payload)
elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED):
if not self._settings.get_boolean([b"enabled"]):
return
if event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED):
self._track_printjob_event(event, payload)
elif event in (Events.ERROR,):
self._track_commerror_event(event, payload)
elif event in (Events.CONNECTED,):
self._printer_connection_parameters = dict(port=payload["port"],
baudrate=payload["baudrate"])
self._record_next_firmware_info = True
elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info:
self._record_next_firmware_info = False
self._track_printer_event(event, payload)
elif hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN") and \
event in (Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN):
self._track_plugin_event(event, payload)
elif hasattr(Events, "PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED") and \
event in (Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED, Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED):
self._track_update_event(event, payload)
elif hasattr(Events, "PLUGIN_PI_SUPPORT_THROTTLE_STATE") and event in (Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE,):
self._throttle_state = payload
self._track_throttle_event(event, payload)
elif hasattr(Events, "PLUGIN_PRINTER_SAFETY_CHECK_WARNING") and event in (Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING,):
self._track_printer_safety_event(event, payload)
##~~ TemplatePlugin
def get_template_configs(self):
@@ -153,18 +157,31 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
##~~ helpers
def _init_tracking(self):
if not self._settings.get_boolean([b"enabled"]):
return
self._init_id()
self._logger.info("Initialized anonymous tracking")
def _init_id(self):
if self._settings.get_boolean([b"enabled"]) and not self._settings.get([b"unique_id"]):
if not self._settings.get([b"unique_id"]):
import uuid
self._settings.set([b"unique_id"], str(uuid.uuid4()))
self._settings.save()
def _start_tracking(self):
if not self._settings.get_boolean([b"enabled"]):
return
if self._ping_worker is None:
ping = self._settings.get_int(["ping"])
if ping:
self._ping_worker = RepeatedTimer(ping, self._track_ping, run_first=True)
self._ping_worker.start()
if self._helpers_get_throttle_state is None:
# cautiously look for the get_throttled helper from pi_support
pi_helper = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if pi_helper and 'get_throttled' in pi_helper:
self._helpers_get_throttle_state = pi_helper['get_throttled']
# now that we have everything set up, phone home.
self._track_startup()
def _track_ping(self):
if not self._settings.get_boolean([b"enabled"]):
return
@@ -173,9 +190,6 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._track("ping", octoprint_uptime=uptime)
def _track_startup(self):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "startup"]):
return
@@ -205,25 +219,19 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._track("shutdown")
def _track_plugin_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "plugin"]):
return
if event.endswith("_installplugin"):
if event.endswith("_install_plugin"):
self._track("install_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_uninstallplugin"):
elif event.endswith("_uninstall_plugin"):
self._track("uninstall_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_enableplugin"):
elif event.endswith("_enable_plugin"):
self._track("enable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_disableplugin"):
elif event.endswith("_disable_plugin"):
self._track("disable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
def _track_update_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "update"]):
return
@@ -233,9 +241,6 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
def _track_throttle_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "throttled"]):
return
@@ -256,9 +261,6 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._track(track_event, **args)
def _track_commerror_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "commerror"]):
return
@@ -282,15 +284,16 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._track(track_event, **args)
def _track_printjob_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
if not self._settings.get_boolean(["events", "printjob"]):
return
if not self._settings.get_boolean(["events", "printjob"]):
unique_id = self._settings.get([b"unique_id"])
if not unique_id:
return
sha = hashlib.sha1()
sha.update(payload.get("path"))
sha.update(self._settings.get([b"unique_id"]))
sha.update(unique_id)
track_event = None
args = dict(origin=payload.get(b"origin"), file=sha.hexdigest())
@@ -300,16 +303,16 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
elif event == Events.PRINT_DONE:
try:
elapsed = int(payload.get(b"time"))
args[b"elapsed"] = elapsed
except ValueError:
elapsed = "unknown"
args[b"elapsed"] = elapsed
pass
track_event = "print_done"
elif event == Events.PRINT_FAILED:
try:
elapsed = int(payload.get(b"time"))
args[b"elapsed"] = elapsed
except ValueError:
elapsed = "unknown"
args[b"elapsed"] = elapsed
pass
args[b"reason"] = payload.get(b"reason", "unknown")
if b"error" in payload and self._settings.get_boolean(["events", "commerror"]):
@@ -317,6 +320,11 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
track_event = "print_failed"
elif event == Events.PRINT_CANCELLED:
try:
elapsed = int(payload.get(b"time"))
args[b"elapsed"] = elapsed
except ValueError:
pass
track_event = "print_cancelled"
if callable(self._helpers_get_throttle_state):
@@ -334,9 +342,6 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._track(track_event, **args)
def _track_printer_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "printer"]):
return
@@ -348,9 +353,6 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._track("printer_connected", **args)
def _track_printer_safety_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
if not self._settings.get_boolean(["events", "printer_safety_check"]):
return
@@ -368,8 +370,15 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
if not self._connectivity_checker.online:
return
if not self._settings.get_boolean([b"enabled"]):
return
unique_id = self._settings.get([b"unique_id"])
if not unique_id:
return
server = self._settings.get([b"server"])
url = server.format(id=self._settings.get([b"unique_id"]), event=event)
url = server.format(id=unique_id, event=event)
# Don't print the URL or UUID! That would expose the UUID in forums/tickets
# if pasted. It's okay for the user to know their uuid, but it shouldn't be shared.
+2 -2
View File
@@ -419,9 +419,9 @@ class PrinterInterface(object):
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
if self.is_printing():
self.pause_print(tags=tags)
self.pause_print(tags=tags, *args, **kwargs)
elif self.is_paused():
self.resume_print(tags=tags)
self.resume_print(tags=tags, *args, **kwargs)
def cancel_print(self, tags=None, *args, **kwargs):
"""
+158 -41
View File
@@ -45,6 +45,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
from collections import deque
self._logger = logging.getLogger(__name__)
self._logger_job = logging.getLogger("{}.job".format(__name__))
self._dict = frozendict if settings().getBoolean(["devel", "useFrozenDictForPrinterState"]) else dict
@@ -97,6 +98,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
except:
self._logger.exception("Error while processing analysis queues from {}".format(name))
#hook card upload
self.sd_card_upload_hooks = plugin_manager().get_hooks("octoprint.printer.sdcardupload")
# comm
self._comm = None
@@ -530,9 +534,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._updateProgressData()
self._setCurrentZ(None)
self._comm.startPrint(pos=pos,
user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"})
def pause_print(self, *args, **kwargs):
def pause_print(self, user=None, *args, **kwargs):
"""
Pause the current printjob.
"""
@@ -542,9 +547,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm.isPaused():
return
self._comm.setPause(True, tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"})
self._comm.setPause(True,
user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"})
def resume_print(self, *args, **kwargs):
def resume_print(self, user=None, *args, **kwargs):
"""
Resume the current printjob.
"""
@@ -554,9 +561,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not self._comm.isPaused():
return
self._comm.setPause(False, tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"})
self._comm.setPause(False,
user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"})
def cancel_print(self, *args, **kwargs):
def cancel_print(self, user=None, *args, **kwargs):
"""
Cancel the current printjob.
"""
@@ -565,7 +574,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# tell comm layer to cancel - will also trigger our cancelled handler
# for further processing
self._comm.cancelPrint(tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"})
self._comm.cancelPrint(user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"})
def log_lines(self, *lines):
serial_logger = logging.getLogger("SERIAL")
@@ -669,7 +679,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return []
return list(map(lambda x: (x[0][1:], x[1]), self._comm.getSdFiles()))
def add_sd_file(self, filename, absolutePath, on_success=None, on_failure=None, *args, **kwargs):
def add_sd_file(self, filename, path, on_success=None, on_failure=None, *args, **kwargs):
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
self._logger.error("No connection to printer or printer is busy")
return
@@ -677,23 +687,67 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._streamingFinishedCallback = on_success
self._streamingFailedCallback = on_failure
def sd_upload_started(local_filename, remote_filename):
eventManager().fire(Events.TRANSFER_STARTED, dict(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)
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)
eventManager().fire(Events.TRANSFER_FAILED, payload)
if callable(self._streamingFailedCallback):
self._streamingFailedCallback(remote_filename, remote_filename, FileDestinations.SDCARD)
for name, hook in self.sd_card_upload_hooks.items():
# first sd card upload plugin that feels responsible gets the job
try:
result = hook(self, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed,
*args, **kwargs)
if result is not None:
return result
except:
self._logger.exception("There was an error running the sd upload hook provided by plugin {}".format(name))
else:
# no plugin feels responsible, use the default implementation
return self._add_sd_file(filename, path, tags=kwargs.get("tags"))
def _get_free_remote_name(self, filename):
self.refresh_sd_files(blocking=True)
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
if valid_file_type(filename, "gcode"):
remoteName = util.get_dos_filename(filename,
existing_filenames=existingSdFiles,
extension="gco",
whitelisted_extensions=["gco", "g"])
# figure out remote filename
remote_name = util.get_dos_filename(filename,
existing_filenames=existingSdFiles,
extension="gco",
whitelisted_extensions=["gco", "g"])
else:
# probably something else added through a plugin, use it's basename as-is
remoteName = os.path.basename(filename)
self._create_estimator("stream")
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName,
special=not valid_file_type(filename, "gcode"),
tags=kwargs.get("tags", set()) | {"trigger:printer.add_sd_file"})
remote_name = os.path.basename(filename)
return remoteName
return remote_name
def _add_sd_file(self, filename, path, tags=None):
if tags is None:
tags = set()
remote_name = self._get_free_remote_name(filename)
self._create_estimator("stream")
self._comm.startFileTransfer(path, filename, "/" + remote_name,
special=not valid_file_type(filename, "gcode"),
tags=tags | {"trigger:printer.add_sd_file"})
return remote_name
def delete_sd_file(self, filename, *args, **kwargs):
if not self._comm or not self._comm.isSdReady():
@@ -923,6 +977,19 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
filament=filament,
user=user))
def _updateJobUser(self, user):
with self._selectedFileMutex:
if self._selectedFile is not None and self._selectedFile.get("user", None) != user:
self._selectedFile["user"] = user
job_data = self.get_current_job()
self._stateMonitor.set_job_data(self._dict(file=job_data["file"],
estimatedPrintTime=job_data["estimatedPrintTime"],
averagePrintTime=job_data["averagePrintTime"],
lastPrintTIme=job_data["lastPrintTime"],
filament=job_data["filament"],
user=user))
def _sendInitialStateUpdate(self, callback):
try:
data = self._stateMonitor.get_current_data()
@@ -1053,10 +1120,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
def on_comm_file_selected(self, full_path, size, sd, user=None):
if full_path is not None:
payload = self._payload_for_print_job_event(location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
print_job_file=full_path)
print_job_file=full_path,
print_job_user=user,
action_user=user)
eventManager().fire(Events.FILE_SELECTED, payload)
self._logger_job.info("Print job selected - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
else:
eventManager().fire(Events.FILE_DESELECTED)
self._logger_job.info("Print job deselected - user: {}".format(user if user else "n/a"))
self._setJobData(full_path, size, sd, user=user)
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
@@ -1067,11 +1141,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printAfterSelect = False
self.start_print(pos=self._posAfterSelect, user=user)
def on_comm_print_job_started(self, suppress_script=False):
def on_comm_print_job_started(self, suppress_script=False, user=None):
self._updateJobUser(user) # the final job owner should always be whoever _started_ the job
self._stateMonitor.trigger_progress_update()
payload = self._payload_for_print_job_event()
payload = self._payload_for_print_job_event(print_job_user=user,
action_user=user)
if payload:
eventManager().fire(Events.PRINT_STARTED, payload)
self._logger_job.info("Print job started - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
if not suppress_script:
self.script("beforePrintStarted",
context=dict(event=payload),
@@ -1091,6 +1172,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
eventManager().fire(Events.PRINT_DONE, payload)
self._logger_job.info("Print job done - origin: {}, path: {}, owner: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner")))
if not suppress_script:
self.script("afterPrintDone",
context=dict(event=payload),
@@ -1114,29 +1199,36 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
def on_comm_print_job_cancelling(self, firmware_error=None):
payload = self._payload_for_print_job_event()
def on_comm_print_job_cancelling(self, firmware_error=None, user=None):
payload = self._payload_for_print_job_event(action_user=user)
if payload:
if firmware_error:
payload["firmwareError"] = firmware_error
eventManager().fire(Events.PRINT_CANCELLING, payload)
def on_comm_print_job_cancelled(self, suppress_script=False):
def on_comm_print_job_cancelled(self, suppress_script=False, user=None):
self._setCurrentZ(None)
self._updateProgressData()
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None)
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None,
action_user=user)
if payload:
payload["time"] = self._comm.getPrintTime()
payload["reason"] = "cancelled"
eventManager().fire(Events.PRINT_CANCELLED, payload)
self._logger_job.info("Print job cancelled - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
if not suppress_script:
self.script("afterPrintCancelled",
context=dict(event=payload),
part_of_job=True,
must_be_set=False)
payload["reason"] = "cancelled"
def finalize():
self._fileManager.log_print(payload["origin"],
payload["path"],
@@ -1150,52 +1242,69 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
thread.daemon = True
thread.start()
def on_comm_print_job_paused(self, suppress_script=False):
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
def on_comm_print_job_paused(self, suppress_script=False, user=None):
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None,
action_user=user)
if payload:
eventManager().fire(Events.PRINT_PAUSED, payload)
self._logger_job.info("Print job paused - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
if not suppress_script:
self.script("afterPrintPaused",
context=dict(event=payload),
part_of_job=True,
must_be_set=False)
def on_comm_print_job_resumed(self, suppress_script=False):
payload = self._payload_for_print_job_event()
def on_comm_print_job_resumed(self, suppress_script=False, user=None):
payload = self._payload_for_print_job_event(action_user=user)
if payload:
eventManager().fire(Events.PRINT_RESUMED, payload)
self._logger_job.info("Print job resumed - origin: {}, path: {}, owner: {}, user: {}".format(payload.get("origin"),
payload.get("path"),
payload.get("owner"),
payload.get("user")))
if not suppress_script:
self.script("beforePrintResumed",
context=dict(event=payload),
part_of_job=True,
must_be_set=False)
def on_comm_file_transfer_started(self, filename, filesize, user=None):
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))
self._sdStreaming = True
self._setJobData(filename, filesize, True, user=user)
self._setJobData(remote_filename, filesize, True, user=user)
self._updateProgressData(completion=0.0, filepos=0, printTime=0)
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
def on_comm_file_transfer_done(self, filename, failed=False):
def on_comm_file_transfer_done(self, local_filename, remote_filename, elapsed, failed=False):
self._sdStreaming = False
# in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for
# both parameters
payload = dict(local=local_filename,
remote=remote_filename,
time=elapsed)
if failed:
if self._streamingFailedCallback is not None:
self._streamingFailedCallback(filename, filename, FileDestinations.SDCARD)
eventManager().fire(Events.TRANSFER_FAILED, payload)
if callable(self._streamingFailedCallback):
self._streamingFailedCallback(remote_filename, remote_filename, FileDestinations.SDCARD)
else:
if self._streamingFinishedCallback is not None:
self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD)
eventManager().fire(Events.TRANSFER_DONE, payload)
if callable(self._streamingFinishedCallback):
self._streamingFinishedCallback(remote_filename, remote_filename, FileDestinations.SDCARD)
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._updateProgressData()
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
def on_comm_file_transfer_failed(self, filename):
self.on_comm_file_transfer_done(filename, failed=True)
def on_comm_file_transfer_failed(self, local_filename, remote_filename, elapsed):
self.on_comm_file_transfer_done(local_filename, remote_filename, elapsed, failed=True)
def on_comm_force_disconnect(self):
self.disconnect()
@@ -1208,7 +1317,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
except:
self._logger.exception("Error while trying to persist print recovery data")
def _payload_for_print_job_event(self, location=None, print_job_file=None, print_job_size=None, position=None):
def _payload_for_print_job_event(self, location=None, print_job_file=None, print_job_size=None, print_job_user=None,
position=None, action_user=None):
if print_job_file is None:
with self._selectedFileMutex:
selected_file = self._selectedFile
@@ -1217,6 +1327,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
print_job_file = selected_file.get("filename", None)
print_job_size = selected_file.get("filesize", None)
print_job_user = selected_file.get("user", None)
location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL
if not print_job_file or not location:
@@ -1247,6 +1358,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if position is not None:
result["position"] = position
if print_job_user is not None:
result["owner"] = print_job_user
if action_user is not None:
result["user"] = action_user
return result
+12
View File
@@ -510,6 +510,17 @@ class Server(object):
implementation.on_settings_initialized()
custom_events_hooks = pluginManager.get_hooks("octoprint.events.register_custom_events")
for name, hook in custom_events_hooks.items():
try:
result = hook()
if isinstance(result, (list, tuple)):
for event in result:
constant, value = octoprint.events.Events.register_event(event, prefix="plugin_{}_".format(name))
self._logger.debug("Registered event {} of plugin {} as Events.{} = \"{}\"".format(event, name, constant, value))
except:
self._logger.exception("Error while retrieving custom event list from plugin {}".format(name))
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory,
settings_plugin_inject_factory]
pluginManager.initialize_implementations()
@@ -1430,6 +1441,7 @@ class Server(object):
"js/lib/pnotify/pnotify.nonblock.min.js",
"js/lib/pnotify/pnotify.reference.min.js",
"js/lib/pnotify/pnotify.tooltip.min.js",
"js/lib/pnotify/pnotify.maxheight.js",
"js/lib/moment-with-locales.min.js",
"js/lib/pusher.color.min.js",
"js/lib/detectmobilebrowser.js",
+3 -1
View File
@@ -341,7 +341,9 @@ def uploadGcodeFile(target):
"""
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode"):
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint, tags={"source:api", "api:files.sd"})
return filename, printer.add_sd_file(filename, absFilename,
on_success=selectAndOrPrint,
tags={"source:api", "api:files.sd"})
else:
selectAndOrPrint(filename, absFilename, destination)
return filename
+4 -4
View File
@@ -50,11 +50,11 @@ def controlJob():
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
action = data.get("action", "toggle")
if action == "toggle":
printer.toggle_pause_print(tags=tags)
printer.toggle_pause_print(tags=tags, user=user)
elif action == "pause":
printer.pause_print(tags=tags)
printer.pause_print(tags=tags, user=user)
elif action == "resume":
printer.resume_print(tags=tags)
printer.resume_print(tags=tags, user=user)
else:
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
@@ -63,7 +63,7 @@ def controlJob():
if command == "cancel":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
printer.cancel_print(tags=tags)
printer.cancel_print(tags=tags, user=user)
return NO_CONTENT
+4
View File
@@ -100,6 +100,8 @@ def getSettings():
"defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"])
},
"webcam": {
"webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]),
"timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]),
"streamUrl": s.get(["webcam", "stream"]),
"streamRatio": s.get(["webcam", "streamRatio"]),
"streamTimeout": s.getInt(["webcam", "streamTimeout"]),
@@ -389,6 +391,8 @@ def _saveSettings(data):
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
if "webcam" in data.keys():
if "webcamEnabled" in data["webcam"]: s.setBoolean(["webcam", "webcamEnabled"], data["webcam"]["webcamEnabled"])
if "timelapseEnabled" in data["webcam"]: s.setBoolean(["webcam", "timelapseEnabled"], data["webcam"]["timelapseEnabled"])
if "streamUrl" in data["webcam"]: s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
if "streamRatio" in data["webcam"] and data["webcam"]["streamRatio"] in ("16:9", "4:3"): s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"])
if "streamTimeout" in data["webcam"]: s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"])
+1
View File
@@ -113,6 +113,7 @@ def getTimelapseData():
finished_list.append(output)
result = dict(config=config,
enabled=settings().getBoolean(["webcam", "timelapseEnabled"]),
files=finished_list)
if unrendered:
+10
View File
@@ -7,13 +7,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import rsa
from flask import Blueprint, request, make_response, jsonify
import logging
import octoprint.server
import octoprint.plugin
from octoprint.server.util import noCachingResponseHandler, corsResponseHandler
from octoprint.server.util.flask import get_remote_address
from octoprint.settings import settings as s
logger = logging.getLogger(__name__)
apps = Blueprint("apps", __name__)
apps.after_request(noCachingResponseHandler)
@@ -21,11 +25,16 @@ apps.after_request(corsResponseHandler)
@apps.route("/auth", methods=["GET"])
def getSessionKey():
logger.warn("Client {} accessed the apps API which has been deprecated since 1.3.11 and will be removed in "
"1.4.0. Clients should use the Application Keys Plugin workflow instead".format(get_remote_address(request)))
unverified_key, valid_until = octoprint.server.appSessionManager.create()
return jsonify(unverifiedKey=unverified_key, validUntil=valid_until)
@apps.route("/auth", methods=["POST"])
def verifySessionKey():
logger.warn("Client {} accessed the apps API which has been deprecated since 1.3.11 and will be removed in "
"1.4.0. Clients should use the Application Keys Plugin workflow instead".format(get_remote_address(request)))
if not "application/json" in request.headers["Content-Type"]:
return None, None, make_response("Expected content-type JSON", 400)
@@ -98,6 +107,7 @@ def _get_registered_apps():
for name, hook in hooks.items():
try:
additional_apps = hook()
logger.warn("Plugin {} is still implementing the appkey hook that is deprecated since 1.3.11 and will be removed in 1.4.0. Switch it over to the Application Keys Plugin workflow.".format(name))
except:
import logging
logging.getLogger(__name__).exception("Error while retrieving additional appkeys from plugin {name}".format(**locals()))
+30 -17
View File
@@ -59,33 +59,46 @@ def loginFromApiKeyRequestHandler():
UI_API_KEY and app session keys are handled as anonymous keys here and ignored.
"""
apikey = get_api_key(_flask.request)
if not apikey:
return
if apikey == octoprint.server.UI_API_KEY:
return
if octoprint.server.appSessionManager.validate(apikey):
return
user = get_user_for_apikey(apikey)
if not loginUser(user):
try:
if loginUserFromApiKey():
_flask.g.login_via_apikey = True
except InvalidApiKeyException:
return _flask.make_response("Invalid API key", 403)
_flask.g.login_via_apikey = True
def loginFromAuthorizationHeaderRequestHandler():
"""
``before_request`` handler for creating login sessions based on the Authorization header.
"""
loginUserFromApiKey()
class InvalidApiKeyException(Exception): pass
def loginUserFromApiKey():
apikey = get_api_key(_flask.request)
if not apikey:
return False
if apikey == octoprint.server.UI_API_KEY:
return False
if octoprint.server.appSessionManager.validate(apikey):
return False
user = get_user_for_apikey(apikey)
if not loginUser(user):
raise InvalidApiKeyException()
else:
return True
def loginUserFromAuthorizationHeader():
authorization_header = get_authorization_header(_flask.request)
user = get_user_for_authorization_header(authorization_header)
loginUser(user)
return loginUser(user)
def loginUser(user, remember=False):
+56 -32
View File
@@ -538,54 +538,78 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
#~~ passive login helper
def passive_login():
user = flask_login.current_user
_cached_local_networks = None
def _local_networks():
global _cached_local_networks
remoteAddr = get_remote_address(flask.request)
ipCheckEnabled = settings().getBoolean(["server", "ipCheck", "enabled"])
ipCheckTrusted = settings().get(["server", "ipCheck", "trustedSubnets"])
if _cached_local_networks is None:
logger = logging.getLogger(__name__)
local_networks = netaddr.IPSet([])
for entry in settings().get(["accessControl", "localNetworks"]):
network = netaddr.IPNetwork(entry)
local_networks.add(network)
logger.debug("Added network {} to localNetworks".format(network))
if network.version == 4:
network_v6 = network.ipv6()
local_networks.add(network_v6)
logger.debug("Also added v6 representation of v4 network {} = {} to localNetworks".format(network, network_v6))
_cached_local_networks = local_networks
return _cached_local_networks
def passive_login():
logger = logging.getLogger(__name__)
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.login_user(flask_login.current_user)
else:
user = flask_login.current_user
remote_address = get_remote_address(flask.request)
ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"])
ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"])
if isinstance(user, LocalProxy):
# noinspection PyProtectedMember
user = user._get_current_object()
def login(u):
# login known user
if not u.is_anonymous:
u = octoprint.server.userManager.login_user(u)
flask_login.login_user(u)
flask_principal.identity_changed.send(flask.current_app._get_current_object(),
identity=flask_principal.Identity(u.get_id()))
if hasattr(u, "session"):
flask.session["usersession.id"] = u.session
flask.g.user = u
return u
logger.info("Passively logging in user {} from {}".format(user.get_id(), remote_address))
if user is not None and user.is_active:
# login known user
logging.getLogger(__name__).info("Passively logging in user {} from {}".format(user.get_id(), remoteAddr))
user = login(user)
response = user.asDict()
response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address,
additional_private=ip_check_trusted)
return flask.jsonify(response)
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
and settings().get(["accessControl", "autologinAs"]) is not None \
and settings().get(["accessControl", "localNetworks"]) is not None:
autologinAs = settings().get(["accessControl", "autologinAs"])
localNetworks = netaddr.IPSet([])
for ip in settings().get(["accessControl", "localNetworks"]):
localNetworks.add(ip)
autologin_as = settings().get(["accessControl", "autologinAs"])
local_networks = _local_networks()
logger.debug("Checking if remote address {} is in localNetworks ({!r})".format(remote_address, local_networks))
try:
if netaddr.IPAddress(remoteAddr) in localNetworks:
autologin_user = octoprint.server.userManager.find_user(autologinAs)
if autologin_user is not None and user.is_active:
autologin_user = octoprint.server.userManager.login_user(autologin_user)
if netaddr.IPAddress(remote_address) in local_networks:
user = octoprint.server.userManager.findUser(autologin_as)
if user is not None and user.is_active():
user = octoprint.server.userManager.login_user(user)
flask.session["usersession.id"] = user.session
flask.g.user = user
flask_login.login_user(user)
flask_principal.identity_changed.send(flask.current_app._get_current_object(),
identity=flask_principal.Identity(user.get_id()))
logging.getLogger(__name__).info("Passively logging in user {} from {} via autologin".format(user.get_id(), remoteAddr))
user = login(autologin_user)
logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(),
remote_address))
response = user.asDict()
response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address,
additional_private=ip_check_trusted)
return flask.jsonify(response)
except:
logger = logging.getLogger(__name__)
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
logger.exception("Could not autologin user {} for networks {}".format(autologin_as, localNetworks))
response = user.as_dict()
response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr,
+2 -2
View File
@@ -180,7 +180,7 @@ def index():
enable_accesscontrol = userManager.enabled
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
enable_timelapse = bool(settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"])
def default_template_filter(template_type, template_key):
if template_type == "navbar":
@@ -355,7 +355,7 @@ def index():
_plugin_vars,
now)
render_kwargs.update(dict(
webcamStream=settings().get(["webcam", "stream"]),
enableWebcam=settings().getBoolean(["webcam", "enableWebcam"]) and bool(settings().get(["webcam", "stream"])),
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
enableAccessControl=enable_accesscontrol,
accessControlActive=accesscontrol_active,
+3
View File
@@ -130,6 +130,7 @@ default_settings = {
"unknownCommandsNeedAck": False,
"sdRelativePath": False,
"sdAlwaysAvailable": False,
"maxNotSdPrinting": 2,
"swallowOkAfterResend": True,
"repetierTargetTemp": False,
"externalHeatupDetection": True,
@@ -209,6 +210,8 @@ default_settings = {
}
},
"webcam": {
"webcamEnabled": True,
"timelapseEnabled": True,
"stream": None,
"streamRatio": "16:9",
"streamTimeout": 5,
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
+14 -2
View File
@@ -195,7 +195,8 @@ $(function() {
moment.locale(LOCALE);
// Dummy translation requests for dynamic strings supplied by the backend
var dummyTranslations = [
// noinspection BadExpressionStatementJS
[
// printer states
gettext("Offline"),
gettext("Opening serial port"),
@@ -203,12 +204,18 @@ $(function() {
gettext("Detecting baudrate"),
gettext("Connecting"),
gettext("Operational"),
gettext("Starting"),
gettext("Starting print from SD"),
gettext("Printing from SD"),
gettext("Sending file to SD"),
gettext("Printing"),
gettext("Paused"),
gettext("Closed"),
gettext("Transferring file to SD")
gettext("Transferring file to SD"),
gettext("Pausing"),
gettext("Resuming"),
gettext("Cancelling"),
gettext("Finishing")
];
//~~ Initialize PNotify
@@ -222,6 +229,11 @@ $(function() {
PNotify.prototype.options.delay = 5000;
PNotify.prototype.options.animate_speed = "fast";
PNotify.prototype.options.maxheight.maxheight = function() {
return $(window).height() - 170; // top margin + header + footer + some safety margin
};
// single button notify
PNotify.singleButtonNotify = function(options) {
if (!options.confirm || !options.confirm.buttons || !options.confirm.buttons.length) {
return new PNotify(options);
@@ -762,6 +762,10 @@ $(function() {
}
};
self.clearSearchQuery = function() {
self.searchQuery("");
};
self.performSearch = function(e) {
var query = self.searchQuery();
if (query !== undefined && query.trim() !== "") {
@@ -122,6 +122,8 @@ $(function() {
self.printer_defaultExtrusionLength = ko.observable(undefined);
self.webcam_webcamEnabled = ko.observable(undefined);
self.webcam_timelapseEnabled = ko.observable(undefined);
self.webcam_streamUrl = ko.observable(undefined);
self.webcam_streamRatio = ko.observable(undefined);
self.webcam_streamTimeout = ko.observable(undefined);
@@ -4,6 +4,7 @@ $(function() {
self.loginState = parameters[0];
self.access = parameters[1];
self.settings = parameters[1];
self.renderProgressBar = undefined;
self.timelapsePopup = undefined;
@@ -580,7 +581,7 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: TimelapseViewModel,
dependencies: ["loginStateViewModel", "accessViewModel"],
dependencies: ["loginStateViewModel", "accessViewModel", "settingsViewModel"],
elements: ["#timelapse", "#timelapse_link"]
});
});
@@ -0,0 +1,54 @@
// Maxheight
(function (factory) {
if (typeof exports === 'object' && typeof module !== 'undefined') {
// CommonJS
module.exports = factory(require('jquery'), require('pnotify'));
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as a module.
define('pnotify.confirm', ['jquery', 'pnotify'], factory);
} else {
// Browser globals
factory(jQuery, PNotify);
}
}(function($, PNotify){
PNotify.prototype.options.maxheight = {
// Maximum height of text area to enforce
maxheight: false
};
var _position = PNotify.prototype.position;
PNotify.prototype.position = function(){
if (typeof this.options.maxheight.maxheight === "function") {
setMaxHeight(this, this.options.maxheight);
}
_position.apply(this, arguments);
};
var setMaxHeight = function(notice, options) {
if (!options.maxheight) return;
var option = options.maxheight;
if (typeof option === "function") {
option = option();
}
var height;
if (typeof option === "number") {
// assuming pixels
height = "" + option + "px";
} else if (typeof option === "string") {
// assuming css string
height = option
} else {
// unknown, ignore
return;
}
notice.text_container.css("max-height", height);
notice.text_container.css("overflow", "auto");
};
PNotify.prototype.modules.maxheight = {
init: setMaxHeight,
update: setMaxHeight
};
}));
+40
View File
@@ -1456,6 +1456,46 @@ input[type="number"].input-nospin {
}
}
// search boxes with clear button
.search-query-with-clear {
position: relative;
.search-clear {
display: inline-block;
color: #ccc;
position: absolute;
right: 28px;
height: 20px;
padding: 4px 0;
cursor: pointer;
visibility: hidden;
}
&.active-clear {
.search-query {
padding-right: 28px;
width: 192px;
}
.search-clear {
visibility: visible;
}
}
input::-ms-clear {
display: none;
}
input[type="search"]::-webkit-search-decoration,
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-results-button,
input[type="search"]::-webkit-search-results-decoration {
-webkit-appearance:none;
}
}
// Navbar loginForm
// Make the overlay always visible so that extensions are able to auto-submit (i.e. password-managers)
#navbar_login:not(.open) #login_dropdown_loggedout {
@@ -374,11 +374,12 @@
<input type="radio" name="errorHandlingGroup" value="disconnect" data-bind="checked: serial_serialErrorBehaviour" id="settings-serialErrorBehaviourDisconnect"> {{ _('Disconnect from the printer') }}
</label>
<label class="radio">
<input type="radio" name="errorHandlingGroup" value="cancel" data-bind="checked: serial_serialErrorBehaviour" id="settings-serialErrorBehaviourCancel"> {{ _('Cancel any ongoing prints but stay connected to the printer') }}
<input type="radio" name="errorHandlingGroup" value="cancel" data-bind="checked: serial_serialErrorBehaviour" id="settings-serialErrorBehaviourCancel"> {{ _('Cancel any ongoing prints but stay connected to the printer') }} <span></span>
<span class="help-block">{{ _('Please note that if you choose this, OctoPrint will still disconnect from the printer in case of <em>fatal</em> errors reported by your firmware (e.g. <code>kill() called</code>, <code>fatal:</code>).') }}</span>
</label>
<label class="radio">
<input type="radio" name="errorHandlingGroup" value="ignore" data-bind="checked: serial_serialErrorBehaviour" id="settings-serialErrorBehaviourIgnore"> {{ _('Ignore') }} <span class="label label-important">{{ _('Warning') }}</span>
<span class="help-block">{{ _('Only choose this if your firmware sends error messages that are not actual errors. Might mask printer issues, be careful!') }}</span>
<span class="help-block">{{ _('Only choose this if your firmware sends error messages that are not actual errors. Might mask printer issues (even fatal errors!), be careful!') }}</span>
</label>
</div>
</div>
@@ -1,6 +1,7 @@
<h3>{{ _('Webcam') }}</h3>
<form class="form-horizontal">
{% include "snippets/settings/webcam/webcamEnabled.jinja2" %}
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamStreamRatio.jinja2" %}
{% include "snippets/settings/webcam/webcamOrientation.jinja2" %}
@@ -16,6 +17,7 @@
<h3>{{ _('Timelapse Recordings') }}</h3>
<form class="form-horizontal">
{% include "snippets/settings/webcam/timelapseEnabled.jinja2" %}
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
{% include "snippets/settings/webcam/watermark.jinja2" %}
+2 -2
View File
@@ -142,14 +142,14 @@
{% include 'overlays/reloadui.jinja2' %}
<!-- End of overlays -->
{% include 'javascripts.jinja2' %}
<!-- Generic plugin template files -->
{% for key in templates.generic.order %}
{% set data = templates.generic.entries[key] %}
{% try "<!-- There was an error with the template {filename} at line number {lineno}: {exception} -->" %}{% include data.template ignore missing %}{% endtry %}
{% endfor %}
<!-- End of generic plugin template files -->
<!-- /ko -->
</div>
<div id="page-container-loading" data-bind="visible: loading">
+4 -1
View File
@@ -1,5 +1,8 @@
<form class="form-search" data-bind="submit: performSearch">
<input type="text" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
<div class="search-query-with-clear" data-bind="css: {'active-clear': searchQuery}">
<input type="search" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
<span class="search-clear" data-bind="click: clearSearchQuery"><i class="fa fa-remove"></i></span>
</div>
</form>
<div class="gcode_files">
<div class="entry back clickable" data-bind="visible: currentPath() != '', click: function() { $root.navigateUp(); }" style="display: none">
@@ -4,7 +4,9 @@
<!-- ko if: userString -->
<span title="{{ _('User who selected this file for printing') }}">{{ _('User') }}</span>: <strong data-bind="text: userString"></strong><br>
<!-- /ko -->
<!-- ko if: settings.webcam_timelapseEnabled -->
<span title="{{ _('Current timelapse configuration') }}">{{ _('Timelapse') }}</span>: <strong data-bind="text: timelapseString"></strong><br>
<!-- /ko -->
<!-- ko foreach: filament -->
<span data-bind="text: 'Filament (' + name() + '): ', title: 'Filament usage for ' + name()"></span><strong data-bind="text: formatFilament(data())"></strong><br>
<!-- /ko -->
@@ -0,0 +1,7 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_timelapseEnabled" id="settings-webcamTimelapseEnabled"> {{ _('Enable timelapse support') }}
</label>
</div>
</div>
@@ -0,0 +1,7 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_webcamEnabled" id="settings-webcamWebcamEnabled"> {{ _('Enable webcam support') }}
</label>
</div>
</div>
+3 -3
View File
@@ -1,5 +1,5 @@
{% if webcamStream %}
<div id="webcam_container" tabindex="0" data-bind="visible: loginState.hasPermissionKo(access.permissions.WEBCAM), event: { keydown: onKeyDown, mouseover: onMouseOver, mouseout: onMouseOut, focus: onFocus }">
{% if enableWebcam %}
<div id="webcam_container" tabindex="0" data-bind="event: { keydown: onKeyDown, mouseover: onMouseOver, mouseout: onMouseOut, focus: onFocus }">
<div class="nowebcam" data-bind="visible: !webcamLoaded()">
<div class="text webcam_loading" data-bind="visible: !webcamLoaded() && !webcamError()">
<p><strong>{{ _('Webcam stream loading...') }}</strong></p>
@@ -7,7 +7,7 @@
<div class="text webcam_error" data-bind="visible: !webcamLoaded() && webcamError()">
<p><strong>{{ _('Webcam stream not loaded') }}</strong></p>
<p data-bind="visible: !loginState.isAdmin()"><small>{{ _('It might not be configured correctly or require authentication. To have this fixed, get in touch with an administrator of this OctoPrint instance.') }}</small></p>
<p data-bind="visible: loginState.isAdmin"><small>{{ _('It might not be configured correctly or require authentication. You can change the URL of the stream under "Settings" > "Webcam & Timelapse" > "Stream URL". If you don\'t have a webcam just set the URL to an empty value.') }}</small></p>
<p data-bind="visible: loginState.isAdmin"><small>{{ _('It might not be configured correctly or require authentication. You can change the URL of the stream under "Settings" > "Webcam & Timelapse" > "Webcam" > "Stream URL". If you don\'t have a webcam you can also just disable webcam support there.') }}</small></p>
<p data-bind="visible: loginState.isUser"><small>{{ _('Currently configured stream URL') }}: <a target="_blank" rel="noreferrer" data-bind="attr: {href: settings.webcam_streamUrl}, text: settings.webcam_streamUrl"></a></small></p>
</div>
</div>
+100 -89
View File
@@ -1,93 +1,104 @@
<div data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_ADMIN)">
<div class="alert" data-bind="visible: isPrinting()">
{{ _('Take note that timelapse configuration is disabled while your printer is printing.') }}
<div style="display: none;" data-bind="visible: loginState.isUser">
<div style="display: none;" data-bind="visible: settings.webcam_snapshotUrl() && settings.webcam_ffmpegPath()">
<div class="alert" data-bind="visible: isPrinting()">
{{ _('Take note that timelapse configuration is disabled while your printer is printing.') }}
</div>
<h1>{{ _('Timelapse Configuration') }}</h1>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
<div class="controls">
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: !isPrinting() && loginState.isUser()">
<option value="off">{{ _('Off') }}</option>
<option value="timed">{{ _('Timed') }}</option>
<option value="zchange">{{ _('On Z Change') }}</option>
</select>
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-info">{{ _('Note') }}</span> {% trans %}Does not work when printing from the printer's SD Card (no way to detect the change in Z reliably). Use "Timed" mode for those prints instead.{% endtrans %}</span>
</div>
</div>
<div id="webcam_timelapse_mindelay" class="control-group" data-bind="visible: timelapseType() == 'zchange'">
<label class="control-label" for="webcam_timelapse_minDelay">{{ _('Minimum interval') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_minDelay" data-bind="value: timelapseMinDelay, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser()">
<span class="add-on">{{ _('sec') }}</span>
</div>
<span class="help-block">{{ _('OctoPrint will rate limit snapshots to this minimum interval. This it to prevent against performance issues with vase mode/continous z prints.') }}</span>
</div>
</div>
<div id="webcam_timelapse_timedsettings" class="control-group" data-bind="visible: intervalInputEnabled">
<label class="control-label" for="webcam_timelapse_interval">{{ _('Snapshot interval') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser()">
<span class="add-on">{{ _('sec') }}</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="webcam_timelapse_fps">{{ _('Timelapse frame rate') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_fps" data-bind="value: timelapseFps, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
<span class="add-on">{{ _('fps') }}</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="webcam_timelapse_postRoll">{{ _('Timelapse post roll') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="0" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
<span class="add-on">{{ _('sec') }}</span>
</div>
<span class="help-block">{{ _('OctoPrint will use the final picture to add this many seconds to the end of your rendered timelapse.') }}</span>
</div>
</div>
<div id="webcam_timelapse_retractionsettings" class="control-group" data-bind="visible: timelapseType() == 'zchange'">
<label class="control-label" for="webcam_timelapse_retractionZHop">{{ _('Retraction Z-Hop') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="0.0" class="input-mini" id="webcam_timelapse_retractionZHop" data-bind="value: timelapseRetractionZHop, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser()">
<span class="add-on">{{ _('mm') }}</span>
</div>
<span class="help-block">{{ _('Enter the retraction z-hop used in the firmware or the gcode file to trigger snapshots for the timelapse only if a real layer change happens. For this to work properly your retraction z-hop has to be different from your layerheight!') }}</span>
</div>
</div>
<div class="control-group" data-bind="visible: loginState.isAdmin">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: persist, enable: isOperational() && !isPrinting() && loginState.isUser()"> {{ _('Save as default') }}
<span class="help-block">{{ _('Check this to make your selected timelapse mode and options persist across restarts.') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<strong class="text-center text-block" data-bind="visible: saveButtonEnabled">{{ _('You have unsaved changes. Don\'t forget to save them.') }}</strong>
<button class="btn btn-primary btn-block" data-bind="click: save, enable: saveButtonEnabled">{{ _('Save changes') }}</button>
<button class="btn btn-block" data-bind="click: reset, enable: resetButtonEnabled">{{ _('Reset to active configuration') }}</button>
</div>
</div>
</form>
</div>
<div class="alert" style="display: none" data-bind="visible: !settings.webcam_snapshotUrl() || !settings.webcam_ffmpegPath()">
<p><strong>{{ _('Timelapse not fully configured') }}</strong></p>
<p data-bind="visible: !loginState.isAdmin()">{{ _('The snapshot URL and/or the path to FFMPEG are missing. To have this fixed, get in touch with an administrator of this OctoPrint instance.') }}</p>
<p data-bind="visible: loginState.isAdmin">{{ _('The snapshot URL and/or the path to FFMPEG are missing. You can change both under "Settings" > "Webcam & Timelapse" > "Timelapse". If you don\'t have a webcam or don\'t want to enable timelapse support you can also just disable it there.') }}</p>
<p data-bind="visible: loginState.isUser"><small>
{{ _('Currently configured snapshot URL') }}: <span data-bind="text: settings.webcam_snapshotUrl"></span><br/>
{{ _('Currently configured path to FFMPEG') }}: <span data-bind="text: settings.webcam_ffmpegPath"></span>
</small></p>
</div>
<h1>{{ _('Timelapse Configuration') }}</h1>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
<div class="controls">
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: !isPrinting()">
<option value="off">{{ _('Off') }}</option>
<option value="timed">{{ _('Timed') }}</option>
<option value="zchange">{{ _('On Z Change') }}</option>
</select>
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-info">{{ _('Note') }}</span> {% trans %}Does not work when printing from the printer's SD Card (no way to detect the change in Z reliably). Use "Timed" mode for those prints instead.{% endtrans %}</span>
</div>
</div>
<div id="webcam_timelapse_mindelay" class="control-group" data-bind="visible: timelapseType() == 'zchange'">
<label class="control-label" for="webcam_timelapse_minDelay">{{ _('Minimum interval') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_minDelay" data-bind="value: timelapseMinDelay, valueUpdate: 'afterkeydown', enable: !isPrinting()">
<span class="add-on">{{ _('sec') }}</span>
</div>
<span class="help-block">{{ _('OctoPrint will rate limit snapshots to this minimum interval. This it to prevent against performance issues with vase mode/continous z prints.') }}</span>
</div>
</div>
<div id="webcam_timelapse_timedsettings" class="control-group" data-bind="visible: intervalInputEnabled">
<label class="control-label" for="webcam_timelapse_interval">{{ _('Snapshot interval') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: !isPrinting()">
<span class="add-on">{{ _('sec') }}</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="webcam_timelapse_fps">{{ _('Timelapse frame rate') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini" id="webcam_timelapse_fps" data-bind="value: timelapseFps, valueUpdate: 'afterkeydown', enable: !isPrinting() && timelapseTypeSelected()">
<span class="add-on">{{ _('fps') }}</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="webcam_timelapse_postRoll">{{ _('Timelapse post roll') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="0" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: !isPrinting() && timelapseTypeSelected()">
<span class="add-on">{{ _('sec') }}</span>
</div>
<span class="help-block">{{ _('OctoPrint will use the final picture to add this many seconds to the end of your rendered timelapse.') }}</span>
</div>
</div>
<div id="webcam_timelapse_retractionsettings" class="control-group" data-bind="visible: timelapseType() == 'zchange'">
<label class="control-label" for="webcam_timelapse_retractionZHop">{{ _('Retraction Z-Hop') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="0.0" class="input-mini" id="webcam_timelapse_retractionZHop" data-bind="value: timelapseRetractionZHop, valueUpdate: 'afterkeydown', enable: !isPrinting()">
<span class="add-on">{{ _('mm') }}</span>
</div>
<span class="help-block">{{ _('Enter the retraction z-hop used in the firmware or the gcode file to trigger snapshots for the timelapse only if a real layer change happens. For this to work properly your retraction z-hop has to be different from your layerheight!') }}</span>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: persist, enable: isOperational() && !isPrinting()"> {{ _('Save as default') }}
<span class="help-block">{{ _('Check this to make your selected timelapse mode and options persist across restarts.') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<strong class="text-center text-block" data-bind="visible: saveButtonEnabled">{{ _('You have unsaved changes. Don\'t forget to save them.') }}</strong>
<button class="btn btn-primary btn-block" data-bind="click: save, enable: saveButtonEnabled">{{ _('Save changes') }}</button>
<button class="btn btn-block" data-bind="click: reset, enable: resetButtonEnabled">{{ _('Reset to active configuration') }}</button>
</div>
</div>
</form>
</div>
<h1 data-bind="visible: renderProgressBarString">{{ _('Timelapse Render Progress') }}</h1>
+4 -12
View File
@@ -338,24 +338,16 @@ def configure_timelapse(config=None, persist=False):
snapshot_url = settings().get(["webcam", "snapshot"])
ffmpeg_path = settings().get(["webcam", "ffmpeg"])
timelapse_enabled = settings().getBoolean(["webcam", "timelapseEnabled"])
timelapse_precondition = snapshot_url is not None and snapshot_url.strip() != "" \
and ffmpeg_path is not None and ffmpeg_path.strip() != ""
type = config["type"]
if not timelapse_precondition and type is not None and type != "off":
if not timelapse_precondition and timelapse_precondition:
logging.getLogger(__name__).warn("Essential timelapse settings unconfigured (snapshot URL or FFMPEG path) "
"but timelapse enabled, forcing disabled timelapse and disabling it "
"in the config as well.")
type = "off"
config["type"] = "off"
"but timelapse enabled.")
if not persist:
# make sure we persist at least that timelapse is now disabled by default - we don't want the above
# warning to log
settings().set(["webcam", "timelapse", "type"], "off")
settings().save()
if type is None or "off" == type:
if not timelapse_enabled or not timelapse_precondition or type is None or "off" == type:
current = None
else:
+145 -70
View File
@@ -338,23 +338,24 @@ class MachineCom(object):
STATE_DETECT_BAUDRATE = 3
STATE_CONNECTING = 4
STATE_OPERATIONAL = 5
STATE_PRINTING = 6
STATE_PAUSED = 7
STATE_CLOSED = 8
STATE_ERROR = 9
STATE_CLOSED_WITH_ERROR = 10
STATE_TRANSFERING_FILE = 11
STATE_CANCELLING = 12
STATE_PAUSING = 13
STATE_RESUMING = 14
STATE_FINISHING = 15
STATE_STARTING = 6
STATE_PRINTING = 7
STATE_PAUSED = 8
STATE_PAUSING = 9
STATE_RESUMING = 10
STATE_FINISHING = 11
STATE_CLOSED = 12
STATE_ERROR = 13
STATE_CLOSED_WITH_ERROR = 14
STATE_TRANSFERING_FILE = 15
STATE_CANCELLING = 16
# be sure to add anything here that signifies an operational state
OPERATIONAL_STATES = (STATE_PRINTING, STATE_OPERATIONAL, STATE_PAUSED, STATE_CANCELLING, STATE_PAUSING,
STATE_RESUMING, STATE_FINISHING, STATE_TRANSFERING_FILE)
OPERATIONAL_STATES = (STATE_PRINTING, STATE_STARTING, STATE_OPERATIONAL, STATE_PAUSED, STATE_CANCELLING,
STATE_PAUSING, STATE_RESUMING, STATE_FINISHING, STATE_TRANSFERING_FILE)
# be sure to add anything here that signifies a printing state
PRINTING_STATES = (STATE_PRINTING, STATE_CANCELLING, STATE_PAUSING, STATE_RESUMING, STATE_FINISHING)
PRINTING_STATES = (STATE_STARTING, STATE_PRINTING, STATE_CANCELLING, STATE_PAUSING, STATE_RESUMING, STATE_FINISHING)
CAPABILITY_AUTOREPORT_TEMP = "AUTOREPORT_TEMP"
CAPABILITY_AUTOREPORT_SD_STATUS = "AUTOREPORT_SD_STATUS"
@@ -492,6 +493,9 @@ class MachineCom(object):
self._temperature_timer = None
self._sd_status_timer = None
self._consecutive_not_sd_printing = 0
self._consecutive_not_sd_printing_maximum = settings().getInt(["serial", "maxNotSdPrinting"])
self._job_queue = JobQueue()
# hooks
@@ -544,6 +548,9 @@ class MachineCom(object):
self._suppress_scripts = set()
self._suppress_scripts_mutex = threading.RLock()
self._action_users = dict()
self._action_users_mutex = threading.RLock()
self._pause_position_timer = None
self._pause_mutex = threading.RLock()
self._cancel_position_timer = None
@@ -655,6 +662,13 @@ class MachineCom(object):
return "Connecting"
elif state == self.STATE_OPERATIONAL:
return "Operational"
elif state == self.STATE_STARTING:
if self.isSdFileSelected():
return "Starting print from SD"
elif self.isStreaming():
return "Sending file to SD"
else:
return "Printing"
elif state == self.STATE_PRINTING:
if self.isSdFileSelected():
return "Printing from SD"
@@ -706,6 +720,9 @@ class MachineCom(object):
def isResuming(self):
return self._state == self.STATE_RESUMING
def isStarting(self):
return self._state == self.STATE_STARTING
def isFinishing(self):
return self._state == self.STATE_FINISHING
@@ -1003,7 +1020,7 @@ class MachineCom(object):
self.sendCommand(line, part_of_job=part_of_job, tags=tags_to_use)
return "\n".join(scriptLines)
def startPrint(self, pos=None, tags=None, external_sd=False):
def startPrint(self, pos=None, tags=None, external_sd=False, user=None):
if not self.isOperational() or self.isPrinting():
return
@@ -1020,14 +1037,15 @@ class MachineCom(object):
try:
with self._jobLock:
self._currentFile.start()
self._consecutive_not_sd_printing = 0
self._changeState(self.STATE_PRINTING)
self._currentFile.start()
self._changeState(self.STATE_STARTING)
if not self.isSdFileSelected():
self.resetLineNumbers(part_of_job=True, tags={"trigger:comm.start_print"})
self._callback.on_comm_print_job_started()
self._callback.on_comm_print_job_started(user=user)
if self.isSdFileSelected():
if not external_sd:
@@ -1052,13 +1070,15 @@ class MachineCom(object):
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.seek(pos)
self.sendCommand(SendQueueMarker(lambda: self._changeState(self.STATE_PRINTING)), part_of_job=True)
# now make sure we actually do something, up until now we only filled up the queue
self._continue_sending()
except:
self._logger.exception("Error while trying to start printing")
self._trigger_error(get_exception_string(), "start_print")
def startFileTransfer(self, filename, localFilename, remoteFilename, special=False, tags=None):
def startFileTransfer(self, path, localFilename, remoteFilename, special=False, tags=None):
if not self.isOperational() or self.isBusy():
self._logger.info("Printer is not operational or busy")
return
@@ -1070,14 +1090,16 @@ class MachineCom(object):
self.resetLineNumbers(tags={"trigger:comm.start_file_transfer"})
if special:
self._currentFile = SpecialStreamingGcodeFileInformation(filename, localFilename, remoteFilename)
self._currentFile = SpecialStreamingGcodeFileInformation(path, localFilename, remoteFilename)
else:
self._currentFile = StreamingGcodeFileInformation(filename, localFilename, remoteFilename)
self._currentFile = StreamingGcodeFileInformation(path, localFilename, remoteFilename)
self._currentFile.start()
self.sendCommand("M28 %s" % remoteFilename, tags=tags | {"trigger:comm.start_file_transfer",})
eventManager().fire(Events.TRANSFER_STARTED, {"local": localFilename, "remote": remoteFilename})
self._callback.on_comm_file_transfer_started(remoteFilename, self._currentFile.getFilesize(), user=self._currentFile.getUser())
self._callback.on_comm_file_transfer_started(localFilename,
remoteFilename,
self._currentFile.getFilesize(),
user=self._currentFile.getUser())
def cancelFileTransfer(self, tags=None):
if not self.isOperational() or not self.isStreaming():
@@ -1097,22 +1119,17 @@ class MachineCom(object):
if failed:
self.deleteSdFile(remote)
payload = {
"local": self._currentFile.getLocalFilename(),
"remote": remote,
"time": self.getPrintTime()
}
local = self._currentFile.getLocalFilename()
elapsed = self.getPrintTime()
def finalize():
self._currentFile = None
self._changeState(self.STATE_OPERATIONAL)
if failed:
self._callback.on_comm_file_transfer_failed(remote)
eventManager().fire(Events.TRANSFER_FAILED, payload)
self._callback.on_comm_file_transfer_failed(local, remote, elapsed)
else:
self._callback.on_comm_file_transfer_done(remote)
eventManager().fire(Events.TRANSFER_DONE, payload)
self._callback.on_comm_file_transfer_done(local, remote, elapsed)
self.refreshSdFiles(tags={"trigger:comm.finish_file_transfer",})
self._sendCommand(SendQueueMarker(finalize))
@@ -1154,7 +1171,14 @@ class MachineCom(object):
self._log("Did not receive parseable position data from printer within {}s, continuing without it".format(timeout))
self._cancel_preparation_done()
def _cancel_preparation_done(self, check_timer=True):
def _cancel_preparation_done(self, check_timer=True, user=None):
if user is None:
with self._action_users_mutex:
try:
user = self._action_users.pop("cancel")
except KeyError:
pass
with self._cancel_mutex:
if self._cancel_position_timer is not None:
self._cancel_position_timer.cancel()
@@ -1164,14 +1188,14 @@ class MachineCom(object):
self._currentFile.done = True
self._recordFilePosition()
self._callback.on_comm_print_job_cancelled()
self._callback.on_comm_print_job_cancelled(user=user)
def finalize():
self._changeState(self.STATE_OPERATIONAL)
self.sendCommand(SendQueueMarker(finalize), part_of_job=True)
self._continue_sending()
def cancelPrint(self, firmware_error=None, disable_log_position=False, tags=None, external_sd=False):
def cancelPrint(self, firmware_error=None, disable_log_position=False, user=None, tags=None, external_sd=False):
if not self.isOperational():
return
@@ -1203,7 +1227,8 @@ class MachineCom(object):
self.sendCommand("M114", part_of_job=True, tags=tags | {"trigger:comm.cancel",
"trigger:record_position"})
self._callback.on_comm_print_job_cancelling(firmware_error=firmware_error)
self._callback.on_comm_print_job_cancelling(firmware_error=firmware_error,
user=user)
with self._jobLock:
self._changeState(self.STATE_CANCELLING)
@@ -1222,6 +1247,9 @@ class MachineCom(object):
self.sendCommand("M26 S0", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # reset position in file to byte 0
if self._log_position_on_cancel and not disable_log_position:
with self._action_users_mutex:
self._action_users["cancel"] = user
self.sendCommand("M400",
on_sent=_on_M400_sent,
part_of_job=True,
@@ -1229,14 +1257,15 @@ class MachineCom(object):
"trigger:record_position"})
self._continue_sending()
else:
self._cancel_preparation_done(check_timer=False)
self._cancel_preparation_done(check_timer=False,
user=user)
def _pause_preparation_failed(self):
timeout = self._timeout_intervals.get("positionLogWait", 10.0)
self._log("Did not receive parseable position data from printer within {}s, continuing without it".format(timeout))
self._pause_preparation_done()
def _pause_preparation_done(self, check_timer=True, suppress_script=None):
def _pause_preparation_done(self, check_timer=True, suppress_script=None, user=None):
if suppress_script is None:
with self._suppress_scripts_mutex:
suppress_script = "pause" in self._suppress_scripts
@@ -1245,6 +1274,13 @@ class MachineCom(object):
except KeyError:
pass
if user is None:
with self._action_users_mutex:
try:
user = self._action_users.pop("pause")
except KeyError:
pass
with self._pause_mutex:
if self._pause_position_timer is not None:
self._pause_position_timer.cancel()
@@ -1252,14 +1288,15 @@ class MachineCom(object):
elif check_timer:
return
self._callback.on_comm_print_job_paused(suppress_script=suppress_script)
self._callback.on_comm_print_job_paused(suppress_script=suppress_script,
user=user)
def finalize():
self._changeState(self.STATE_PAUSED)
self.sendCommand(SendQueueMarker(finalize), part_of_job=True)
self._continue_sending()
def setPause(self, pause, local_handling=True, tags=None):
def setPause(self, pause, local_handling=True, user=None, tags=None):
if self.isStreaming():
return
@@ -1276,8 +1313,8 @@ class MachineCom(object):
self._pauseWaitStartTime = None
self._changeState(self.STATE_RESUMING)
self._callback.on_comm_print_job_resumed(suppress_script=not local_handling)
self.sendCommand(SendQueueMarker(lambda: self._changeState(self.STATE_PRINTING)), part_of_job=True)
self._callback.on_comm_print_job_resumed(suppress_script=not local_handling,
user=user)
if self.isSdFileSelected():
if local_handling:
@@ -1288,6 +1325,8 @@ class MachineCom(object):
part_of_job=True,
tags=tags | {"trigger:comm.set_pause", "trigger:resume"})
self.sendCommand(SendQueueMarker(lambda: self._changeState(self.STATE_PRINTING)), part_of_job=True)
# now make sure we actually do something, up until now we only filled up the queue
self._continue_sending()
@@ -1326,6 +1365,9 @@ class MachineCom(object):
"trigger:record_position"})
if self._log_position_on_pause:
with self._action_users_mutex:
self._action_users["pause"] = user
self.sendCommand("M400",
on_sent=_on_M400_sent,
part_of_job=True,
@@ -1334,7 +1376,9 @@ class MachineCom(object):
"trigger:record_position"})
self._continue_sending()
else:
self._pause_preparation_done(check_timer=False, suppress_script=not local_handling)
self._pause_preparation_done(check_timer=False,
suppress_script=not local_handling,
user=user)
def getSdFiles(self):
return self._sdFiles
@@ -1905,24 +1949,36 @@ class MachineCom(object):
current = int(match.group("current"))
total = int(match.group("total"))
if self.isSdPrinting() and current == total == 0:
if current == total == 0 \
and self.isSdPrinting() \
and not self.isStarting() \
and not self.isStarting() \
and not self.isFinishing():
# apparently not SD printing - some Marlin versions report it like that for some reason
self.cancelPrint(external_sd=True)
self._consecutive_not_sd_printing += 1
if self._consecutive_not_sd_printing > self._consecutive_not_sd_printing_maximum:
self.cancelPrint(external_sd=True)
elif self.isSdFileSelected():
if not self.isSdPrinting() and current != total and current > 0:
self.startPrint(external_sd=True)
else:
self._consecutive_not_sd_printing = 0
if self.isSdFileSelected():
if not self.isSdPrinting() and current != total and current > 0:
self.startPrint(external_sd=True)
self._currentFile.pos = current
if self._currentFile.size == 0:
self._currentFile.size = total
self._currentFile.pos = current
if self._currentFile.size == 0:
self._currentFile.size = total
if not self._currentFile.done:
self._callback.on_comm_progress()
elif 'Not SD printing' in line and self.isSdFileSelected() and self.isPrinting() and not self.isFinishing():
# something went wrong, printer is reporting that we actually are not printing right now...
self.cancelPrint(external_sd=True)
if not self._currentFile.done:
self._callback.on_comm_progress()
elif 'Not SD printing' in line \
and self.isSdPrinting() \
and not self.isStarting() \
and not self.isFinishing():
self._consecutive_not_sd_printing += 1
if self._consecutive_not_sd_printing > self._consecutive_not_sd_printing_maximum:
# something went wrong, printer is reporting that we actually are not printing right now...
self.cancelPrint(external_sd=True)
elif 'File opened' in line and not self._ignore_select:
# answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d"
match = regex_sdFileOpened.search(line)
@@ -2022,6 +2078,7 @@ class MachineCom(object):
### Operational (idle or busy)
elif self._state in (self.STATE_OPERATIONAL,
self.STATE_STARTING,
self.STATE_PRINTING,
self.STATE_PAUSED,
self.STATE_TRANSFERING_FILE):
@@ -2193,7 +2250,7 @@ class MachineCom(object):
def _continue_sending(self):
while self._active:
job_active = self._state == self.STATE_PRINTING and not (self._currentFile is None or self._currentFile.done or self.isSdPrinting())
job_active = self._state in (self.STATE_STARTING, self.STATE_PRINTING) and not (self._currentFile is None or self._currentFile.done or self.isSdPrinting())
if self._send_from_command_queue():
# we found something in the command queue to send
@@ -2260,7 +2317,14 @@ class MachineCom(object):
from sd, busy with a long running command or heating, no poll will be done.
"""
if self.isOperational() and not self._temperature_autoreporting and not self._connection_closing and not self.isStreaming() and not self._long_running_command and not self._heating and not self._dwelling_until and not self._manualStreaming:
if self.isOperational() \
and not self._temperature_autoreporting \
and not self._connection_closing \
and not self.isStreaming() \
and not self._long_running_command \
and not self._heating \
and not self._dwelling_until \
and not self._manualStreaming:
self.sendCommand("M105", cmd_type="temperature_poll", tags={"trigger:comm.poll_temperature"})
def _poll_sd_status(self):
@@ -2271,7 +2335,13 @@ class MachineCom(object):
command or heating, no poll will be done.
"""
if self.isOperational() and not self._sdstatus_autoreporting and not self._connection_closing and self.isSdFileSelected() and not self._long_running_command and not self._dwelling_until and not self._heating:
if self.isOperational() \
and not self._sdstatus_autoreporting \
and not self._connection_closing \
and self.isSdFileSelected() \
and not self._long_running_command \
and not self._dwelling_until \
and not self._heating:
self.sendCommand("M27", cmd_type="sd_status_poll", tags={"trigger:comm.poll_sd_status"})
def _set_autoreport_temperature_interval(self, interval=None):
@@ -2480,13 +2550,13 @@ class MachineCom(object):
serial_obj = serial.Serial(str(port),
baudrates[0],
timeout=read_timeout,
write_timeout=10000,
write_timeout=0,
parity=serial.PARITY_ODD)
else:
serial_obj = serial.Serial(str(port),
baudrate,
timeout=read_timeout,
write_timeout=10000,
write_timeout=0,
parity=serial.PARITY_ODD)
serial_obj.close()
serial_obj.parity = serial.PARITY_NONE
@@ -2682,7 +2752,7 @@ class MachineCom(object):
with self._jobLock:
while self._active:
# we loop until we've actually enqueued a line for sending
if self._state != self.STATE_PRINTING:
if self._state not in (self.STATE_STARTING, self.STATE_PRINTING):
# we are no longer printing, return false
return False
@@ -3293,6 +3363,11 @@ class MachineCom(object):
self._errorValue = "Could not write to serial port"
self.close(is_error=True)
break
# if we have failed to write data after an initial retry then the printer/system
# may be busy, so give things a little time before we try again. Extend this
# period each time we fail until either we write the data or run out of retry attempts.
if passes > 1:
sleep((passes-1)/10.0)
##~~ command handlers
@@ -3619,7 +3694,7 @@ class MachineComPrintCallback(object):
def on_comm_progress(self):
pass
def on_comm_print_job_started(self, suppress_script=False):
def on_comm_print_job_started(self, suppress_script=False, user=None):
pass
def on_comm_print_job_failed(self, reason=None):
@@ -3628,16 +3703,16 @@ class MachineComPrintCallback(object):
def on_comm_print_job_done(self, suppress_script=False):
pass
def on_comm_print_job_cancelling(self, firmware_error=None):
def on_comm_print_job_cancelling(self, firmware_error=None, user=None):
pass
def on_comm_print_job_cancelled(self, suppress_script=False):
def on_comm_print_job_cancelled(self, suppress_script=False, user=None):
pass
def on_comm_print_job_paused(self, suppress_script=False):
def on_comm_print_job_paused(self, suppress_script=False, user=None):
pass
def on_comm_print_job_resumed(self, suppress_script=False):
def on_comm_print_job_resumed(self, suppress_script=False, user=None):
pass
def on_comm_z_change(self, newZ):
@@ -3652,13 +3727,13 @@ class MachineComPrintCallback(object):
def on_comm_sd_files(self, files):
pass
def on_comm_file_transfer_started(self, filename, filesize, user=None):
def on_comm_file_transfer_started(self, local_filename, remote_filename, filesize, user=None):
pass
def on_comm_file_transfer_done(self, filename):
def on_comm_file_transfer_done(self, local_filename, remote_filename, elapsed):
pass
def on_comm_file_transfer_failed(self, filename):
def on_comm_file_transfer_failed(self, local_filename, remote_filename, elapsed):
pass
def on_comm_force_disconnect(self):
+6
View File
@@ -28,6 +28,7 @@ class UnknownPip(Exception):
class PipCaller(CommandlineCaller):
process_dependency_links = pkg_resources.Requirement.parse("pip>=1.5")
no_cache_dir = pkg_resources.Requirement.parse("pip>=1.6")
disable_pip_version_check = pkg_resources.Requirement.parse("pip>=6.0")
no_use_wheel = pkg_resources.Requirement.parse("pip==1.5.0")
broken = pkg_resources.Requirement.parse("pip>=6.0.1,<=6.0.3")
@@ -48,6 +49,11 @@ class PipCaller(CommandlineCaller):
logger.debug("Found --no-cache-dir flag, version {} doesn't support that yet though, removing.".format(pip_version))
args.remove("--no-cache-dir")
# strip --disable-pip-version-check for versions that don't support it
if not pip_version in cls.disable_pip_version_check and "--disable-pip-version-check" in args:
logger.debug("Found --disable-pip-version-check flag, version {} doesn't support that yet though, removing.".format(pip_version))
args.remove("--disable-pip-version-check")
# add --no-use-wheel for versions that otherwise break
if pip_version in cls.no_use_wheel and not "--no-use-wheel" in args:
logger.debug("Version {} needs --no-use-wheel to properly work.".format(pip_version))