Merge branch 'maintenance' into pr/2968

# Conflicts:
#	src/octoprint/plugins/tracking/__init__.py
This commit is contained in:
Gina Häußge committed 2019-01-16 18:34:30 +01:00
commit 987379d6e7
40 files changed
+866 -200

No files matched your search

+1
View File
@@ -94,6 +94,7 @@ 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
+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>
+25 -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,10 @@ 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)
* ``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 +419,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 +449,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
+25 -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):
"""
@@ -239,7 +258,7 @@ class EventManager(object):
return
self._registeredListeners[event].remove(callback)
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
self._logger.debug("Unsubscribed listener {!r} for event {}".format(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,
+6 -3
View File
@@ -839,12 +839,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,
-17
View File
@@ -2059,20 +2059,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
@@ -684,7 +684,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)
@@ -834,18 +834,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)
@@ -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
@@ -12,6 +12,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"
@@ -290,7 +291,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"
@@ -316,5 +323,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)
+25 -13
View File
@@ -16,6 +16,7 @@ from octoprint.server import admin_permission
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
@@ -363,7 +364,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")
@@ -485,10 +486,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,
@@ -521,7 +524,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:
@@ -580,8 +583,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,
@@ -723,8 +727,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"],
@@ -743,8 +748,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():
@@ -961,6 +967,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
versions=notification.get("versions", []),
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"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
@@ -974,5 +985,6 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
"octoprint.events.register_custom_events": _register_custom_events
}
@@ -150,9 +150,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
@@ -176,6 +179,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"
@@ -188,6 +196,7 @@ __plugin_implementation__ = PrinterSafetyCheckPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received,
"octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received,
"octoprint.events.register_custom_events": register_custom_events
}
@@ -944,17 +944,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...
@@ -1198,6 +1202,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"
@@ -1220,7 +1228,8 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.cli.commands": cli.commands
"octoprint.cli.commands": cli.commands,
"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)
+25 -14
View File
@@ -115,31 +115,42 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
##~~ EventHandlerPlugin
# noinspection PyUnresolvedReferences
def on_event(self, event, payload):
if not self._settings.get_boolean([b"enabled"]):
return
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 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):
@@ -206,13 +217,13 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
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):
+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):
"""
+157 -41
View File
@@ -41,6 +41,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
@@ -93,6 +94,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
@@ -521,9 +525,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.
"""
@@ -533,9 +538,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.
"""
@@ -545,9 +552,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.
"""
@@ -556,7 +565,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")
@@ -659,8 +669,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm is None or not self._comm.isSdReady():
return []
return 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
@@ -668,23 +678,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._streamingFailedCallback):
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():
@@ -914,6 +968,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()
@@ -1044,10 +1111,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()))
@@ -1058,11 +1132,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),
@@ -1082,6 +1163,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),
@@ -1105,23 +1190,29 @@ 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),
@@ -1141,52 +1232,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()
@@ -1199,7 +1307,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
@@ -1208,6 +1317,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:
@@ -1238,6 +1348,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
@@ -446,6 +446,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()
@@ -1359,6 +1370,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
@@ -336,7 +336,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
@@ -49,17 +49,17 @@ 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)
elif 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
+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)
@@ -95,6 +104,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()))
+39 -18
View File
@@ -535,15 +535,38 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
#~~ passive login helper
_cached_local_networks = None
def _local_networks():
global _cached_local_networks
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
remoteAddr = get_remote_address(flask.request)
ipCheckEnabled = settings().getBoolean(["server", "ipCheck", "enabled"])
ipCheckTrusted = settings().get(["server", "ipCheck", "trustedSubnets"])
remote_address = get_remote_address(flask.request)
ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"])
ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"])
if user is not None and not user.is_anonymous() and user.is_active():
flask_principal.identity_changed.send(flask.current_app._get_current_object(),
@@ -552,25 +575,24 @@ def passive_login():
flask.session["usersession.id"] = user.session
flask.g.user = user
logging.getLogger(__name__).info("Passively logging in user {} from {}".format(user.get_id(), remoteAddr))
logger.info("Passively logging in user {} from {}".format(user.get_id(), remote_address))
response = user.asDict()
response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr,
additional_private=ipCheckTrusted)
response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address,
additional_private=ip_check_trusted)
return flask.jsonify(response)
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:
user = octoprint.server.userManager.findUser(autologinAs)
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
@@ -579,16 +601,15 @@ def passive_login():
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))
logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(),
remote_address))
response = user.asDict()
response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr,
additional_private=ipCheckTrusted)
response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address,
additional_private=ip_check_trusted)
return flask.jsonify(response)
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))
return "", 204
+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
+5
View File
@@ -194,6 +194,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);
@@ -733,6 +733,10 @@ $(function() {
}
};
self.clearSearchQuery = function() {
self.searchQuery("");
};
self.performSearch = function(e) {
var query = self.searchQuery();
if (query !== undefined && query.trim() !== "") {
@@ -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
@@ -1415,6 +1415,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 {
+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">
+67 -36
View File
@@ -539,6 +539,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
@@ -998,7 +1001,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
@@ -1022,7 +1025,7 @@ class MachineCom(object):
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:
@@ -1053,7 +1056,7 @@ class MachineCom(object):
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
@@ -1065,14 +1068,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():
@@ -1092,22 +1097,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))
@@ -1149,7 +1149,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()
@@ -1159,14 +1166,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
@@ -1198,7 +1205,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)
@@ -1217,6 +1225,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,
@@ -1224,14 +1235,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
@@ -1240,6 +1252,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()
@@ -1247,14 +1266,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
@@ -1271,7 +1291,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._callback.on_comm_print_job_resumed(suppress_script=not local_handling,
user=user)
self.sendCommand(SendQueueMarker(lambda: self._changeState(self.STATE_PRINTING)), part_of_job=True)
if self.isSdFileSelected():
@@ -1321,6 +1342,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,
@@ -1329,7 +1353,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
@@ -2475,13 +2501,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
@@ -3288,6 +3314,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
@@ -3614,7 +3645,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):
@@ -3623,16 +3654,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):
@@ -3647,13 +3678,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
@@ -27,6 +27,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")
@@ -47,6 +48,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))