From 3de5bca48b1b4b19c356a545efe99f84bead2bd5 Mon Sep 17 00:00:00 2001
From: sylvled <39048447+sylvled@users.noreply.github.com>
Date: Mon, 7 May 2018 10:28:14 +0200
Subject: [PATCH 001/656] Update config_yaml.rst
gcodeAnalysis and gcodeViewer were without section name. Added them.
---
docs/configuration/config_yaml.rst | 2 ++
1 file changed, 2 insertions(+)
diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst
index 790702fd1..de5c420f2 100644
--- a/docs/configuration/config_yaml.rst
+++ b/docs/configuration/config_yaml.rst
@@ -616,6 +616,7 @@ Settings pertaining to the server side GCODE analysis implementation.
.. code-block:: yaml
+gcodeAnalysis:
# Maximum number of extruders to support/to sanity check for
maxExtruders: 10
@@ -635,6 +636,7 @@ Settings pertaining to the built in GCODE Viewer.
.. code-block:: yaml
+ gcodeViewer:
# Whether to enable the GCODE viewer in the UI
enabled: true
From 4cb103e042966af0a2138a1bd3c5550277bb9eba Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 8 Jun 2018 11:03:44 +0200
Subject: [PATCH 002/656] Fix cancel_preparation call in case of failure
It should be _failed if the timer runs out, not _done. Only difference
is a log entry though, so not that big of a deal.
---
src/octoprint/util/comm.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index c1309e1de..ffc3efbda 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -1177,7 +1177,7 @@ class MachineCom(object):
if self._cancel_position_timer is not None:
self._cancel_position_timer.cancel()
self._cancel_position_timer = ResettableTimer(self._timeout_intervals.get("positionLogWait", 10.0),
- self._cancel_preparation_done)
+ self._cancel_preparation_failed)
self._cancel_position_timer.daemon = True
self._cancel_position_timer.start()
self.sendCommand("M114", tags=tags | {"trigger:comm.cancel",
From 13e5cf45ec949dc0e15d4f61c0e5284349b1eb85 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 23 Mar 2018 14:52:38 +0100
Subject: [PATCH 003/656] Fix reset handling while printing
Could get stuck in cancelling due to resend issues.
Should fix #2509
---
.../plugins/virtual_printer/virtual.py | 105 +++++++-------
src/octoprint/static/js/app/dataupdater.js | 31 ++++-
src/octoprint/util/comm.py | 131 +++++++++++++++---
3 files changed, 190 insertions(+), 77 deletions(-)
diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py
index 8895a5625..7531df71e 100644
--- a/src/octoprint/plugins/virtual_printer/virtual.py
+++ b/src/octoprint/plugins/virtual_printer/virtual.py
@@ -168,72 +168,73 @@ class VirtualPrinter(object):
.format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options=settings().get(["devel", "virtualPrinter"]))
def _reset(self):
- self._clearQueue(self.incoming)
- self._clearQueue(self.outgoing)
- self._clearQueue(self.buffered)
+ with self._incoming_lock:
+ self._relative = True
+ self._lastX = 0.0
+ self._lastY = 0.0
+ self._lastZ = 0.0
+ self._lastE = [0.0] * self.extruderCount
+ self._lastF = 200
- self._relative = True
- self._lastX = 0.0
- self._lastY = 0.0
- self._lastZ = 0.0
- self._lastE = [0.0] * self.extruderCount
- self._lastF = 200
+ self._unitModifier = 1
+ self._feedrate_multiplier = 100
+ self._flowrate_multiplier = 100
- self._unitModifier = 1
- self._feedrate_multiplier = 100
- self._flowrate_multiplier = 100
-
- self._sdCardReady = True
- self._sdPrinting = False
- if self._sdPrinter:
+ self._sdCardReady = True
self._sdPrinting = False
- self._sdPrintingSemaphore.set()
- self._sdPrinter = None
- self._selectedSdFile = None
- self._selectedSdFileSize = None
- self._selectedSdFilePos = None
+ if self._sdPrinter:
+ self._sdPrinting = False
+ self._sdPrintingSemaphore.set()
+ self._sdPrinter = None
+ self._selectedSdFile = None
+ self._selectedSdFileSize = None
+ self._selectedSdFilePos = None
- if self._writingToSdHandle:
- try:
- self._writingToSdHandle.close()
- except:
- pass
- self._writingToSd = False
- self._writingToSdHandle = None
- self._newSdFilePos = None
+ if self._writingToSdHandle:
+ try:
+ self._writingToSdHandle.close()
+ except:
+ pass
+ self._writingToSd = False
+ self._writingToSdHandle = None
+ self._newSdFilePos = None
- self._heatingUp = False
+ self._heatingUp = False
- self.currentLine = 0
- self.lastN = 0
+ self.currentLine = 0
+ self.lastN = 0
- self._debug_awol = False
- self._debug_sleep = None
- self._sleepAfterNext.clear()
- self._sleepAfter.clear()
+ self._debug_awol = False
+ self._debug_sleep = None
+ self._sleepAfterNext.clear()
+ self._sleepAfter.clear()
- self._dont_answer = False
+ self._dont_answer = False
- self._debug_drop_connection = False
+ self._debug_drop_connection = False
- self._killed = False
+ self._killed = False
- self._triggerResendAt100 = True
- self._triggerResendWithTimeoutAt105 = True
- self._triggerResendWithMissingLinenoAt110 = True
- self._triggerResendWithChecksumMismatchAt115 = True
+ self._triggerResendAt100 = True
+ self._triggerResendWithTimeoutAt105 = True
+ self._triggerResendWithMissingLinenoAt110 = True
+ self._triggerResendWithChecksumMismatchAt115 = True
- if self._temperature_reporter is not None:
- self._temperature_reporter.cancel()
- self._temperature_reporter = None
+ if self._temperature_reporter is not None:
+ self._temperature_reporter.cancel()
+ self._temperature_reporter = None
- if self._sdstatus_reporter is not None:
- self._sdstatus_reporter.cancel()
- self._sdstatus_reporter = None
+ if self._sdstatus_reporter is not None:
+ self._sdstatus_reporter.cancel()
+ self._sdstatus_reporter = None
- if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]):
- for item in settings().get(["devel", "virtualPrinter", "resetLines"]):
- self._send(item + "\n")
+ self._clearQueue(self.incoming)
+ self._clearQueue(self.outgoing)
+ self._clearQueue(self.buffered)
+
+ if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]):
+ for item in settings().get(["devel", "virtualPrinter", "resetLines"]):
+ self._send(item + "\n")
@property
def timeout(self):
diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js
index 54074ac8f..e33367740 100644
--- a/src/octoprint/static/js/app/dataupdater.js
+++ b/src/octoprint/static/js/app/dataupdater.js
@@ -218,6 +218,9 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
});
};
+ self._printerErrorCancelNotification = undefined;
+ self._printerErrorDisconnectNotification = undefined;
+ self._printerResetNotification = undefined;
self._onEvent = function(event) {
self._ifInitialized(function() {
var type = event.data["type"];
@@ -226,7 +229,10 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
if (type === "PrintCancelling" && payload.firmwareError) {
- new PNotify({
+ if (self._printerErrorCancelNotification !== undefined) {
+ self._printerErrorCancelNotification.remove();
+ }
+ self._printerErrorCancelNotification = new PNotify({
title: gettext("Error reported by printer"),
text: _.sprintf(gettext("Your printer's firmware reported an error. Due to that the ongoing print job will be cancelled. Reported error: %(firmwareError)s"), payload),
type: "error",
@@ -271,7 +277,10 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
}
if (title && text) {
- new PNotify({
+ if (self._printerErrorDisconnectNotification !== undefined) {
+ self._printerErrorDisconnectNotification.remove();
+ }
+ self._printerErrorDisconnectNotification = new PNotify({
title: title,
text: text,
type: "error",
@@ -279,9 +288,23 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
});
}
} else if (type === "PrinterReset") {
- new PNotify({
+ var severity = undefined,
+ text = undefined;
+ if (payload.idle) {
+ text = gettext("It looks like your printer reset while a connection was active. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD.");
+ severity = "alert";
+ } else {
+ text = gettext("It looks like your printer reset while a connection was active. Due to this the ongoing job was aborted. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD.");
+ severity = "error";
+ }
+
+ if (self._printerResetNotification !== undefined) {
+ self._printerResetNotification.remove();
+ }
+ self._printerResetNotification = new PNotify({
title: gettext("Printer reset detected"),
- text: gettext("It looks like your printer reset while a connection was active. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD."),
+ text: text,
+ type: severity,
hide: false
});
}
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index ffc3efbda..7ca2027dd 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -382,7 +382,7 @@ class MachineCom(object):
self._baudrateDetectRetry = 0
self._temperatureTargetSetThreshold = 25
self._tempOffsets = dict()
- self._command_queue = TypedQueue()
+ self._command_queue = CommandQueue()
self._currentZ = None
self._currentF = None
self._heatupWaitStartTime = None
@@ -1622,7 +1622,7 @@ class MachineCom(object):
# process resends
elif lower_line.startswith("resend") or lower_line.startswith("rs"):
- self._handleResendRequest(line)
+ self._handle_resend_request(line)
handled = True
# process timeouts
@@ -2002,23 +2002,27 @@ class MachineCom(object):
self.STATE_PAUSED,
self.STATE_TRANSFERING_FILE):
if line == "start": # exact match, to be on the safe side
- if self._state in (self.STATE_OPERATIONAL,):
- message = "Printer sent 'start' while already operational. External reset? " \
- "Resetting line numbers to be on the safe side"
- self._log(message)
- self._logger.warn(message)
- self._onExternalReset()
+ with self.job_put_on_hold():
+ idle = self._state in (self.STATE_OPERATIONAL,)
+ if idle:
+ message = "Printer sent 'start' while already operational. External reset? " \
+ "Resetting line numbers to be on the safe side"
+ self._log(message)
+ self._logger.warn(message)
- else:
- verb = "streaming to SD" if self.isStreaming() else "printing"
- message = "Printer sent 'start' while {}. External reset? " \
- "Aborting job since printer lost state.".format(verb)
- self._log(message)
- self._logger.warn(message)
- self.cancelPrint(disable_log_position=True)
- self._onExternalReset()
+ self._on_external_reset()
- eventManager().fire(Events.PRINTER_RESET)
+ else:
+ verb = "streaming to SD" if self.isStreaming() else "printing"
+ message = "Printer sent 'start' while {}. External reset? " \
+ "Aborting job since printer lost state.".format(verb)
+ self._log(message)
+ self._logger.warn(message)
+
+ self._on_external_reset()
+ self.cancelPrint(disable_log_position=True)
+
+ eventManager().fire(Events.PRINTER_RESET, payload=dict(idle=idle))
except:
self._logger.exception("Something crashed inside the serial connection loop, please report this in OctoPrint's bug tracker:")
@@ -2291,7 +2295,19 @@ class MachineCom(object):
eventManager().fire(Events.CONNECTED, payload)
self.sendGcodeScript("afterPrinterConnected", replacements=dict(event=payload))
- def _onExternalReset(self):
+ def _on_external_reset(self):
+ # hold queue processing, clear queues and acknowledgements, reset line number and last lines
+ with self._send_queue.blocked():
+ self._clear_to_send.clear(completely=True)
+ with self._command_queue.blocked():
+ self._command_queue.clear()
+ self._send_queue.clear()
+
+ with self._line_mutex:
+ self._currentLine = 0
+ self._lastLines.clear()
+
+ self.sayHello(tags={"trigger:comm.on_external_reset"})
self.resetLineNumbers(tags={"trigger:comm.on_external_reset"})
if self._temperature_autoreporting:
@@ -2620,13 +2636,19 @@ class MachineCom(object):
self._logger.debug("Command \"{}\" from file not enqueued, doing another iteration".format(line))
- def _handleResendRequest(self, line):
+ def _handle_resend_request(self, line):
try:
lineToResend = parse_resend_line(line)
if lineToResend is None:
return False
- if self._resendDelta is None and lineToResend == self._currentLine:
+ if self._resendDelta is None and lineToResend == self._currentLine == 1:
+ # We probably just handled a resend and this request originates from lines sent before that
+ self._logger.info("Got a resend request for line 1 which is also our current line. It looks "
+ "like we just handled a reset and this is a left over of this")
+ return False
+
+ elif self._resendDelta is None and lineToResend == self._currentLine:
# We don't expect to have an active resend request and the printer is requesting a resend of
# a line we haven't yet sent.
#
@@ -2647,7 +2669,7 @@ class MachineCom(object):
if lastCommError is not None \
and ("line number" in lastCommError.lower() or "expected line" in lastCommError.lower()) \
and lineToResend == self._lastResendNumber \
- and self._resendDelta is not None and self._currentResendCount < self._resendDelta:
+ and self._resendDelta is not None and self._currentResendCount < resendDelta:
self._logger.info("Ignoring resend request for line %d, that still originates from lines we sent "
"before we got the first resend request" % lineToResend)
self._currentResendCount += 1
@@ -3782,12 +3804,52 @@ class SpecialStreamingGcodeFileInformation(StreamingGcodeFileInformation):
return None
return line
+class CommandQueue(TypedQueue):
+ def __init__(self, *args, **kwargs):
+ TypedQueue.__init__(self, *args, **kwargs)
+ self._unblocked = threading.Event()
+ self._unblocked.set()
+
+ def block(self):
+ self._unblocked.clear()
+
+ def unblock(self):
+ self._unblocked.set()
+
+ @contextlib.contextmanager
+ def blocked(self):
+ self.block()
+ try:
+ yield
+ finally:
+ self.unblock()
+
+ def get(self, *args, **kwargs):
+ self._unblocked.wait()
+ return TypedQueue.get(self, *args, **kwargs)
+
+ def put(self, *args, **kwargs):
+ self._unblocked.wait()
+ return TypedQueue.put(self, *args, **kwargs)
+
+ def clear(self):
+ cleared = []
+ while True:
+ try:
+ cleared.append(TypedQueue.get(self, False))
+ TypedQueue.task_done(self)
+ except queue.Empty:
+ break
+ return cleared
class SendQueue(PrependableQueue):
def __init__(self, maxsize=0):
PrependableQueue.__init__(self, maxsize=maxsize)
+ self._unblocked = threading.Event()
+ self._unblocked.set()
+
self._resend_queue = PrependableQueue()
self._send_queue = PrependableQueue()
self._lookup = set()
@@ -3803,16 +3865,43 @@ class SendQueue(PrependableQueue):
with self.mutex:
self._resend_active = resend_active
+ def block(self):
+ self._unblocked.clear()
+
+ def unblock(self):
+ self._unblocked.set()
+
+ @contextlib.contextmanager
+ def blocked(self):
+ self.block()
+ try:
+ yield
+ finally:
+ self.unblock()
+
def prepend(self, item, item_type=None, target=None, block=True, timeout=None):
+ self._unblocked.wait()
PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout)
def put(self, item, item_type=None, target=None, block=True, timeout=None):
+ self._unblocked.wait()
PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout)
def get(self, block=True, timeout=None):
+ self._unblocked.wait()
item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout)
return item
+ def clear(self):
+ cleared = []
+ while True:
+ try:
+ cleared.append(PrependableQueue.get(self, False))
+ PrependableQueue.task_done(self)
+ except queue.Empty:
+ break
+ return cleared
+
def _put(self, item):
_, item_type, target = item
if item_type is not None:
From 534f3aa2d4f2655eac1ecc31458925fa88b3b5e0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Sat, 9 Jun 2018 10:15:56 +0200
Subject: [PATCH 004/656] Fix for potential division by zero on SD upload
Closes #2675
---
src/octoprint/util/comm.py | 12 +++++++-----
1 file changed, 7 insertions(+), 5 deletions(-)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index 7ca2027dd..341d85832 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -3781,11 +3781,13 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
def _report_stats(self):
duration = time.time() - self._start_time
- stats = dict(lines=self._read_lines,
- rate=float(self._read_lines) / duration,
- time_per_line=duration * 1000.0 / float(self._read_lines),
- duration=duration)
- self._logger.info("Finished in {duration:.3f} s. Approx. transfer rate of {rate:.3f} lines/s or {time_per_line:.3f} ms per line".format(**stats))
+ read_lines = self._read_lines
+ if duration > 0 and read_lines > 0:
+ stats = dict(lines=read_lines,
+ rate=float(read_lines) / duration,
+ time_per_line=duration * 1000.0 / float(read_lines),
+ duration=duration)
+ self._logger.info("Finished in {duration:.3f} s. Approx. transfer rate of {rate:.3f} lines/s or {time_per_line:.3f} ms per line".format(**stats))
class SpecialStreamingGcodeFileInformation(StreamingGcodeFileInformation):
From 6e441492844eb771b3f222278359feb594001082 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Sat, 9 Jun 2018 11:58:53 +0200
Subject: [PATCH 005/656] Treat scripts triggered by job as part of the job
Including blocking their sending via job_on_hold.
Closes #2583
---
src/octoprint/printer/standard.py | 8 +++-
src/octoprint/util/comm.py | 78 ++++++++++++++++++++-----------
2 files changed, 58 insertions(+), 28 deletions(-)
diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py
index 3a043d8db..7de61daeb 100644
--- a/src/octoprint/printer/standard.py
+++ b/src/octoprint/printer/standard.py
@@ -285,7 +285,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
for command in commands:
self._comm.sendCommand(command, tags=kwargs.get("tags", set()) | {"trigger:printer.commands"})
- def script(self, name, context=None, must_be_set=True, *args, **kwargs):
+ def script(self, name, context=None, must_be_set=True, part_of_job=False, *args, **kwargs):
if self._comm is None:
return
@@ -293,6 +293,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
raise ValueError("name must be set")
result = self._comm.sendGcodeScript(name,
+ part_of_job=part_of_job,
replacements=context,
tags=kwargs.get("tags", set()) | {"trigger:printer.script"})
if not result and must_be_set:
@@ -1040,6 +1041,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not suppress_script:
self.script("beforePrintStarted",
context=dict(event=payload),
+ part_of_job=True,
must_be_set=False)
def on_comm_print_job_done(self, suppress_script=False):
@@ -1058,6 +1060,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not suppress_script:
self.script("afterPrintDone",
context=dict(event=payload),
+ part_of_job=True,
must_be_set=False)
def log_print():
@@ -1101,6 +1104,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not suppress_script:
self.script("afterPrintCancelled",
context=dict(event=payload),
+ part_of_job=True,
must_be_set=False)
def finalize():
@@ -1123,6 +1127,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
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):
@@ -1132,6 +1137,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
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):
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index 341d85832..64032f1d0 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -483,6 +483,8 @@ class MachineCom(object):
self._temperature_timer = None
self._sd_status_timer = None
+ self._script_queue = ScriptQueue()
+
# hooks
self._pluginManager = octoprint.plugin.plugin_manager()
@@ -968,13 +970,17 @@ class MachineCom(object):
scriptLines))
- def sendGcodeScript(self, scriptName, replacements=None, tags=None):
+ def sendGcodeScript(self, scriptName, replacements=None, tags=None, part_of_job=False):
if tags is None:
tags = set()
scriptLines = self._getGcodeScript(scriptName, replacements=replacements)
+ tags_to_use = tags | {"trigger:comm.send_gcode_script", "source:script", "script:{}".format(scriptName)}
for line in scriptLines:
- self.sendCommand(line, tags=tags | {"trigger:comm.send_gcode_script", "source:script", "script:{}".format(scriptName)})
+ if part_of_job:
+ self._script_queue.put((line, tags_to_use))
+ else:
+ self.sendCommand(line, tags=tags_to_use)
return "\n".join(scriptLines)
def startPrint(self, pos=None, tags=None, external_sd=False):
@@ -1026,7 +1032,7 @@ class MachineCom(object):
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.seek(pos)
- line, pos, lineno = self._getNext()
+ line, pos, lineno = self._get_next_from_job()
if line is not None:
self.sendCommand(line, tags=tags | {"trigger:comm.start_print",
"source:file",
@@ -1034,7 +1040,7 @@ class MachineCom(object):
"fileline:{}".format(lineno)})
# now make sure we actually do something, up until now we only filled up the queue
- self._sendFromQueue()
+ self._send_from_command_queue()
except:
self._logger.exception("Error while trying to start printing")
self._trigger_error(get_exception_string(), "start_print")
@@ -1261,7 +1267,7 @@ class MachineCom(object):
self.sendCommand("M24", tags=tags | {"trigger:comm.set_pause","trigger:resume"})
self.sendCommand("M27", tags=tags | {"trigger:comm.set_pause", "trigger:resume"})
else:
- line, pos, lineno = self._getNext()
+ line, pos, lineno = self._get_next_from_job()
if line is not None:
if not tags:
tags = set()
@@ -1273,7 +1279,7 @@ class MachineCom(object):
self.sendCommand(line, tags=tags_to_use)
# now make sure we actually do something, up until now we only filled up the queue
- self._sendFromQueue()
+ self._send_from_command_queue()
elif pause and self.isPrinting():
if not self._pauseWaitStartTime:
@@ -2174,26 +2180,29 @@ 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())
- if self._state == self.STATE_PRINTING and not (self._currentFile is None or self._currentFile.done or self.isSdPrinting()):
- # we are printing, we really want to send either something from the command
- # queue or the next line from our file, so we only return here if we actually DO
- # send something
- if self._sendFromQueue():
- # we found something in the queue to send
- return True
+ if self._send_from_command_queue():
+ # we found something in the command queue to send
+ return True
- elif self.job_on_hold:
- return False
+ elif self.job_on_hold:
+ # job is on hold, that means we must not send from either script queue or file
+ return False
- elif self._sendNext():
- # we sent the next line from the file
- return True
+ elif self._send_from_script_queue():
+ # we found something in the script queue to send
+ return True
- self._logger.debug("No command sent on ok while printing, doing another iteration")
- else:
- # just send stuff from the command queue and be done with it
- return self._sendFromQueue()
+ elif job_active and self._send_from_job():
+ # we sent the next line from the file
+ return True
+
+ elif not job_active:
+ # nothing sent but also no job active, so we can just return false
+ return False
+
+ self._logger.debug("No command sent on ok while printing, doing another iteration")
def _process_registered_message(self, line, feedback_matcher, feedback_controls, feedback_errors):
feedback_match = feedback_matcher.search(line)
@@ -2341,7 +2350,7 @@ class MachineCom(object):
return get("temperature", busy_default)
- def _sendFromQueue(self):
+ def _send_from_command_queue(self):
# We loop here to make sure that if we do NOT send the first command
# from the queue, we'll send the second (if there is one). We do not
# want to get stuck here by throwing away commands.
@@ -2587,7 +2596,7 @@ class MachineCom(object):
return ret
- def _getNext(self):
+ def _get_next_from_job(self):
if self._currentFile is None:
return None
@@ -2603,7 +2612,7 @@ class MachineCom(object):
return SendQueueMarker(finalize), None, None
return line, pos, lineno
- def _sendNext(self):
+ def _send_from_job(self):
with self._jobLock:
while self._active:
# we loop until we've actually enqueued a line for sending
@@ -2615,7 +2624,7 @@ class MachineCom(object):
# job is on hold, return false
return False
- line, pos, lineno = self._getNext()
+ line, pos, lineno = self._get_next_from_job()
if isinstance(line, QueueMarker):
self.sendCommand(line)
self._callback.on_comm_progress()
@@ -2631,11 +2640,23 @@ class MachineCom(object):
result = self._sendCommand(line, tags={"source:file", "filepos:{}".format(pos), "fileline:{}".format(lineno)})
self._callback.on_comm_progress()
if result:
- # line sent, return true
+ # line from file sent, return true
return True
self._logger.debug("Command \"{}\" from file not enqueued, doing another iteration".format(line))
+ def _send_from_script_queue(self):
+ try:
+ line, tags = self._script_queue.get_nowait()
+ result = self._sendCommand(line, tags=tags)
+ if result:
+ # line from script sent, return true
+ return True
+ except queue.Empty:
+ pass
+
+ return False
+
def _handle_resend_request(self, line):
try:
lineToResend = parse_resend_line(line)
@@ -3806,6 +3827,9 @@ class SpecialStreamingGcodeFileInformation(StreamingGcodeFileInformation):
return None
return line
+class ScriptQueue(PrependableQueue):
+ pass
+
class CommandQueue(TypedQueue):
def __init__(self, *args, **kwargs):
TypedQueue.__init__(self, *args, **kwargs)
From 85ef3f1df2fd55ab9c80822764998d8016c52532 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Sat, 9 Jun 2018 13:07:34 +0200
Subject: [PATCH 006/656] Fix modals not hiding fully anymore
---
src/octoprint/static/js/app/helpers.js | 3 ---
1 file changed, 3 deletions(-)
diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js
index 49af106bc..1eb161d05 100644
--- a/src/octoprint/static/js/app/helpers.js
+++ b/src/octoprint/static/js/app/helpers.js
@@ -674,7 +674,6 @@ function showMessageDialog(msg, options) {
if (onclose && _.isFunction(onclose)) {
onclose();
}
- modal.remove();
});
if (onshow) {
@@ -749,7 +748,6 @@ function showConfirmationDialog(msg, onacknowledge, options) {
onproceed(e);
}
modal.modal("hide");
- modal.remove();
});
return modal;
@@ -834,7 +832,6 @@ function showSelectionDialog(options) {
if (onclose && _.isFunction(onclose)) {
onclose(event);
}
- modal.remove();
});
modal.modal("show");
From 392149b5047a9adf2ff94aff0b94ce2dbc25f936 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Thu, 14 Jun 2018 19:25:46 +0200
Subject: [PATCH 007/656] Add view model list to coreui object
---
src/octoprint/static/js/app/main.js | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js
index 5f980c3f7..cdd1886f8 100644
--- a/src/octoprint/static/js/app/main.js
+++ b/src/octoprint/static/js/app/main.js
@@ -49,7 +49,8 @@ $(function() {
mobile: false,
desktop: false
- }
+ },
+ viewmodels: {}
};
var browserVisibilityCallbacks = [];
@@ -400,6 +401,7 @@ $(function() {
pass++;
}
log.info("... dependency resolution done");
+ OctoPrint.coreui.viewmodels = viewModelMap;
//~~ some additional hooks and initializations
From 86b886ede72dff8c3d96cae424ecba7464edee9e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 15 Jun 2018 12:32:07 +0200
Subject: [PATCH 008/656] Remove resend repetition code
It's apparently completely broken and the fact that no one noticed
and reported that means it never really gets used either from the looks
of it.
So instead of allowing it to introduce broken resend handling, we'll
rather remove it for now.
---
src/octoprint/plugins/virtual_printer/virtual.py | 2 --
src/octoprint/settings.py | 1 -
src/octoprint/util/comm.py | 13 -------------
3 files changed, 16 deletions(-)
diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py
index 7531df71e..e1aa40202 100644
--- a/src/octoprint/plugins/virtual_printer/virtual.py
+++ b/src/octoprint/plugins/virtual_printer/virtual.py
@@ -680,8 +680,6 @@ class VirtualPrinter(object):
if not self._brokenResend:
self._sendOk()
- if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
- request_resend()
request_resend()
def _debugTrigger(self, data):
diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py
index af433e9f4..498e4c025 100644
--- a/src/octoprint/settings.py
+++ b/src/octoprint/settings.py
@@ -382,7 +382,6 @@ default_settings = {
"includeFilenameInOpened": True,
"hasBed": True,
"repetierStyleTargetTemperature": False,
- "repetierStyleResends": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"reprapfwM114": False,
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index 64032f1d0..62010267d 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -445,8 +445,6 @@ class MachineCom(object):
self._lastCommError = None
self._lastResendNumber = None
self._currentResendCount = 0
- self._resendSwallowRepetitions = settings().getBoolean(["serial", "ignoreIdenticalResends"])
- self._resendSwallowRepetitionsCounter = 0
self._firmware_detection = settings().getBoolean(["serial", "firmwareDetection"])
self._firmware_info_received = not self._firmware_detection
@@ -1771,7 +1769,6 @@ class MachineCom(object):
self._logger.info("Detected Repetier firmware, enabling relevant features for issue free communication")
self._alwaysSendChecksum = True
- self._resendSwallowRepetitions = True
self._blockWhileDwelling = True
supportRepetierTargetTemp = True
disable_external_heatup_detection = True
@@ -2696,20 +2693,10 @@ class MachineCom(object):
self._currentResendCount += 1
return True
- # If we ignore resend repetitions (Repetier firmware...), check if we
- # need to do this now. If the same line number has been requested we
- # already saw and resent, we'll ignore it up to times.
- if self._resendSwallowRepetitions and lineToResend == self._lastResendNumber and self._resendSwallowRepetitionsCounter > 0:
- self._logger.info("Ignoring resend request for line %d, that is probably a repetition sent by the "
- "firmware to ensure it arrives, not a real request" % lineToResend)
- self._resendSwallowRepetitionsCounter -= 1
- return True
-
self._resendActive = True
self._resendDelta = resendDelta
self._lastResendNumber = lineToResend
self._currentResendCount = 0
- self._resendSwallowRepetitionsCounter = settings().getInt(["serial", "identicalResendsCountdown"])
if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0 or self._resendDelta < 0:
error_text = "Printer requested line %d but no sufficient history is available, can't resend" % lineToResend
From 688e4d36d1dbbf4a4fc1cdd749582614d0ce0bab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Sat, 9 Jun 2018 14:24:19 +0200
Subject: [PATCH 009/656] Fix script order
beforePrint* should always precede any commands from the print job.
Also make sure we only jump from "finishing" to "operational" after the
afterPrintDone script has been sent. Also wait for all moves to finish.
---
src/octoprint/util/comm.py | 123 +++++++++++++++++++------------------
1 file changed, 63 insertions(+), 60 deletions(-)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index 62010267d..bf347ad80 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -481,7 +481,7 @@ class MachineCom(object):
self._temperature_timer = None
self._sd_status_timer = None
- self._script_queue = ScriptQueue()
+ self._job_queue = JobQueue()
# hooks
self._pluginManager = octoprint.plugin.plugin_manager()
@@ -884,7 +884,7 @@ class MachineCom(object):
def fakeOk(self):
self._handle_ok()
- def sendCommand(self, cmd, cmd_type=None, processed=False, force=False, on_sent=None, tags=None):
+ def sendCommand(self, cmd, cmd_type=None, part_of_job=False, processed=False, force=False, on_sent=None, tags=None):
if not isinstance(cmd, QueueMarker):
cmd = to_unicode(cmd, errors="replace")
if not processed:
@@ -892,7 +892,13 @@ class MachineCom(object):
if not cmd:
return False
- if self.isPrinting() and not self.isSdFileSelected() and not self.job_on_hold and not force:
+ if tags is None:
+ tags = set()
+
+ if part_of_job:
+ self._job_queue.put((cmd, cmd_type, on_sent, tags | {"source:job"}))
+ return True
+ elif self.isPrinting() and not self.isSdFileSelected() and not self.job_on_hold and not force:
try:
self._command_queue.put((cmd, cmd_type, on_sent, tags), item_type=cmd_type)
return True
@@ -975,10 +981,7 @@ class MachineCom(object):
scriptLines = self._getGcodeScript(scriptName, replacements=replacements)
tags_to_use = tags | {"trigger:comm.send_gcode_script", "source:script", "script:{}".format(scriptName)}
for line in scriptLines:
- if part_of_job:
- self._script_queue.put((line, tags_to_use))
- else:
- self.sendCommand(line, tags=tags_to_use)
+ 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):
@@ -1003,7 +1006,7 @@ class MachineCom(object):
self._changeState(self.STATE_PRINTING)
if not self.isSdFileSelected():
- self.resetLineNumbers(tags={"trigger:comm.start_print"})
+ self.resetLineNumbers(part_of_job=True, tags={"trigger:comm.start_print"})
self._callback.on_comm_print_job_started()
@@ -1012,14 +1015,19 @@ class MachineCom(object):
# make sure to ignore the "file selected" later on, otherwise we'll reset our progress data
self._ignore_select = True
self.sendCommand("M23 {filename}".format(filename=self._currentFile.getFilename()),
+ part_of_job=True,
tags=tags | {"trigger:comm.start_print",})
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.pos = pos
- self.sendCommand("M26 S{}".format(pos), tags=tags | {"trigger:comm.start_print",})
+ self.sendCommand("M26 S{}".format(pos),
+ part_of_job=True,
+ tags=tags | {"trigger:comm.start_print",})
else:
self._currentFile.pos = 0
- self.sendCommand("M24", tags=tags | {"trigger:comm.start_print",})
+ self.sendCommand("M24",
+ part_of_job=True,
+ tags=tags | {"trigger:comm.start_print",})
interval = self._timeout_intervals.get("sdStatus", 1.0)
if interval <= 0:
@@ -1030,15 +1038,8 @@ class MachineCom(object):
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.seek(pos)
- line, pos, lineno = self._get_next_from_job()
- if line is not None:
- self.sendCommand(line, tags=tags | {"trigger:comm.start_print",
- "source:file",
- "filepos:{}".format(pos),
- "fileline:{}".format(lineno)})
-
# now make sure we actually do something, up until now we only filled up the queue
- self._send_from_command_queue()
+ self._continue_sending()
except:
self._logger.exception("Error while trying to start printing")
self._trigger_error(get_exception_string(), "start_print")
@@ -1152,7 +1153,7 @@ class MachineCom(object):
def finalize():
self._changeState(self.STATE_OPERATIONAL)
- self.sendCommand(SendQueueMarker(finalize))
+ 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):
@@ -1184,8 +1185,8 @@ class MachineCom(object):
self._cancel_preparation_failed)
self._cancel_position_timer.daemon = True
self._cancel_position_timer.start()
- self.sendCommand("M114", tags=tags | {"trigger:comm.cancel",
- "trigger:record_position"})
+ 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)
@@ -1194,9 +1195,9 @@ class MachineCom(object):
if self.isSdFileSelected():
if not external_sd:
- self.sendCommand("M25", tags=tags | {"trigger:comm.cancel",}) # pause print
- self.sendCommand("M27", tags=tags | {"trigger:comm.cancel",}) # get current byte position in file
- self.sendCommand("M26 S0", tags=tags | {"trigger:comm.cancel",}) # reset position in file to byte 0
+ self.sendCommand("M25", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # pause print
+ self.sendCommand("M27", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # get current byte position in file
+ self.sendCommand("M26 S0", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # reset position in file to byte 0
if self._sd_status_timer is not None:
try:
self._sd_status_timer.cancel()
@@ -1205,9 +1206,10 @@ class MachineCom(object):
if self._log_position_on_cancel and not disable_log_position:
self.sendCommand("M400",
- on_sent=_on_M400_sent,
- tags=tags | {"trigger:comm.cancel",
- "trigger:record_position"})
+ on_sent=_on_M400_sent,
+ part_of_job=True,
+ tags=tags | {"trigger:comm.cancel",
+ "trigger:record_position"})
self._continue_sending()
else:
self._cancel_preparation_done(check_timer=False)
@@ -1237,7 +1239,7 @@ class MachineCom(object):
def finalize():
self._changeState(self.STATE_PAUSED)
- self.sendCommand(SendQueueMarker(finalize))
+ self.sendCommand(SendQueueMarker(finalize), part_of_job=True)
self._continue_sending()
def setPause(self, pause, local_handling=True, tags=None):
@@ -1258,26 +1260,19 @@ class MachineCom(object):
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)))
+ self.sendCommand(SendQueueMarker(lambda: self._changeState(self.STATE_PRINTING)), part_of_job=True)
if self.isSdFileSelected():
if local_handling:
- self.sendCommand("M24", tags=tags | {"trigger:comm.set_pause","trigger:resume"})
- self.sendCommand("M27", tags=tags | {"trigger:comm.set_pause", "trigger:resume"})
- else:
- line, pos, lineno = self._get_next_from_job()
- if line is not None:
- if not tags:
- tags = set()
- tags_to_use = tags | {"trigger:comm.set_pause",
- "trigger:resume",
- "source:file",
- "filepos:{}".format(pos),
- "fileline:{}".format(lineno)}
- self.sendCommand(line, tags=tags_to_use)
+ self.sendCommand("M24",
+ part_of_job=True,
+ tags=tags | {"trigger:comm.set_pause","trigger:resume"})
+ self.sendCommand("M27",
+ part_of_job=True,
+ tags=tags | {"trigger:comm.set_pause", "trigger:resume"})
# now make sure we actually do something, up until now we only filled up the queue
- self._send_from_command_queue()
+ self._continue_sending()
elif pause and self.isPrinting():
if not self._pauseWaitStartTime:
@@ -1285,7 +1280,9 @@ class MachineCom(object):
self._changeState(self.STATE_PAUSING)
if self.isSdFileSelected() and local_handling:
- self.sendCommand("M25", tags=tags | {"trigger:comm.set_pause", "trigger:pause"}) # pause print
+ self.sendCommand("M25",
+ part_of_job=True,
+ tags=tags | {"trigger:comm.set_pause", "trigger:pause"}) # pause print
if not local_handling:
with self._suppress_scripts_mutex:
@@ -1305,16 +1302,19 @@ class MachineCom(object):
self._pause_preparation_failed)
self._pause_position_timer.daemon = True
self._pause_position_timer.start()
- self.sendCommand("M114", tags=tags | {"trigger:comm.set_pause",
- "trigger:pause",
- "trigger:record_position"})
+ self.sendCommand("M114",
+ part_of_job=True,
+ tags=tags | {"trigger:comm.set_pause",
+ "trigger:pause",
+ "trigger:record_position"})
if self._log_position_on_pause:
self.sendCommand("M400",
- on_sent=_on_M400_sent,
- tags=tags | {"trigger:comm.set_pause",
- "trigger:pause",
- "trigger:record_position"})
+ on_sent=_on_M400_sent,
+ part_of_job=True,
+ tags=tags | {"trigger:comm.set_pause",
+ "trigger:pause",
+ "trigger:record_position"})
self._continue_sending()
else:
self._pause_preparation_done(check_timer=False, suppress_script=not local_handling)
@@ -1391,14 +1391,16 @@ class MachineCom(object):
self.sendCommand(self._hello_command, force=True, tags=tags | {"trigger:comm.say_hello",})
self._clear_to_send.set()
- def resetLineNumbers(self, number=0, tags=None):
+ def resetLineNumbers(self, number=0, part_of_job=False, tags=None):
if not self.isOperational():
return
if tags is None:
tags = set()
- self.sendCommand("M110 N%d" % number, tags=tags | {"trigger:comm.reset_line_numbers",})
+ self.sendCommand("M110 N{}".format(number),
+ part_of_job=part_of_job,
+ tags=tags | {"trigger:comm.reset_line_numbers",})
##~~ record aborted file positions
@@ -2187,7 +2189,7 @@ class MachineCom(object):
# job is on hold, that means we must not send from either script queue or file
return False
- elif self._send_from_script_queue():
+ elif self._send_from_job_queue():
# we found something in the script queue to send
return True
@@ -2595,7 +2597,7 @@ class MachineCom(object):
def _get_next_from_job(self):
if self._currentFile is None:
- return None
+ return None, None, None
line, pos, lineno = self._currentFile.getNext()
if line is None:
@@ -2603,6 +2605,7 @@ class MachineCom(object):
self._finishFileTransfer()
else:
self._changeState(self.STATE_FINISHING)
+ self.sendCommand("M400", part_of_job=True)
self._callback.on_comm_print_job_done()
def finalize():
self._changeState(self.STATE_OPERATIONAL)
@@ -2623,7 +2626,7 @@ class MachineCom(object):
line, pos, lineno = self._get_next_from_job()
if isinstance(line, QueueMarker):
- self.sendCommand(line)
+ self.sendCommand(line, part_of_job=True)
self._callback.on_comm_progress()
# end of file, return false so that the next round in continue_sending will process
@@ -2642,10 +2645,10 @@ class MachineCom(object):
self._logger.debug("Command \"{}\" from file not enqueued, doing another iteration".format(line))
- def _send_from_script_queue(self):
+ def _send_from_job_queue(self):
try:
- line, tags = self._script_queue.get_nowait()
- result = self._sendCommand(line, tags=tags)
+ line, cmd_type, on_sent, tags = self._job_queue.get_nowait()
+ result = self._sendCommand(line, cmd_type=cmd_type, on_sent=on_sent, tags=tags)
if result:
# line from script sent, return true
return True
@@ -3814,7 +3817,7 @@ class SpecialStreamingGcodeFileInformation(StreamingGcodeFileInformation):
return None
return line
-class ScriptQueue(PrependableQueue):
+class JobQueue(PrependableQueue):
pass
class CommandQueue(TypedQueue):
From 17c6c83503e4526762d0ef9f1cdff6023f0f1247 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 15 Jun 2018 17:02:53 +0200
Subject: [PATCH 010/656] Fix SD printing
---
.../plugins/virtual_printer/virtual.py | 2 +-
src/octoprint/printer/standard.py | 8 ++++--
src/octoprint/util/comm.py | 27 ++++++++++++-------
3 files changed, 25 insertions(+), 12 deletions(-)
diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py
index e1aa40202..e37785151 100644
--- a/src/octoprint/plugins/virtual_printer/virtual.py
+++ b/src/octoprint/plugins/virtual_printer/virtual.py
@@ -1158,10 +1158,10 @@ class VirtualPrinter(object):
def _finishSdPrint(self):
if not self._killed:
self._sdPrintingSemaphore.clear()
+ self._output("Done printing file")
self._selectedSdFilePos = 0
self._sdPrinting = False
self._sdPrinter = None
- self._output("Done printing file")
def _waitForHeatup(self, heater, only_wait_if_higher):
delta = 1
diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py
index 7de61daeb..c1355bbad 100644
--- a/src/octoprint/printer/standard.py
+++ b/src/octoprint/printer/standard.py
@@ -440,8 +440,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._validateJob(path, sd)
origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
- path_on_disk = self._fileManager.path_on_disk(origin, path)
- path_in_storage = self._fileManager.path_in_storage(origin, path_on_disk)
+ if sd:
+ path_on_disk = "/" + path
+ path_in_storage = path
+ else:
+ path_on_disk = self._fileManager.path_on_disk(origin, path)
+ path_in_storage = self._fileManager.path_in_storage(origin, path_on_disk)
recovery_data = self._fileManager.get_recovery_data()
if recovery_data:
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index bf347ad80..e595d5746 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -1011,9 +1011,15 @@ class MachineCom(object):
self._callback.on_comm_print_job_started()
if self.isSdFileSelected():
+ interval = self._timeout_intervals.get("sdStatus", 1.0)
+ if interval <= 0:
+ interval = 1.0
+ self._sd_status_timer = RepeatedTimer(interval, self._poll_sd_status, run_first=True)
+
if not external_sd:
# make sure to ignore the "file selected" later on, otherwise we'll reset our progress data
self._ignore_select = True
+
self.sendCommand("M23 {filename}".format(filename=self._currentFile.getFilename()),
part_of_job=True,
tags=tags | {"trigger:comm.start_print",})
@@ -1025,15 +1031,15 @@ class MachineCom(object):
else:
self._currentFile.pos = 0
+ def start_polling():
+ self._sd_status_timer.start()
+
self.sendCommand("M24",
+ on_sent=start_polling,
part_of_job=True,
tags=tags | {"trigger:comm.start_print",})
-
- interval = self._timeout_intervals.get("sdStatus", 1.0)
- if interval <= 0:
- interval = 1.0
- self._sd_status_timer = RepeatedTimer(interval, self._poll_sd_status, run_first=True)
- self._sd_status_timer.start()
+ else:
+ self._sd_status_timer.start()
else:
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.seek(pos)
@@ -1890,7 +1896,7 @@ class MachineCom(object):
self._currentFile.size = total
self._callback.on_comm_progress()
- elif 'Not SD printing' in line and self.isSdFileSelected() and self.isPrinting():
+ 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)
elif 'File opened' in line and not self._ignore_select:
@@ -1933,6 +1939,8 @@ class MachineCom(object):
self._changeState(self.STATE_PRINTING)
elif 'Done printing file' in line and self.isSdPrinting():
# printer is reporting file finished printing
+ self._changeState(self.STATE_FINISHING)
+
self._currentFile.done = True
self._currentFile.pos = 0
@@ -1942,11 +1950,12 @@ class MachineCom(object):
except:
pass
- self._changeState(self.STATE_FINISHING)
+ self.sendCommand("M400", part_of_job=True)
self._callback.on_comm_print_job_done()
def finalize():
self._changeState(self.STATE_OPERATIONAL)
- self.sendCommand(SendQueueMarker(finalize))
+ self.sendCommand(SendQueueMarker(finalize), part_of_job=True)
+ self._continue_sending()
elif 'Done saving file' in line:
if self._trigger_ok_for_m29:
# workaround for most versions of Marlin out in the wild
From fe2dbf699d15985a008442bc1b635f603f3a76fe Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 15 Jun 2018 18:15:13 +0200
Subject: [PATCH 011/656] SWU: Lock down UI while updating
Implements #1217
---
.../plugins/softwareupdate/static/js/softwareupdate.js | 4 +---
.../softwareupdate/templates/softwareupdate_settings.jinja2 | 4 +++-
src/octoprint/static/js/app/viewmodels/printerstate.js | 2 +-
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
index 6a1192f43..d0484a5b8 100644
--- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
+++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
@@ -399,8 +399,6 @@ $(function() {
};
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
- if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
-
self.checking(true);
OctoPrint.plugins.softwareupdate.check(force)
.done(function(data) {
@@ -590,7 +588,7 @@ $(function() {
};
self._showWorkingDialog = function(title) {
- if (!self.loginState.isAdmin()) {
+ if (!self.loginState.isAdmin() && !self.loginState.isUser()) {
return;
}
diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2
index 68b61d78a..106d64bc5 100644
--- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2
+++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2
@@ -111,7 +111,9 @@
-
+
+
{{ _('Update in progress, please wait.') }}
+
{{ _('Update done, please close this window.') }}
+
+
+
+
+
+
diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py
index 07a44eb81..581051299 100644
--- a/src/octoprint/util/__init__.py
+++ b/src/octoprint/util/__init__.py
@@ -1302,7 +1302,7 @@ class CountedEvent(object):
self._event.wait(timeout)
def blocked(self):
- return self.counter == 0
+ return self.counter <= 0
def acquire(self, blocking=1):
return self._mutex.acquire(blocking=blocking)
@@ -1313,7 +1313,6 @@ class CountedEvent(object):
def _internal_set(self, value):
self._counter = value
if self._counter <= 0:
- self._counter = 0
self._event.clear()
else:
if self._max is not None and self._counter > self._max:
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index f8fa1c02f..5b6f23f0f 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -351,6 +351,7 @@ class MachineCom(object):
CAPABILITY_AUTOREPORT_TEMP = "AUTOREPORT_TEMP"
CAPABILITY_AUTOREPORT_SD_STATUS = "AUTOREPORT_SD_STATUS"
CAPABILITY_BUSY_PROTOCOL = "BUSY_PROTOCOL"
+ CAPABILITY_EMERGENCY_PARSER = "EMERGENCY_PARSER"
CAPABILITY_SUPPORT_ENABLED = "enabled"
CAPABILITY_SUPPORT_DETECTED = "detected"
@@ -438,7 +439,8 @@ class MachineCom(object):
self._capability_support = {
self.CAPABILITY_AUTOREPORT_TEMP: settings().getBoolean(["serial", "capabilities", "autoreport_temp"]),
self.CAPABILITY_AUTOREPORT_SD_STATUS: settings().getBoolean(["serial", "capabilities", "autoreport_sdstatus"]),
- self.CAPABILITY_BUSY_PROTOCOL: settings().getBoolean(["serial", "capabilities", "busy_protocol"])
+ self.CAPABILITY_BUSY_PROTOCOL: settings().getBoolean(["serial", "capabilities", "busy_protocol"]),
+ self.CAPABILITY_EMERGENCY_PARSER: settings().getBoolean(["serial", "capabilities", "emergency_parser"])
}
self._lastLines = deque([], 50)
@@ -477,7 +479,7 @@ class MachineCom(object):
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
- self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
+ self._clear_to_send = CountedEvent(name="comm.clear_to_send")
self._send_queue = SendQueue()
self._temperature_timer = None
self._sd_status_timer = None
@@ -541,6 +543,7 @@ class MachineCom(object):
self._log_position_on_pause = settings().getBoolean(["serial", "logPositionOnPause"])
self._log_position_on_cancel = settings().getBoolean(["serial", "logPositionOnCancel"])
+ self._abort_heatup_on_cancel = settings().getBoolean(["serial", "abortHeatupOnCancel"])
# print job
self._currentFile = None
@@ -1197,6 +1200,13 @@ class MachineCom(object):
with self._jobLock:
self._changeState(self.STATE_CANCELLING)
+ if self._abort_heatup_on_cancel:
+ # abort any ongoing heatups immediately to get back control over the printer
+ self.sendCommand("M108",
+ part_of_job=False,
+ tags=tags | {"trigger:comm.cancel", "trigger:abort_heatup"},
+ force=True)
+
if self.isSdFileSelected():
if not external_sd:
self.sendCommand("M25", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # pause print
@@ -1825,6 +1835,8 @@ class MachineCom(object):
elif capability == self.CAPABILITY_AUTOREPORT_SD_STATUS and enabled:
self._logger.info("Firmware states that it supports sd status autoreporting")
self._set_autoreport_sdstatus_interval()
+ elif capability == self.CAPABILITY_EMERGENCY_PARSER and enabled:
+ self._logger.info("Firmware states that it supports emergency GCODEs M108 and M410 to be sent without waiting for an acknowledgement first")
# notify plugins
for name, hook in self._firmware_info_hooks["capabilities"].items():
@@ -2982,17 +2994,7 @@ class MachineCom(object):
continue
# now comes the part where we increase line numbers and send stuff - no turning back now
- command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands
- command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands
- checksum_enabled = not self._neverSendChecksum and ((self.isPrinting() and self._currentFile and self._currentFile.checksum) or
- self._alwaysSendChecksum or
- not self._firmware_info_received)
-
- command_to_send = command.encode("ascii", errors="replace")
- if command_requiring_checksum or (command_allowing_checksum and checksum_enabled):
- self._do_increment_and_send_with_checksum(command_to_send)
- else:
- self._do_send_without_checksum(command_to_send)
+ self._do_send(command, gcode=gcode)
# trigger "sent" phase and use up one "ok"
if on_sent is not None and callable(on_sent):
@@ -3152,6 +3154,24 @@ class MachineCom(object):
##~~ actual sending via serial
+ def _needs_checksum(self, gcode=None):
+ command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands
+ command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands
+ return command_requiring_checksum or (command_allowing_checksum and self._checksum_enabled)
+
+ @property
+ def _checksum_enabled(self):
+ return not self._neverSendChecksum and ((self.isPrinting() and self._currentFile and self._currentFile.checksum) or
+ self._alwaysSendChecksum or
+ not self._firmware_info_received)
+
+ def _do_send(self, command, gcode=None):
+ command_to_send = command.encode("ascii", errors="replace")
+ if self._needs_checksum(gcode):
+ self._do_increment_and_send_with_checksum(command_to_send)
+ else:
+ self._do_send_without_checksum(command_to_send)
+
def _do_increment_and_send_with_checksum(self, cmd):
with self._line_mutex:
linenumber = self._currentLine
@@ -3420,7 +3440,12 @@ class MachineCom(object):
self._resendDelta = None
def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
- # emergency stop, jump the queue with the M112
+ self._logger.info("Force-sending M112 to the printer")
+
+ # emergency stop, jump the queue with the M112, regardless of whether the EMERGENCY_PARSER capability is
+ # available or not
+ #
+ # send the M112 once without and with checksum
self._do_send_without_checksum("M112")
self._do_increment_and_send_with_checksum("M112")
@@ -3448,6 +3473,32 @@ class MachineCom(object):
# I hope it got it the first time because as far as I can tell, there is no way to know
return None,
+ def _gcode_M108_queuing(self, cmd, gcode=None, *args, **kwargs):
+ # only jump the queue with M108 if the EMERGENCY_PARSER capability is available
+ if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False):
+ return
+
+ self._logger.info("Force-sending M108 to the printer")
+ self._do_send(cmd, gcode=gcode)
+
+ # use up an ok since we will get one back for this command and don't want to get out of sync
+ self._clear_to_send.clear()
+
+ return None,
+
+ def _gcode_M410_queuing(self, cmd, gcode=None, *args, **kwargs):
+ # only jump the queue with M410 if the EMERGENCY_PARSER capability is available
+ if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False):
+ return
+
+ self._logger.info("Force-sending M410 to the printer")
+ self._do_send(cmd, gcode=gcode)
+
+ # use up an ok since we will get one back for this command and don't want to get out of sync
+ self._clear_to_send.clear()
+
+ return None,
+
def _gcode_M114_queued(self, *args, **kwargs):
self._reset_position_timers()
_gcode_M114_sent = _gcode_M114_queued
From 5ff790048dcb931723f67d463c7f5cbf503f780b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 26 Sep 2018 15:52:10 +0200
Subject: [PATCH 211/656] Fix unit tests
---
src/octoprint/util/__init__.py | 5 ++++-
src/octoprint/util/comm.py | 2 +-
tests/util/test_counted_event.py | 18 ++++++++++++++++++
3 files changed, 23 insertions(+), 2 deletions(-)
diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py
index 581051299..b23681bc4 100644
--- a/src/octoprint/util/__init__.py
+++ b/src/octoprint/util/__init__.py
@@ -1270,8 +1270,9 @@ class ResettableTimer(threading.Thread):
class CountedEvent(object):
- def __init__(self, value=0, maximum=None, **kwargs):
+ def __init__(self, value=0, minimum=0, maximum=None, **kwargs):
self._counter = 0
+ self._min = minimum
self._max = kwargs.get("max", maximum)
self._mutex = threading.RLock()
self._event = threading.Event()
@@ -1313,6 +1314,8 @@ class CountedEvent(object):
def _internal_set(self, value):
self._counter = value
if self._counter <= 0:
+ if self._min is not None and self._counter < self._min:
+ self._counter = self._min
self._event.clear()
else:
if self._max is not None and self._counter > self._max:
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index 5b6f23f0f..f83290daf 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -479,7 +479,7 @@ class MachineCom(object):
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
- self._clear_to_send = CountedEvent(name="comm.clear_to_send")
+ self._clear_to_send = CountedEvent(name="comm.clear_to_send", minimum=None)
self._send_queue = SendQueue()
self._temperature_timer = None
self._sd_status_timer = None
diff --git a/tests/util/test_counted_event.py b/tests/util/test_counted_event.py
index 87c2f7baa..703e9078d 100644
--- a/tests/util/test_counted_event.py
+++ b/tests/util/test_counted_event.py
@@ -88,6 +88,24 @@ class CountedEventTest(unittest.TestCase):
self.assertEqual(0, event._counter)
self.assertFalse(event._event.is_set())
+ def test_clear_more_than_available_without_minimum(self):
+ """The counter may sink below zero if initialized without a minimum."""
+
+ event = CountedEvent(1, minimum=None)
+
+ self.assertEqual(1, event._counter)
+ self.assertTrue(event._event.is_set())
+
+ event.clear()
+
+ self.assertEqual(0, event._counter)
+ self.assertFalse(event._event.is_set())
+
+ event.clear()
+
+ self.assertEqual(-1, event._counter)
+ self.assertFalse(event._event.is_set())
+
def test_blocked(self):
"""Blocked should only be true if the counter is 0."""
From cb9bedb6a017383cb52e66a8f2a387f7b129ba6c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Thu, 27 Sep 2018 18:43:46 +0200
Subject: [PATCH 212/656] Add hooks to control sockjs registrations and
messages
---
src/octoprint/server/util/sockjs.py | 124 +++++++++++++-----
src/octoprint/static/js/app/client/socket.js | 4 +
src/octoprint/static/js/app/dataupdater.js | 9 +-
.../static/js/app/viewmodels/loginstate.js | 12 ++
src/octoprint/users.py | 5 +
5 files changed, 123 insertions(+), 31 deletions(-)
diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py
index 7debafa0e..656c32613 100644
--- a/src/octoprint/server/util/sockjs.py
+++ b/src/octoprint/server/util/sockjs.py
@@ -88,11 +88,17 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self._pluginManager = pluginManager
self._remoteAddress = None
+ self._user = None
self._throttleFactor = 1
self._lastCurrent = 0
self._baseRateLimit = 0.5
+ self._register_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.register")
+ self._emit_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.emit")
+
+ self._registered = False
+
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
if forwardedFor is not None:
@@ -132,39 +138,14 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
safe_mode=octoprint.server.safe_mode
))
- self._printer.register_callback(self)
- self._fileManager.register_slicingprogress_callback(self)
- octoprint.timelapse.register_callback(self)
- self._pluginManager.register_message_receiver(self.on_plugin_message)
-
- self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
- for event in octoprint.events.all_events():
- self._eventManager.subscribe(event, self._onEvent)
-
- octoprint.timelapse.notify_callbacks(octoprint.timelapse.current)
-
- # This is a horrible hack for now to allow displaying a notification that a render job is still
- # active in the backend on a fresh connect of a client. This needs to be substituted with a proper
- # job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints
- # start and so on.
- #
- # For now this is the easiest way though to at least inform the user that a timelapse is still ongoing.
- #
- # TODO remove when central job management becomes available and takes care of this for us
- if octoprint.timelapse.current_render_job is not None:
- self._emit("event", {"type": Events.MOVIE_RENDERING, "payload": octoprint.timelapse.current_render_job})
+ self._register()
def on_close(self):
- self._printer.unregister_callback(self)
- self._fileManager.unregister_slicingprogress_callback(self)
- octoprint.timelapse.unregister_callback(self)
- self._pluginManager.unregister_message_receiver(self.on_plugin_message)
-
- self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
- for event in octoprint.events.all_events():
- self._eventManager.unsubscribe(event, self._onEvent)
+ self._unregister()
self._logger.info("Client connection closed: %s" % self._remoteAddress)
+
+ self._user = None
self._remoteAddress = None
def on_message(self, message):
@@ -175,7 +156,29 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self._logger.warn("Invalid JSON received from client {}, ignoring: {!r}".format(self._remoteAddress, message))
return
- if "throttle" in message:
+ if "auth" in message:
+ try:
+ parts = message["auth"].split(":")
+ if not len(parts) == 2:
+ raise ValueError()
+ except ValueError:
+ self._logger.warn("Got invalid auth message from client {}, ignoring: {!r]".format(self._remoteAddress,
+ message["auth"]))
+ else:
+ user_id, user_session = parts
+ user = self._userManager.findUser(userid=user_id, session=user_session)
+
+ if user is not None:
+ self._user = user
+ self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(),
+ self._remoteAddress))
+ else:
+ self._user = None
+ self._logger.warn("Unknown user/session combo: {}:{}".format(user_id, user_session))
+
+ self._register()
+
+ elif "throttle" in message:
try:
throttle = int(message["throttle"])
if throttle < 1:
@@ -257,6 +260,16 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self.sendEvent(event, payload)
def _emit(self, type, payload):
+ proceed = True
+ for name, hook in self._emit_hooks.items():
+ try:
+ proceed = proceed and hook(self, self._user, type, payload)
+ except:
+ self._logger.exception("Error processing emit hook handler from plugin {}".format(name))
+
+ if not proceed:
+ return
+
try:
self.send({type: payload})
except Exception as e:
@@ -264,3 +277,54 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
else:
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
+
+ def _register(self):
+ proceed = True
+ for name, hook in self._register_hooks.items():
+ try:
+ proceed = proceed and hook(self, self._user)
+ except:
+ self._logger.exception("Error processing register hook handler for plugin {}".format(name))
+
+ if not proceed:
+ return
+
+ if self._registered:
+ return
+
+ self._printer.register_callback(self)
+ self._fileManager.register_slicingprogress_callback(self)
+ octoprint.timelapse.register_callback(self)
+ self._pluginManager.register_message_receiver(self.on_plugin_message)
+
+ self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
+ for event in octoprint.events.all_events():
+ self._eventManager.subscribe(event, self._onEvent)
+
+ octoprint.timelapse.notify_callbacks(octoprint.timelapse.current)
+
+ # This is a horrible hack for now to allow displaying a notification that a render job is still
+ # active in the backend on a fresh connect of a client. This needs to be substituted with a proper
+ # job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints
+ # start and so on.
+ #
+ # For now this is the easiest way though to at least inform the user that a timelapse is still ongoing.
+ #
+ # TODO remove when central job management becomes available and takes care of this for us
+ if octoprint.timelapse.current_render_job is not None:
+ self._emit("event", {"type": Events.MOVIE_RENDERING, "payload": octoprint.timelapse.current_render_job})
+
+ self._registered = True
+
+ def _unregister(self):
+ self._printer.unregister_callback(self)
+ self._fileManager.unregister_slicingprogress_callback(self)
+ octoprint.timelapse.unregister_callback(self)
+ self._pluginManager.unregister_message_receiver(self.on_plugin_message)
+
+ self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
+ for event in octoprint.events.all_events():
+ self._eventManager.unsubscribe(event, self._onEvent)
+
+ self._registered = False
+
diff --git a/src/octoprint/static/js/app/client/socket.js b/src/octoprint/static/js/app/client/socket.js
index b1d70b7a4..9562ed017 100644
--- a/src/octoprint/static/js/app/client/socket.js
+++ b/src/octoprint/static/js/app/client/socket.js
@@ -85,6 +85,10 @@
this.sendMessage("throttle", this.rateThrottleFactor);
};
+ OctoPrintSocketClient.prototype.sendAuth = function(userId, session) {
+ this.sendMessage("auth", userId + ":" + session);
+ };
+
OctoPrintSocketClient.prototype.sendMessage = function(type, payload) {
var data = {};
data[type] = payload;
diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js
index e33367740..098eb0aa7 100644
--- a/src/octoprint/static/js/app/dataupdater.js
+++ b/src/octoprint/static/js/app/dataupdater.js
@@ -342,6 +342,12 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
})
};
+ self._onReauthMessage = function(event) {
+ self._ifInitialized(function() {
+ callViewModels(self.allViewModels, "onDataUpdaterReauthRequired", [event.data.reason]);
+ })
+ };
+
self._onIncreaseRate = function(measurement, minimum) {
log.debug("We are fast (" + measurement + " < " + minimum + "), increasing refresh rate");
OctoPrint.socket.increaseRate();
@@ -372,5 +378,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
.onMessage("slicingProgress", self._onSlicingProgress)
.onMessage("event", self._onEvent)
.onMessage("timelapse", self._onTimelapse)
- .onMessage("plugin", self._onPluginMessage);
+ .onMessage("plugin", self._onPluginMessage)
+ .onMessage("reauthRequired", self._onReauthMessage);
}
diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js
index e4d0fd98a..c67273c2a 100644
--- a/src/octoprint/static/js/app/viewmodels/loginstate.js
+++ b/src/octoprint/static/js/app/viewmodels/loginstate.js
@@ -61,6 +61,10 @@ $(function() {
log.info("User " + response.name + " logged in")
}
+ if (response.session) {
+ OctoPrint.socket.sendAuth(response.name, response.session);
+ }
+
// Show warning if connecting from what seems to be an external IP address, unless ignored
var ignorePublicAddressWarning = localStorage["loginState.ignorePublicAddressWarning"];
if (ignorePublicAddressWarning === undefined) {
@@ -202,6 +206,14 @@ $(function() {
self.login();
};
+ self.onDataUpdaterReauthRequired = function(reason) {
+ if (reason === "logout" || reason === "removed") {
+ self.logout();
+ } else {
+ self.requestData();
+ }
+ };
+
self.onAllBound = function(allViewModels) {
self.allViewModels = allViewModels;
self.startupDeferred.resolve();
diff --git a/src/octoprint/users.py b/src/octoprint/users.py
index 30b7f1f46..e47df6d66 100644
--- a/src/octoprint/users.py
+++ b/src/octoprint/users.py
@@ -518,6 +518,11 @@ class SessionUser(wrapt.ObjectProxy):
self._self_session = "".join(random.choice(chars) for _ in range(10))
self._self_created = time.time()
+ def asDict(self):
+ result = self.__wrapped__.asDict()
+ result.update(dict(session=self.session))
+ return result
+
@property
def session(self):
return self._self_session
From 6bc5b8a7a93f210b59eec90857cc062723bb87a0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Thu, 27 Sep 2018 18:44:03 +0200
Subject: [PATCH 213/656] Forcelogin: lock down sockjs socket as well
---
src/octoprint/plugins/forcelogin/__init__.py | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)
diff --git a/src/octoprint/plugins/forcelogin/__init__.py b/src/octoprint/plugins/forcelogin/__init__.py
index dc11bc6dd..cdf7c9e50 100644
--- a/src/octoprint/plugins/forcelogin/__init__.py
+++ b/src/octoprint/plugins/forcelogin/__init__.py
@@ -80,6 +80,15 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
if user is None or not user.is_authenticated():
raise tornado.web.HTTPError(403)
+ def socket_register_validator(self, socket, user):
+ return user is not None and not user.is_anonymous() and user.is_active()
+
+ def socket_emit_validator(self, socket, user, message, payload):
+ if message in ("connected", "reauthRequired"):
+ return True
+
+ return user is not None and not user.is_anonymous() and user.is_active()
+
__plugin_name__ = "Force Login"
__plugin_author__ = "Gina Häußge"
@@ -92,5 +101,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users
__plugin_implementation__ = ForceLoginPlugin()
__plugin_hooks__ = {
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
- "octoprint.server.http.access_validator": __plugin_implementation__.access_validator
+ "octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
+ "octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
+ "octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
}
From a9f76dd1a3fccd01592a4287b9dfdbb4730e185c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Thu, 27 Sep 2018 18:47:00 +0200
Subject: [PATCH 214/656] Forcelogin: allow socket when ACL isn't setup yet
---
src/octoprint/plugins/forcelogin/__init__.py | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/src/octoprint/plugins/forcelogin/__init__.py b/src/octoprint/plugins/forcelogin/__init__.py
index cdf7c9e50..1640b8ead 100644
--- a/src/octoprint/plugins/forcelogin/__init__.py
+++ b/src/octoprint/plugins/forcelogin/__init__.py
@@ -81,9 +81,17 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
raise tornado.web.HTTPError(403)
def socket_register_validator(self, socket, user):
+ if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
+ # ACL hasn't been configured yet, make an exception
+ return True
+
return user is not None and not user.is_anonymous() and user.is_active()
def socket_emit_validator(self, socket, user, message, payload):
+ if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
+ # ACL hasn't been configured yet, make an exception
+ return True
+
if message in ("connected", "reauthRequired"):
return True
From e53ae8cd56b8f263bdcfa84bc7b2a0ba1e61a4d9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 28 Sep 2018 17:15:37 +0200
Subject: [PATCH 215/656] Forcelogin: Access to settings isn't needed either
---
src/octoprint/plugins/forcelogin/__init__.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/plugins/forcelogin/__init__.py b/src/octoprint/plugins/forcelogin/__init__.py
index 1640b8ead..70768486f 100644
--- a/src/octoprint/plugins/forcelogin/__init__.py
+++ b/src/octoprint/plugins/forcelogin/__init__.py
@@ -59,7 +59,7 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
# ACL hasn't been configured yet, make an exception
return
- if flask.request.endpoint in ("api.login", "api.getSettings"):
+ if flask.request.endpoint in ("api.login",):
return
user = flask_login.current_user
From fed257b5d8069c72d21e7392e7fa7b69109b8095 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 28 Sep 2018 17:19:31 +0200
Subject: [PATCH 216/656] Forcelogin: Fix spinner
---
.../plugins/forcelogin/templates/forcelogin_index.jinja2 | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
index 7ccc0432e..3b8b36ce4 100644
--- a/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
+++ b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
@@ -29,7 +29,7 @@
-
+
From 87e7a19fdda3a7648fee0e7a95873c9cf6f4bab0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 28 Sep 2018 17:57:05 +0200
Subject: [PATCH 217/656] Forcelogin: Support theming via custom hook
---
src/octoprint/plugins/forcelogin/__init__.py | 27 +++++++++++++++++++
.../templates/parts/forcelogin_css.jinja2 | 4 +++
2 files changed, 31 insertions(+)
diff --git a/src/octoprint/plugins/forcelogin/__init__.py b/src/octoprint/plugins/forcelogin/__init__.py
index 70768486f..1c5ce3f6b 100644
--- a/src/octoprint/plugins/forcelogin/__init__.py
+++ b/src/octoprint/plugins/forcelogin/__init__.py
@@ -35,6 +35,33 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin,
def on_ui_render(self, now, request, render_kwargs):
from flask import render_template, make_response
+
+ """
+ Support theming of the login dialog, just in case the core UI is themed as well.
+
+ Example usage by a plugin:
+
+ def forcelogin_theming():
+ from flask import url_for
+ return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")]
+
+ __plugin_hooks__ = {
+ "octoprint.plugin.forcelogin.theming": forcelogin_theming
+ }
+
+ Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
+ url_for like in the example above to be prepared for any configured prefix URLs.
+ """
+ additional_assets = []
+ for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items():
+ try:
+ assets = hook()
+ if isinstance(assets, (tuple, list)):
+ additional_assets += assets
+ except:
+ self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name))
+
+ render_kwargs.update(dict(forcelogin_theming=additional_assets))
return make_response(render_template("forcelogin_index.jinja2", **render_kwargs))
def get_ui_custom_tracked_files(self):
diff --git a/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_css.jinja2 b/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_css.jinja2
index db4f97d87..f0df93c78 100644
--- a/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_css.jinja2
+++ b/src/octoprint/plugins/forcelogin/templates/parts/forcelogin_css.jinja2
@@ -4,3 +4,7 @@
+
+{% for url in forcelogin_theming %}
+
+{% endfor %}
From b054ec47adb7201877c2f99446b1b9499e2bf6ab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Sat, 29 Sep 2018 13:28:09 +0200
Subject: [PATCH 218/656] Special handling for fatal errors
If the firmware locks up it doesn't make sense to stay connected to
it even if we are supposed to only cancel an ongoing print.
---
src/octoprint/util/comm.py | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index f83290daf..9492b0e18 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -2507,6 +2507,9 @@ class MachineCom(object):
"cannot open",
"open failed",
"cannot enter")
+ _fatal_errors = ("system stopped",
+ "kill() called",
+ "fatal:")
def _handle_errors(self, line):
if line is None:
return
@@ -2554,11 +2557,12 @@ class MachineCom(object):
level=logging.WARN)
if not self._ignore_errors:
- if self._disconnect_on_errors:
+ if self._disconnect_on_errors or any(map(lambda x: x in lower_line, self._fatal_errors)):
self._trigger_error(stripped_error, "firmware")
elif self.isPrinting():
self.cancelPrint(firmware_error=stripped_error)
self._clear_to_send.set()
+
else:
self._log("WARNING! Received an error from the printer's firmware, ignoring that as configured "
"but you might want to investigate what happened here! Error: {}".format(stripped_error))
From fc97d0b4240ac9354602bcf888725cca1e96d856 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Sat, 29 Sep 2018 14:38:35 +0200
Subject: [PATCH 219/656] Virtual: simulate some fatal errors
---
src/octoprint/plugins/virtual_printer/virtual.py | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py
index 6ece08e91..bed0a65b7 100644
--- a/src/octoprint/plugins/virtual_printer/virtual.py
+++ b/src/octoprint/plugins/virtual_printer/virtual.py
@@ -732,6 +732,10 @@ class VirtualPrinter(object):
| Triggers a resend error with a missing checksum
trigger_missing_lineno
| Triggers a "no line number with checksum" error w/o resend request
+ trigger_fatal_error_marlin
+ | Triggers a fatal error/simulated heater fail, Marlin style
+ trigger_fatal_error_repetier
+ | Triggers a fatal error/simulated heater fail, Repetier style
drop_connection
| Drops the serial connection
prepare_ok
@@ -782,6 +786,11 @@ class VirtualPrinter(object):
self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, checksum=False))
elif data == "trigger_missing_lineno":
self._prepared_errors.append(lambda cur, last, line: self._send(self._error("lineno_missing", last)))
+ elif data == "trigger_fatal_error_marlin":
+ self._send("Error:Thermal Runaway, system stopped! Heater_ID: bed")
+ self._send("Error:Printer halted. kill() called!")
+ elif data == "trigger_fatal_error_repetier":
+ self._send("fatal: Heater/sensor error - Printer stopped and heaters disabled due to this error. Fix error and restart with M999.")
elif data == "drop_connection":
self._debug_drop_connection = True
elif data == "reset":
From bbbe85f737804b83fa771aeb595895dc73365a7c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Sat, 29 Sep 2018 14:38:54 +0200
Subject: [PATCH 220/656] Multiline fatal error parsing for Marlin
---
src/octoprint/util/comm.py | 13 +++++++++++--
1 file changed, 11 insertions(+), 2 deletions(-)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index 9492b0e18..c8cd4a2ee 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -76,6 +76,9 @@ regexes_parameters = dict(
regex_minMaxError = re.compile("Error:[0-9]\n")
"""Regex matching first line of min/max errors from the firmware."""
+regex_marlinKillError = re.compile("Heating failed|Thermal Runaway|MAXTEMP triggered|MINTEMP triggered|Invalid extruder number|Watchdog barked|KILL caused")
+"""Regex matching first line of kill causing errors from Marlin."""
+
regex_sdPrintingByte = re.compile("(?P[0-9]*)/(?P[0-9]*)")
"""Regex matching SD printing status reports.
@@ -2507,8 +2510,7 @@ class MachineCom(object):
"cannot open",
"open failed",
"cannot enter")
- _fatal_errors = ("system stopped",
- "kill() called",
+ _fatal_errors = ("kill() called",
"fatal:")
def _handle_errors(self, line):
if line is None:
@@ -2521,6 +2523,13 @@ class MachineCom(object):
# special delivery for firmware that goes "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
line = line.rstrip() + self._readline()
lower_line = line.lower()
+ elif regex_marlinKillError.search(line):
+ # special delivery for marlin kill errors that are split across multiple error lines
+ next_line = self._readline().strip()
+ if next_line.lower().startswith("error:"):
+ next_line = next_line[6:].strip()
+ line = line.rstrip() + " - " + next_line
+ lower_line = line.lower()
stripped_error = (line[6:] if lower_line.startswith("error:") else line[2:]).strip()
From f88147003c0cc4ae93e18aa3bc2d775d27349a57 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Sat, 29 Sep 2018 14:54:08 +0200
Subject: [PATCH 221/656] Repetier firmware reports fatal errors with another
prefix
---
src/octoprint/util/comm.py | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index c8cd4a2ee..bee3e0837 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -2518,6 +2518,11 @@ class MachineCom(object):
lower_line = line.lower()
+ if lower_line.startswith("fatal:"):
+ # hello Repetier firmware -_-
+ line = "Error:" + line
+ lower_line = line.lower()
+
if lower_line.startswith('error:') or line.startswith('!!'):
if regex_minMaxError.match(line):
# special delivery for firmware that goes "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
From 4e3adcc3f3ca92005643d2d365f5195764d61d14 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 24 Aug 2018 11:58:56 +0200
Subject: [PATCH 222/656] Add no_firstrun_access decorator
---
src/octoprint/server/util/flask.py | 24 +++++++++++++++++++-----
1 file changed, 19 insertions(+), 5 deletions(-)
diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py
index 567291bbd..1befcb36b 100644
--- a/src/octoprint/server/util/flask.py
+++ b/src/octoprint/server/util/flask.py
@@ -1146,11 +1146,7 @@ def restricted_access(func):
"""
@functools.wraps(func)
def decorated_view(*args, **kwargs):
- # if OctoPrint hasn't been set up yet, abort
- if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
- return flask.make_response("OctoPrint isn't setup yet", 403)
-
- return flask_login.login_required(func)(*args, **kwargs)
+ return flask_login.login_required(no_firstrun_access(func))(*args, **kwargs)
return decorated_view
@@ -1172,6 +1168,24 @@ def firstrun_only_access(func):
return decorated_view
+def no_firstrun_access(func):
+ """
+ If you decorate a view with this, it will ensure that first setup as been done for
+ OctoPrint's Access Control. Otherwise it
+ will cause a HTTP 403 status code to be returned by the decorated resource.
+ """
+
+ @functools.wraps(func)
+ def decorated_view(*args, **kwargs):
+ # if OctoPrint hasn't been set up yet, abort
+ if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and \
+ (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
+ return flask.make_response("OctoPrint isn't setup yet", 403)
+ return func(*args, **kwargs)
+
+ return decorated_view
+
+
class AppSessionManager(object):
VALIDITY_UNVERIFIED = 1 * 60 # 1 minute
From b428faacc8d30082f897c3905def0788b1345b9a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 24 Aug 2018 11:59:23 +0200
Subject: [PATCH 223/656] Appauth plugin: WIP
---
src/octoprint/plugins/appauth/__init__.py | 269 ++++++++++++++++++
.../plugins/appauth/static/js/appauth.js | 169 +++++++++++
.../templates/appauth_usersettings.jinja2 | 42 +++
3 files changed, 480 insertions(+)
create mode 100644 src/octoprint/plugins/appauth/__init__.py
create mode 100644 src/octoprint/plugins/appauth/static/js/appauth.js
create mode 100644 src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2
diff --git a/src/octoprint/plugins/appauth/__init__.py b/src/octoprint/plugins/appauth/__init__.py
new file mode 100644
index 000000000..08d0bcf6b
--- /dev/null
+++ b/src/octoprint/plugins/appauth/__init__.py
@@ -0,0 +1,269 @@
+# coding=utf-8
+from __future__ import absolute_import
+
+import flask
+import threading
+import os
+from binascii import hexlify
+from collections import defaultdict
+
+import octoprint.plugin
+from octoprint.settings import valid_boolean_trues
+from octoprint.server.util.flask import restricted_access, no_firstrun_access
+from octoprint.server import NO_CONTENT, current_user, user_permission
+
+
+class AppAlreadyExists(Exception):
+ pass
+
+
+class PendingDecision(object):
+ def __init__(self, app_id, app_token, user_id, user_token):
+ self.app_id = app_id
+ self.app_token = app_token
+ self.user_id = user_id
+ self.user_token = user_token
+
+ def external(self):
+ return dict(app_id=self.app_id,
+ user_id=self.user_id,
+ user_token=self.user_token)
+
+
+class ReadyDecision(object):
+ def __init__(self, app_id, app_token, user_id, api_key):
+ self.app_id = app_id
+ self.app_token = app_token
+ self.user_id = user_id
+ self.api_key = api_key
+
+ @classmethod
+ def for_pending(cls, pending, api_key):
+ return cls(pending.app_id, pending.app_token, pending.user_id, api_key)
+
+
+class ActiveKey(object):
+ def __init__(self, app_id, api_key):
+ self.app_id = app_id
+ self.api_key = api_key
+
+ def external(self):
+ return dict(app_id=self.app_id,
+ api_key=self.api_key)
+
+
+class AppAuthPlugin(octoprint.plugin.AssetPlugin,
+ octoprint.plugin.BlueprintPlugin,
+ octoprint.plugin.SimpleApiPlugin,
+ octoprint.plugin.TemplatePlugin):
+
+ def __init__(self):
+ self._pending_decisions = []
+ self._pending_lock = threading.RLock()
+
+ self._ready_decisions = []
+ self._ready_lock = threading.RLock()
+
+ self._keys = defaultdict(list)
+ self._keys_lock = threading.RLock()
+
+ ##-- AssetPlugin hooks
+
+ def get_assets(self):
+ return dict(js=["js/appauth.js"])
+
+ ##~~ BlueprintPlugin mixin
+
+ @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
+ @no_firstrun_access
+ def handle_request(self):
+ data = flask.request.json
+ if not "app" in data:
+ return flask.make_response("No app name provided", 400)
+
+ app_name = data["app"]
+ user_id = None
+ if "user" in data:
+ user_id = data["user"]
+
+ app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
+
+ self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access",
+ app_name=app_name,
+ user_token=user_token,
+ user_id=user_id))
+ response = flask.jsonify(app_token=app_token)
+ response.status_code = 202
+ response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
+ return response
+
+ @octoprint.plugin.BlueprintPlugin.route("/request/")
+ @no_firstrun_access
+ def handle_decision_poll(self, app_token):
+ if self._is_pending(app_token):
+ return flask.make_response("Awaiting decision", 202)
+
+ result = self._get_decision(app_token)
+ if result is not None:
+ return flask.jsonify(api_key=result)
+
+ return flask.abort(404)
+
+ @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"])
+ @restricted_access
+ def handle_decision(self, user_token):
+ data = flask.request.json
+ if not "decision" in data:
+ return flask.make_response("No decision provided", 400)
+ decision = data["decision"] in valid_boolean_trues
+ user_id = current_user.get_name()
+
+ result = self._set_decision(user_token, decision, user_id)
+ if not result:
+ return flask.abort(404)
+
+ return NO_CONTENT
+
+ def is_blueprint_protected(self):
+ return False # No API key required to request API access
+
+ ##~~ SimpleApiPlugin mixin
+
+ def get_api_commands(self):
+ return dict(generate=["app"],
+ revoke=["key"])
+
+ def on_api_get(self, request):
+ user_id = current_user.get_name()
+ if not user_id:
+ return flask.abort(403)
+
+ return flask.jsonify(keys=map(lambda x: x.external(), self._api_keys_for_user(user_id)),
+ pending=dict((x.user_token, x.external()) for x in self._get_pending(user_id)))
+
+ def on_api_command(self, command, data):
+ user_id = current_user.get_name()
+ if not user_id:
+ return flask.abort(403)
+
+ if command == "revoke":
+ api_key = data.get("key")
+ if not api_key:
+ return flask.abort(400)
+
+ self._delete_api_key(user_id, api_key)
+
+ elif command == "generate":
+ # manual generateKey
+ app_name = data.get("app")
+ if not app_name:
+ return flask.abort(400)
+
+ api_key = self._generate_key()
+ try:
+ self._add_api_key(user_id, app_name.trim(), api_key)
+ except AppAlreadyExists:
+ return flask.abort(409)
+
+ return NO_CONTENT
+
+ ##~~ key validator hook
+
+ def validate_api_key(self, api_key, *args, **kwargs):
+ return self._user_for_api_key(api_key)
+
+ ##~~ Helpers
+
+ def _add_pending_decision(self, app_name, user_id=None):
+ app_token = self._generate_key()
+ user_token = self._generate_key()
+
+ with self._pending_lock:
+ self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token))
+
+ return app_token, user_token
+
+ def _is_pending(self, app_token):
+ with self._pending_lock:
+ for data in self._pending_decisions:
+ if data.app_token == app_token:
+ return True
+
+ return False
+
+ def _get_pending(self, user_id):
+ result = []
+ with self._pending_lock:
+ for data in self._pending_decisions:
+ if data.user_id == user_id or data.user_id is None:
+ result.append(data)
+ return result
+
+ def _set_decision(self, user_token, decision, user_id):
+ with self._pending_lock:
+ for data in self._pending_decisions:
+ if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
+ pending = data
+ break
+ else:
+ return False # not found
+
+ if decision:
+ with self._ready_lock:
+ self._ready_decisions.append(ReadyDecision.for_pending(pending, self._generate_key()))
+
+ with self._pending_lock:
+ self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
+
+ return True
+
+ def _get_decision(self, app_token):
+ with self._ready_lock:
+ for data in self._ready_decisions:
+ if data.app_token == app_token:
+ decision = data
+ break
+ else:
+ return False # not found
+
+ self._add_api_key(decision.user_id, decision.app_id, decision.api_key)
+
+ with self._ready_lock:
+ self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
+
+ return decision.api_key
+
+ def _add_api_key(self, user_id, app_name, api_key):
+ with self._keys_lock:
+ # TODO: persist to disk
+ for key in self._keys[user_id]:
+ if key.app_id.lower() == app_name.lower():
+ raise AppAlreadyExists("app {} does already exist".format(app_name))
+ self._keys[user_id].append(ActiveKey(app_name, api_key))
+
+ def _delete_api_key(self, user_id, api_key):
+ with self._keys_lock:
+ # TODO: persist to disk
+ self._keys[user_id] = filter(lambda x: x.api_key != api_key, self._keys[user_id])
+
+ def _user_for_api_key(self, api_key):
+ with self._keys_lock:
+ for user_id, data in self._keys.items():
+ if filter(lambda x: x.api_key == api_key, data):
+ return self._user_manager.findUser(userid=user_id)
+ return None
+
+ def _api_keys_for_user(self, user_id):
+ with self._keys_lock:
+ return self._keys.get(user_id, [])
+
+ def _generate_key(self):
+ return hexlify(os.urandom(16))
+
+__plugin_name__ = "AppAuth Plugin"
+__plugin_description__ = "TODO"
+__plugin_author__ = "Gina Häußge, Aldo Hoeben"
+__plugin_implementation__ = AppAuthPlugin()
+__plugin_hooks__ = {
+ "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
+}
diff --git a/src/octoprint/plugins/appauth/static/js/appauth.js b/src/octoprint/plugins/appauth/static/js/appauth.js
new file mode 100644
index 000000000..74ec1e6e1
--- /dev/null
+++ b/src/octoprint/plugins/appauth/static/js/appauth.js
@@ -0,0 +1,169 @@
+(function (global, factory) {
+ if (typeof define === "function" && define.amd) {
+ define(["OctoPrintClient"], factory);
+ } else {
+ factory(global.OctoPrintClient);
+ }
+})(this, function(OctoPrintClient) {
+ var OctoPrintAppAuthClient = function(base) {
+ this.base = base;
+ };
+
+ OctoPrintAppAuthClient.prototype.getKeys = function(opts) {
+ return this.base.simpleApiGet("appauth", opts);
+ };
+
+ OctoPrintAppAuthClient.prototype.generateKey = function(app, opts) {
+ return this.base.simpleApiCommand("appauth", "generate", {"app": app}, opts);
+ };
+
+ OctoPrintAppAuthClient.prototype.revokeKey = function(key, opts) {
+ return this.base.simpleApiCommand("appauth", "revoke", {"key": key}, opts);
+ };
+
+ OctoPrintAppAuthClient.prototype.decide = function(token, decision, opts) {
+ return this.base.postJson(this.base.getBlueprintUrl("appauth") + "decision/" + token, {decision: !!decision}, opts);
+ };
+
+ OctoPrintClient.registerPluginComponent("appauth", OctoPrintAppAuthClient);
+ return OctoPrintAppAuthClient;
+});
+
+$(function() {
+ function AppAuthViewModel(parameters) {
+ var self = this;
+ self.loginState = parameters[0];
+
+ self.keys = new ItemListHelper(
+ "plugin.appauth.keys",
+ {
+ "app": function (a, b) {
+ // sorts descending
+ if (a["app"] > b["app"]) return -1;
+ if (a["app"] < b["app"]) return 1;
+ return 0;
+ }
+ },
+ {
+ },
+ "app",
+ [],
+ [],
+ 10
+ );
+ self.pending = {};
+ self.openRequests = {};
+
+ self.editorApp = ko.observable();
+
+ self.requestData = function() {
+ OctoPrint.plugins.appauth.getKeys()
+ .done(self.fromResponse);
+ };
+
+ self.fromResponse = function(response) {
+ self.keys.updateItems(response.keys);
+ self.pending = response.pending;
+ _.each(self.pending, function(data, token) {
+ self.openRequests[token] = self.promptForAccess(data.app_id, token);
+ })
+ };
+
+ self.generateKey = function() {
+ return OctoPrint.plugins.appauth.generateKey(self.editorApp())
+ .done(self.requestData);
+ };
+
+ self.revokeKey = function(key) {
+ return OctoPrint.plugins.appauth.revokeKey(key)
+ .done(self.requestData);
+ };
+
+ self.allowApp = function(token) {
+ return OctoPrint.plugins.appauth.decide(token, true)
+ .done(self.requestData);
+ };
+
+ self.denyApp = function(token) {
+ return OctoPrint.plugins.appauth.decide(token, false)
+ .done(self.requestData);
+ };
+
+ self.promptForAccess = function(app, token) {
+ var message = gettext("\"%(app)s\" has requested access to control OctoPrint through the API. Do you want to allow access to this application with your user account?");
+ message = _.sprintf(message, {app: app});
+
+ return new PNotify({
+ title: gettext("Access Request"),
+ text: message,
+ confirm: {
+ confirm: true,
+ buttons: [{
+ text: gettext("Allow"),
+ click: function(notice) {
+ self.allowApp(token);
+ }
+ }, {
+ text: gettext("Deny"),
+ click: function(notice) {
+ self.denyApp(token);
+ }
+ }]
+ },
+ buttons: {
+ sticker: false,
+ closer: false
+ }
+ });
+ };
+
+ self.onUserSettingsShown = function() {
+ self.requestData();
+ };
+
+ self.onUserLoggedIn = function() {
+ self.requestData();
+ };
+
+ self.onDataUpdaterPluginMessage = function(plugin, data) {
+ if (plugin !== "appauth") {
+ return;
+ }
+
+ var app, token, user;
+
+ if (data.type === "request_access" && self.loginState.isUser()) {
+ app = data.app_name;
+ token = data.user_token;
+ user = data.user_id;
+
+ if (user && user !== self.loginState.username()) {
+ return;
+ }
+
+ if (self.pending[token] === undefined) {
+ return;
+ }
+
+ self.openRequests[token] = self.promptForAccess(app, token);
+
+ } else if (data.type === "end_request") {
+ token = data.user_token;
+
+ if (self.openRequests[token] !== undefined) {
+ // another instance responded to the access request before the current user did
+ if (self.openRequests[token].state !== "closed") {
+ self.openRequests[token].remove();
+ }
+ delete self.openRequests[token]
+ }
+ }
+ };
+ }
+
+ OCTOPRINT_VIEWMODELS.push([
+ AppAuthViewModel,
+ ["loginStateViewModel"],
+ ["#usersettings_plugin_appauth"]
+ ]);
+});
diff --git a/src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2 b/src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2
new file mode 100644
index 000000000..aeb2f9e67
--- /dev/null
+++ b/src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2
@@ -0,0 +1,42 @@
+
+
+
+
+
From 3fe2b611bc24343f987a1dede555e68f1c114c08 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 31 Aug 2018 20:35:16 +0200
Subject: [PATCH 229/656] Appkeys: fix template config
---
src/octoprint/plugins/appkeys/__init__.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py
index 27c261b69..91b0ca960 100644
--- a/src/octoprint/plugins/appkeys/__init__.py
+++ b/src/octoprint/plugins/appkeys/__init__.py
@@ -70,7 +70,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
##~~ TemplatePlugin
def get_template_configs(self):
- return [dict(type="usersettings", name=gettext("Application Keys"), custom_bindings=False)]
+ return [dict(type="usersettings", name=gettext("Application Keys"))]
##~~ AssetPlugin
From 257fc0d1cdf16949582f95ef09be59aa48587278 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 31 Aug 2018 20:45:16 +0200
Subject: [PATCH 230/656] Appkeys: allow fetching of all keys
Also added TODO list ;)
---
src/octoprint/plugins/appkeys/__init__.py | 35 ++++++++++++++++---
.../appkeys/static/clientjs/appkeys.js | 4 +++
2 files changed, 34 insertions(+), 5 deletions(-)
diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py
index 91b0ca960..2666047b9 100644
--- a/src/octoprint/plugins/appkeys/__init__.py
+++ b/src/octoprint/plugins/appkeys/__init__.py
@@ -11,7 +11,18 @@ from flask_babel import gettext
import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, no_firstrun_access
-from octoprint.server import NO_CONTENT, current_user, user_permission
+from octoprint.server import NO_CONTENT, current_user, admin_permission
+
+
+"""
+TODO:
+ * add key persistence
+ * add central management settings panel for *all* user's keys
+ * bulk delete: delete all, all on page, all by user?
+ * write documentation
+ * API docs
+ * JS client docs
+"""
class AppAlreadyExists(Exception):
@@ -43,13 +54,15 @@ class ReadyDecision(object):
class ActiveKey(object):
- def __init__(self, app_id, api_key):
+ def __init__(self, app_id, api_key, user_id):
self.app_id = app_id
self.api_key = api_key
+ self.user_id = user_id
def external(self):
return dict(app_id=self.app_id,
- api_key=self.api_key)
+ api_key=self.api_key,
+ user_id=self.user_id)
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
@@ -148,7 +161,12 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
if not user_id:
return flask.abort(403)
- return flask.jsonify(keys=map(lambda x: x.external(), self._api_keys_for_user(user_id)),
+ if request.values.get("all") in valid_boolean_trues and admin_permission.can():
+ keys = self._all_api_keys()
+ else:
+ keys = self._api_keys_for_user(user_id)
+
+ return flask.jsonify(keys=map(lambda x: x.external(), keys),
pending=dict((x.user_token, x.external()) for x in self._get_pending(user_id)))
def on_api_command(self, command, data):
@@ -246,7 +264,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
if key.app_id.lower() == app_name.lower():
return key.api_key
- key = ActiveKey(app_name, self._generate_key())
+ key = ActiveKey(app_name, self._generate_key(), user_id)
self._keys[user_id].append(key)
return key.api_key
@@ -266,6 +284,13 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
with self._keys_lock:
return self._keys.get(user_id, [])
+ def _all_api_keys(self):
+ with self._keys_lock:
+ result = []
+ for user_id, keys in self._keys.items():
+ result += keys
+ return result
+
def _generate_key(self):
return hexlify(os.urandom(16))
diff --git a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js
index 1e70f4b89..580ad1364 100644
--- a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js
+++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js
@@ -13,6 +13,10 @@
return this.base.simpleApiGet("appkeys", opts);
};
+ OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
+ return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
+ };
+
OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
};
From b0e7df47a69b4527932a26fbcdc4185203ff41c8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 3 Sep 2018 18:38:36 +0200
Subject: [PATCH 231/656] Appkeys: Add key persistence
---
src/octoprint/plugins/appkeys/__init__.py | 54 ++++++++++++++++++++++-
1 file changed, 52 insertions(+), 2 deletions(-)
diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py
index 2666047b9..5f491db96 100644
--- a/src/octoprint/plugins/appkeys/__init__.py
+++ b/src/octoprint/plugins/appkeys/__init__.py
@@ -4,6 +4,9 @@ from __future__ import absolute_import
import flask
import threading
import os
+import yaml
+import codecs
+import time
from binascii import hexlify
from collections import defaultdict
from flask_babel import gettext
@@ -12,6 +15,7 @@ import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, no_firstrun_access
from octoprint.server import NO_CONTENT, current_user, admin_permission
+from octoprint.util import atomic_write
"""
@@ -64,6 +68,14 @@ class ActiveKey(object):
api_key=self.api_key,
user_id=self.user_id)
+ def internal(self):
+ return dict(app_id=self.app_id,
+ api_key=self.api_key)
+
+ @classmethod
+ def for_internal(cls, internal, user_id):
+ return cls(internal["app_id"], internal["api_key"], user_id)
+
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
@@ -80,6 +92,12 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
self._keys = defaultdict(list)
self._keys_lock = threading.RLock()
+ self._key_path = None
+
+ def initialize(self):
+ self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
+ self._load_keys()
+
##~~ TemplatePlugin
def get_template_configs(self):
@@ -259,19 +277,19 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
def _add_api_key(self, user_id, app_name):
with self._keys_lock:
- # TODO: persist to disk
for key in self._keys[user_id]:
if key.app_id.lower() == app_name.lower():
return key.api_key
key = ActiveKey(app_name, self._generate_key(), user_id)
self._keys[user_id].append(key)
+ self._save_keys()
return key.api_key
def _delete_api_key(self, user_id, api_key):
with self._keys_lock:
- # TODO: persist to disk
self._keys[user_id] = filter(lambda x: x.api_key != api_key, self._keys[user_id])
+ self._save_keys()
def _user_for_api_key(self, api_key):
with self._keys_lock:
@@ -294,6 +312,38 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
def _generate_key(self):
return hexlify(os.urandom(16))
+ def _load_keys(self):
+ with self._keys_lock:
+ if not os.path.exists(self._key_path):
+ return
+
+ try:
+ with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f:
+ persisted = yaml.safe_load(f)
+ except:
+ self._logger.exception("Could not load application keys from {}".format(self._key_path))
+ return
+
+ if not isinstance(persisted, dict):
+ return
+
+ keys = dict()
+ for user_id, persisted_keys in persisted.items():
+ keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys]
+ self._keys = keys
+
+ def _save_keys(self):
+ with self._keys_lock:
+ to_persist = dict()
+ for user_id, keys in self._keys.items():
+ to_persist[user_id] = [x.internal() for x in keys]
+
+ try:
+ with atomic_write(self._key_path) as f:
+ yaml.safe_dump(to_persist, f)
+ except:
+ self._logger.exception("Could not write application keys to {}".format(self._key_path))
+
__plugin_name__ = "Application Keys Plugin"
__plugin_description__ = "TODO"
__plugin_author__ = "Gina Häußge, Aldo Hoeben"
From e95e546c0882e74075a73e84be328bc084712cd6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 15 Oct 2018 12:48:41 +0200
Subject: [PATCH 232/656] Appkey: Copy key to clipboard
---
src/octoprint/plugins/appkeys/__init__.py | 1 -
.../plugins/appkeys/templates/appkeys_usersettings.jinja2 | 2 +-
2 files changed, 1 insertion(+), 2 deletions(-)
diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py
index 5f491db96..d61f5ed8f 100644
--- a/src/octoprint/plugins/appkeys/__init__.py
+++ b/src/octoprint/plugins/appkeys/__init__.py
@@ -20,7 +20,6 @@ from octoprint.util import atomic_write
"""
TODO:
- * add key persistence
* add central management settings panel for *all* user's keys
* bulk delete: delete all, all on page, all by user?
* write documentation
diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2
index 0eae9334d..c2472ff2a 100644
--- a/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2
+++ b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2
@@ -13,7 +13,7 @@
-
{{ _('API Key') }}:
+
{{ _('API Key') }}:
From 7f9764c38607982295ffc633024c8a9fb945edcd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 15 Oct 2018 17:11:07 +0200
Subject: [PATCH 233/656] Announcements: fix a bug & add docs
---
docs/bundledplugins/index.rst | 1 +
src/octoprint/plugins/announcements/__init__.py | 17 +++++++++++++----
2 files changed, 14 insertions(+), 4 deletions(-)
diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst
index 26a520699..7dc337991 100644
--- a/docs/bundledplugins/index.rst
+++ b/docs/bundledplugins/index.rst
@@ -8,6 +8,7 @@ Bundled Plugins
:maxdepth: 2
action_command_prompt.rst
+ announcements.rst
cura.rst
discovery.rst
logging.rst
diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py
index bccea5198..8ff8e289a 100644
--- a/src/octoprint/plugins/announcements/__init__.py
+++ b/src/octoprint/plugins/announcements/__init__.py
@@ -372,15 +372,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
result = []
if "entries" in feed:
for entry in feed["entries"]:
- internal_entry = self._to_internal_entry(entry, read_until=read_until)
- if internal_entry:
- result.append(internal_entry)
+ try:
+ internal_entry = self._to_internal_entry(entry, read_until=read_until)
+ if internal_entry:
+ result.append(internal_entry)
+ except:
+ self._logger.exception("Error while converting entry from feed, skipping it")
return result
def _to_internal_entry(self, entry, read_until=None):
"""Convert feed entries to internal data structure."""
- published = calendar.timegm(entry["published_parsed"])
+ timestamp = entry.get("published_parsed",
+ entry.get("updated_parsed",
+ None))
+ if timestamp is None:
+ return None
+
+ published = calendar.timegm(timestamp)
read = True
if read_until is not None:
From efa556a812e542216c3e45bd7aa731773850512e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Mon, 15 Oct 2018 17:23:21 +0200
Subject: [PATCH 234/656] Announcements: forgot to git add the new doc page -_-
---
docs/bundledplugins/announcements.rst | 67 +++++++++++++++++++++++++++
1 file changed, 67 insertions(+)
create mode 100644 docs/bundledplugins/announcements.rst
diff --git a/docs/bundledplugins/announcements.rst b/docs/bundledplugins/announcements.rst
new file mode 100644
index 000000000..44dfe63e1
--- /dev/null
+++ b/docs/bundledplugins/announcements.rst
@@ -0,0 +1,67 @@
+.. _sec-bundledplugins-announcements:
+
+Announcement Plugin
+===================
+
+The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11).
+
+It displays announcements fetched from OctoPrint's websites, such as important updates, release announcements, new
+plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels
+via RSS or Atom feed URLs.
+
+.. _fig-bundledplugins-announcements-example1:
+.. figure:: ../images/bundledplugins-announcements-example1.png
+ :align: center
+ :alt: Example notification
+
+ An example notification from the Announcement Plugin.
+
+.. _fig-bundledplugins-announcements-example2:
+.. figure:: ../images/bundledplugins-announcements-example2.png
+ :align: center
+ :alt: Announcement reader
+
+ The Announcement Plugin's reader dialog.
+
+.. _fig-bundledplugins-announcements-settings:
+.. figure:: ../images/bundledplugins-announcements-settings.png
+ :align: center
+ :alt: Announcement settings
+
+ The Announcement Plugin's settings dialog.
+
+.. _sec-bundledplugins-announcements-configuration:
+
+Configuring the plugin
+----------------------
+
+The plugin allows enabling and disabling the preconfigured announcement channels via its settings dialog.
+
+On top of that it's possible to add additional announcement channels (as RSS or Atom feed URLs) or change the
+configuration of the existing channels through ``config.yaml``.
+
+The available configuration keys are:
+
+ * ``channels``: Configured announcement channels. A mapping from a unique identifier to a configuration structure
+ that follows this format:
+
+ * ``name``: Name of the channel, used e.g. in the title of the displayed notifications.
+ * ``description``: Description of the channel.
+ * ``priority``: ``1`` for high priority announcements (red notification), ``2`` for regular ones (yellow notification).
+ * ``type``: Currently unused.
+ * ``url``: URL for the feed acting as notification source, must be RSS or Atom format.
+
+ * ``enabled_channels``: List of identifiers of enabled channels.
+ * ``forced_channels``: List of identifiers of channels that cannot be disabled (currently only ``_important`` which is used sparingly).
+ * ``channel_order``: List of channel identifiers in the order they should appear in the UI.
+ * ``ttl``: Time to live of the channel cache in minutes (default: 6 hours).
+ * ``display_limit``: Limit of items to display per channel (default: 3).
+ * ``summary_limit``: Limit of characters to display from each channel entry (default: 300).
+
+.. _sec-bundledplugins-announcements-sourcecode:
+
+Source code
+-----------
+
+The source of the Announcement plugin is bundled with OctoPrint and can be found in
+its source repository under ``src/octoprint/plugins/announcements``.
From 7b5d2e3e0c3c09e0f0d419bb428e8c01baa3f820 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Thu, 18 Oct 2018 17:32:32 +0200
Subject: [PATCH 235/656] Allow whitespace after : in M114 responses
Closes #2839
---
src/octoprint/util/comm.py | 4 ++--
tests/util/test_comm_helpers.py | 6 ++++++
2 files changed, 8 insertions(+), 2 deletions(-)
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index bee3e0837..68ffbf039 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -126,7 +126,7 @@ Groups will be as follows:
* ``target``: new target temperature (float)
"""
-regex_position = re.compile("X:(?P{float})\s*Y:(?P{float})\s*Z:(?P{float})\s*((E:(?P{float}))|(?P(E\d+:{float}\s*)+))".format(float=regex_float_pattern))
+regex_position = re.compile("X:\s*(?P{float})\s*Y:\s*(?P{float})\s*Z:\s*(?P{float})\s*((E:\s*(?P{float}))|(?P(E\d+:\s*{float}\s*)+))".format(float=regex_float_pattern))
"""Regex for matching position reporting.
Groups will be as follows:
@@ -138,7 +138,7 @@ Groups will be as follows:
* ``es``: multiple E coordinates if present, to be parsed further with regex_e_positions
"""
-regex_e_positions = re.compile("E(?P\d+):(?P{float})".format(float=regex_float_pattern))
+regex_e_positions = re.compile("E(?P\d+):\s*(?P{float})".format(float=regex_float_pattern))
"""Regex for matching multiple E coordinates in a position report.
Groups will be as follows:
diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py
index 119ff406d..1524dbd99 100644
--- a/tests/util/test_comm_helpers.py
+++ b/tests/util/test_comm_helpers.py
@@ -333,6 +333,12 @@ class TestCommHelpers(unittest.TestCase):
e4=0.0,
e5=0.0)),
+ # whitespace after the :, e.g. AlfaWise U20, see #2839
+ ("X:150.0 Y:150.0 Z: 0.7 E: 0.0", dict(x=150.0,
+ y=150.0,
+ z=0.7,
+ e=0.0)),
+
# invalid
("", None),
("X:62.417 Y:64.781 Z:0.2", None)
From ac2354907a5b55d94e256d9de7bf63452ed46085 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Thu, 18 Oct 2018 17:33:08 +0200
Subject: [PATCH 236/656] Remove some trailing whitespace
---
tests/util/test_comm_helpers.py | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py
index 1524dbd99..dc3adae14 100644
--- a/tests/util/test_comm_helpers.py
+++ b/tests/util/test_comm_helpers.py
@@ -267,11 +267,11 @@ class TestCommHelpers(unittest.TestCase):
("NAME. Malyan VER: 3.7 MODEL: M300 HW: HG01",
dict(NAME="Malyan", VER="3.7", MODEL="M300", HW="HG01")),
("FIRMWARE_NAME:Marlin 1.1.0 From Archive SOURCE_CODE_URL:http:// ... PROTOCOL_VERSION:1.0 MACHINE_TYPE:www.cxsw3d.com EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000",
- dict(FIRMWARE_NAME="Marlin 1.1.0 From Archive",
- SOURCE_CODE_URL="http:// ...",
- PROTOCOL_VERSION="1.0",
- MACHINE_TYPE="www.cxsw3d.com",
- EXTRUDER_COUNT="1",
+ dict(FIRMWARE_NAME="Marlin 1.1.0 From Archive",
+ SOURCE_CODE_URL="http:// ...",
+ PROTOCOL_VERSION="1.0",
+ MACHINE_TYPE="www.cxsw3d.com",
+ EXTRUDER_COUNT="1",
UUID="00000000-0000-0000-0000-000000000000"))
)
@unpack
From 025986794fbb84039f0f32fcd3eef83678d2792e Mon Sep 17 00:00:00 2001
From: Eyal Soha
Date: Thu, 11 Oct 2018 10:21:08 -0400
Subject: [PATCH 237/656] Remove requirement to have messages.pot to use
babel_extract
---
src/octoprint_setuptools/__init__.py | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py
index 328be4558..158408a53 100644
--- a/src/octoprint_setuptools/__init__.py
+++ b/src/octoprint_setuptools/__init__.py
@@ -524,8 +524,7 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
translation_dir = os.path.join(source_folder, "translations")
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join(source_folder, package, "translations")
- if os.path.isdir(translation_dir) and os.path.isfile(pot_file):
- cmdclass.update(get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, bundled_dir=bundled_dir, pack_name_prefix="{name}-i18n-".format(**locals()), pack_path_prefix="_plugins/{identifier}/".format(**locals())))
+ cmdclass.update(get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, bundled_dir=bundled_dir, pack_name_prefix="{name}-i18n-".format(**locals()), pack_path_prefix="_plugins/{identifier}/".format(**locals())))
from setuptools import find_packages
packages = list(set([package] + filter(lambda x: x.startswith("{package}.".format(package=package)), find_packages(where=source_folder, exclude=ignored_packages)) + additional_packages))
From 108db045cec69bdb71c724ed4b3811f8c034c7f5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Thu, 18 Oct 2018 18:06:01 +0200
Subject: [PATCH 238/656] Small changes to the contribution guidelines
* allow PRs against `maintenance` branch for improvements and small
new features
* suggest getting in touch on the forum for larger changes
---
CONTRIBUTING.md | 12 ++++++++----
1 file changed, 8 insertions(+), 4 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 861215f4d..e4321207d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -27,7 +27,7 @@ to **address problems in a timely manner** but also keep it possible for them
to **fix bugs, add new and improve on existing functionality** instead of doing
nothing but ticket management.
-
+
- **[Read the FAQ](https://faq.octoprint.org)**
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
@@ -301,7 +301,8 @@ the documentation.
the discussion going on how best to solve *this* in OctoPrint's plugin
system - maybe that's the actual PR you have been waiting for to contribute :)
2. If you plan to make **any large or otherwise disruptive changes to the
- code or appearance, please open a "Brainstorming" ticket first** so
+ code or appearance, please get in touch on the
+ [forums](https://discourse.octoprint.org/c/development)** first so
that we can determine if it's a good time for your specific pull
request. It might be that we're currently in the process of making
heavy changes to the code locations you'd target as well, or your
@@ -311,7 +312,8 @@ the documentation.
3. Create your pull request **from a custom branch** on your end (e.g.
`dev/myNewFeature`)[1].
4. Create your pull request **only against the `maintenance` or `devel` branch**:
- * if it's a bug fix for a bug in the current stable version: `maintenance` branch
+ * if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a
+ *small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
* otherwise: `devel` branch
5. Create **one pull request per feature/bug fix**.
6. Make sure there are **only relevant changes** included in your PR. No
@@ -472,7 +474,9 @@ the local version identifier to allow for an exact determination of the active c
* 2017-11-22: Added note on how to run the unit tests
* 2018-03-15: Link to new community forum and some clarifications re bug
reporting
- * 2018-03-29: "Where to find version numbers" is now located on the FAQ
+ * 2018-03-29: "Where to find version numbers" is now located on the FAQ
+ * 2018-10-18: Allow PRs against `maintenance` branch for improvements and small
+ new features, suggest getting in touch on the forum for larger changes
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
From 2f89082df21d37aab22553643ddab3c8000b8cf3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 19 Oct 2018 13:14:31 +0200
Subject: [PATCH 239/656] Missed something in yesterday's changes to contrib
guide
---
CONTRIBUTING.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e4321207d..97299046d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -39,11 +39,11 @@ nothing but ticket management.
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
such support issues.
- If you are a **developer** that wants to brainstorm a pull request or possible
- changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
- `[Brainstorming] New plugin hook for doing some cool stuff`).
+ changes to the plugin system, please get in touch on the
+ [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/development).
- If you need **support**, have a **question** or some **other reason** that
doesn't fit any of the above categories, the issue tracker is not the right place.
- Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead.
+ Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/support) instead.
No matter what kind of ticket you create, never mix two or more "ticket reasons"
into one ticket: One ticket per bug, request, brainstorming thread please.
@@ -53,7 +53,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please.
> A bot is in place that monitors new tickets, automatically
> categorizes them and checks new bug reports for usage of the provided template.
> That bot will only bother you if you open a ticket that appears to be a bug (no
-> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it
+> `[Request]` in the title) without the complete template, and it
> will do that only to ensure that all information needed to solve the issue is
> available for the maintainers to directly start tackling that problem.
From df8226b8c5bdc2a38cf82fd09586790fbf2c915c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Thu, 18 Oct 2018 18:06:01 +0200
Subject: [PATCH 240/656] Small changes to the contribution guidelines
* allow PRs against `maintenance` branch for improvements and small
new features
* suggest getting in touch on the forum for larger changes
---
CONTRIBUTING.md | 12 ++++++++----
1 file changed, 8 insertions(+), 4 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 861215f4d..e4321207d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -27,7 +27,7 @@ to **address problems in a timely manner** but also keep it possible for them
to **fix bugs, add new and improve on existing functionality** instead of doing
nothing but ticket management.
-
+
- **[Read the FAQ](https://faq.octoprint.org)**
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
@@ -301,7 +301,8 @@ the documentation.
the discussion going on how best to solve *this* in OctoPrint's plugin
system - maybe that's the actual PR you have been waiting for to contribute :)
2. If you plan to make **any large or otherwise disruptive changes to the
- code or appearance, please open a "Brainstorming" ticket first** so
+ code or appearance, please get in touch on the
+ [forums](https://discourse.octoprint.org/c/development)** first so
that we can determine if it's a good time for your specific pull
request. It might be that we're currently in the process of making
heavy changes to the code locations you'd target as well, or your
@@ -311,7 +312,8 @@ the documentation.
3. Create your pull request **from a custom branch** on your end (e.g.
`dev/myNewFeature`)[1].
4. Create your pull request **only against the `maintenance` or `devel` branch**:
- * if it's a bug fix for a bug in the current stable version: `maintenance` branch
+ * if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a
+ *small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
* otherwise: `devel` branch
5. Create **one pull request per feature/bug fix**.
6. Make sure there are **only relevant changes** included in your PR. No
@@ -472,7 +474,9 @@ the local version identifier to allow for an exact determination of the active c
* 2017-11-22: Added note on how to run the unit tests
* 2018-03-15: Link to new community forum and some clarifications re bug
reporting
- * 2018-03-29: "Where to find version numbers" is now located on the FAQ
+ * 2018-03-29: "Where to find version numbers" is now located on the FAQ
+ * 2018-10-18: Allow PRs against `maintenance` branch for improvements and small
+ new features, suggest getting in touch on the forum for larger changes
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
From e57c46fb67c50a7e9a1ea76842da88d480d54d8c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 19 Oct 2018 13:14:31 +0200
Subject: [PATCH 241/656] Missed something in yesterday's changes to contrib
guide
---
CONTRIBUTING.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e4321207d..97299046d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -39,11 +39,11 @@ nothing but ticket management.
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
such support issues.
- If you are a **developer** that wants to brainstorm a pull request or possible
- changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
- `[Brainstorming] New plugin hook for doing some cool stuff`).
+ changes to the plugin system, please get in touch on the
+ [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/development).
- If you need **support**, have a **question** or some **other reason** that
doesn't fit any of the above categories, the issue tracker is not the right place.
- Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead.
+ Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/support) instead.
No matter what kind of ticket you create, never mix two or more "ticket reasons"
into one ticket: One ticket per bug, request, brainstorming thread please.
@@ -53,7 +53,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please.
> A bot is in place that monitors new tickets, automatically
> categorizes them and checks new bug reports for usage of the provided template.
> That bot will only bother you if you open a ticket that appears to be a bug (no
-> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it
+> `[Request]` in the title) without the complete template, and it
> will do that only to ensure that all information needed to solve the issue is
> available for the maintainers to directly start tackling that problem.
From 36b07b2337be96ca665429a3e81b2602da3bddce Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 19 Oct 2018 13:58:37 +0200
Subject: [PATCH 242/656] discovery: enumerate zeroconf service names on
collision
Fixes #2852
---
src/octoprint/plugins/discovery/__init__.py | 16 ++++++++++++++--
1 file changed, 14 insertions(+), 2 deletions(-)
diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py
index 031ef7d48..90e50cc15 100644
--- a/src/octoprint/plugins/discovery/__init__.py
+++ b/src/octoprint/plugins/discovery/__init__.py
@@ -194,8 +194,20 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
params["txtRecord"] = pybonjour.TXTRecord(txt_record)
key = (reg_type, port)
- self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
- self._logger.info(u"Registered {name} for {reg_type}".format(**locals()))
+
+ counter = 0
+ while True:
+ try:
+ self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
+ self._logger.info(u"Registered '{name}' for {regtype}".format(**params))
+ return True
+ except pybonjour.BonjourError as be:
+ if be.errorCode == pybonjour.kDNSServiceErr_NameConflict:
+ # Name already registered by different service, let's try a counter postfix. See #2852
+ counter += 1
+ params["name"] = u"{} ({})".format(name, counter)
+ else:
+ raise
def zeroconf_unregister(self, reg_type, port=None):
"""
From 9e48b8ab65ad046dbddf513bce8ec9c34f74b2cd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 19 Oct 2018 14:12:53 +0200
Subject: [PATCH 243/656] make sure to strip comments from address
---
src/octoprint/util/net.py | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py
index 05106ac74..494102887 100644
--- a/src/octoprint/util/net.py
+++ b/src/octoprint/util/net.py
@@ -45,7 +45,12 @@ def is_lan_address(address, additional_private=None):
if "/" in prefix:
# v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
_, prefix = prefix.split("/")
- return netaddr.IPNetwork("{}/{}".format(address["addr"], prefix))
+
+ addr = address["addr"]
+ if "%" in addr:
+ # interface comment in netifaces output, e.g. "fe80::457f:bbee:d579:1063%wlan0"
+ addr = addr[:addr.find("%")]
+ return netaddr.IPNetwork("{}/{}".format(addr, prefix))
except:
pass
From 8e39eac2079f4a7990bcf372a800979e988cfd13 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 19 Oct 2018 14:17:16 +0200
Subject: [PATCH 244/656] discovery: start name counter at 1
We want our second instance with the same name to show up as (2) not (1)
---
src/octoprint/plugins/discovery/__init__.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py
index 90e50cc15..d5fb2fb41 100644
--- a/src/octoprint/plugins/discovery/__init__.py
+++ b/src/octoprint/plugins/discovery/__init__.py
@@ -195,7 +195,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
key = (reg_type, port)
- counter = 0
+ counter = 1
while True:
try:
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
From 757dfcf5c7da9b7b154dd538ab84443ca643a3e5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 19 Oct 2018 16:19:51 +0200
Subject: [PATCH 245/656] unmap ipv6 mapped v4 addresses on lan check
---
src/octoprint/util/net.py | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py
index 494102887..0b7a00bd7 100644
--- a/src/octoprint/util/net.py
+++ b/src/octoprint/util/net.py
@@ -25,6 +25,10 @@ else:
HAS_V6 = False
def is_lan_address(address, additional_private=None):
+ if address.lower().startswith("::ffff:" and "." in address):
+ # ipv6 mapped ipv4 address, unmap
+ address = address[len("::ffff:"):]
+
ip = netaddr.IPAddress(address)
if ip.is_private() or ip.is_loopback():
return True
From 169275b052a27317bf25b1aef3d4f5c76b932935 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 19 Oct 2018 16:39:18 +0200
Subject: [PATCH 246/656] Fix wrong position of parentheses, add unit tests
---
src/octoprint/util/net.py | 2 +-
tests/util/test_net.py | 2 ++
2 files changed, 3 insertions(+), 1 deletion(-)
diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py
index 0b7a00bd7..2ca5cfea3 100644
--- a/src/octoprint/util/net.py
+++ b/src/octoprint/util/net.py
@@ -25,7 +25,7 @@ else:
HAS_V6 = False
def is_lan_address(address, additional_private=None):
- if address.lower().startswith("::ffff:" and "." in address):
+ if address.lower().startswith("::ffff:") and "." in address:
# ipv6 mapped ipv4 address, unmap
address = address[len("::ffff:"):]
diff --git a/tests/util/test_net.py b/tests/util/test_net.py
index e773ddac4..a1a33cec0 100644
--- a/tests/util/test_net.py
+++ b/tests/util/test_net.py
@@ -38,6 +38,8 @@ class UtilNetTest(unittest.TestCase):
("10.1.2.3", [], True),
("fc00::1", [], True),
("::1", [], True),
+ ("::ffff:192.168.1.1", [], True),
+ ("::ffff:8.8.8.8", [], False),
("11.1.2.3", [], False),
("11.1.2.3", ["11/8"], True),
("12.1.1.123", [], True),
From b77380a8ac7255f3331d9689c3776a4b4fab13fe Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 19 Oct 2018 16:50:58 +0200
Subject: [PATCH 247/656] Add logging for active/passive login
---
src/octoprint/server/api/__init__.py | 5 ++++-
src/octoprint/server/util/flask.py | 5 +++++
2 files changed, 9 insertions(+), 1 deletion(-)
diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py
index bf9b7efbe..ed4cc7cee 100644
--- a/src/octoprint/server/api/__init__.py
+++ b/src/octoprint/server/api/__init__.py
@@ -215,9 +215,12 @@ def login():
login_user(user, remember=remember)
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
+ remote_addr = get_remote_address(request)
+ logging.getLogger(__name__).info("Actively logging in user {} from {}".format(user.get_id(), remote_addr))
+
response = user.asDict()
response["_is_external_client"] = s().getBoolean(["server", "ipCheck", "enabled"]) \
- and not util_net.is_lan_address(get_remote_address(request),
+ and not util_net.is_lan_address(remote_addr,
additional_private=s().get(["server", "ipCheck", "trustedSubnets"]))
return jsonify(response)
diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py
index 567291bbd..3eab0c30f 100644
--- a/src/octoprint/server/util/flask.py
+++ b/src/octoprint/server/util/flask.py
@@ -526,6 +526,8 @@ 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))
+
response = user.asDict()
response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr,
additional_private=ipCheckTrusted)
@@ -551,6 +553,9 @@ 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))
+
response = user.asDict()
response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr,
additional_private=ipCheckTrusted)
From 087a9ece2c2b8fd290d592bee87b8b4c849da576 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Fri, 19 Oct 2018 17:00:42 +0200
Subject: [PATCH 248/656] Make sure to show only one external address warning
notification at once
---
src/octoprint/static/js/app/viewmodels/loginstate.js | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js
index c67273c2a..d00e7f804 100644
--- a/src/octoprint/static/js/app/viewmodels/loginstate.js
+++ b/src/octoprint/static/js/app/viewmodels/loginstate.js
@@ -20,6 +20,8 @@ $(function() {
self.elementPasswordInput = undefined;
self.elementLoginButton = undefined;
+ self.externalAddressNotification = undefined;
+
self.userMenuText = ko.pureComputed(function() {
if (self.loggedIn()) {
return self.username();
@@ -80,10 +82,15 @@ $(function() {
"everyone with an internet connection.
Please see " +
"this blog post for " +
"ways to safely access your OctoPrint instance from remote.
" +
- "
If you know what you are doing or you are sure this message is" +
+ "
If you know what you are doing or you are sure this message is " +
"mistaken since you are in an isolated LAN, feel free to ignore it.