From 47cfcd7b122464fa8d895295b193e1bff3983a91 Mon Sep 17 00:00:00 2001 From: Salandora Date: Mon, 26 May 2014 10:45:55 +0200 Subject: [PATCH 01/29] Event Progress bugfix --- src/octoprint/events.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 6b3324545..638713dcd 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -330,8 +330,8 @@ class CommandTrigger(GenericEventListener): if "job" in currentData.keys() and currentData["job"] is not None: params["__filename"] = currentData["job"]["file"]["name"] if "progress" in currentData.keys() and currentData["progress"] is not None \ - and "progress" in currentData["progress"].keys() and currentData["progress"]["progress"] is not None: - params["__progress"] = str(round(currentData["progress"]["progress"] * 100)) + and "completion" in currentData["progress"].keys() and currentData["progress"]["completion"] is not None: + params["__progress"] = str(round(currentData["progress"]["completion"] * 100)) # now add the payload keys as well if isinstance(payload, dict): From 3d6cb623f0c5f0f94068f3272992aba7a8912b55 Mon Sep 17 00:00:00 2001 From: Salandora Date: Mon, 26 May 2014 10:46:47 +0200 Subject: [PATCH 02/29] Autodetect Baudrate bugfix --- 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 1c0f49d99..237061718 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -944,7 +944,7 @@ class MachineCom(object): try: self._log("Connecting to: %s" % self._port) if self._baudrate == 0: - self._serial = serial.Serial(str(self._port), 115200, timeout=0.1, writeTimeout=10000) + self._serial = serial.Serial(str(self._port), 115200, timeout=settings().getFloat(["serial", "timeout", "connection"]), writeTimeout=10000) else: self._serial = serial.Serial(str(self._port), self._baudrate, timeout=settings().getFloat(["serial", "timeout", "connection"]), writeTimeout=10000) except: From f6e2a5900859bb96592a24e356a7546a98e196ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Jul 2014 13:02:00 +0200 Subject: [PATCH 03/29] Correctly handle GET requests on /api/printer/{tool|bed} when printer is not operational Closes #515 --- src/octoprint/server/api/printer.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index a42297296..391898701 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -125,6 +125,9 @@ def printerToolCommand(): @api.route("/printer/tool", methods=["GET"]) def printerToolState(): + if not printer.isOperational(): + return make_response("Printer is not operational", 409) + def deleteBed(x): data = dict(x) @@ -181,6 +184,9 @@ def printerBedCommand(): @api.route("/printer/bed", methods=["GET"]) def printerBedState(): + if not printer.isOperational(): + return make_response("Printer is not operational", 409) + def deleteTools(x): data = dict(x) @@ -189,7 +195,11 @@ def printerBedState(): del data[k] return data - return jsonify(_getTemperatureData(deleteTools)) + data = _getTemperatureData(deleteTools) + if isinstance(data, Response): + return data + else: + return jsonify(data) ##~~ Print head From be99c597255ede9b2e9f17239b911b8452cdd382 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Jul 2014 15:34:00 +0200 Subject: [PATCH 04/29] Properly handle exceptions other than a non-zero return code for slicing and timelapse rendering Closes #508 --- src/octoprint/slicers/cura/__init__.py | 19 +++++++++++++------ src/octoprint/timelapse.py | 20 ++++++++++++-------- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/octoprint/slicers/cura/__init__.py b/src/octoprint/slicers/cura/__init__.py index 3467b208b..083a3f036 100644 --- a/src/octoprint/slicers/cura/__init__.py +++ b/src/octoprint/slicers/cura/__init__.py @@ -1,3 +1,5 @@ +import sarge + __author__ = "Ross Hendrickson savorywatt" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -49,14 +51,19 @@ class Cura(object): import threading def start_thread(call_back, call_back_args, call_args, cwd): - import subprocess self._logger.info("Running %r in %s" % (call_args, cwd)) + command = " ".join(call_args) try: - subprocess.check_call(call_args, cwd=cwd) - call_back(*call_back_args) - except subprocess.CalledProcessError as (e): - self._logger.warn("Could not slice via Cura, got return code %r" % e.returncode) - call_back_args.append("Got returncode %r" % e.returncode) + p = sarge.run(command, cwd=cwd) + if p.returncode == 0: + call_back(*call_back_args) + else: + self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode) + call_back_args.append("Got returncode %r" % p.returncode) + call_back(*call_back_args) + except: + self._logger.exception("Could not slice via Cura, got an unknown error") + call_back_args.append("Unknown error, please consult the log file") call_back(*call_back_args) executable = self.cura_path diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 0c4f45402..0e35a2917 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -305,14 +305,18 @@ class Timelapse(object): command_str = " ".join(command) self._logger.debug("Executing command: %s" % command_str) - p = sarge.run(command_str, stderr=sarge.Capture()) - if p.returncode == 0: - eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)}) - else: - returncode = p.returncode - stderr_text = p.stderr.text - self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text)) - eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text}) + try: + p = sarge.run(command_str, stderr=sarge.Capture()) + if p.returncode == 0: + eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)}) + else: + returncode = p.returncode + stderr_text = p.stderr.text + self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text)) + eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text}) + except: + self._logger.exception("Could not render movie due to unknown error") + eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"}) def cleanCaptureDir(self): if not os.path.isdir(self._captureDir): From f9d10860623692b792871e8f075f227e75c21139 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 31 Jul 2014 18:16:53 +0200 Subject: [PATCH 05/29] UI now displays last print time as approx. total print time if available, otherwise uses estimated print time if available Closes #523 --- docs/api/datamodel.rst | 4 ++++ src/octoprint/printer.py | 16 +++++++++++----- src/octoprint/static/js/app/viewmodels/files.js | 6 +++--- .../static/js/app/viewmodels/printerstate.js | 10 +++++++--- src/octoprint/templates/index.jinja2 | 9 ++++----- 5 files changed, 29 insertions(+), 16 deletions(-) diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index 76fc003c4..7511332d1 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -164,6 +164,10 @@ Job information - 0..1 - Integer - The estimated print time for the file, in seconds. + * - ``lastPrintTime`` + - 0..1 + - Integer + - The print time of the last print of the file, in seconds. * - ``filament`` - 0..1 - Object diff --git a/src/octoprint/printer.py b/src/octoprint/printer.py index ee96fc947..875af19c4 100644 --- a/src/octoprint/printer.py +++ b/src/octoprint/printer.py @@ -95,6 +95,7 @@ class Printer(): "date": None }, "estimatedPrintTime": None, + "lastPrintTime": None, "filament": { "length": None, "volume": None @@ -389,6 +390,7 @@ class Printer(): self._selectedFile = None estimatedPrintTime = None + lastPrintTime = None date = None filament = None if filename: @@ -398,11 +400,14 @@ class Printer(): date = int(os.stat(filename).st_ctime) fileData = self._gcodeManager.getFileData(filename) - if fileData is not None and "gcodeAnalysis" in fileData.keys(): - if "estimatedPrintTime" in fileData["gcodeAnalysis"].keys(): - estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"] - if "filament" in fileData["gcodeAnalysis"].keys(): - filament = fileData["gcodeAnalysis"]["filament"] + if fileData is not None: + if "gcodeAnalysis" in fileData: + if estimatedPrintTime is None and "estimatedPrintTime" in fileData["gcodeAnalysis"]: + estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"] + if "filament" in fileData["gcodeAnalysis"].keys(): + filament = fileData["gcodeAnalysis"]["filament"] + if "prints" in fileData and "last" in fileData["prints"] and "lastPrintTime" in fileData["prints"]["last"]: + lastPrintTime = fileData["prints"]["last"]["lastPrintTime"] self._stateMonitor.setJobData({ "file": { @@ -412,6 +417,7 @@ class Printer(): "date": date }, "estimatedPrintTime": estimatedPrintTime, + "lastPrintTime": lastPrintTime, "filament": filament, }) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 115ea6183..e9bc301f1 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -274,12 +274,12 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { } while (filament.hasOwnProperty("tool" + i)); } } - output += "Estimated Print Time: " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]); + output += "Estimated Print Time: " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]) + "
"; } if (data["prints"] && data["prints"]["last"]) { - output += "
Last Printed: " + formatTimeAgo(data["prints"]["last"]["date"]); + output += "Last Printed: " + formatTimeAgo(data["prints"]["last"]["date"]) + "
"; if (data["prints"]["last"]["lastPrintTime"]) { - output += "
Last Print Time: " + formatDuration(data["prints"]["last"]["lastPrintTime"]); + output += "Last Print Time: " + formatDuration(data["prints"]["last"]["lastPrintTime"]); } } return output; diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index 2865c3871..7dfad2971 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -24,13 +24,16 @@ function PrinterStateViewModel(loginStateViewModel) { self.filament = ko.observableArray([]); self.estimatedPrintTime = ko.observable(undefined); + self.lastPrintTime = ko.observable(undefined); self.currentHeight = ko.observable(undefined); self.estimatedPrintTimeString = ko.computed(function() { - if (!self.estimatedPrintTime()) - return "-"; - return formatDuration(self.estimatedPrintTime()); + if (self.lastPrintTime()) + return formatDuration(self.lastPrintTime()); + if (self.estimatedPrintTime()) + return formatDuration(self.estimatedPrintTime()); + return "-"; }); self.byteString = ko.computed(function() { if (!self.filesize()) @@ -123,6 +126,7 @@ function PrinterStateViewModel(loginStateViewModel) { } self.estimatedPrintTime(data.estimatedPrintTime); + self.lastPrintTime(data.lastPrintTime); var result = []; if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) { diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index 505655f28..17255f91e 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -125,12 +125,11 @@
Machine State:
File:  (SD)
- -
- - Estimated Print Time:
Timelapse:
- Height:
+ +
+ + Approx. Total Print Time:
Print Time:
Print Time Left:
Printed:
From 8aab0ee318664c2ae014ac882f66075e291e72bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 1 Aug 2014 14:20:11 +0200 Subject: [PATCH 06/29] Should fix #529 --- src/octoprint/printer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/printer.py b/src/octoprint/printer.py index 875af19c4..44d9afffe 100644 --- a/src/octoprint/printer.py +++ b/src/octoprint/printer.py @@ -406,7 +406,7 @@ class Printer(): estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"] if "filament" in fileData["gcodeAnalysis"].keys(): filament = fileData["gcodeAnalysis"]["filament"] - if "prints" in fileData and "last" in fileData["prints"] and "lastPrintTime" in fileData["prints"]["last"]: + if "prints" in fileData and fileData["prints"] and "last" in fileData["prints"] and fileData["prints"]["last"] and "lastPrintTime" in fileData["prints"]["last"]: lastPrintTime = fileData["prints"]["last"]["lastPrintTime"] self._stateMonitor.setJobData({ From 1ef9c617b3a819de3f14c15d4f5c95d1610e72de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sat, 2 Aug 2014 10:24:41 +0200 Subject: [PATCH 07/29] Trying to get large file uploads to work --- requirements.txt | 2 +- src/octoprint/server/__init__.py | 39 +--- src/octoprint/server/api/files.py | 3 +- src/octoprint/server/util.py | 318 +++++++++++++++++++++++++++++- 4 files changed, 328 insertions(+), 34 deletions(-) diff --git a/requirements.txt b/requirements.txt index a069eb3b9..f52c102ba 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ flask==0.9 werkzeug==0.8.3 -tornado==3.0.2 +tornado>=4.0 sockjs-tornado>=1.0.0 PyYAML==3.10 Flask-Login==0.2.2 diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 18f2fa480..08f141f84 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -34,7 +34,8 @@ user_permission = Permission(RoleNeed("user")) # only import the octoprint stuff down here, as it might depend on things defined above to be initialized already from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection, admin_validator, \ - UrlForwardHandler, user_validator, GcodeWatchdogHandler, UploadCleanupWatchdogHandler + UrlForwardHandler, user_validator, GcodeWatchdogHandler, UploadCleanupWatchdogHandler, LargeUploadHandler, \ + access_validation_factory, StreamedWsgiContainer, StreamingFallbackHandler from octoprint.printer import Printer, getConnectionOptions from octoprint.settings import settings import octoprint.gcodefiles as gcodefiles @@ -106,8 +107,8 @@ class Server(): self._debug = debug self._allowRoot = allowRoot self._logConf = logConf + self._server = None - def run(self): if not self._allowRoot: self._checkForRoot() @@ -180,35 +181,15 @@ class Server(): self._router = SockJSRouter(self._createSocketConnection, "/sockjs") - def access_validation_factory(validator): - """ - Creates an access validation wrapper using the supplied validator. - - :param validator: the access validator to use inside the validation wrapper - :return: an access validation wrapper taking a request as parameter and performing the request validation - """ - def f(request): - """ - Creates a custom wsgi and Flask request context in order to be able to process user information - stored in the current session. - - :param request: The Tornado request for which to create the environment and context - """ - wsgi_environ = tornado.wsgi.WSGIContainer.environ(request) - with app.request_context(wsgi_environ): - app.session_interface.open_session(app, flask.request) - loginManager.reload_user() - validator(flask.request) - return f - self._tornado_app = Application(self._router.urls + [ - (r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {"path": settings().getBaseFolder("timelapse"), "as_attachment": True}), - (r"/downloads/files/local/([^/]*\.(gco|gcode))", LargeResponseHandler, {"path": settings().getBaseFolder("uploads"), "as_attachment": True}), - (r"/downloads/logs/([^/]*)", LargeResponseHandler, {"path": settings().getBaseFolder("logs"), "as_attachment": True, "access_validation": access_validation_factory(admin_validator)}), - (r"/downloads/camera/current", UrlForwardHandler, {"url": settings().get(["webcam", "snapshot"]), "as_attachment": True, "access_validation": access_validation_factory(user_validator)}), - (r".*", FallbackHandler, {"fallback": WSGIContainer(app.wsgi_app)}) + (r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, dict(path=settings().getBaseFolder("timelapse"), as_attachment=True)), + (r"/downloads/files/local/([^/]*\.(gco|gcode))", LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)), + (r"/downloads/logs/([^/]*)", LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=access_validation_factory(app, loginManager, admin_validator))), + (r"/downloads/camera/current", UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=access_validation_factory(app, loginManager, user_validator))), + (r"/uploads/files/([^/]*)", LargeUploadHandler, dict(access_validation=access_validation_factory(app, loginManager, user_validator))), + (r".*", StreamingFallbackHandler, dict(fallback=StreamedWsgiContainer(app.wsgi_app))) ]) - self._server = HTTPServer(self._tornado_app) + self._server = HTTPServer(self._tornado_app, max_body_size=1*1024*1024*1024) self._server.listen(self._port, address=self._host) eventManager.fire(events.Events.STARTUP) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 258ff9505..1d17da2bc 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -4,7 +4,7 @@ from octoprint.events import Events __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -from flask import request, jsonify, make_response, url_for +from flask import request, jsonify, make_response, url_for, redirect import octoprint.gcodefiles as gcodefiles import octoprint.util as util @@ -188,6 +188,7 @@ def uploadGcodeFile(target): r = make_response(jsonify(files=files, done=done), 201) r.headers["Location"] = location + #return redirect(url_for("index", _external=True) + "uploads/files/" + target, code=307) return r diff --git a/src/octoprint/server/util.py b/src/octoprint/server/util.py index 434a8d3bf..b6a57be8f 100644 --- a/src/octoprint/server/util.py +++ b/src/octoprint/server/util.py @@ -1,11 +1,16 @@ # coding=utf-8 +from io import FileIO +from tempfile import NamedTemporaryFile, TemporaryFile +from tornado.httputil import HTTPHeaders +from tornado.wsgi import WSGIContainer from octoprint.filemanager.destinations import FileDestinations __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' from flask.ext.principal import identity_changed, Identity -from tornado.web import StaticFileHandler, HTTPError, RequestHandler, asynchronous +from tornado.web import StaticFileHandler, HTTPError, RequestHandler, asynchronous, stream_request_body, FallbackHandler +import tornado.escape, tornado.httputil from tornado.httpclient import AsyncHTTPClient, HTTPRequest from flask import url_for, make_response, request, current_app from flask.ext.login import login_required, login_user, current_user @@ -232,6 +237,313 @@ class PrinterStateConnection(SockJSConnection): self.send({type: payload}) +@stream_request_body +class StreamingFallbackHandler(FallbackHandler): + """A `RequestHandler` that wraps another HTTP server callback. + + The fallback is a callable object that accepts an + `~.httputil.HTTPServerRequest`, such as an `Application` or + `tornado.wsgi.WSGIContainer`. This is most useful to use both + Tornado ``RequestHandlers`` and WSGI in the same server. Typical + usage:: + + wsgi_app = tornado.wsgi.WSGIContainer( + django.core.handlers.wsgi.WSGIHandler()) + application = tornado.web.Application([ + (r"/foo", FooHandler), + (r".*", FallbackHandler, dict(fallback=wsgi_app), + ]) + """ + def initialize(self, fallback): + self.fallback = fallback + + self._length_left = int(self.request.headers.get("Content-Length", 0)) + self._tmpfile = TemporaryFile() + + def data_received(self, chunk): + self._tmpfile.write(chunk) + self._length_left -= len(chunk) + if self._length_left <= 0: + self.finished_body() + + def finished_body(self): + self._tmpfile.seek(0) + try: + body_stream = self._tmpfile + self.fallback(self.request, body_stream) + finally: + self._tmpfile.close() + + def prepare(self): + pass + + def __getattribute__(self, name): + if name in ("get", "post", "put", "patch"): + return lambda *args, **kwargs: None + return object.__getattribute__(self, name) + + +class StreamedWsgiContainer(object): + + def __init__(self, wsgi_application): + self.wsgi_application = wsgi_application + + def __call__(self, request, body_stream): + data = {} + response = [] + + def start_response(status, response_headers, exc_info=None): + data["status"] = status + data["headers"] = response_headers + return response.append + app_response = self.wsgi_application( + StreamedWsgiContainer.environ(request, body_stream), start_response) + try: + response.extend(app_response) + body = b"".join(response) + finally: + if hasattr(app_response, "close"): + app_response.close() + if not data: + raise Exception("WSGI app did not call start_response") + + status_code = int(data["status"].split()[0]) + headers = data["headers"] + header_set = set(k.lower() for (k, v) in headers) + body = tornado.escape.utf8(body) + if status_code != 304: + if "content-length" not in header_set: + headers.append(("Content-Length", str(len(body)))) + if "content-type" not in header_set: + headers.append(("Content-Type", "text/html; charset=UTF-8")) + if "server" not in header_set: + headers.append(("Server", "TornadoServer/%s" % tornado.version)) + + parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")] + for key, value in headers: + parts.append(tornado.escape.utf8(key) + b": " + tornado.escape.utf8(value) + b"\r\n") + parts.append(b"\r\n") + parts.append(body) + request.write(b"".join(parts)) + request.finish() + self._log(status_code, request) + + @staticmethod + def environ(request, body_stream): + """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. + """ + from tornado.wsgi import to_wsgi_str + import sys + import io + + hostport = request.host.split(":") + if len(hostport) == 2: + host = hostport[0] + port = int(hostport[1]) + else: + host = request.host + port = 443 if request.protocol == "https" else 80 + environ = { + "REQUEST_METHOD": request.method, + "SCRIPT_NAME": "", + "PATH_INFO": to_wsgi_str(tornado.escape.url_unescape( + request.path, encoding=None, plus=False)), + "QUERY_STRING": request.query, + "REMOTE_ADDR": request.remote_ip, + "SERVER_NAME": host, + "SERVER_PORT": str(port), + "SERVER_PROTOCOL": request.version, + "wsgi.version": (1, 0), + "wsgi.url_scheme": request.protocol, + "wsgi.input": body_stream, + "wsgi.errors": sys.stderr, + "wsgi.multithread": False, + "wsgi.multiprocess": True, + "wsgi.run_once": False, + } + if "Content-Type" in request.headers: + environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") + if "Content-Length" in request.headers: + environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") + for key, value in request.headers.items(): + environ["HTTP_" + key.replace("-", "_").upper()] = value + return environ + + def _log(self, status_code, request): + access_log = logging.getLogger("tornado.access") + + if status_code < 400: + log_method = access_log.info + elif status_code < 500: + log_method = access_log.warning + else: + log_method = access_log.error + request_time = 1000.0 * request.request_time() + summary = request.method + " " + request.uri + " (" + \ + request.remote_ip + ")" + log_method("%d %s %.2fms", status_code, summary, request_time) + + +def access_validation_factory(app, login_manager, validator): + """ + Creates an access validation wrapper using the supplied validator. + + :param validator: the access validator to use inside the validation wrapper + :return: an access validation wrapper taking a request as parameter and performing the request validation + """ + def f(request): + """ + Creates a custom wsgi and Flask request context in order to be able to process user information + stored in the current session. + + :param request: The Tornado request for which to create the environment and context + """ + import flask + import io + + wsgi_environ = StreamedWsgiContainer.environ(request, io.BytesIO("")) + with app.request_context(wsgi_environ): + app.session_interface.open_session(app, flask.request) + login_manager.reload_user() + validator(flask.request) + return f + + +@stream_request_body +class LargeUploadHandler(RequestHandler): + + def initialize(self, files_only=False, access_validation=None): + self.files_only = files_only + self._access_validation = access_validation + + # Parts information will be stored here + self.parts = dict() + + # Part currently being processed + self._current_part = None + # bytes left to process in the stream + self._bytes_left = int(self.request.headers.get("Content-Length", 0)) + # buffer needed for identifying form data parts + self._buffer = "" + + # we only support multipart/form-data content, so check for that + content_type = self.request.headers.get("Content-Type", "") + if not self._bytes_left or not content_type.startswith("multipart"): + raise HTTPError(405) + + # extract the multipart boundary + fields = content_type.split(";") + for field in fields: + k, sep, v = field.strip().partition("=") + if k == "boundary" and v: + if v.startswith(b'"') and v.endswith(b'"'): + self.boundary = tornado.escape.utf8(v[1:-1]) + else: + self.boundary = tornado.escape.utf8(v) + break + else: + raise HTTPError(400) + + def data_received(self, chunk): + self._bytes_left -= len(chunk) + data = self._buffer + chunk + + # check for boundary + delimiter = b"--%s" % self.boundary + delimiter_loc = data.find(delimiter) + delimiter_len = len(delimiter) + end_of_header = None + if delimiter_loc != -1: + # found the delimiter in the currently available data + data, self._buffer = data[0:delimiter], data[delimiter:] + end_of_header = self._buffer.find("\r\n\r\n") + else: + # make sure any boundary (with single or double ==) contained at the end of chunk does not get + # truncated by this processing round => save it to the buffer for next round + endlen = len(self.boundary) + 4 + data, self._buffer = data[0:-endlen], data[-endlen:] + + # stream data to part handler + if data: + if self._current_part: + self.ondata(self._current_part, data) + + if end_of_header >= 0: + self._header(self._buffer[delimiter_len+2:end_of_header]) + self._buffer = self._buffer[end_of_header + 4] + + if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--": + # we saw the last boundary and are at the end of our request + if self._current_part: + self.onclose(self._current_part) + self._current_part = None + return self.onfinish() + + def _header(self, header): + # close any open parts + if self._current_part: + self.onclose(self._current_part) + self._current_part = None + + header_check = header.find(self.boundary) + if header_check != -1: + # TODO log warning + header = header[header_check:] + + # convert to dict + header = HTTPHeaders.parse(header.decode("utf-8")) + disp_header = header.get("Content-Disposition", "") + disposition, disp_params = tornado.httputil._parse_header(disp_header) + + next = False + if disposition != "form-data": + # TODO log warning + return + if not disp_params.get("name"): + # TODO log warning + return + + if self.files_only and "filename" not in disp_params: + # TODO log warning + return + else: + self._current_part = self.onpart(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if self._files_only else None) + + def onpart(self, name, content_type, filename=None): + if content_type is None: + # we got a key-value-pair + return dict(name=name, value=b"") + elif content_type == "application/octet-stream": + # this is a file + tmpfile = NamedTemporaryFile() + return dict(name=name, filename=filename, file=tmpfile) + else: + return dict() + + def ondata(self, part, data): + if "value" in part: + part["value"] += data + elif "file" in part: + part["file"].write(data) + + def onclose(self, part): + for part in self.parts: + if "value" in part: + self._get_argument() + self.parts[part["name"]] = part + + def onfinish(self): + pass + + def post(self, *args, **kwargs): + if self._access_validation is not None: + self._access_validation(self.request) + + + + raise HTTPError(550, "Yay") + + #~~ customized large response handler @@ -479,7 +791,7 @@ class ReverseProxied(object): return self.app(environ, start_response) -def redirectToTornado(request, target): +def redirectToTornado(request, target, code=302): requestUrl = request.url appBaseUrl = requestUrl[:requestUrl.find(url_for("index") + "api")] @@ -487,7 +799,7 @@ def redirectToTornado(request, target): if "?" in requestUrl: fragment = requestUrl[requestUrl.rfind("?"):] redirectUrl += fragment - return redirect(redirectUrl) + return redirect(redirectUrl, code=code) class UploadCleanupWatchdogHandler(PatternMatchingEventHandler): From d770c20b5abb1c4454f8ab52251cd7ccf83b4ac0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sun, 3 Aug 2014 18:53:10 +0200 Subject: [PATCH 08/29] Working streaming file upload for now --- src/octoprint/server/__init__.py | 8 +- src/octoprint/server/api/files.py | 105 +---------- src/octoprint/server/util.py | 280 +++++++++++++++++++++++++----- 3 files changed, 244 insertions(+), 149 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 08f141f84..07e6a04e7 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -34,8 +34,8 @@ user_permission = Permission(RoleNeed("user")) # only import the octoprint stuff down here, as it might depend on things defined above to be initialized already from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection, admin_validator, \ - UrlForwardHandler, user_validator, GcodeWatchdogHandler, UploadCleanupWatchdogHandler, LargeUploadHandler, \ - access_validation_factory, StreamedWsgiContainer, StreamingFallbackHandler + UrlForwardHandler, user_validator, GcodeWatchdogHandler, UploadCleanupWatchdogHandler, \ + access_validation_factory, StreamedWsgiContainer, StreamingFallbackHandler, PrintableFilesUploadHandler from octoprint.printer import Printer, getConnectionOptions from octoprint.settings import settings import octoprint.gcodefiles as gcodefiles @@ -186,8 +186,8 @@ class Server(): (r"/downloads/files/local/([^/]*\.(gco|gcode))", LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)), (r"/downloads/logs/([^/]*)", LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=access_validation_factory(app, loginManager, admin_validator))), (r"/downloads/camera/current", UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=access_validation_factory(app, loginManager, user_validator))), - (r"/uploads/files/([^/]*)", LargeUploadHandler, dict(access_validation=access_validation_factory(app, loginManager, user_validator))), - (r".*", StreamingFallbackHandler, dict(fallback=StreamedWsgiContainer(app.wsgi_app))) + (r"/api/files/([^/]*)", PrintableFilesUploadHandler, dict(path=settings().getBaseFolder("uploads"), access_validation=access_validation_factory(app, loginManager, user_validator))), + (r".*", FallbackHandler, dict(fallback=WSGIContainer(app.wsgi_app))) ]) self._server = HTTPServer(self._tornado_app, max_body_size=1*1024*1024*1024) self._server.listen(self._port, address=self._host) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 1d17da2bc..555e730a4 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -86,110 +86,7 @@ def _verifyFileExists(origin, filename): @api.route("/files/", methods=["POST"]) @restricted_access def uploadGcodeFile(target): - if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 404) - - if not "file" in request.files.keys(): - return make_response("No file included", 400) - - if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): - return make_response("SD card support is disabled", 404) - - file = request.files["file"] - sd = target == FileDestinations.SDCARD - selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues - printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues - - if sd: - # validate that all preconditions for SD upload are met before attempting it - if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())): - return make_response("Can not upload to SD card, printer is either not operational or already busy", 409) - if not printer.isSdReady(): - return make_response("Can not upload to SD card, not yet initialized", 409) - - # determine current job - currentFilename = None - currentOrigin = None - currentJob = printer.getCurrentJob() - if currentJob is not None and "file" in currentJob.keys(): - currentJobFile = currentJob["file"] - if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): - currentFilename = currentJobFile["name"] - currentOrigin = currentJobFile["origin"] - - # determine future filename of file to be uploaded, abort if it can't be uploaded - futureFilename = gcodeManager.getFutureFilename(file) - if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): - return make_response("Can not upload file %s, wrong format?" % file.filename, 415) - - # prohibit overwriting currently selected file while it's being printed - if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused(): - return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) - - def fileProcessingFinished(filename, absFilename, destination): - """ - Callback for when the file processing (upload, optional slicing, addition to analysis queue) has - finished. - - Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. - """ - if destination == FileDestinations.SDCARD: - return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint) - else: - selectAndOrPrint(filename, absFilename, destination) - return filename - - def selectAndOrPrint(filename, absFilename, destination): - """ - Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only - the case after they have finished streaming to the printer, which is why this callback is also used - for the corresponding call to addSdFile. - - Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the - exact file is already selected, such reloading it. - """ - if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination): - printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) - - filename, done = gcodeManager.addFile(file, target, fileProcessingFinished) - if filename is None: - return make_response("Could not upload the file %s" % file.filename, 500) - - sdFilename = None - if isinstance(filename, tuple): - filename, sdFilename = filename - - eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) - - files = {} - location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) - files.update({ - FileDestinations.LOCAL: { - "name": filename, - "origin": FileDestinations.LOCAL, - "refs": { - "resource": location, - "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename - } - } - }) - - if sd and sdFilename: - location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) - files.update({ - FileDestinations.SDCARD: { - "name": sdFilename, - "origin": FileDestinations.SDCARD, - "refs": { - "resource": location - } - } - }) - - r = make_response(jsonify(files=files, done=done), 201) - r.headers["Location"] = location - #return redirect(url_for("index", _external=True) + "uploads/files/" + target, code=307) - return r + return redirect(url_for("index", _external=True) + "uploads/files/" + target, code=307) @api.route("/files//", methods=["GET"]) diff --git a/src/octoprint/server/util.py b/src/octoprint/server/util.py index b6a57be8f..ca9ee2417 100644 --- a/src/octoprint/server/util.py +++ b/src/octoprint/server/util.py @@ -1,8 +1,6 @@ # coding=utf-8 -from io import FileIO -from tempfile import NamedTemporaryFile, TemporaryFile +from tempfile import TemporaryFile from tornado.httputil import HTTPHeaders -from tornado.wsgi import WSGIContainer from octoprint.filemanager.destinations import FileDestinations __author__ = "Gina Häußge " @@ -28,7 +26,7 @@ import logging from functools import wraps from watchdog.events import PatternMatchingEventHandler -from octoprint.settings import settings +from octoprint.settings import settings, valid_boolean_trues import octoprint.timelapse import octoprint.server from octoprint.users import ApiUser @@ -237,29 +235,68 @@ class PrinterStateConnection(SockJSConnection): self.send({type: payload}) +@stream_request_body +class UploadStorageFallbackHandler(RequestHandler): + + def initialize(self, delegate, folder): + self.delegate = delegate + self.folder = folder + + # Parts information will be stored here + self.parts = dict() + + # files will be stored here + self.files = dict() + + # values will be stored here + self.values = dict() + + # Part currently being processed + self._current_part = None + # buffer needed for identifying form data parts + self._buffer = b"" + + # we only support multipart/form-data content, so check for that + self._bytes_left = self.request.headers.get("Content-Length", 0) + content_type = self.request.headers.get("Content-Type", "") + if not self._bytes_left or not content_type.startswith("multipart"): + raise HTTPError(405) + + # extract the multipart boundary + fields = content_type.split(";") + for field in fields: + k, sep, v = field.strip().partition("=") + if k == "boundary" and v: + if v.startswith(b'"') and v.endswith(b'"'): + self.boundary = tornado.escape.utf8(v[1:-1]) + else: + self.boundary = tornado.escape.utf8(v) + break + else: + raise HTTPError(400) + + + @stream_request_body class StreamingFallbackHandler(FallbackHandler): """A `RequestHandler` that wraps another HTTP server callback. The fallback is a callable object that accepts an `~.httputil.HTTPServerRequest`, such as an `Application` or - `tornado.wsgi.WSGIContainer`. This is most useful to use both + `octoprint.server.util.StreamedWSGIContainer`. This is most useful to use both Tornado ``RequestHandlers`` and WSGI in the same server. Typical usage:: - wsgi_app = tornado.wsgi.WSGIContainer( + wsgi_app = octoprint.server.util.StreamedWSGIContainer( django.core.handlers.wsgi.WSGIHandler()) application = tornado.web.Application([ (r"/foo", FooHandler), - (r".*", FallbackHandler, dict(fallback=wsgi_app), + (r".*", StreamingFallbackHandler, dict(fallback=wsgi_app), ]) """ def initialize(self, fallback): self.fallback = fallback - self._length_left = int(self.request.headers.get("Content-Length", 0)) - self._tmpfile = TemporaryFile() - def data_received(self, chunk): self._tmpfile.write(chunk) self._length_left -= len(chunk) @@ -268,17 +305,18 @@ class StreamingFallbackHandler(FallbackHandler): def finished_body(self): self._tmpfile.seek(0) - try: - body_stream = self._tmpfile - self.fallback(self.request, body_stream) - finally: - self._tmpfile.close() def prepare(self): - pass + self._length_left = int(self.request.headers.get("Content-Length", 0)) + self._tmpfile = TemporaryFile() def __getattribute__(self, name): if name in ("get", "post", "put", "patch"): + try: + body_stream = self._tmpfile + self.fallback(self.request, body_stream) + finally: + self._tmpfile.close() return lambda *args, **kwargs: None return object.__getattribute__(self, name) @@ -399,9 +437,9 @@ def access_validation_factory(app, login_manager, validator): :param request: The Tornado request for which to create the environment and context """ import flask - import io + import tornado.wsgi - wsgi_environ = StreamedWsgiContainer.environ(request, io.BytesIO("")) + wsgi_environ = tornado.wsgi.WSGIContainer.environ(request) with app.request_context(wsgi_environ): app.session_interface.open_session(app, flask.request) login_manager.reload_user() @@ -410,25 +448,32 @@ def access_validation_factory(app, login_manager, validator): @stream_request_body -class LargeUploadHandler(RequestHandler): +class PrintableFilesUploadHandler(RequestHandler): - def initialize(self, files_only=False, access_validation=None): - self.files_only = files_only + def initialize(self, path, postfix=".tmp", files_only=False, access_validation=None): + self._path = path + self._postfix = postfix + self._files_only = files_only self._access_validation = access_validation # Parts information will be stored here self.parts = dict() + # files will be stored here + self.files = dict() + + # values will be stored here + self.values = dict() + # Part currently being processed self._current_part = None - # bytes left to process in the stream - self._bytes_left = int(self.request.headers.get("Content-Length", 0)) # buffer needed for identifying form data parts - self._buffer = "" + self._buffer = b"" # we only support multipart/form-data content, so check for that + bytes_left = self.request.headers.get("Content-Length", 0) content_type = self.request.headers.get("Content-Type", "") - if not self._bytes_left or not content_type.startswith("multipart"): + if not bytes_left or not content_type.startswith("multipart"): raise HTTPError(405) # extract the multipart boundary @@ -445,9 +490,10 @@ class LargeUploadHandler(RequestHandler): raise HTTPError(400) def data_received(self, chunk): - self._bytes_left -= len(chunk) data = self._buffer + chunk + self.process_data(data) + def process_data(self, data): # check for boundary delimiter = b"--%s" % self.boundary delimiter_loc = data.find(delimiter) @@ -455,7 +501,7 @@ class LargeUploadHandler(RequestHandler): end_of_header = None if delimiter_loc != -1: # found the delimiter in the currently available data - data, self._buffer = data[0:delimiter], data[delimiter:] + data, self._buffer = data[0:delimiter_loc], data[delimiter_loc:] end_of_header = self._buffer.find("\r\n\r\n") else: # make sure any boundary (with single or double ==) contained at the end of chunk does not get @@ -470,14 +516,15 @@ class LargeUploadHandler(RequestHandler): if end_of_header >= 0: self._header(self._buffer[delimiter_len+2:end_of_header]) - self._buffer = self._buffer[end_of_header + 4] + self._buffer = self._buffer[end_of_header + 4:] if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--": # we saw the last boundary and are at the end of our request if self._current_part: self.onclose(self._current_part) self._current_part = None - return self.onfinish() + self._buffer = b"" + self.onfinish() def _header(self, header): # close any open parts @@ -495,7 +542,6 @@ class LargeUploadHandler(RequestHandler): disp_header = header.get("Content-Disposition", "") disposition, disp_params = tornado.httputil._parse_header(disp_header) - next = False if disposition != "form-data": # TODO log warning return @@ -503,20 +549,30 @@ class LargeUploadHandler(RequestHandler): # TODO log warning return - if self.files_only and "filename" not in disp_params: + if self._files_only and "filename" not in disp_params: # TODO log warning return else: - self._current_part = self.onpart(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if self._files_only else None) + self._current_part = self.onpart(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None) def onpart(self, name, content_type, filename=None): + from octoprint.server import gcodeManager + if content_type is None: # we got a key-value-pair return dict(name=name, value=b"") - elif content_type == "application/octet-stream": + elif filename is not None: # this is a file - tmpfile = NamedTemporaryFile() - return dict(name=name, filename=filename, file=tmpfile) + upload = Object() + upload.filename = filename + + sane_filename = gcodeManager.getFutureFilename(upload) + if sane_filename is None: + return dict() + + local_path = os.path.join(self._path, sane_filename + self._postfix) + handle = open(local_path, "wb") + return dict(name=name, filename=filename, sane_filename=sane_filename, content_type=content_type, local_path=local_path, file=handle) else: return dict() @@ -527,21 +583,161 @@ class LargeUploadHandler(RequestHandler): part["file"].write(data) def onclose(self, part): - for part in self.parts: - if "value" in part: - self._get_argument() - self.parts[part["name"]] = part + escaped_name = tornado.escape.utf8(part["name"]) + + self.parts[escaped_name] = part + if "file" in part: + part["file"].close() + del part["file"] + self.files[escaped_name] = part + elif "value" in part: + escaped_value = tornado.escape.utf8(part["value"]) + self.values[escaped_name] = escaped_value + self.request.body_arguments.setdefault(escaped_name, []).append(escaped_value) def onfinish(self): - pass + # we now do something horrible and replace the body by a version stripped of all files. Yes, I feel bad for this + import io + new_body = b"" + for name, value in self.values.iteritems(): + new_body += b"--%s\r\n" % self.boundary + new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n\r\n" % name + new_body += value + new_body += b"--%s--\r\n" % self.boundary + self.request.body = new_body + self.request.headers["Content-Length"] = len(new_body) def post(self, *args, **kwargs): + while len(self._buffer): + self.process_data(self._buffer) + + from octoprint.server import gcodeManager, printer, eventManager + if self._access_validation is not None: self._access_validation(self.request) + target = self.request.path.split("/")[-1] + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + self.set_status(404, reason="Unknown target: %s" % target) + return - raise HTTPError(550, "Yay") + if not "file" in self.files: + self.set_status(400, reason="No file included") + return + + if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): + self.set_status(404, reason="SD card support is disabled") + return + + import octoprint.util + + upload = Object() + upload.filename = self.files["file"]["filename"] + upload.sane_filename = self.files["file"]["sane_filename"] + upload.save = lambda new_name: octoprint.util.safeRename(self.files["file"]["local_path"], new_name) + + sd = target == FileDestinations.SDCARD + selectAfterUpload = "select" in self.values and self.values["select"] in valid_boolean_trues + printAfterSelect = "print" in self.values and self.values["print"] in valid_boolean_trues + + if sd: + # validate that all preconditions for SD upload are met before attempting it + if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())): + self.set_status(409, reason="Can not upload to SD card, printer is either not operational or already busy") + return + if not printer.isSdReady(): + self.set_status(409, "Can not upload to SD card, not yet initialized") + return + + # determine current job + currentFilename = None + currentOrigin = None + currentJob = printer.getCurrentJob() + if currentJob is not None and "file" in currentJob.keys(): + currentJobFile = currentJob["file"] + if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): + currentFilename = currentJobFile["name"] + currentOrigin = currentJobFile["origin"] + + # determine future filename of file to be uploaded, abort if it can't be uploaded + futureFilename = upload.sane_filename + if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): + self.set_status(415, reason="Can not upload file %s, wrong format?" % upload.filename) + return + + # prohibit overwriting currently selected file while it's being printed + if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused(): + self.set_status(409, reason="Trying to overwrite file that is currently being printed: %s" % currentFilename) + return + + def fileProcessingFinished(filename, absFilename, destination): + """ + Callback for when the file processing (upload, optional slicing, addition to analysis queue) has + finished. + + Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. + """ + if destination == FileDestinations.SDCARD: + return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint) + else: + selectAndOrPrint(filename, absFilename, destination) + return filename + + def selectAndOrPrint(filename, absFilename, destination): + """ + Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only + the case after they have finished streaming to the printer, which is why this callback is also used + for the corresponding call to addSdFile. + + Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the + exact file is already selected, such reloading it. + """ + if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination): + printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) + + filename, done = gcodeManager.addFile(upload, target, fileProcessingFinished) + if filename is None: + return make_response("Could not upload the file %s" % upload.filename, 500) + + sdFilename = None + if isinstance(filename, tuple): + filename, sdFilename = filename + + eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) + + """ + files = {} + location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) + files.update({ + FileDestinations.LOCAL: { + "name": filename, + "origin": FileDestinations.LOCAL, + "refs": { + "resource": location, + "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename + } + } + }) + + if sd and sdFilename: + location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) + files.update({ + FileDestinations.SDCARD: { + "name": sdFilename, + "origin": FileDestinations.SDCARD, + "refs": { + "resource": location + } + } + }) + """ + + import tornado.escape + + self.set_status(201) + #self.set_header("Location", location) + self.finish(tornado.escape.json_encode(dict(files={}, done=done))) #~~ customized large response handler @@ -875,3 +1071,5 @@ class GcodeWatchdogHandler(PatternMatchingEventHandler): self._upload(event.src_path) +class Object(object): + pass \ No newline at end of file From e9ca09da876d227e6017fb15fb39d3f215e0e55f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 4 Aug 2014 14:45:46 +0200 Subject: [PATCH 09/29] Introduced UploadStorageFallbackHandler which rewrites multipart file upload forms to store the contained files in temporary files (like nginx-upload), made the file upload API in OctoPrint utilize this --- src/octoprint/server/__init__.py | 6 +- src/octoprint/server/api/files.py | 113 ++++++- src/octoprint/server/util.py | 475 ++++++++++++++++++++++++++---- 3 files changed, 540 insertions(+), 54 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 07e6a04e7..8f29dd53b 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -35,7 +35,8 @@ user_permission = Permission(RoleNeed("user")) # only import the octoprint stuff down here, as it might depend on things defined above to be initialized already from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection, admin_validator, \ UrlForwardHandler, user_validator, GcodeWatchdogHandler, UploadCleanupWatchdogHandler, \ - access_validation_factory, StreamedWsgiContainer, StreamingFallbackHandler, PrintableFilesUploadHandler + access_validation_factory, WsgiInputContainer, StreamingFallbackHandler, PrintableFilesUploadHandler, \ + UploadStorageFallbackHandler from octoprint.printer import Printer, getConnectionOptions from octoprint.settings import settings import octoprint.gcodefiles as gcodefiles @@ -186,8 +187,7 @@ class Server(): (r"/downloads/files/local/([^/]*\.(gco|gcode))", LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)), (r"/downloads/logs/([^/]*)", LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=access_validation_factory(app, loginManager, admin_validator))), (r"/downloads/camera/current", UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=access_validation_factory(app, loginManager, user_validator))), - (r"/api/files/([^/]*)", PrintableFilesUploadHandler, dict(path=settings().getBaseFolder("uploads"), access_validation=access_validation_factory(app, loginManager, user_validator))), - (r".*", FallbackHandler, dict(fallback=WSGIContainer(app.wsgi_app))) + (r".*", UploadStorageFallbackHandler, dict(fallback=WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp")) ]) self._server = HTTPServer(self._tornado_app, max_body_size=1*1024*1024*1024) self._server.listen(self._port, address=self._host) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 555e730a4..eb71c14cf 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -86,7 +86,115 @@ def _verifyFileExists(origin, filename): @api.route("/files/", methods=["POST"]) @restricted_access def uploadGcodeFile(target): - return redirect(url_for("index", _external=True) + "uploads/files/" + target, code=307) + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 404) + + if "file.name" in request.values and "file.path" in request.values: + import shutil + upload = Object() + upload.filename = request.values["file.name"] + upload.save = lambda new_path: shutil.move(request.values["file.path"], new_path) + elif "file" in request.files: + upload = request.files["file"] + else: + return make_response("No file included", 400) + + if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): + return make_response("SD card support is disabled", 404) + + sd = target == FileDestinations.SDCARD + selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues + printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues + + if sd: + # validate that all preconditions for SD upload are met before attempting it + if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())): + return make_response("Can not upload to SD card, printer is either not operational or already busy", 409) + if not printer.isSdReady(): + return make_response("Can not upload to SD card, not yet initialized", 409) + + # determine current job + currentFilename = None + currentOrigin = None + currentJob = printer.getCurrentJob() + if currentJob is not None and "file" in currentJob.keys(): + currentJobFile = currentJob["file"] + if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): + currentFilename = currentJobFile["name"] + currentOrigin = currentJobFile["origin"] + + # determine future filename of file to be uploaded, abort if it can't be uploaded + futureFilename = gcodeManager.getFutureFilename(upload) + if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): + return make_response("Can not upload file %s, wrong format?" % upload.filename, 415) + + # prohibit overwriting currently selected file while it's being printed + if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused(): + return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) + + def fileProcessingFinished(filename, absFilename, destination): + """ + Callback for when the file processing (upload, optional slicing, addition to analysis queue) has + finished. + + Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. + """ + if destination == FileDestinations.SDCARD: + return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint) + else: + selectAndOrPrint(filename, absFilename, destination) + return filename + + def selectAndOrPrint(filename, absFilename, destination): + """ + Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only + the case after they have finished streaming to the printer, which is why this callback is also used + for the corresponding call to addSdFile. + + Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the + exact file is already selected, such reloading it. + """ + if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination): + printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) + + filename, done = gcodeManager.addFile(upload, target, fileProcessingFinished) + if filename is None: + return make_response("Could not upload the file %s" % upload.filename, 500) + + sdFilename = None + if isinstance(filename, tuple): + filename, sdFilename = filename + + eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) + + files = {} + location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) + files.update({ + FileDestinations.LOCAL: { + "name": filename, + "origin": FileDestinations.LOCAL, + "refs": { + "resource": location, + "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename + } + } + }) + + if sd and sdFilename: + location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) + files.update({ + FileDestinations.SDCARD: { + "name": sdFilename, + "origin": FileDestinations.SDCARD, + "refs": { + "resource": location + } + } + }) + + r = make_response(jsonify(files=files, done=done), 201) + r.headers["Location"] = location + return r @api.route("/files//", methods=["GET"]) @@ -172,3 +280,6 @@ def deleteGcodeFile(filename, target): return NO_CONTENT + +class Object(object): + pass diff --git a/src/octoprint/server/util.py b/src/octoprint/server/util.py index ca9ee2417..f4e6f4aba 100644 --- a/src/octoprint/server/util.py +++ b/src/octoprint/server/util.py @@ -237,44 +237,354 @@ class PrinterStateConnection(SockJSConnection): @stream_request_body class UploadStorageFallbackHandler(RequestHandler): + """ + A `RequestHandler` similar to `tornado.web.FallbackHandler` which fetches any files contained in the request bodies + of content type `multipart`, stores them in temporary files and supplies the `fallback` with the file's `name`, + `content_type`, `path` and `size` instead via a rewritten body. - def initialize(self, delegate, folder): - self.delegate = delegate - self.folder = folder + Basically similar to what the nginx upload module does. - # Parts information will be stored here - self.parts = dict() + Basic request body example: - # files will be stored here - self.files = dict() + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file"; filename="test.gcode" + Content-Type: application/octet-stream - # values will be stored here - self.values = dict() + ... + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="apikey" + + my_funny_apikey + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="select" + + true + ------WebKitFormBoundarypYiSUx63abAmhT5C-- + + That would get turned into: + + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="apikey" + + my_funny_apikey + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="select" + + true + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.path" + + /tmp/tmpzupkro + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.name" + + test.gcode + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.content_type" + + application/octet-stream + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.size" + + 349182 + ------WebKitFormBoundarypYiSUx63abAmhT5C-- + + The underlying application can then access the contained files via their respective paths and just move them + where necessary. + """ + + # the request methods that may contain a request body + BODY_METHODS = ("POST", "PATCH", "PUT") + + def initialize(self, fallback, file_prefix="tmp", file_suffix="", path=None, suffixes=None): + if not suffixes: + suffixes = dict() + + self._fallback = fallback + self._file_prefix = file_prefix + self._file_suffix = file_suffix + self._path = path + + self._suffixes = dict((key, key) for key in ("name", "path", "content_type", "size")) + for suffix_type, suffix in suffixes.iteritems(): + if suffix_type in self._suffixes and suffix is not None: + self._suffixes[suffix_type] = suffix + + # Parts, files and values will be stored here + self._parts = dict() + self._files = [] # Part currently being processed self._current_part = None + + # content type of request body + self._content_type = None + + # bytes left to read according to content_length of request body + self._bytes_left = 0 + # buffer needed for identifying form data parts self._buffer = b"" - # we only support multipart/form-data content, so check for that - self._bytes_left = self.request.headers.get("Content-Length", 0) - content_type = self.request.headers.get("Content-Type", "") - if not self._bytes_left or not content_type.startswith("multipart"): - raise HTTPError(405) + # buffer for new body + self._new_body = b"" - # extract the multipart boundary - fields = content_type.split(";") - for field in fields: - k, sep, v = field.strip().partition("=") - if k == "boundary" and v: - if v.startswith(b'"') and v.endswith(b'"'): - self.boundary = tornado.escape.utf8(v[1:-1]) + # logger + self._logger = logging.getLogger(__name__) + + def prepare(self): + """ + Prepares the processing of the request. If it's a request that may contain a request body (as defined in + `UploadStorageFallbackHandler.BODY_METHODS) prepares the multipart parsing if content type fits. If it's a + body-less request, just calls the `fallback` with an empty body and finishes the request. + """ + if self.request.method in UploadStorageFallbackHandler.BODY_METHODS: + self._bytes_left = self.request.headers.get("Content-Length", 0) + self._content_type = self.request.headers.get("Content-Type", None) + + # request might contain a body + if self.is_multipart(): + if not self._bytes_left: + # we don't support requests without a content-length + raise HTTPError(400, reason="No Content-Length supplied") + + # extract the multipart boundary + fields = self._content_type.split(";") + for field in fields: + k, sep, v = field.strip().partition("=") + if k == "boundary" and v: + if v.startswith(b'"') and v.endswith(b'"'): + self._multipart_boundary = tornado.escape.utf8(v[1:-1]) + else: + self._multipart_boundary = tornado.escape.utf8(v) + break else: - self.boundary = tornado.escape.utf8(v) - break + self._multipart_boundary = None else: - raise HTTPError(400) + self._fallback(self.request, b"") + self._finished = True + def data_received(self, chunk): + """ + Called by Tornado on receiving a chunk of the request body. If request is a multipart request, takes care of + processing the multipart data structure via `self._process_multipart_data`. If not, just adds the chunk to + internal in-memory buffer. + + :param chunk: chunk of data received from Tornado + """ + + data = self._buffer + chunk + if self.is_multipart(): + self._process_multipart_data(data) + else: + self._buffer = data + + def is_multipart(self): + """Checks whether this request is a `multipart` request""" + return self._content_type is not None and self._content_type.startswith("multipart") + + def _process_multipart_data(self, data): + """ + Processes the given data, parsing it for multipart definitions and calling the appropriate methods. + + :param data: the data to process as a string + """ + + # check for boundary + delimiter = b"--%s" % self._multipart_boundary + delimiter_loc = data.find(delimiter) + delimiter_len = len(delimiter) + end_of_header = None + if delimiter_loc != -1: + # found the delimiter in the currently available data + data, self._buffer = data[0:delimiter_loc], data[delimiter_loc:] + end_of_header = self._buffer.find("\r\n\r\n") + else: + # make sure any boundary (with single or double ==) contained at the end of chunk does not get + # truncated by this processing round => save it to the buffer for next round + endlen = len(self._multipart_boundary) + 4 + data, self._buffer = data[0:-endlen], data[-endlen:] + + # stream data to part handler + if data: + if self._current_part: + self._on_data(self._current_part, data) + + if end_of_header >= 0: + self._on_header(self._buffer[delimiter_len+2:end_of_header]) + self._buffer = self._buffer[end_of_header + 4:] + + if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--": + # we saw the last boundary and are at the end of our request + if self._current_part: + self._on_close(self._current_part) + self._current_part = None + self._buffer = b"" + self._on_finish() + + def _on_header(self, header): + """ + Called for a new multipart header, takes care of parsing the header and calling `self._on_part` with the + relevant data, setting the current part in the process. + + :param header: header to parse + """ + + # close any open parts + if self._current_part: + self._on_close(self._current_part) + self._current_part = None + + header_check = header.find(self._multipart_boundary) + if header_check != -1: + self._logger.warn("Header still contained multipart boundary, stripping it...") + header = header[header_check:] + + # convert to dict + header = HTTPHeaders.parse(header.decode("utf-8")) + disp_header = header.get("Content-Disposition", "") + disposition, disp_params = tornado.httputil._parse_header(disp_header) + + if disposition != "form-data": + self._logger.warn("Got a multipart header without form-data content disposition, ignoring that one") + return + if not disp_params.get("name"): + self._logger.warn("Got a multipart header without name, ignoring that one") + return + + self._current_part = self._on_part(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None) + + def _on_part(self, name, content_type, filename=None): + """ + Called for new parts in the multipart stream. If `filename` is given creates new `file` part (which leads + to storage of the data as temporary file on disk), if not creates a new `data` part (which stores + incoming data in memory). + + Structure of `file` parts: + + * `name`: name of the part + * `filename`: filename associated with the part + * `path`: path to the temporary file storing the file's data + * `content_type`: content type of the part + * `file`: file handle for the temporary file (mode "wb", not deleted on close!) + + Structure of `data` parts: + + * `name`: name of the part + * `content_type`: content type of the part + * `data`: bytes of the part (initialized to "") + + :param name: name of the part + :param content_type: content type of the part + :param filename: filename associated with the part. + :return: dict describing the new part + """ + if filename is not None: + # this is a file + import tempfile + handle = tempfile.NamedTemporaryFile(mode="wb", prefix=self._file_prefix, suffix=self._file_suffix, dir=self._path, delete=False) + return dict(name=tornado.escape.utf8(name), + filename=tornado.escape.utf8(filename), + path=tornado.escape.utf8(handle.name), + content_type=tornado.escape.utf8(content_type), + file=handle) + + else: + return dict(name=tornado.escape.utf8(name), content_type=content_type, data=b"") + + def _on_data(self, part, data): + """ + Called when new bytes are received for the given `part`, takes care of writing them to their storage. + + :param part: part for which data was received + :param data: data chunk which was received + """ + if "file" in part: + part["file"].write(data) + else: + part["data"] += data + + def _on_close(self, part): + """ + Called when a part gets closed, takes care of storing the finished part in the internal parts storage and for + `file` parts closing the temporary file and storing the part in the internal files storage. + + :param part: part which was closed + """ + name = part["name"] + self._parts[name] = part + if "file" in part: + self._files.append(part["path"]) + part["file"].close() + del part["file"] + + def _on_finish(self): + """ + Called when the request body has been read completely. Takes care of creating the replacement body out of the + logged parts, turning `file` parts into new + :return: + """ + + self._new_body = b"" + for name, part in self._parts.iteritems(): + if "filename" in part: + # add form fields for filename, path, size and content_type for all files contained in the request + fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems()) + for n, p in fields.iteritems(): + key = name + "." + n + self._new_body += b"--%s\r\n" % self._multipart_boundary + self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key + self._new_body += b"\r\n" + self._new_body += p + b"\r\n" + elif "data" in part: + self._new_body += b"--%s\r\n" % self._multipart_boundary + value = part["data"] + self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % name + if "content_type" in part and part["content_type"] is not None: + self._new_body += b"Content-Type: %s\r\n" % part["content_type"] + self._new_body += b"\r\n" + self._new_body += value + self._new_body += b"--%s--\r\n" % self._multipart_boundary + + def _handle_method(self, *args, **kwargs): + """ + Handler for any request method, takes care of defining the new request body if necessary and forwarding + the current request and changed body to the `fallback`. + """ + + # determine which body to supply + body = b"" + if self.is_multipart(): + # make sure we really processed all data in the buffer + while len(self._buffer): + self._process_multipart_data(self._buffer) + + # use rewritten body + body = self._new_body + + elif self.request.method in UploadStorageFallbackHandler.BODY_METHODS: + # directly use data from buffer + body = self._buffer + + # rewrite content length + self.request.headers["Content-Length"] = len(body) + + try: + # call the configured fallback with request and body to use + self._fallback(self.request, body) + finally: + # make sure the temporary files are removed again + for f in self._files: + util.silentRemove(f) + + # make all http methods trigger _handle_method + get = _handle_method + post = _handle_method + put = _handle_method + patch = _handle_method + delete = _handle_method + head = _handle_method + options = _handle_method @stream_request_body @@ -294,39 +604,88 @@ class StreamingFallbackHandler(FallbackHandler): (r".*", StreamingFallbackHandler, dict(fallback=wsgi_app), ]) """ - def initialize(self, fallback): - self.fallback = fallback - def data_received(self, chunk): - self._tmpfile.write(chunk) - self._length_left -= len(chunk) - if self._length_left <= 0: - self.finished_body() + NO_BODY_METHODS = ("GET", "HEAD", "OPTIONS") - def finished_body(self): - self._tmpfile.seek(0) + def initialize(self, fallback, max_size=50*1024*1024*1024, file_prefix="tmp"): + self._fallback = fallback + self._max_size = max_size + self._file_prefix = file_prefix def prepare(self): - self._length_left = int(self.request.headers.get("Content-Length", 0)) - self._tmpfile = TemporaryFile() + if self.request.method not in StreamingFallbackHandler.NO_BODY_METHODS: + import tempfile + self._length_left = int(self.request.headers.get("Content-Length", 0)) + self._tempfile = tempfile.TemporaryFile(prefix=self._file_prefix) + else: + import io + self._fallback(self.request, io.BytesIO()) + self._finished = True - def __getattribute__(self, name): - if name in ("get", "post", "put", "patch"): - try: - body_stream = self._tmpfile - self.fallback(self.request, body_stream) - finally: - self._tmpfile.close() - return lambda *args, **kwargs: None - return object.__getattribute__(self, name) + def data_received(self, chunk): + if self.request.method not in StreamingFallbackHandler.NO_BODY_METHODS: + self._tempfile.write(chunk) + self._length_left -= len(chunk) + if self._length_left <= 0: + self.finished_body() + + def finished_body(self): + self._tempfile.seek(0) + + def get(self, *args, **kwargs): + return self._handle_method() + + def post(self, *args, **kwargs): + return self._handle_method() + + def put(self, *args, **kwargs): + return self._handle_method() + + def delete(self, *args, **kwargs): + return self._handle_method() + + def head(self, *args, **kwargs): + return self._handle_method() + + def options(self, *args, **kwargs): + return self._handle_method() + + def _handle_method(self): + try: + self._fallback(self.request, self._tempfile) + finally: + self._tempfile.close() -class StreamedWsgiContainer(object): +class WsgiInputContainer(object): + """ + A WSGI container for use with Tornado that allows supplying the request body to be used for `wsgi.input` in the + generated WSGI environment upon call. + + A `RequestHandler` can thus provide the WSGI application with a stream for the request body, or a modified body. + + Example usage: + + wsgi_app = octoprint.server.util.WsgiInputContainer(octoprint_app) + application = tornado.web.Application([ + (r".*", UploadStorageFallbackHandler, dict(fallback=wsgi_app), + ]) + + The implementation logic is basically the same as `tornado.wsgi.WSGIContainer` but the `__call__` and `environ` + + """ def __init__(self, wsgi_application): self.wsgi_application = wsgi_application - def __call__(self, request, body_stream): + def __call__(self, request, body=None): + """ + Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado `HTTPServerRequest`. + + :param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from + :param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream + """ + data = {} response = [] @@ -335,7 +694,7 @@ class StreamedWsgiContainer(object): data["headers"] = response_headers return response.append app_response = self.wsgi_application( - StreamedWsgiContainer.environ(request, body_stream), start_response) + WsgiInputContainer.environ(request, body), start_response) try: response.extend(app_response) body = b"".join(response) @@ -367,13 +726,29 @@ class StreamedWsgiContainer(object): self._log(status_code, request) @staticmethod - def environ(request, body_stream): - """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. + def environ(request, body=None): + """ + Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. + + An optional `body` to be used for populating `wsgi.input` can be supplied (either a string or a stream). If not + supplied, `request.body` will be wrapped into a `io.BytesIO` stream and used instead. + + :param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from + :param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream """ from tornado.wsgi import to_wsgi_str import sys import io + # determine the request_body to supply as wsgi.input + if body is not None: + if isinstance(body, (bytes, str)): + request_body = io.BytesIO(tornado.escape.utf8(body)) + else: + request_body = body + else: + request_body = io.BytesIO(tornado.escape.utf8(request.body)) + hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] @@ -393,7 +768,7 @@ class StreamedWsgiContainer(object): "SERVER_PROTOCOL": request.version, "wsgi.version": (1, 0), "wsgi.url_scheme": request.protocol, - "wsgi.input": body_stream, + "wsgi.input": request_body, "wsgi.errors": sys.stderr, "wsgi.multithread": False, "wsgi.multiprocess": True, From b4af85f405a1a0bd90814f6f65bb6dabf1e272ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 5 Aug 2014 11:26:13 +0200 Subject: [PATCH 10/29] Finalizing upload streaming support Major refactoring of octoprint.server.util (divided into smaller submodules), extended Tornado to allow for request-specific max content lengths, introduced settings parameters to configure maximum upload size, maximum request body size and file suffixes See #455 --- src/octoprint/server/__init__.py | 52 +- src/octoprint/server/api/__init__.py | 14 +- src/octoprint/server/api/connection.py | 6 +- src/octoprint/server/api/files.py | 27 +- src/octoprint/server/api/job.py | 6 +- src/octoprint/server/api/log.py | 9 +- src/octoprint/server/api/printer.py | 8 +- src/octoprint/server/api/settings.py | 6 +- src/octoprint/server/api/timelapse.py | 9 +- src/octoprint/server/api/users.py | 6 +- src/octoprint/server/util.py | 1450 ------------------------ src/octoprint/server/util/__init__.py | 100 ++ src/octoprint/server/util/flask.py | 154 +++ src/octoprint/server/util/sockjs.py | 124 ++ src/octoprint/server/util/tornado.py | 853 ++++++++++++++ src/octoprint/server/util/watchdog.py | 87 ++ src/octoprint/settings.py | 14 +- src/octoprint/util/__init__.py | 4 + 18 files changed, 1422 insertions(+), 1507 deletions(-) delete mode 100644 src/octoprint/server/util.py create mode 100644 src/octoprint/server/util/__init__.py create mode 100644 src/octoprint/server/util/flask.py create mode 100644 src/octoprint/server/util/sockjs.py create mode 100644 src/octoprint/server/util/tornado.py create mode 100644 src/octoprint/server/util/watchdog.py diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 8f29dd53b..96890a401 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1,13 +1,13 @@ # coding=utf-8 -import uuid +from __future__ import absolute_import __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -import flask -import tornado.wsgi +import uuid from sockjs.tornado import SockJSRouter -from flask import Flask, render_template, send_from_directory, make_response +from flask import Flask, render_template, send_from_directory from flask.ext.login import LoginManager from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed from watchdog.observers import Observer @@ -33,18 +33,16 @@ admin_permission = Permission(RoleNeed("admin")) user_permission = Permission(RoleNeed("user")) # only import the octoprint stuff down here, as it might depend on things defined above to be initialized already -from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection, admin_validator, \ - UrlForwardHandler, user_validator, GcodeWatchdogHandler, UploadCleanupWatchdogHandler, \ - access_validation_factory, WsgiInputContainer, StreamingFallbackHandler, PrintableFilesUploadHandler, \ - UploadStorageFallbackHandler from octoprint.printer import Printer, getConnectionOptions from octoprint.settings import settings import octoprint.gcodefiles as gcodefiles -import octoprint.util as util import octoprint.users as users import octoprint.events as events import octoprint.timelapse import octoprint._version +import octoprint.util + +from . import util UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes) @@ -121,10 +119,8 @@ class Server(): global loginManager global debug - from tornado.wsgi import WSGIContainer - from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop - from tornado.web import Application, FallbackHandler + from tornado.web import Application debug = self._debug @@ -152,12 +148,12 @@ class Server(): if settings().getBoolean(["accessControl", "enabled"]): userManagerName = settings().get(["accessControl", "userManager"]) try: - clazz = util.getClass(userManagerName) + clazz = octoprint.util.getClass(userManagerName) userManager = clazz() except AttributeError, e: logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName) - app.wsgi_app = ReverseProxied(app.wsgi_app) + app.wsgi_app = util.ReverseProxied(app.wsgi_app) app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV" loginManager = LoginManager() @@ -182,14 +178,18 @@ class Server(): self._router = SockJSRouter(self._createSocketConnection, "/sockjs") + upload_suffixes = dict(name=settings().get(["server", "uploads", "nameSuffix"]), path=settings().get(["server", "uploads", "pathSuffix"])) self._tornado_app = Application(self._router.urls + [ - (r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, dict(path=settings().getBaseFolder("timelapse"), as_attachment=True)), - (r"/downloads/files/local/([^/]*\.(gco|gcode))", LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)), - (r"/downloads/logs/([^/]*)", LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=access_validation_factory(app, loginManager, admin_validator))), - (r"/downloads/camera/current", UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=access_validation_factory(app, loginManager, user_validator))), - (r".*", UploadStorageFallbackHandler, dict(fallback=WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp")) + (r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("timelapse"), as_attachment=True)), + (r"/downloads/files/local/([^/]*\.(gco|gcode))", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)), + (r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))), + (r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))), + (r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes)) ]) - self._server = HTTPServer(self._tornado_app, max_body_size=1*1024*1024*1024) + max_body_sizes = [ + ("POST", r"/api/files/([^/]*)", settings().getInt(["server", "uploads", "maxSize"])) + ] + self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=10*1024) self._server.listen(self._port, address=self._host) eventManager.fire(events.Events.STARTUP) @@ -201,8 +201,8 @@ class Server(): # start up watchdogs observer = Observer() - observer.schedule(GcodeWatchdogHandler(gcodeManager, printer), settings().getBaseFolder("watched")) - observer.schedule(UploadCleanupWatchdogHandler(gcodeManager), settings().getBaseFolder("uploads")) + observer.schedule(util.watchdog.GcodeWatchdogHandler(gcodeManager, printer), settings().getBaseFolder("watched")) + observer.schedule(util.watchdog.UploadCleanupWatchdogHandler(gcodeManager), settings().getBaseFolder("uploads")) observer.start() try: @@ -218,7 +218,7 @@ class Server(): def _createSocketConnection(self, session): global printer, gcodeManager, userManager, eventManager - return PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session) + return util.sockjs.PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session) def _checkForRoot(self): if "geteuid" in dir(os) and os.geteuid() == 0: @@ -283,7 +283,7 @@ class Server(): with open(logConf, "r") as f: configFromFile = yaml.safe_load(f) - config = util.dict_merge(defaultConfig, configFromFile) + config = octoprint.util.dict_merge(defaultConfig, configFromFile) logging.config.dictConfig(config) if settings().getBoolean(["serial", "log"]): @@ -292,5 +292,5 @@ class Server(): logging.getLogger("SERIAL").debug("Enabling serial logging") if __name__ == "__main__": - octoprint = Server() - octoprint.run() + server = Server() + server.run() diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 2af447263..5e021ac1c 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -1,8 +1,9 @@ # coding=utf-8 -from octoprint.server.util import getApiKey, getUserForApiKey +from __future__ import absolute_import __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import netaddr @@ -15,8 +16,11 @@ from flask.ext.principal import Identity, identity_changed, AnonymousIdentity import octoprint.util as util import octoprint.users import octoprint.server -from octoprint.server import restricted_access, admin_permission, NO_CONTENT, UI_API_KEY +from octoprint.server import admin_permission, NO_CONTENT, UI_API_KEY from octoprint.settings import settings as s, valid_boolean_trues +from octoprint.server.util import get_api_key, get_user_for_apikey +from octoprint.server.util.flask import restricted_access + #~~ init api blueprint, including sub modules @@ -67,7 +71,7 @@ def beforeApiRequests(): if request.method == 'OPTIONS' and s().getBoolean(["api", "allowCrossOrigin"]): return optionsAllowOrigin(request) - apikey = getApiKey(request) + apikey = get_api_key(request) if apikey is None: # no api key => 401 return make_response("No API key provided", 401) @@ -84,7 +88,7 @@ def beforeApiRequests(): # global api key => continue regular request processing return - user = getUserForApiKey(apikey) + user = get_user_for_apikey(apikey) if user is not None: # user specific api key => continue regular request processing return @@ -143,7 +147,7 @@ def apiPrinterState(): def apiVersion(): return jsonify({ "server": octoprint.server.VERSION, - "api": octoprint.server.api.VERSION + "api": VERSION }) #~~ system control diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index 683c4e9de..f947e8601 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -1,13 +1,17 @@ # coding=utf-8 +from __future__ import absolute_import + __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, jsonify, make_response from octoprint.settings import settings from octoprint.printer import getConnectionOptions -from octoprint.server import printer, restricted_access, NO_CONTENT +from octoprint.server import printer, NO_CONTENT from octoprint.server.api import api +from octoprint.server.util.flask import restricted_access import octoprint.util as util diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index eb71c14cf..8f0dd0622 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -1,17 +1,20 @@ # coding=utf-8 -from octoprint.events import Events +from __future__ import absolute_import __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -from flask import request, jsonify, make_response, url_for, redirect +from flask import request, jsonify, make_response, url_for import octoprint.gcodefiles as gcodefiles import octoprint.util as util from octoprint.filemanager.destinations import FileDestinations from octoprint.settings import settings, valid_boolean_trues -from octoprint.server import printer, gcodeManager, eventManager, restricted_access, NO_CONTENT +from octoprint.server import printer, gcodeManager, eventManager, NO_CONTENT +from octoprint.server.util.flask import restricted_access from octoprint.server.api import api +from octoprint.events import Events #~~ GCODE file handling @@ -89,13 +92,16 @@ def uploadGcodeFile(target): if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Unknown target: %s" % target, 404) - if "file.name" in request.values and "file.path" in request.values: + input_name = "file" + input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) + input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) + if input_upload_name in request.values and input_upload_path in request.values: import shutil - upload = Object() - upload.filename = request.values["file.name"] - upload.save = lambda new_path: shutil.move(request.values["file.path"], new_path) - elif "file" in request.files: - upload = request.files["file"] + upload = util.Object() + upload.filename = request.values[input_upload_name] + upload.save = lambda new_path: shutil.move(request.values[input_upload_path], new_path) + elif input_name in request.files: + upload = request.files[input_name] else: return make_response("No file included", 400) @@ -280,6 +286,3 @@ def deleteGcodeFile(filename, target): return NO_CONTENT - -class Object(object): - pass diff --git a/src/octoprint/server/api/job.py b/src/octoprint/server/api/job.py index 3ee86a1a3..84eacd8a9 100644 --- a/src/octoprint/server/api/job.py +++ b/src/octoprint/server/api/job.py @@ -1,10 +1,14 @@ # coding=utf-8 +from __future__ import absolute_import + __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, make_response, jsonify -from octoprint.server import printer, restricted_access, NO_CONTENT +from octoprint.server import printer, NO_CONTENT +from octoprint.server.util.flask import restricted_access from octoprint.server.api import api import octoprint.util as util diff --git a/src/octoprint/server/api/log.py b/src/octoprint/server/api/log.py index 44159d27d..b1131b320 100644 --- a/src/octoprint/server/api/log.py +++ b/src/octoprint/server/api/log.py @@ -1,6 +1,9 @@ # coding=utf-8 +from __future__ import absolute_import + __author__ = "Marc Hannappel Salandora" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import os @@ -9,8 +12,8 @@ from werkzeug.utils import secure_filename from octoprint.settings import settings -from octoprint.server import restricted_access, NO_CONTENT, admin_permission -from octoprint.server.util import redirectToTornado +from octoprint.server import NO_CONTENT, admin_permission +from octoprint.server.util.flask import redirect_to_tornado, restricted_access from octoprint.server.api import api from octoprint.util import getFreeBytes @@ -27,7 +30,7 @@ def getLogFiles(): @restricted_access @admin_permission.require(403) def downloadLog(filename): - return redirectToTornado(request, url_for("index") + "downloads/logs/" + filename) + return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename) @api.route("/logs/", methods=["DELETE"]) diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index 391898701..55ae6d3b1 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -1,13 +1,17 @@ # coding=utf-8 +from __future__ import absolute_import + __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -from flask import request, jsonify, make_response +from flask import request, jsonify, make_response, Response import re from octoprint.settings import settings, valid_boolean_trues -from octoprint.server import printer, restricted_access, NO_CONTENT +from octoprint.server import printer, NO_CONTENT from octoprint.server.api import api +from octoprint.server.util.flask import restricted_access import octoprint.util as util #~~ Printer diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index b2306d9e2..8c7a5c565 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -1,6 +1,9 @@ # coding=utf-8 +from __future__ import absolute_import + __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging @@ -9,8 +12,9 @@ from flask import request, jsonify from octoprint.settings import settings from octoprint.printer import getConnectionOptions -from octoprint.server import restricted_access, admin_permission +from octoprint.server import admin_permission from octoprint.server.api import api +from octoprint.server.util.flask import restricted_access #~~ settings diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 91898e180..11f27e5b3 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -1,6 +1,9 @@ # coding=utf-8 +from __future__ import absolute_import + __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import os @@ -11,8 +14,8 @@ import octoprint.timelapse import octoprint.util as util from octoprint.settings import settings, valid_boolean_trues -from octoprint.server import restricted_access, admin_permission -from octoprint.server.util import redirectToTornado +from octoprint.server import admin_permission +from octoprint.server.util.flask import redirect_to_tornado, restricted_access from octoprint.server.api import api @@ -46,7 +49,7 @@ def getTimelapseData(): @api.route("/timelapse/", methods=["GET"]) def downloadTimelapse(filename): - return redirectToTornado(request, url_for("index") + "downloads/timelapse/" + filename) + return redirect_to_tornado(request, url_for("index") + "downloads/timelapse/" + filename) @api.route("/timelapse/", methods=["DELETE"]) diff --git a/src/octoprint/server/api/users.py b/src/octoprint/server/api/users.py index 9228acc98..2b6f4022d 100644 --- a/src/octoprint/server/api/users.py +++ b/src/octoprint/server/api/users.py @@ -1,14 +1,18 @@ # coding=utf-8 +from __future__ import absolute_import + __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, jsonify, abort, make_response from flask.ext.login import current_user import octoprint.users as users -from octoprint.server import restricted_access, SUCCESS, admin_permission, userManager +from octoprint.server import SUCCESS, admin_permission, userManager from octoprint.server.api import api +from octoprint.server.util.flask import restricted_access #~~ user settings diff --git a/src/octoprint/server/util.py b/src/octoprint/server/util.py deleted file mode 100644 index f4e6f4aba..000000000 --- a/src/octoprint/server/util.py +++ /dev/null @@ -1,1450 +0,0 @@ -# coding=utf-8 -from tempfile import TemporaryFile -from tornado.httputil import HTTPHeaders -from octoprint.filemanager.destinations import FileDestinations - -__author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' - -from flask.ext.principal import identity_changed, Identity -from tornado.web import StaticFileHandler, HTTPError, RequestHandler, asynchronous, stream_request_body, FallbackHandler -import tornado.escape, tornado.httputil -from tornado.httpclient import AsyncHTTPClient, HTTPRequest -from flask import url_for, make_response, request, current_app -from flask.ext.login import login_required, login_user, current_user -from werkzeug.utils import redirect -from sockjs.tornado import SockJSConnection - -import datetime -import stat -import mimetypes -import email -import time -import os -import threading -import logging -from functools import wraps -from watchdog.events import PatternMatchingEventHandler - -from octoprint.settings import settings, valid_boolean_trues -import octoprint.timelapse -import octoprint.server -from octoprint.users import ApiUser -from octoprint.events import Events -from octoprint import gcodefiles -import octoprint.util as util - -def restricted_access(func, apiEnabled=True): - """ - If you decorate a view with this, it will ensure that first setup has been - done for OctoPrint's Access Control plus that any conditions of the - login_required decorator are met. It also allows to login using the masterkey or any - of the user's apikeys if API access is enabled globally and for the decorated view. - - If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun" - flag from the settings being set to True and the userManager not indicating - that it's user database has been customized from default), the decorator - will cause a HTTP 403 status code to be returned by the decorated resource. - - If an API key is provided and it matches a known key, the user will be logged in and - the view will be called directly. If the provided key doesn't match any known key, - a HTTP 403 status code will be returned by the decorated resource. - - Otherwise the result of calling login_required will be returned. - """ - @wraps(func) - def decorated_view(*args, **kwargs): - # if OctoPrint hasn't been set up yet, abort - if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()): - return make_response("OctoPrint isn't setup yet", 403) - - # if API is globally enabled, enabled for this request and an api key is provided that is not the current UI API key, try to use that - apikey = getApiKey(request) - if settings().get(["api", "enabled"]) and apiEnabled and apikey is not None and apikey != octoprint.server.UI_API_KEY: - if apikey == settings().get(["api", "key"]): - # master key was used - user = ApiUser() - else: - # user key might have been used - user = octoprint.server.userManager.findUser(apikey=apikey) - - if user is None: - return make_response("Invalid API key", 401) - if login_user(user, remember=False): - identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) - return func(*args, **kwargs) - - # call regular login_required decorator - return login_required(func)(*args, **kwargs) - return decorated_view - - -def api_access(func): - @wraps(func) - def decorated_view(*args, **kwargs): - if not settings().get(["api", "enabled"]): - make_response("API disabled", 401) - apikey = getApiKey(request) - if apikey is None: - make_response("No API key provided", 401) - if apikey != settings().get(["api", "key"]): - make_response("Invalid API key", 403) - return func(*args, **kwargs) - return decorated_view - - -def getUserForApiKey(apikey): - if settings().get(["api", "enabled"]) and apikey is not None: - if apikey == settings().get(["api", "key"]): - # master key was used - return ApiUser() - else: - # user key might have been used - return octoprint.server.userManager.findUser(apikey=apikey) - else: - return None - - -def getApiKey(request): - # Check Flask GET/POST arguments - if hasattr(request, "values") and "apikey" in request.values: - return request.values["apikey"] - - # Check Tornado GET/POST arguments - if hasattr(request, "arguments") and "apikey" in request.arguments \ - and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0: - return request.arguments["apikey"] - - # Check Tornado and Flask headers - if "X-Api-Key" in request.headers.keys(): - return request.headers.get("X-Api-Key") - - return None - - -#~~ Printer state - - -class PrinterStateConnection(SockJSConnection): - EVENTS = [Events.UPDATED_FILES, Events.METADATA_ANALYSIS_FINISHED, Events.MOVIE_RENDERING, Events.MOVIE_DONE, - Events.MOVIE_FAILED, Events.SLICING_STARTED, Events.SLICING_DONE, Events.SLICING_FAILED, - Events.TRANSFER_STARTED, Events.TRANSFER_DONE] - - def __init__(self, printer, gcodeManager, userManager, eventManager, session): - SockJSConnection.__init__(self, session) - - self._logger = logging.getLogger(__name__) - - self._temperatureBacklog = [] - self._temperatureBacklogMutex = threading.Lock() - self._logBacklog = [] - self._logBacklogMutex = threading.Lock() - self._messageBacklog = [] - self._messageBacklogMutex = threading.Lock() - - self._printer = printer - self._gcodeManager = gcodeManager - self._userManager = userManager - self._eventManager = eventManager - - def _getRemoteAddress(self, info): - forwardedFor = info.headers.get("X-Forwarded-For") - if forwardedFor is not None: - return forwardedFor.split(",")[0] - return info.ip - - def on_open(self, info): - remoteAddress = self._getRemoteAddress(info) - self._logger.info("New connection from client: %s" % remoteAddress) - - # connected => update the API key, might be necessary if the client was left open while the server restarted - self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION}) - - self._printer.registerCallback(self) - self._gcodeManager.registerCallback(self) - octoprint.timelapse.registerCallback(self) - - self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress}) - for event in PrinterStateConnection.EVENTS: - self._eventManager.subscribe(event, self._onEvent) - - octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current) - - def on_close(self): - self._logger.info("Client connection closed") - self._printer.unregisterCallback(self) - self._gcodeManager.unregisterCallback(self) - octoprint.timelapse.unregisterCallback(self) - - self._eventManager.fire(Events.CLIENT_CLOSED) - for event in PrinterStateConnection.EVENTS: - self._eventManager.unsubscribe(event, self._onEvent) - - def on_message(self, message): - pass - - def sendCurrentData(self, data): - # add current temperature, log and message backlogs to sent data - with self._temperatureBacklogMutex: - temperatures = self._temperatureBacklog - self._temperatureBacklog = [] - - with self._logBacklogMutex: - logs = self._logBacklog - self._logBacklog = [] - - with self._messageBacklogMutex: - messages = self._messageBacklog - self._messageBacklog = [] - - data.update({ - "temps": temperatures, - "logs": logs, - "messages": messages - }) - self._emit("current", data) - - def sendHistoryData(self, data): - self._emit("history", data) - - def sendEvent(self, type, payload=None): - self._emit("event", {"type": type, "payload": payload}) - - def sendFeedbackCommandOutput(self, name, output): - self._emit("feedbackCommandOutput", {"name": name, "output": output}) - - def sendTimelapseConfig(self, timelapseConfig): - self._emit("timelapse", timelapseConfig) - - def addLog(self, data): - with self._logBacklogMutex: - self._logBacklog.append(data) - - def addMessage(self, data): - with self._messageBacklogMutex: - self._messageBacklog.append(data) - - def addTemperature(self, data): - with self._temperatureBacklogMutex: - self._temperatureBacklog.append(data) - - def _onEvent(self, event, payload): - self.sendEvent(event, payload) - - def _emit(self, type, payload): - self.send({type: payload}) - - -@stream_request_body -class UploadStorageFallbackHandler(RequestHandler): - """ - A `RequestHandler` similar to `tornado.web.FallbackHandler` which fetches any files contained in the request bodies - of content type `multipart`, stores them in temporary files and supplies the `fallback` with the file's `name`, - `content_type`, `path` and `size` instead via a rewritten body. - - Basically similar to what the nginx upload module does. - - Basic request body example: - - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file"; filename="test.gcode" - Content-Type: application/octet-stream - - ... - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="apikey" - - my_funny_apikey - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="select" - - true - ------WebKitFormBoundarypYiSUx63abAmhT5C-- - - That would get turned into: - - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="apikey" - - my_funny_apikey - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="select" - - true - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file.path" - - /tmp/tmpzupkro - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file.name" - - test.gcode - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file.content_type" - - application/octet-stream - ------WebKitFormBoundarypYiSUx63abAmhT5C - Content-Disposition: form-data; name="file.size" - - 349182 - ------WebKitFormBoundarypYiSUx63abAmhT5C-- - - The underlying application can then access the contained files via their respective paths and just move them - where necessary. - """ - - # the request methods that may contain a request body - BODY_METHODS = ("POST", "PATCH", "PUT") - - def initialize(self, fallback, file_prefix="tmp", file_suffix="", path=None, suffixes=None): - if not suffixes: - suffixes = dict() - - self._fallback = fallback - self._file_prefix = file_prefix - self._file_suffix = file_suffix - self._path = path - - self._suffixes = dict((key, key) for key in ("name", "path", "content_type", "size")) - for suffix_type, suffix in suffixes.iteritems(): - if suffix_type in self._suffixes and suffix is not None: - self._suffixes[suffix_type] = suffix - - # Parts, files and values will be stored here - self._parts = dict() - self._files = [] - - # Part currently being processed - self._current_part = None - - # content type of request body - self._content_type = None - - # bytes left to read according to content_length of request body - self._bytes_left = 0 - - # buffer needed for identifying form data parts - self._buffer = b"" - - # buffer for new body - self._new_body = b"" - - # logger - self._logger = logging.getLogger(__name__) - - def prepare(self): - """ - Prepares the processing of the request. If it's a request that may contain a request body (as defined in - `UploadStorageFallbackHandler.BODY_METHODS) prepares the multipart parsing if content type fits. If it's a - body-less request, just calls the `fallback` with an empty body and finishes the request. - """ - if self.request.method in UploadStorageFallbackHandler.BODY_METHODS: - self._bytes_left = self.request.headers.get("Content-Length", 0) - self._content_type = self.request.headers.get("Content-Type", None) - - # request might contain a body - if self.is_multipart(): - if not self._bytes_left: - # we don't support requests without a content-length - raise HTTPError(400, reason="No Content-Length supplied") - - # extract the multipart boundary - fields = self._content_type.split(";") - for field in fields: - k, sep, v = field.strip().partition("=") - if k == "boundary" and v: - if v.startswith(b'"') and v.endswith(b'"'): - self._multipart_boundary = tornado.escape.utf8(v[1:-1]) - else: - self._multipart_boundary = tornado.escape.utf8(v) - break - else: - self._multipart_boundary = None - else: - self._fallback(self.request, b"") - self._finished = True - - def data_received(self, chunk): - """ - Called by Tornado on receiving a chunk of the request body. If request is a multipart request, takes care of - processing the multipart data structure via `self._process_multipart_data`. If not, just adds the chunk to - internal in-memory buffer. - - :param chunk: chunk of data received from Tornado - """ - - data = self._buffer + chunk - if self.is_multipart(): - self._process_multipart_data(data) - else: - self._buffer = data - - def is_multipart(self): - """Checks whether this request is a `multipart` request""" - return self._content_type is not None and self._content_type.startswith("multipart") - - def _process_multipart_data(self, data): - """ - Processes the given data, parsing it for multipart definitions and calling the appropriate methods. - - :param data: the data to process as a string - """ - - # check for boundary - delimiter = b"--%s" % self._multipart_boundary - delimiter_loc = data.find(delimiter) - delimiter_len = len(delimiter) - end_of_header = None - if delimiter_loc != -1: - # found the delimiter in the currently available data - data, self._buffer = data[0:delimiter_loc], data[delimiter_loc:] - end_of_header = self._buffer.find("\r\n\r\n") - else: - # make sure any boundary (with single or double ==) contained at the end of chunk does not get - # truncated by this processing round => save it to the buffer for next round - endlen = len(self._multipart_boundary) + 4 - data, self._buffer = data[0:-endlen], data[-endlen:] - - # stream data to part handler - if data: - if self._current_part: - self._on_data(self._current_part, data) - - if end_of_header >= 0: - self._on_header(self._buffer[delimiter_len+2:end_of_header]) - self._buffer = self._buffer[end_of_header + 4:] - - if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--": - # we saw the last boundary and are at the end of our request - if self._current_part: - self._on_close(self._current_part) - self._current_part = None - self._buffer = b"" - self._on_finish() - - def _on_header(self, header): - """ - Called for a new multipart header, takes care of parsing the header and calling `self._on_part` with the - relevant data, setting the current part in the process. - - :param header: header to parse - """ - - # close any open parts - if self._current_part: - self._on_close(self._current_part) - self._current_part = None - - header_check = header.find(self._multipart_boundary) - if header_check != -1: - self._logger.warn("Header still contained multipart boundary, stripping it...") - header = header[header_check:] - - # convert to dict - header = HTTPHeaders.parse(header.decode("utf-8")) - disp_header = header.get("Content-Disposition", "") - disposition, disp_params = tornado.httputil._parse_header(disp_header) - - if disposition != "form-data": - self._logger.warn("Got a multipart header without form-data content disposition, ignoring that one") - return - if not disp_params.get("name"): - self._logger.warn("Got a multipart header without name, ignoring that one") - return - - self._current_part = self._on_part(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None) - - def _on_part(self, name, content_type, filename=None): - """ - Called for new parts in the multipart stream. If `filename` is given creates new `file` part (which leads - to storage of the data as temporary file on disk), if not creates a new `data` part (which stores - incoming data in memory). - - Structure of `file` parts: - - * `name`: name of the part - * `filename`: filename associated with the part - * `path`: path to the temporary file storing the file's data - * `content_type`: content type of the part - * `file`: file handle for the temporary file (mode "wb", not deleted on close!) - - Structure of `data` parts: - - * `name`: name of the part - * `content_type`: content type of the part - * `data`: bytes of the part (initialized to "") - - :param name: name of the part - :param content_type: content type of the part - :param filename: filename associated with the part. - :return: dict describing the new part - """ - if filename is not None: - # this is a file - import tempfile - handle = tempfile.NamedTemporaryFile(mode="wb", prefix=self._file_prefix, suffix=self._file_suffix, dir=self._path, delete=False) - return dict(name=tornado.escape.utf8(name), - filename=tornado.escape.utf8(filename), - path=tornado.escape.utf8(handle.name), - content_type=tornado.escape.utf8(content_type), - file=handle) - - else: - return dict(name=tornado.escape.utf8(name), content_type=content_type, data=b"") - - def _on_data(self, part, data): - """ - Called when new bytes are received for the given `part`, takes care of writing them to their storage. - - :param part: part for which data was received - :param data: data chunk which was received - """ - if "file" in part: - part["file"].write(data) - else: - part["data"] += data - - def _on_close(self, part): - """ - Called when a part gets closed, takes care of storing the finished part in the internal parts storage and for - `file` parts closing the temporary file and storing the part in the internal files storage. - - :param part: part which was closed - """ - name = part["name"] - self._parts[name] = part - if "file" in part: - self._files.append(part["path"]) - part["file"].close() - del part["file"] - - def _on_finish(self): - """ - Called when the request body has been read completely. Takes care of creating the replacement body out of the - logged parts, turning `file` parts into new - :return: - """ - - self._new_body = b"" - for name, part in self._parts.iteritems(): - if "filename" in part: - # add form fields for filename, path, size and content_type for all files contained in the request - fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems()) - for n, p in fields.iteritems(): - key = name + "." + n - self._new_body += b"--%s\r\n" % self._multipart_boundary - self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key - self._new_body += b"\r\n" - self._new_body += p + b"\r\n" - elif "data" in part: - self._new_body += b"--%s\r\n" % self._multipart_boundary - value = part["data"] - self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % name - if "content_type" in part and part["content_type"] is not None: - self._new_body += b"Content-Type: %s\r\n" % part["content_type"] - self._new_body += b"\r\n" - self._new_body += value - self._new_body += b"--%s--\r\n" % self._multipart_boundary - - def _handle_method(self, *args, **kwargs): - """ - Handler for any request method, takes care of defining the new request body if necessary and forwarding - the current request and changed body to the `fallback`. - """ - - # determine which body to supply - body = b"" - if self.is_multipart(): - # make sure we really processed all data in the buffer - while len(self._buffer): - self._process_multipart_data(self._buffer) - - # use rewritten body - body = self._new_body - - elif self.request.method in UploadStorageFallbackHandler.BODY_METHODS: - # directly use data from buffer - body = self._buffer - - # rewrite content length - self.request.headers["Content-Length"] = len(body) - - try: - # call the configured fallback with request and body to use - self._fallback(self.request, body) - finally: - # make sure the temporary files are removed again - for f in self._files: - util.silentRemove(f) - - # make all http methods trigger _handle_method - get = _handle_method - post = _handle_method - put = _handle_method - patch = _handle_method - delete = _handle_method - head = _handle_method - options = _handle_method - - -@stream_request_body -class StreamingFallbackHandler(FallbackHandler): - """A `RequestHandler` that wraps another HTTP server callback. - - The fallback is a callable object that accepts an - `~.httputil.HTTPServerRequest`, such as an `Application` or - `octoprint.server.util.StreamedWSGIContainer`. This is most useful to use both - Tornado ``RequestHandlers`` and WSGI in the same server. Typical - usage:: - - wsgi_app = octoprint.server.util.StreamedWSGIContainer( - django.core.handlers.wsgi.WSGIHandler()) - application = tornado.web.Application([ - (r"/foo", FooHandler), - (r".*", StreamingFallbackHandler, dict(fallback=wsgi_app), - ]) - """ - - NO_BODY_METHODS = ("GET", "HEAD", "OPTIONS") - - def initialize(self, fallback, max_size=50*1024*1024*1024, file_prefix="tmp"): - self._fallback = fallback - self._max_size = max_size - self._file_prefix = file_prefix - - def prepare(self): - if self.request.method not in StreamingFallbackHandler.NO_BODY_METHODS: - import tempfile - self._length_left = int(self.request.headers.get("Content-Length", 0)) - self._tempfile = tempfile.TemporaryFile(prefix=self._file_prefix) - else: - import io - self._fallback(self.request, io.BytesIO()) - self._finished = True - - def data_received(self, chunk): - if self.request.method not in StreamingFallbackHandler.NO_BODY_METHODS: - self._tempfile.write(chunk) - self._length_left -= len(chunk) - if self._length_left <= 0: - self.finished_body() - - def finished_body(self): - self._tempfile.seek(0) - - def get(self, *args, **kwargs): - return self._handle_method() - - def post(self, *args, **kwargs): - return self._handle_method() - - def put(self, *args, **kwargs): - return self._handle_method() - - def delete(self, *args, **kwargs): - return self._handle_method() - - def head(self, *args, **kwargs): - return self._handle_method() - - def options(self, *args, **kwargs): - return self._handle_method() - - def _handle_method(self): - try: - self._fallback(self.request, self._tempfile) - finally: - self._tempfile.close() - - -class WsgiInputContainer(object): - """ - A WSGI container for use with Tornado that allows supplying the request body to be used for `wsgi.input` in the - generated WSGI environment upon call. - - A `RequestHandler` can thus provide the WSGI application with a stream for the request body, or a modified body. - - Example usage: - - wsgi_app = octoprint.server.util.WsgiInputContainer(octoprint_app) - application = tornado.web.Application([ - (r".*", UploadStorageFallbackHandler, dict(fallback=wsgi_app), - ]) - - The implementation logic is basically the same as `tornado.wsgi.WSGIContainer` but the `__call__` and `environ` - - """ - - def __init__(self, wsgi_application): - self.wsgi_application = wsgi_application - - def __call__(self, request, body=None): - """ - Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado `HTTPServerRequest`. - - :param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from - :param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream - """ - - data = {} - response = [] - - def start_response(status, response_headers, exc_info=None): - data["status"] = status - data["headers"] = response_headers - return response.append - app_response = self.wsgi_application( - WsgiInputContainer.environ(request, body), start_response) - try: - response.extend(app_response) - body = b"".join(response) - finally: - if hasattr(app_response, "close"): - app_response.close() - if not data: - raise Exception("WSGI app did not call start_response") - - status_code = int(data["status"].split()[0]) - headers = data["headers"] - header_set = set(k.lower() for (k, v) in headers) - body = tornado.escape.utf8(body) - if status_code != 304: - if "content-length" not in header_set: - headers.append(("Content-Length", str(len(body)))) - if "content-type" not in header_set: - headers.append(("Content-Type", "text/html; charset=UTF-8")) - if "server" not in header_set: - headers.append(("Server", "TornadoServer/%s" % tornado.version)) - - parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")] - for key, value in headers: - parts.append(tornado.escape.utf8(key) + b": " + tornado.escape.utf8(value) + b"\r\n") - parts.append(b"\r\n") - parts.append(body) - request.write(b"".join(parts)) - request.finish() - self._log(status_code, request) - - @staticmethod - def environ(request, body=None): - """ - Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. - - An optional `body` to be used for populating `wsgi.input` can be supplied (either a string or a stream). If not - supplied, `request.body` will be wrapped into a `io.BytesIO` stream and used instead. - - :param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from - :param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream - """ - from tornado.wsgi import to_wsgi_str - import sys - import io - - # determine the request_body to supply as wsgi.input - if body is not None: - if isinstance(body, (bytes, str)): - request_body = io.BytesIO(tornado.escape.utf8(body)) - else: - request_body = body - else: - request_body = io.BytesIO(tornado.escape.utf8(request.body)) - - hostport = request.host.split(":") - if len(hostport) == 2: - host = hostport[0] - port = int(hostport[1]) - else: - host = request.host - port = 443 if request.protocol == "https" else 80 - environ = { - "REQUEST_METHOD": request.method, - "SCRIPT_NAME": "", - "PATH_INFO": to_wsgi_str(tornado.escape.url_unescape( - request.path, encoding=None, plus=False)), - "QUERY_STRING": request.query, - "REMOTE_ADDR": request.remote_ip, - "SERVER_NAME": host, - "SERVER_PORT": str(port), - "SERVER_PROTOCOL": request.version, - "wsgi.version": (1, 0), - "wsgi.url_scheme": request.protocol, - "wsgi.input": request_body, - "wsgi.errors": sys.stderr, - "wsgi.multithread": False, - "wsgi.multiprocess": True, - "wsgi.run_once": False, - } - if "Content-Type" in request.headers: - environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") - if "Content-Length" in request.headers: - environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") - for key, value in request.headers.items(): - environ["HTTP_" + key.replace("-", "_").upper()] = value - return environ - - def _log(self, status_code, request): - access_log = logging.getLogger("tornado.access") - - if status_code < 400: - log_method = access_log.info - elif status_code < 500: - log_method = access_log.warning - else: - log_method = access_log.error - request_time = 1000.0 * request.request_time() - summary = request.method + " " + request.uri + " (" + \ - request.remote_ip + ")" - log_method("%d %s %.2fms", status_code, summary, request_time) - - -def access_validation_factory(app, login_manager, validator): - """ - Creates an access validation wrapper using the supplied validator. - - :param validator: the access validator to use inside the validation wrapper - :return: an access validation wrapper taking a request as parameter and performing the request validation - """ - def f(request): - """ - Creates a custom wsgi and Flask request context in order to be able to process user information - stored in the current session. - - :param request: The Tornado request for which to create the environment and context - """ - import flask - import tornado.wsgi - - wsgi_environ = tornado.wsgi.WSGIContainer.environ(request) - with app.request_context(wsgi_environ): - app.session_interface.open_session(app, flask.request) - login_manager.reload_user() - validator(flask.request) - return f - - -@stream_request_body -class PrintableFilesUploadHandler(RequestHandler): - - def initialize(self, path, postfix=".tmp", files_only=False, access_validation=None): - self._path = path - self._postfix = postfix - self._files_only = files_only - self._access_validation = access_validation - - # Parts information will be stored here - self.parts = dict() - - # files will be stored here - self.files = dict() - - # values will be stored here - self.values = dict() - - # Part currently being processed - self._current_part = None - # buffer needed for identifying form data parts - self._buffer = b"" - - # we only support multipart/form-data content, so check for that - bytes_left = self.request.headers.get("Content-Length", 0) - content_type = self.request.headers.get("Content-Type", "") - if not bytes_left or not content_type.startswith("multipart"): - raise HTTPError(405) - - # extract the multipart boundary - fields = content_type.split(";") - for field in fields: - k, sep, v = field.strip().partition("=") - if k == "boundary" and v: - if v.startswith(b'"') and v.endswith(b'"'): - self.boundary = tornado.escape.utf8(v[1:-1]) - else: - self.boundary = tornado.escape.utf8(v) - break - else: - raise HTTPError(400) - - def data_received(self, chunk): - data = self._buffer + chunk - self.process_data(data) - - def process_data(self, data): - # check for boundary - delimiter = b"--%s" % self.boundary - delimiter_loc = data.find(delimiter) - delimiter_len = len(delimiter) - end_of_header = None - if delimiter_loc != -1: - # found the delimiter in the currently available data - data, self._buffer = data[0:delimiter_loc], data[delimiter_loc:] - end_of_header = self._buffer.find("\r\n\r\n") - else: - # make sure any boundary (with single or double ==) contained at the end of chunk does not get - # truncated by this processing round => save it to the buffer for next round - endlen = len(self.boundary) + 4 - data, self._buffer = data[0:-endlen], data[-endlen:] - - # stream data to part handler - if data: - if self._current_part: - self.ondata(self._current_part, data) - - if end_of_header >= 0: - self._header(self._buffer[delimiter_len+2:end_of_header]) - self._buffer = self._buffer[end_of_header + 4:] - - if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--": - # we saw the last boundary and are at the end of our request - if self._current_part: - self.onclose(self._current_part) - self._current_part = None - self._buffer = b"" - self.onfinish() - - def _header(self, header): - # close any open parts - if self._current_part: - self.onclose(self._current_part) - self._current_part = None - - header_check = header.find(self.boundary) - if header_check != -1: - # TODO log warning - header = header[header_check:] - - # convert to dict - header = HTTPHeaders.parse(header.decode("utf-8")) - disp_header = header.get("Content-Disposition", "") - disposition, disp_params = tornado.httputil._parse_header(disp_header) - - if disposition != "form-data": - # TODO log warning - return - if not disp_params.get("name"): - # TODO log warning - return - - if self._files_only and "filename" not in disp_params: - # TODO log warning - return - else: - self._current_part = self.onpart(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None) - - def onpart(self, name, content_type, filename=None): - from octoprint.server import gcodeManager - - if content_type is None: - # we got a key-value-pair - return dict(name=name, value=b"") - elif filename is not None: - # this is a file - upload = Object() - upload.filename = filename - - sane_filename = gcodeManager.getFutureFilename(upload) - if sane_filename is None: - return dict() - - local_path = os.path.join(self._path, sane_filename + self._postfix) - handle = open(local_path, "wb") - return dict(name=name, filename=filename, sane_filename=sane_filename, content_type=content_type, local_path=local_path, file=handle) - else: - return dict() - - def ondata(self, part, data): - if "value" in part: - part["value"] += data - elif "file" in part: - part["file"].write(data) - - def onclose(self, part): - escaped_name = tornado.escape.utf8(part["name"]) - - self.parts[escaped_name] = part - if "file" in part: - part["file"].close() - del part["file"] - self.files[escaped_name] = part - elif "value" in part: - escaped_value = tornado.escape.utf8(part["value"]) - self.values[escaped_name] = escaped_value - self.request.body_arguments.setdefault(escaped_name, []).append(escaped_value) - - def onfinish(self): - # we now do something horrible and replace the body by a version stripped of all files. Yes, I feel bad for this - import io - new_body = b"" - for name, value in self.values.iteritems(): - new_body += b"--%s\r\n" % self.boundary - new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n\r\n" % name - new_body += value - new_body += b"--%s--\r\n" % self.boundary - self.request.body = new_body - self.request.headers["Content-Length"] = len(new_body) - - def post(self, *args, **kwargs): - while len(self._buffer): - self.process_data(self._buffer) - - from octoprint.server import gcodeManager, printer, eventManager - - if self._access_validation is not None: - self._access_validation(self.request) - - target = self.request.path.split("/")[-1] - - if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - self.set_status(404, reason="Unknown target: %s" % target) - return - - if not "file" in self.files: - self.set_status(400, reason="No file included") - return - - if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): - self.set_status(404, reason="SD card support is disabled") - return - - import octoprint.util - - upload = Object() - upload.filename = self.files["file"]["filename"] - upload.sane_filename = self.files["file"]["sane_filename"] - upload.save = lambda new_name: octoprint.util.safeRename(self.files["file"]["local_path"], new_name) - - sd = target == FileDestinations.SDCARD - selectAfterUpload = "select" in self.values and self.values["select"] in valid_boolean_trues - printAfterSelect = "print" in self.values and self.values["print"] in valid_boolean_trues - - if sd: - # validate that all preconditions for SD upload are met before attempting it - if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())): - self.set_status(409, reason="Can not upload to SD card, printer is either not operational or already busy") - return - if not printer.isSdReady(): - self.set_status(409, "Can not upload to SD card, not yet initialized") - return - - # determine current job - currentFilename = None - currentOrigin = None - currentJob = printer.getCurrentJob() - if currentJob is not None and "file" in currentJob.keys(): - currentJobFile = currentJob["file"] - if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): - currentFilename = currentJobFile["name"] - currentOrigin = currentJobFile["origin"] - - # determine future filename of file to be uploaded, abort if it can't be uploaded - futureFilename = upload.sane_filename - if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): - self.set_status(415, reason="Can not upload file %s, wrong format?" % upload.filename) - return - - # prohibit overwriting currently selected file while it's being printed - if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused(): - self.set_status(409, reason="Trying to overwrite file that is currently being printed: %s" % currentFilename) - return - - def fileProcessingFinished(filename, absFilename, destination): - """ - Callback for when the file processing (upload, optional slicing, addition to analysis queue) has - finished. - - Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. - """ - if destination == FileDestinations.SDCARD: - return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint) - else: - selectAndOrPrint(filename, absFilename, destination) - return filename - - def selectAndOrPrint(filename, absFilename, destination): - """ - Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only - the case after they have finished streaming to the printer, which is why this callback is also used - for the corresponding call to addSdFile. - - Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the - exact file is already selected, such reloading it. - """ - if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination): - printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) - - filename, done = gcodeManager.addFile(upload, target, fileProcessingFinished) - if filename is None: - return make_response("Could not upload the file %s" % upload.filename, 500) - - sdFilename = None - if isinstance(filename, tuple): - filename, sdFilename = filename - - eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) - - """ - files = {} - location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) - files.update({ - FileDestinations.LOCAL: { - "name": filename, - "origin": FileDestinations.LOCAL, - "refs": { - "resource": location, - "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename - } - } - }) - - if sd and sdFilename: - location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) - files.update({ - FileDestinations.SDCARD: { - "name": sdFilename, - "origin": FileDestinations.SDCARD, - "refs": { - "resource": location - } - } - }) - """ - - import tornado.escape - - self.set_status(201) - #self.set_header("Location", location) - self.finish(tornado.escape.json_encode(dict(files={}, done=done))) - - -#~~ customized large response handler - - -class LargeResponseHandler(StaticFileHandler): - - CHUNK_SIZE = 16 * 1024 - - def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None): - StaticFileHandler.initialize(self, path, default_filename) - self._as_attachment = as_attachment - self._access_validation = access_validation - - def get(self, path, include_body=True): - if self._access_validation is not None: - self._access_validation(self.request) - - path = self.parse_url_path(path) - abspath = os.path.abspath(os.path.join(self.root, path)) - # os.path.abspath strips a trailing / - # it needs to be temporarily added back for requests to root/ - if not (abspath + os.path.sep).startswith(self.root): - raise HTTPError(403, "%s is not in root static directory", path) - if os.path.isdir(abspath) and self.default_filename is not None: - # need to look at the request.path here for when path is empty - # but there is some prefix to the path that was already - # trimmed by the routing - if not self.request.path.endswith("/"): - self.redirect(self.request.path + "/") - return - abspath = os.path.join(abspath, self.default_filename) - if not os.path.exists(abspath): - raise HTTPError(404) - if not os.path.isfile(abspath): - raise HTTPError(403, "%s is not a file", path) - - stat_result = os.stat(abspath) - modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME]) - - self.set_header("Last-Modified", modified) - - mime_type, encoding = mimetypes.guess_type(abspath) - if mime_type: - self.set_header("Content-Type", mime_type) - - cache_time = self.get_cache_time(path, modified, mime_type) - - if cache_time > 0: - self.set_header("Expires", datetime.datetime.utcnow() + - datetime.timedelta(seconds=cache_time)) - self.set_header("Cache-Control", "max-age=" + str(cache_time)) - - self.set_extra_headers(path) - - # Check the If-Modified-Since, and don't send the result if the - # content has not been modified - ims_value = self.request.headers.get("If-Modified-Since") - if ims_value is not None: - date_tuple = email.utils.parsedate(ims_value) - if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple)) - if if_since >= modified: - self.set_status(304) - return - - if not include_body: - assert self.request.method == "HEAD" - self.set_header("Content-Length", stat_result[stat.ST_SIZE]) - else: - with open(abspath, "rb") as file: - while True: - data = file.read(LargeResponseHandler.CHUNK_SIZE) - if not data: - break - self.write(data) - self.flush() - - def set_extra_headers(self, path): - if self._as_attachment: - self.set_header("Content-Disposition", "attachment") - - -##~~ URL Forward Handler for forwarding requests to a preconfigured static URL - - -class UrlForwardHandler(RequestHandler): - - def initialize(self, url=None, as_attachment=False, basename=None, access_validation=None): - RequestHandler.initialize(self) - self._url = url - self._as_attachment = as_attachment - self._basename = basename - self._access_validation = access_validation - - @asynchronous - def get(self, *args, **kwargs): - if self._access_validation is not None: - self._access_validation(self.request) - - if self._url is None: - raise HTTPError(404) - - client = AsyncHTTPClient() - r = HTTPRequest(url=self._url, method=self.request.method, body=self.request.body, headers=self.request.headers, follow_redirects=False, allow_nonstandard_methods=True) - - try: - return client.fetch(r, self.handle_response) - except HTTPError as e: - if hasattr(e, "response") and e.response: - self.handle_response(e.response) - else: - raise HTTPError(500) - - def handle_response(self, response): - if response.error and not isinstance(response.error, HTTPError): - raise HTTPError(500) - - filename = None - - self.set_status(response.code) - for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"): - value = response.headers.get(name) - if value: - self.set_header(name, value) - - if name == "Content-Type": - filename = self.get_filename(value) - - if self._as_attachment: - if filename is not None: - self.set_header("Content-Disposition", "attachment; filename=%s" % filename) - else: - self.set_header("Content-Disposition", "attachment") - - if response.body: - self.write(response.body) - self.finish() - - def get_filename(self, content_type): - if not self._basename: - return None - - typeValue = map(str.strip, content_type.split(";")) - if len(typeValue) == 0: - return None - - extension = mimetypes.guess_extension(typeValue[0]) - if not extension: - return None - - return "%s%s" % (self._basename, extension) - - -#~~ admin access validator for use with tornado - - -def admin_validator(request): - """ - Validates that the given request is made by an admin user, identified either by API key or existing Flask - session. - - Must be executed in an existing Flask request context! - - :param request: The Flask request object - """ - - apikey = getApiKey(request) - if settings().get(["api", "enabled"]) and apikey is not None: - user = getUserForApiKey(apikey) - else: - user = current_user - - if user is None or not user.is_authenticated() or not user.is_admin(): - raise HTTPError(403) - - -#~~ user access validator for use with tornado - - -def user_validator(request): - """ - Validates that the given request is made by an authenticated user, identified either by API key or existing Flask - session. - - Must be executed in an existing Flask request context! - - :param request: The Flask request object - """ - - apikey = getApiKey(request) - if settings().get(["api", "enabled"]) and apikey is not None: - user = getUserForApiKey(apikey) - else: - user = current_user - - if user is None or not user.is_authenticated(): - raise HTTPError(403) - - -#~~ reverse proxy compatible wsgi middleware - - -class ReverseProxied(object): - """ - Wrap the application in this middleware and configure the - front-end server to add these headers, to let you quietly bind - this to a URL other than / and to an HTTP scheme that is - different than what is used locally. - - In nginx: - location /myprefix { - proxy_pass http://192.168.0.1:5001; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Scheme $scheme; - proxy_set_header X-Script-Name /myprefix; - } - - Alternatively define prefix and scheme via config.yaml: - server: - baseUrl: /myprefix - scheme: http - - :param app: the WSGI application - """ - - def __init__(self, app): - self.app = app - - def __call__(self, environ, start_response): - script_name = environ.get('HTTP_X_SCRIPT_NAME', '') - if not script_name: - script_name = settings().get(["server", "baseUrl"]) - - if script_name: - environ['SCRIPT_NAME'] = script_name - path_info = environ['PATH_INFO'] - if path_info.startswith(script_name): - environ['PATH_INFO'] = path_info[len(script_name):] - - scheme = environ.get('HTTP_X_SCHEME', '') - if not scheme: - scheme = settings().get(["server", "scheme"]) - - if scheme: - environ['wsgi.url_scheme'] = scheme - return self.app(environ, start_response) - - -def redirectToTornado(request, target, code=302): - requestUrl = request.url - appBaseUrl = requestUrl[:requestUrl.find(url_for("index") + "api")] - - redirectUrl = appBaseUrl + target - if "?" in requestUrl: - fragment = requestUrl[requestUrl.rfind("?"):] - redirectUrl += fragment - return redirect(redirectUrl, code=code) - - -class UploadCleanupWatchdogHandler(PatternMatchingEventHandler): - """ - Takes care of automatically deleting metadata entries for files that get deleted from the uploads folder - """ - - patterns = map(lambda x: "*.%s" % x, gcodefiles.GCODE_EXTENSIONS) - - def __init__(self, gcode_manager): - PatternMatchingEventHandler.__init__(self) - self._gcode_manager = gcode_manager - - def on_deleted(self, event): - filename = self._gcode_manager._getBasicFilename(event.src_path) - if not filename: - return - - self._gcode_manager.removeFileFromMetadata(filename) - - -class GcodeWatchdogHandler(PatternMatchingEventHandler): - """ - Takes care of automatically "uploading" files that get added to the watched folder. - """ - - patterns = map(lambda x: "*.%s" % x, gcodefiles.SUPPORTED_EXTENSIONS) - - def __init__(self, gcodeManager, printer): - PatternMatchingEventHandler.__init__(self) - - self._logger = logging.getLogger(__name__) - - self._gcodeManager = gcodeManager - self._printer = printer - - def _upload(self, path): - class WatchdogFileWrapper(object): - - def __init__(self, path): - self._path = path - self.filename = os.path.basename(self._path) - - def save(self, target): - util.safeRename(self._path, target) - - fileWrapper = WatchdogFileWrapper(path) - - # determine current job - currentFilename = None - currentOrigin = None - currentJob = self._printer.getCurrentJob() - if currentJob is not None and "file" in currentJob.keys(): - currentJobFile = currentJob["file"] - if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): - currentFilename = currentJobFile["name"] - currentOrigin = currentJobFile["origin"] - - # determine future filename of file to be uploaded, abort if it can't be uploaded - futureFilename = self._gcodeManager.getFutureFilename(fileWrapper) - if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): - self._logger.warn("Could not add %s: Invalid file" % fileWrapper.filename) - return - - # prohibit overwriting currently selected file while it's being printed - if futureFilename == currentFilename and not currentOrigin == FileDestinations.SDCARD and self._printer.isPrinting() or self._printer.isPaused(): - self._logger.warn("Could not add %s: Trying to overwrite file that is currently being printed" % fileWrapper.filename) - return - - self._gcodeManager.addFile(fileWrapper, FileDestinations.LOCAL) - - def on_created(self, event): - self._upload(event.src_path) - - -class Object(object): - pass \ No newline at end of file diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py new file mode 100644 index 000000000..66e673015 --- /dev/null +++ b/src/octoprint/server/util/__init__.py @@ -0,0 +1,100 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from octoprint.settings import settings +import octoprint.timelapse +import octoprint.server +from octoprint.users import ApiUser + +from . import flask +from . import sockjs +from . import tornado +from . import watchdog + + +def get_user_for_apikey(apikey): + if settings().get(["api", "enabled"]) and apikey is not None: + if apikey == settings().get(["api", "key"]): + # master key was used + return ApiUser() + else: + # user key might have been used + return octoprint.server.userManager.findUser(apikey=apikey) + else: + return None + + +def get_api_key(request): + # Check Flask GET/POST arguments + if hasattr(request, "values") and "apikey" in request.values: + return request.values["apikey"] + + # Check Tornado GET/POST arguments + if hasattr(request, "arguments") and "apikey" in request.arguments \ + and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0: + return request.arguments["apikey"] + + # Check Tornado and Flask headers + if "X-Api-Key" in request.headers.keys(): + return request.headers.get("X-Api-Key") + + return None + + +#~~ reverse proxy compatible WSGI middleware + + +class ReverseProxied(object): + """ + Wrap the application in this middleware and configure the + front-end server to add these headers, to let you quietly bind + this to a URL other than / and to an HTTP scheme that is + different than what is used locally. + + In nginx: + location /myprefix { + proxy_pass http://192.168.0.1:5001; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Scheme $scheme; + proxy_set_header X-Script-Name /myprefix; + } + + Alternatively define prefix and scheme via config.yaml: + server: + baseUrl: /myprefix + scheme: http + + :param app: the WSGI application + :param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix + :param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme + """ + + def __init__(self, app, header_script_name="HTTP_X_SCRIPT_NAME", header_scheme="HTTP_X_SCHEME"): + self.app = app + self._header_script_name = header_script_name + self._header_scheme = header_scheme + + def __call__(self, environ, start_response): + script_name = environ.get(self._header_script_name, '') + if not script_name: + script_name = settings().get(["server", "baseUrl"]) + + if script_name: + environ['SCRIPT_NAME'] = script_name + path_info = environ['PATH_INFO'] + if path_info.startswith(script_name): + environ['PATH_INFO'] = path_info[len(script_name):] + + scheme = environ.get(self._header_scheme, '') + if not scheme: + scheme = settings().get(["server", "scheme"]) + + if scheme: + environ['wsgi.url_scheme'] = scheme + return self.app(environ, start_response) + diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py new file mode 100644 index 000000000..414f5be51 --- /dev/null +++ b/src/octoprint/server/util/flask.py @@ -0,0 +1,154 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import tornado.web +import flask +import flask.ext.login +import flask.ext.principal +import functools + +from octoprint.settings import settings +import octoprint.server +import octoprint.users + + +#~~ access validators for use with tornado + + +def admin_validator(request): + """ + Validates that the given request is made by an admin user, identified either by API key or existing Flask + session. + + Must be executed in an existing Flask request context! + + :param request: The Flask request object + """ + + user = _get_flask_user_from_request(request) + if user is None or not user.is_authenticated() or not user.is_admin(): + raise tornado.web.HTTPError(403) + + +def user_validator(request): + """ + Validates that the given request is made by an authenticated user, identified either by API key or existing Flask + session. + + Must be executed in an existing Flask request context! + + :param request: The Flask request object + """ + + user = _get_flask_user_from_request(request) + if user is None or not user.is_authenticated(): + raise tornado.web.HTTPError(403) + + +def _get_flask_user_from_request(request): + """ + Retrieves the current flask user from the request context. Uses API key if available, otherwise the current + user session if available. + + :param request: flask request from which to retrieve the current user + :return: the user or None if no user could be determined + """ + import octoprint.server.util + import flask.ext.login + from octoprint.settings import settings + + apikey = octoprint.server.util.get_api_key(request) + if settings().get(["api", "enabled"]) and apikey is not None: + user = octoprint.server.util.get_user_for_apikey(apikey) + else: + user = flask.ext.login.current_user + + return user + + +def redirect_to_tornado(request, target, code=302): + """ + Redirects from flask to tornado, flask request context must exist. + + :param request: + :param target: + :param code: + :return: + """ + + import flask + + requestUrl = request.url + appBaseUrl = requestUrl[:requestUrl.find(flask.url_for("index") + "api")] + + redirectUrl = appBaseUrl + target + if "?" in requestUrl: + fragment = requestUrl[requestUrl.rfind("?"):] + redirectUrl += fragment + return flask.redirect(redirectUrl, code=code) + + +def restricted_access(func, api_enabled=True): + """ + If you decorate a view with this, it will ensure that first setup has been + done for OctoPrint's Access Control plus that any conditions of the + login_required decorator are met. It also allows to login using the masterkey or any + of the user's apikeys if API access is enabled globally and for the decorated view. + + If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun" + flag from the settings being set to True and the userManager not indicating + that it's user database has been customized from default), the decorator + will cause a HTTP 403 status code to be returned by the decorated resource. + + If an API key is provided and it matches a known key, the user will be logged in and + the view will be called directly. If the provided key doesn't match any known key, + a HTTP 403 status code will be returned by the decorated resource. + + Otherwise the result of calling login_required will be returned. + """ + @functools.wraps(func) + def decorated_view(*args, **kwargs): + # if OctoPrint hasn't been set up yet, abort + if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()): + return flask.make_response("OctoPrint isn't setup yet", 403) + + # if API is globally enabled, enabled for this request and an api key is provided that is not the current UI API key, try to use that + apikey = octoprint.server.util.get_api_key(flask.request) + if settings().get(["api", "enabled"]) and api_enabled and apikey is not None and apikey != octoprint.server.UI_API_KEY: + if apikey == settings().get(["api", "key"]): + # master key was used + user = octoprint.users.ApiUser() + else: + # user key might have been used + user = octoprint.server.userManager.findUser(apikey=apikey) + + if user is None: + return flask.make_response("Invalid API key", 401) + if flask.ext.login.login_user(user, remember=False): + flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id())) + return func(*args, **kwargs) + + # call regular login_required decorator + return flask.ext.login.login_required(func)(*args, **kwargs) + return decorated_view + + +def api_access(func): + @functools.wraps(func) + def decorated_view(*args, **kwargs): + if not settings().get(["api", "enabled"]): + flask.make_response("API disabled", 401) + apikey = octoprint.server.util.get_api_key(flask.request) + if apikey is None: + flask.make_response("No API key provided", 401) + if apikey != settings().get(["api", "key"]): + flask.make_response("Invalid API key", 403) + return func(*args, **kwargs) + return decorated_view + + + diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py new file mode 100644 index 000000000..bbd96863c --- /dev/null +++ b/src/octoprint/server/util/sockjs.py @@ -0,0 +1,124 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import logging +import threading +import sockjs.tornado + +import octoprint.timelapse +import octoprint.server +from octoprint.events import Events + + +class PrinterStateConnection(sockjs.tornado.SockJSConnection): + EVENTS = [Events.UPDATED_FILES, Events.METADATA_ANALYSIS_FINISHED, Events.MOVIE_RENDERING, Events.MOVIE_DONE, + Events.MOVIE_FAILED, Events.SLICING_STARTED, Events.SLICING_DONE, Events.SLICING_FAILED, + Events.TRANSFER_STARTED, Events.TRANSFER_DONE] + + def __init__(self, printer, gcodeManager, userManager, eventManager, session): + sockjs.tornado.SockJSConnection.__init__(self, session) + + self._logger = logging.getLogger(__name__) + + self._temperatureBacklog = [] + self._temperatureBacklogMutex = threading.Lock() + self._logBacklog = [] + self._logBacklogMutex = threading.Lock() + self._messageBacklog = [] + self._messageBacklogMutex = threading.Lock() + + self._printer = printer + self._gcodeManager = gcodeManager + self._userManager = userManager + self._eventManager = eventManager + + def _getRemoteAddress(self, info): + forwardedFor = info.headers.get("X-Forwarded-For") + if forwardedFor is not None: + return forwardedFor.split(",")[0] + return info.ip + + def on_open(self, info): + remoteAddress = self._getRemoteAddress(info) + self._logger.info("New connection from client: %s" % remoteAddress) + + # connected => update the API key, might be necessary if the client was left open while the server restarted + self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION}) + + self._printer.registerCallback(self) + self._gcodeManager.registerCallback(self) + octoprint.timelapse.registerCallback(self) + + self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress}) + for event in PrinterStateConnection.EVENTS: + self._eventManager.subscribe(event, self._onEvent) + + octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current) + + def on_close(self): + self._logger.info("Client connection closed") + self._printer.unregisterCallback(self) + self._gcodeManager.unregisterCallback(self) + octoprint.timelapse.unregisterCallback(self) + + self._eventManager.fire(Events.CLIENT_CLOSED) + for event in PrinterStateConnection.EVENTS: + self._eventManager.unsubscribe(event, self._onEvent) + + def on_message(self, message): + pass + + def sendCurrentData(self, data): + # add current temperature, log and message backlogs to sent data + with self._temperatureBacklogMutex: + temperatures = self._temperatureBacklog + self._temperatureBacklog = [] + + with self._logBacklogMutex: + logs = self._logBacklog + self._logBacklog = [] + + with self._messageBacklogMutex: + messages = self._messageBacklog + self._messageBacklog = [] + + data.update({ + "temps": temperatures, + "logs": logs, + "messages": messages + }) + self._emit("current", data) + + def sendHistoryData(self, data): + self._emit("history", data) + + def sendEvent(self, type, payload=None): + self._emit("event", {"type": type, "payload": payload}) + + def sendFeedbackCommandOutput(self, name, output): + self._emit("feedbackCommandOutput", {"name": name, "output": output}) + + def sendTimelapseConfig(self, timelapseConfig): + self._emit("timelapse", timelapseConfig) + + def addLog(self, data): + with self._logBacklogMutex: + self._logBacklog.append(data) + + def addMessage(self, data): + with self._messageBacklogMutex: + self._messageBacklog.append(data) + + def addTemperature(self, data): + with self._temperatureBacklogMutex: + self._temperatureBacklog.append(data) + + def _onEvent(self, event, payload): + self.sendEvent(event, payload) + + def _emit(self, type, payload): + self.send({type: payload}) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py new file mode 100644 index 000000000..38a5252e2 --- /dev/null +++ b/src/octoprint/server/util/tornado.py @@ -0,0 +1,853 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import logging +import os +import datetime +import stat +import mimetypes +import email +import time + +import tornado +import tornado.web +import tornado.gen +import tornado.escape +import tornado.httputil +import tornado.httpserver +import tornado.httpclient +import tornado.http1connection +import tornado.iostream +import tornado.tcpserver + +import octoprint.util + + +#~~ WSGI middleware + + +@tornado.web.stream_request_body +class UploadStorageFallbackHandler(tornado.web.RequestHandler): + """ + A `RequestHandler` similar to `tornado.web.FallbackHandler` which fetches any files contained in the request bodies + of content type `multipart`, stores them in temporary files and supplies the `fallback` with the file's `name`, + `content_type`, `path` and `size` instead via a rewritten body. + + Basically similar to what the nginx upload module does. + + Basic request body example: + + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file"; filename="test.gcode" + Content-Type: application/octet-stream + + ... + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="apikey" + + my_funny_apikey + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="select" + + true + ------WebKitFormBoundarypYiSUx63abAmhT5C-- + + That would get turned into: + + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="apikey" + + my_funny_apikey + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="select" + + true + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.path" + + /tmp/tmpzupkro + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.name" + + test.gcode + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.content_type" + + application/octet-stream + ------WebKitFormBoundarypYiSUx63abAmhT5C + Content-Disposition: form-data; name="file.size" + + 349182 + ------WebKitFormBoundarypYiSUx63abAmhT5C-- + + The underlying application can then access the contained files via their respective paths and just move them + where necessary. + """ + + # the request methods that may contain a request body + BODY_METHODS = ("POST", "PATCH", "PUT") + + def initialize(self, fallback, file_prefix="tmp", file_suffix="", path=None, suffixes=None): + if not suffixes: + suffixes = dict() + + self._fallback = fallback + self._file_prefix = file_prefix + self._file_suffix = file_suffix + self._path = path + + self._suffixes = dict((key, key) for key in ("name", "path", "content_type", "size")) + for suffix_type, suffix in suffixes.iteritems(): + if suffix_type in self._suffixes and suffix is not None: + self._suffixes[suffix_type] = suffix + + # Parts, files and values will be stored here + self._parts = dict() + self._files = [] + + # Part currently being processed + self._current_part = None + + # content type of request body + self._content_type = None + + # bytes left to read according to content_length of request body + self._bytes_left = 0 + + # buffer needed for identifying form data parts + self._buffer = b"" + + # buffer for new body + self._new_body = b"" + + # logger + self._logger = logging.getLogger(__name__) + + def prepare(self): + """ + Prepares the processing of the request. If it's a request that may contain a request body (as defined in + `UploadStorageFallbackHandler.BODY_METHODS) prepares the multipart parsing if content type fits. If it's a + body-less request, just calls the `fallback` with an empty body and finishes the request. + """ + if self.request.method in UploadStorageFallbackHandler.BODY_METHODS: + self._bytes_left = self.request.headers.get("Content-Length", 0) + self._content_type = self.request.headers.get("Content-Type", None) + + # request might contain a body + if self.is_multipart(): + if not self._bytes_left: + # we don't support requests without a content-length + raise tornado.web.HTTPError(400, reason="No Content-Length supplied") + + # extract the multipart boundary + fields = self._content_type.split(";") + for field in fields: + k, sep, v = field.strip().partition("=") + if k == "boundary" and v: + if v.startswith(b'"') and v.endswith(b'"'): + self._multipart_boundary = tornado.escape.utf8(v[1:-1]) + else: + self._multipart_boundary = tornado.escape.utf8(v) + break + else: + self._multipart_boundary = None + else: + self._fallback(self.request, b"") + self._finished = True + + def data_received(self, chunk): + """ + Called by Tornado on receiving a chunk of the request body. If request is a multipart request, takes care of + processing the multipart data structure via `self._process_multipart_data`. If not, just adds the chunk to + internal in-memory buffer. + + :param chunk: chunk of data received from Tornado + """ + + data = self._buffer + chunk + if self.is_multipart(): + self._process_multipart_data(data) + else: + self._buffer = data + + def is_multipart(self): + """Checks whether this request is a `multipart` request""" + return self._content_type is not None and self._content_type.startswith("multipart") + + def _process_multipart_data(self, data): + """ + Processes the given data, parsing it for multipart definitions and calling the appropriate methods. + + :param data: the data to process as a string + """ + + # check for boundary + delimiter = b"--%s" % self._multipart_boundary + delimiter_loc = data.find(delimiter) + delimiter_len = len(delimiter) + end_of_header = None + if delimiter_loc != -1: + # found the delimiter in the currently available data + data, self._buffer = data[0:delimiter_loc], data[delimiter_loc:] + end_of_header = self._buffer.find("\r\n\r\n") + else: + # make sure any boundary (with single or double ==) contained at the end of chunk does not get + # truncated by this processing round => save it to the buffer for next round + endlen = len(self._multipart_boundary) + 4 + data, self._buffer = data[0:-endlen], data[-endlen:] + + # stream data to part handler + if data: + if self._current_part: + self._on_data(self._current_part, data) + + if end_of_header >= 0: + self._on_header(self._buffer[delimiter_len+2:end_of_header]) + self._buffer = self._buffer[end_of_header + 4:] + + if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--": + # we saw the last boundary and are at the end of our request + if self._current_part: + self._on_close(self._current_part) + self._current_part = None + self._buffer = b"" + self._on_finish() + + def _on_header(self, header): + """ + Called for a new multipart header, takes care of parsing the header and calling `self._on_part` with the + relevant data, setting the current part in the process. + + :param header: header to parse + """ + + # close any open parts + if self._current_part: + self._on_close(self._current_part) + self._current_part = None + + header_check = header.find(self._multipart_boundary) + if header_check != -1: + self._logger.warn("Header still contained multipart boundary, stripping it...") + header = header[header_check:] + + # convert to dict + header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8")) + disp_header = header.get("Content-Disposition", "") + disposition, disp_params = tornado.httputil._parse_header(disp_header) + + if disposition != "form-data": + self._logger.warn("Got a multipart header without form-data content disposition, ignoring that one") + return + if not disp_params.get("name"): + self._logger.warn("Got a multipart header without name, ignoring that one") + return + + self._current_part = self._on_part(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None) + + def _on_part(self, name, content_type, filename=None): + """ + Called for new parts in the multipart stream. If `filename` is given creates new `file` part (which leads + to storage of the data as temporary file on disk), if not creates a new `data` part (which stores + incoming data in memory). + + Structure of `file` parts: + + * `name`: name of the part + * `filename`: filename associated with the part + * `path`: path to the temporary file storing the file's data + * `content_type`: content type of the part + * `file`: file handle for the temporary file (mode "wb", not deleted on close!) + + Structure of `data` parts: + + * `name`: name of the part + * `content_type`: content type of the part + * `data`: bytes of the part (initialized to "") + + :param name: name of the part + :param content_type: content type of the part + :param filename: filename associated with the part. + :return: dict describing the new part + """ + if filename is not None: + # this is a file + import tempfile + handle = tempfile.NamedTemporaryFile(mode="wb", prefix=self._file_prefix, suffix=self._file_suffix, dir=self._path, delete=False) + return dict(name=tornado.escape.utf8(name), + filename=tornado.escape.utf8(filename), + path=tornado.escape.utf8(handle.name), + content_type=tornado.escape.utf8(content_type), + file=handle) + + else: + return dict(name=tornado.escape.utf8(name), content_type=content_type, data=b"") + + def _on_data(self, part, data): + """ + Called when new bytes are received for the given `part`, takes care of writing them to their storage. + + :param part: part for which data was received + :param data: data chunk which was received + """ + if "file" in part: + part["file"].write(data) + else: + part["data"] += data + + def _on_close(self, part): + """ + Called when a part gets closed, takes care of storing the finished part in the internal parts storage and for + `file` parts closing the temporary file and storing the part in the internal files storage. + + :param part: part which was closed + """ + name = part["name"] + self._parts[name] = part + if "file" in part: + self._files.append(part["path"]) + part["file"].close() + del part["file"] + + def _on_finish(self): + """ + Called when the request body has been read completely. Takes care of creating the replacement body out of the + logged parts, turning `file` parts into new + :return: + """ + + self._new_body = b"" + for name, part in self._parts.iteritems(): + if "filename" in part: + # add form fields for filename, path, size and content_type for all files contained in the request + fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems()) + for n, p in fields.iteritems(): + key = name + "." + n + self._new_body += b"--%s\r\n" % self._multipart_boundary + self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key + self._new_body += b"\r\n" + self._new_body += p + b"\r\n" + elif "data" in part: + self._new_body += b"--%s\r\n" % self._multipart_boundary + value = part["data"] + self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % name + if "content_type" in part and part["content_type"] is not None: + self._new_body += b"Content-Type: %s\r\n" % part["content_type"] + self._new_body += b"\r\n" + self._new_body += value + self._new_body += b"--%s--\r\n" % self._multipart_boundary + + def _handle_method(self, *args, **kwargs): + """ + Handler for any request method, takes care of defining the new request body if necessary and forwarding + the current request and changed body to the `fallback`. + """ + + # determine which body to supply + body = b"" + if self.is_multipart(): + # make sure we really processed all data in the buffer + while len(self._buffer): + self._process_multipart_data(self._buffer) + + # use rewritten body + body = self._new_body + + elif self.request.method in UploadStorageFallbackHandler.BODY_METHODS: + # directly use data from buffer + body = self._buffer + + # rewrite content length + self.request.headers["Content-Length"] = len(body) + + try: + # call the configured fallback with request and body to use + self._fallback(self.request, body) + finally: + # make sure the temporary files are removed again + for f in self._files: + octoprint.util.silentRemove(f) + + # make all http methods trigger _handle_method + get = _handle_method + post = _handle_method + put = _handle_method + patch = _handle_method + delete = _handle_method + head = _handle_method + options = _handle_method + + +class WsgiInputContainer(object): + """ + A WSGI container for use with Tornado that allows supplying the request body to be used for `wsgi.input` in the + generated WSGI environment upon call. + + A `RequestHandler` can thus provide the WSGI application with a stream for the request body, or a modified body. + + Example usage: + + wsgi_app = octoprint.server.util.WsgiInputContainer(octoprint_app) + application = tornado.web.Application([ + (r".*", UploadStorageFallbackHandler, dict(fallback=wsgi_app), + ]) + + The implementation logic is basically the same as `tornado.wsgi.WSGIContainer` but the `__call__` and `environ` + methods have been adjusted to for an optionally supplied `body` argument which is then used for `wsgi.input`. + """ + + def __init__(self, wsgi_application): + self.wsgi_application = wsgi_application + + def __call__(self, request, body=None): + """ + Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado `HTTPServerRequest`. + + :param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from + :param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream + """ + + data = {} + response = [] + + def start_response(status, response_headers, exc_info=None): + data["status"] = status + data["headers"] = response_headers + return response.append + app_response = self.wsgi_application( + WsgiInputContainer.environ(request, body), start_response) + try: + response.extend(app_response) + body = b"".join(response) + finally: + if hasattr(app_response, "close"): + app_response.close() + if not data: + raise Exception("WSGI app did not call start_response") + + status_code = int(data["status"].split()[0]) + headers = data["headers"] + header_set = set(k.lower() for (k, v) in headers) + body = tornado.escape.utf8(body) + if status_code != 304: + if "content-length" not in header_set: + headers.append(("Content-Length", str(len(body)))) + if "content-type" not in header_set: + headers.append(("Content-Type", "text/html; charset=UTF-8")) + if "server" not in header_set: + headers.append(("Server", "TornadoServer/%s" % tornado.version)) + + parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")] + for key, value in headers: + parts.append(tornado.escape.utf8(key) + b": " + tornado.escape.utf8(value) + b"\r\n") + parts.append(b"\r\n") + parts.append(body) + request.write(b"".join(parts)) + request.finish() + self._log(status_code, request) + + @staticmethod + def environ(request, body=None): + """ + Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. + + An optional `body` to be used for populating `wsgi.input` can be supplied (either a string or a stream). If not + supplied, `request.body` will be wrapped into a `io.BytesIO` stream and used instead. + + :param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from + :param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream + """ + from tornado.wsgi import to_wsgi_str + import sys + import io + + # determine the request_body to supply as wsgi.input + if body is not None: + if isinstance(body, (bytes, str)): + request_body = io.BytesIO(tornado.escape.utf8(body)) + else: + request_body = body + else: + request_body = io.BytesIO(tornado.escape.utf8(request.body)) + + hostport = request.host.split(":") + if len(hostport) == 2: + host = hostport[0] + port = int(hostport[1]) + else: + host = request.host + port = 443 if request.protocol == "https" else 80 + environ = { + "REQUEST_METHOD": request.method, + "SCRIPT_NAME": "", + "PATH_INFO": to_wsgi_str(tornado.escape.url_unescape( + request.path, encoding=None, plus=False)), + "QUERY_STRING": request.query, + "REMOTE_ADDR": request.remote_ip, + "SERVER_NAME": host, + "SERVER_PORT": str(port), + "SERVER_PROTOCOL": request.version, + "wsgi.version": (1, 0), + "wsgi.url_scheme": request.protocol, + "wsgi.input": request_body, + "wsgi.errors": sys.stderr, + "wsgi.multithread": False, + "wsgi.multiprocess": True, + "wsgi.run_once": False, + } + if "Content-Type" in request.headers: + environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") + if "Content-Length" in request.headers: + environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") + for key, value in request.headers.items(): + environ["HTTP_" + key.replace("-", "_").upper()] = value + return environ + + def _log(self, status_code, request): + access_log = logging.getLogger("tornado.access") + + if status_code < 400: + log_method = access_log.info + elif status_code < 500: + log_method = access_log.warning + else: + log_method = access_log.error + request_time = 1000.0 * request.request_time() + summary = request.method + " " + request.uri + " (" + \ + request.remote_ip + ")" + log_method("%d %s %.2fms", status_code, summary, request_time) + + +#~~ customized HTTP1Connection implementation + + +class CustomHTTPServer(tornado.httpserver.HTTPServer): + """ + Custom implementation of `tornado.httpserver.HTTPServer` that allows defining max body sizes depending on path and + method. + + The implementation is mostly taken from `tornado.httpserver.HTTPServer`, the only difference is the creation + of a `CustomHTTP1ConnectionParameters` instance instead of `tornado.http1connection.HTTP1ConnectionParameters` + which is supplied with the two new constructor arguments `max_body_sizes` and `max_default_body_size` and the + creation of a `CustomHTTP1ServerConnection` instead of a `tornado.http1connection.HTTP1ServerConnection` upon + connection by a client. + + `max_body_sizes` is expected to be an iterable containing tuples of the form (method, path regex, maximum body size), + with method and path regex having to match in order for maximum body size to take affect. + + `default_max_body_size` is the default maximum body size to apply if no specific one from `max_body_sizes` matches. + """ + + def __init__(self, request_callback, no_keep_alive=False, io_loop=None, + xheaders=False, ssl_options=None, protocol=None, + decompress_request=False, + chunk_size=None, max_header_size=None, + idle_connection_timeout=None, body_timeout=None, + max_body_sizes=None, default_max_body_size=None, max_buffer_size=None): + self.request_callback = request_callback + self.no_keep_alive = no_keep_alive + self.xheaders = xheaders + self.protocol = protocol + self.conn_params = CustomHTTP1ConnectionParameters( + decompress=decompress_request, + chunk_size=chunk_size, + max_header_size=max_header_size, + header_timeout=idle_connection_timeout or 3600, + max_body_sizes=max_body_sizes, + default_max_body_size=default_max_body_size, + body_timeout=body_timeout) + tornado.tcpserver.TCPServer.__init__(self, io_loop=io_loop, ssl_options=ssl_options, + max_buffer_size=max_buffer_size, + read_chunk_size=chunk_size) + self._connections = set() + + + def handle_stream(self, stream, address): + context = tornado.httpserver._HTTPRequestContext(stream, address, + self.protocol) + conn = CustomHTTP1ServerConnection( + stream, self.conn_params, context) + self._connections.add(conn) + conn.start_serving(self) + + +class CustomHTTP1ServerConnection(tornado.http1connection.HTTP1ServerConnection): + """ + A custom implementation of `tornado.http1connection.HTTP1ServerConnection` which utilizes a `CustomHTTP1Connection` + instead of a `tornado.http1connection.HTTP1Connection` in `_server_request_loop`. The implementation logic is + otherwise the same as `tornado.http1connection.HTTP1ServerConnection`. + """ + + @tornado.gen.coroutine + def _server_request_loop(self, delegate): + try: + while True: + conn = CustomHTTP1Connection(self.stream, False, + self.params, self.context) + request_delegate = delegate.start_request(self, conn) + try: + ret = yield conn.read_response(request_delegate) + except (tornado.iostream.StreamClosedError, + tornado.iostream.UnsatisfiableReadError): + return + except tornado.http1connection._QuietException: + # This exception was already logged. + conn.close() + return + except Exception: + tornado.http1connection.gen_log.error("Uncaught exception", exc_info=True) + conn.close() + return + if not ret: + return + yield tornado.gen.moment + finally: + delegate.on_close(self) + + +class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection): + """ + A custom implementation of `tornado.http1connection.HTTP1Connection` which upon checking the `Content-Length` of + the request against the configured maximum utilizes `max_body_sizes` and `default_max_body_size` as a fallback. + """ + + def __init__(self, stream, is_client, params=None, context=None): + tornado.http1connection.HTTP1Connection.__init__(self, stream, is_client, params=params, context=context) + + import re + self._max_body_sizes = map(lambda x: (x[0], re.compile(x[1]), x[2]), self.params.max_body_sizes or dict()) + self._default_max_body_size = self.params.default_max_body_size or self.stream.max_buffer_size + + def _read_body(self, headers, delegate): + """ + Basically the same as `tornado.http1connection.HTTP1Connection._read_body`, but determines the maximum + content length individually for the request (utilizing `._get_max_content_length`). + + If the individual max content length is 0 or smaller no content length is checked. If the content length of the + current request exceeds the individual max content length, the request processing is aborted and an + `HTTPInputError` is raised. + """ + content_length = headers.get("Content-Length") + if content_length: + content_length = int(content_length) + max_content_length = self._get_max_content_length(self._request_start_line.method, self._request_start_line.path) + if 0 <= max_content_length < content_length: + raise tornado.httputil.HTTPInputError("Content-Length too long") + return self._read_fixed_body(content_length, delegate) + if headers.get("Transfer-Encoding") == "chunked": + return self._read_chunked_body(delegate) + if self.is_client: + return self._read_body_until_close(delegate) + return None + + def _get_max_content_length(self, method, path): + """ + Gets the max content length for the given method and path. Checks whether method and path match against any + of the specific maximum content lengths supplied in `max_body_sizes` and returns that as the maximum content + length if available, otherwise returns `default_max_body_size`. + + :param method: method of the request to match against + :param path: path od the request to match against + :return: determine maximum content length to apply to this request, max return 0 for unlimited allowed content + length + """ + + for m, p, s in self._max_body_sizes: + if method == m and p.match(path): + return s + return self._default_max_body_size + + +class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionParameters): + """ + An implementation of `tornado.http1connection.HTTP1ConnectionParameters` that adds to new parameters + `max_body_sizes` and `default_max_body_size`. + + For a description of these please see the documentation of `CustomHTTPServer` above. + """ + + def __init__(self, *args, **kwargs): + tornado.http1connection.HTTP1ConnectionParameters.__init__(self, args, kwargs) + self.max_body_sizes = kwargs["max_body_sizes"] if "max_body_sizes" in kwargs else dict() + self.default_max_body_size = kwargs["default_max_body_size"] if "default_max_body_size" in kwargs else dict() + +#~~ customized large response handler + + +class LargeResponseHandler(tornado.web.StaticFileHandler): + + CHUNK_SIZE = 16 * 1024 + + def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None): + tornado.web.StaticFileHandler.initialize(self, path, default_filename) + self._as_attachment = as_attachment + self._access_validation = access_validation + + def get(self, path, include_body=True): + if self._access_validation is not None: + self._access_validation(self.request) + + path = self.parse_url_path(path) + abspath = os.path.abspath(os.path.join(self.root, path)) + # os.path.abspath strips a trailing / + # it needs to be temporarily added back for requests to root/ + if not (abspath + os.path.sep).startswith(self.root): + raise tornado.web.HTTPError(403, "%s is not in root static directory", path) + if os.path.isdir(abspath) and self.default_filename is not None: + # need to look at the request.path here for when path is empty + # but there is some prefix to the path that was already + # trimmed by the routing + if not self.request.path.endswith("/"): + self.redirect(self.request.path + "/") + return + abspath = os.path.join(abspath, self.default_filename) + if not os.path.exists(abspath): + raise tornado.web.HTTPError(404) + if not os.path.isfile(abspath): + raise tornado.web.HTTPError(403, "%s is not a file", path) + + stat_result = os.stat(abspath) + modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME]) + + self.set_header("Last-Modified", modified) + + mime_type, encoding = mimetypes.guess_type(abspath) + if mime_type: + self.set_header("Content-Type", mime_type) + + cache_time = self.get_cache_time(path, modified, mime_type) + + if cache_time > 0: + self.set_header("Expires", datetime.datetime.utcnow() + + datetime.timedelta(seconds=cache_time)) + self.set_header("Cache-Control", "max-age=" + str(cache_time)) + + self.set_extra_headers(path) + + # Check the If-Modified-Since, and don't send the result if the + # content has not been modified + ims_value = self.request.headers.get("If-Modified-Since") + if ims_value is not None: + date_tuple = email.utils.parsedate(ims_value) + if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple)) + if if_since >= modified: + self.set_status(304) + return + + if not include_body: + assert self.request.method == "HEAD" + self.set_header("Content-Length", stat_result[stat.ST_SIZE]) + else: + with open(abspath, "rb") as file: + while True: + data = file.read(LargeResponseHandler.CHUNK_SIZE) + if not data: + break + self.write(data) + self.flush() + + def set_extra_headers(self, path): + if self._as_attachment: + self.set_header("Content-Disposition", "attachment") + + +##~~ URL Forward Handler for forwarding requests to a preconfigured static URL + + +class UrlForwardHandler(tornado.web.RequestHandler): + + def initialize(self, url=None, as_attachment=False, basename=None, access_validation=None): + tornado.web.RequestHandler.initialize(self) + self._url = url + self._as_attachment = as_attachment + self._basename = basename + self._access_validation = access_validation + + @tornado.web.asynchronous + def get(self, *args, **kwargs): + if self._access_validation is not None: + self._access_validation(self.request) + + if self._url is None: + raise tornado.web.HTTPError(404) + + client = tornado.httpclient.AsyncHTTPClient() + r = tornado.httpclient.HTTPRequest(url=self._url, method=self.request.method, body=self.request.body, headers=self.request.headers, follow_redirects=False, allow_nonstandard_methods=True) + + try: + return client.fetch(r, self.handle_response) + except tornado.web.HTTPError as e: + if hasattr(e, "response") and e.response: + self.handle_response(e.response) + else: + raise tornado.web.HTTPError(500) + + def handle_response(self, response): + if response.error and not isinstance(response.error, tornado.web.HTTPError): + raise tornado.web.HTTPError(500) + + filename = None + + self.set_status(response.code) + for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"): + value = response.headers.get(name) + if value: + self.set_header(name, value) + + if name == "Content-Type": + filename = self.get_filename(value) + + if self._as_attachment: + if filename is not None: + self.set_header("Content-Disposition", "attachment; filename=%s" % filename) + else: + self.set_header("Content-Disposition", "attachment") + + if response.body: + self.write(response.body) + self.finish() + + def get_filename(self, content_type): + if not self._basename: + return None + + typeValue = map(str.strip, content_type.split(";")) + if len(typeValue) == 0: + return None + + extension = mimetypes.guess_extension(typeValue[0]) + if not extension: + return None + + return "%s%s" % (self._basename, extension) + + +#~~ Factory method for creating Flask access validation wrappers from the Tornado request context + + +def access_validation_factory(app, login_manager, validator): + """ + Creates an access validation wrapper using the supplied validator. + + :param validator: the access validator to use inside the validation wrapper + :return: an access validation wrapper taking a request as parameter and performing the request validation + """ + def f(request): + """ + Creates a custom wsgi and Flask request context in order to be able to process user information + stored in the current session. + + :param request: The Tornado request for which to create the environment and context + """ + import flask + + wsgi_environ = WsgiInputContainer.environ(request) + with app.request_context(wsgi_environ): + app.session_interface.open_session(app, flask.request) + login_manager.reload_user() + validator(flask.request) + return f diff --git a/src/octoprint/server/util/watchdog.py b/src/octoprint/server/util/watchdog.py new file mode 100644 index 000000000..e6ced528e --- /dev/null +++ b/src/octoprint/server/util/watchdog.py @@ -0,0 +1,87 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import logging +import os +import watchdog.events + +import octoprint.gcodefiles +import octoprint.util +from octoprint.settings import settings + + +class UploadCleanupWatchdogHandler(watchdog.events.PatternMatchingEventHandler): + """ + Takes care of automatically deleting metadata entries for files that get deleted from the uploads folder + """ + + patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.GCODE_EXTENSIONS) + + def __init__(self, gcode_manager): + watchdog.events.PatternMatchingEventHandler.__init__(self) + self._gcode_manager = gcode_manager + + def on_deleted(self, event): + filename = self._gcode_manager._getBasicFilename(event.src_path) + if not filename: + return + + self._gcode_manager.removeFileFromMetadata(filename) + + +class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): + """ + Takes care of automatically "uploading" files that get added to the watched folder. + """ + + patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.SUPPORTED_EXTENSIONS) + + def __init__(self, gcodeManager, printer): + watchdog.events.PatternMatchingEventHandler.__init__(self) + + self._logger = logging.getLogger(__name__) + + self._gcodeManager = gcodeManager + self._printer = printer + + def _upload(self, path): + class WatchdogFileWrapper(object): + + def __init__(self, path): + self._path = path + self.filename = os.path.basename(self._path) + + def save(self, target): + octoprint.util.safeRename(self._path, target) + + fileWrapper = WatchdogFileWrapper(path) + + # determine current job + currentFilename = None + currentOrigin = None + currentJob = self._printer.getCurrentJob() + if currentJob is not None and "file" in currentJob.keys(): + currentJobFile = currentJob["file"] + if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): + currentFilename = currentJobFile["name"] + currentOrigin = currentJobFile["origin"] + + # determine future filename of file to be uploaded, abort if it can't be uploaded + futureFilename = self._gcodeManager.getFutureFilename(fileWrapper) + if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not octoprint.gcodefiles.isGcodeFileName(futureFilename)): + self._logger.warn("Could not add %s: Invalid file" % fileWrapper.filename) + return + + # prohibit overwriting currently selected file while it's being printed + if futureFilename == currentFilename and not currentOrigin == octoprint.gcodefiles.FileDestinations.SDCARD and self._printer.isPrinting() or self._printer.isPaused(): + self._logger.warn("Could not add %s: Trying to overwrite file that is currently being printed" % fileWrapper.filename) + return + + self._gcodeManager.addFile(fileWrapper, octoprint.gcodefiles.FileDestinations.LOCAL) + + def on_created(self, event): + self._upload(event.src_path) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index d599791ed..a31b07805 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -42,7 +42,13 @@ default_settings = { "port": 5000, "firstRun": True, "baseUrl": "", - "scheme": "" + "scheme": "", + "uploads": { + "maxSize": 1 * 1024 * 1024 * 1024, # 1GB + "nameSuffix": ".name", + "pathSuffix": ".path" + }, + "maxSize": 100 * 1024, # 100 KB }, "webcam": { "stream": None, @@ -375,7 +381,11 @@ class Settings(object): return None if isinstance(value, bool): return value - return value.lower() in valid_boolean_trues + if isinstance(value, (int, float)): + return value != 0 + if isinstance(value, (str, unicode)): + return value.lower() in valid_boolean_trues + return value is not None def getBaseFolder(self, type): if type not in default_settings["folder"].keys(): diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 5df97e7f0..d889ddcef 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -248,3 +248,7 @@ def dict_merge(a, b): else: result[k] = deepcopy(v) return result + + +class Object(object): + pass From 2d68b6e5894e2fac993d2808d02287fe54656412 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 5 Aug 2014 11:37:50 +0200 Subject: [PATCH 11/29] Get default max body size from settings too --- src/octoprint/server/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 96890a401..57e9cfa9d 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -189,7 +189,7 @@ class Server(): max_body_sizes = [ ("POST", r"/api/files/([^/]*)", settings().getInt(["server", "uploads", "maxSize"])) ] - self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=10*1024) + self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=settings().getInt(["server", "maxSize"])) self._server.listen(self._port, address=self._host) eventManager.fire(events.Events.STARTUP) From 9d69951faaa0a88f416b6900436a3fd6fce094c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 5 Aug 2014 12:33:08 +0200 Subject: [PATCH 12/29] Fixed double file request after file upload causing autoscrolling to uploaded file to not work --- src/octoprint/static/js/app/viewmodels/files.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index e9bc301f1..aa838a217 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -106,13 +106,18 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { self.isSdReady(data.flags.sdReady); }; + self._otherRequestInProgress = false; self.requestData = function(filenameToFocus, locationToFocus) { + if (self._otherRequestInProgress) return; + + self._otherRequestInProgress = true; $.ajax({ url: API_BASEURL + "files", method: "GET", dataType: "json", success: function(response) { self.fromResponse(response, filenameToFocus, locationToFocus); + self._otherRequestInProgress = false; } }); }; From d4e7c2e1b15eab0f282b4e738a4446244d5a9585 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 5 Aug 2014 19:03:04 +0200 Subject: [PATCH 13/29] We actually do want to run the configured system commands on the shell, so set shell to True Also includes a workaround for sarge bug no. 21 Closes #489 --- src/octoprint/server/api/__init__.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 2af447263..530970dc6 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -161,7 +161,12 @@ def performSystemAction(): if availableAction["action"] == action: logger.info("Performing command: %s" % availableAction["command"]) try: - p = sarge.run(availableAction["command"], stderr=sarge.Capture()) + # Note: we put the command in brackets since sarge (up to the most recently released version) has + # a bug concerning shell=True commands. Once sarge 0.1.4 we can upgrade to that and remove this + # workaround again + # + # See https://bitbucket.org/vinay.sajip/sarge/issue/21/behavior-is-not-like-popen-using-shell + p = sarge.run([availableAction["command"]], stderr=sarge.Capture(), shell=True) if p.returncode != 0: returncode = p.returncode stderr_text = p.stderr.text From 5dc033358080948caa63b91ef69476c4438d4c85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 6 Aug 2014 10:18:23 +0200 Subject: [PATCH 14/29] First couple of print statements for debugging a Heisenbug --- src/octoprint/server/util/tornado.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 38a5252e2..29a8c0bb3 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -156,6 +156,8 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): else: self._multipart_boundary = None else: + print("### In UploadStorageFallbackHandler.prepare, invoking fallback") + self._fallback(self.request, b"") self._finished = True @@ -411,6 +413,8 @@ class WsgiInputContainer(object): :param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream """ + print("### In WsgiInputContainer.__call__") + data = {} response = [] From 61f84302f37be5bb17b10942e2dfc7e8760891d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 6 Aug 2014 10:41:42 +0200 Subject: [PATCH 15/29] More debugging --- src/octoprint/server/util/tornado.py | 31 ++++++++++++++-------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 29a8c0bb3..214e53da7 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -134,6 +134,8 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): body-less request, just calls the `fallback` with an empty body and finishes the request. """ if self.request.method in UploadStorageFallbackHandler.BODY_METHODS: + print("### In UploadStorageFallbackHandler.prepare, processing body: %r" % self.request) + self._bytes_left = self.request.headers.get("Content-Length", 0) self._content_type = self.request.headers.get("Content-Type", None) @@ -156,7 +158,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): else: self._multipart_boundary = None else: - print("### In UploadStorageFallbackHandler.prepare, invoking fallback") + print("### In UploadStorageFallbackHandler.prepare, invoking fallback: %r" % self.request) self._fallback(self.request, b"") self._finished = True @@ -203,23 +205,22 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): data, self._buffer = data[0:-endlen], data[-endlen:] # stream data to part handler - if data: - if self._current_part: - self._on_data(self._current_part, data) + if data and self._current_part: + self._on_part_data(self._current_part, data) if end_of_header >= 0: - self._on_header(self._buffer[delimiter_len+2:end_of_header]) + self._on_part_header(self._buffer[delimiter_len+2:end_of_header]) self._buffer = self._buffer[end_of_header + 4:] if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--": # we saw the last boundary and are at the end of our request if self._current_part: - self._on_close(self._current_part) + self._on_part_finish(self._current_part) self._current_part = None self._buffer = b"" - self._on_finish() + self._on_request_body_finish() - def _on_header(self, header): + def _on_part_header(self, header): """ Called for a new multipart header, takes care of parsing the header and calling `self._on_part` with the relevant data, setting the current part in the process. @@ -229,7 +230,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): # close any open parts if self._current_part: - self._on_close(self._current_part) + self._on_part_finish(self._current_part) self._current_part = None header_check = header.find(self._multipart_boundary) @@ -249,9 +250,9 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): self._logger.warn("Got a multipart header without name, ignoring that one") return - self._current_part = self._on_part(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None) + self._current_part = self._on_part_start(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None) - def _on_part(self, name, content_type, filename=None): + def _on_part_start(self, name, content_type, filename=None): """ Called for new parts in the multipart stream. If `filename` is given creates new `file` part (which leads to storage of the data as temporary file on disk), if not creates a new `data` part (which stores @@ -289,7 +290,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): else: return dict(name=tornado.escape.utf8(name), content_type=content_type, data=b"") - def _on_data(self, part, data): + def _on_part_data(self, part, data): """ Called when new bytes are received for the given `part`, takes care of writing them to their storage. @@ -301,7 +302,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): else: part["data"] += data - def _on_close(self, part): + def _on_part_finish(self, part): """ Called when a part gets closed, takes care of storing the finished part in the internal parts storage and for `file` parts closing the temporary file and storing the part in the internal files storage. @@ -315,7 +316,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): part["file"].close() del part["file"] - def _on_finish(self): + def _on_request_body_finish(self): """ Called when the request body has been read completely. Takes care of creating the replacement body out of the logged parts, turning `file` parts into new @@ -413,7 +414,7 @@ class WsgiInputContainer(object): :param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream """ - print("### In WsgiInputContainer.__call__") + print("### In WsgiInputContainer.__call__: %r" % request) data = {} response = [] From 3eab5503f1556e7305797d35158a0c6ed67c1d8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 6 Aug 2014 11:22:46 +0200 Subject: [PATCH 16/29] And even more debugging --- src/octoprint/server/util/tornado.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 214e53da7..6837fbd5b 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -178,6 +178,9 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): else: self._buffer = data + def on_finish(self): + pass + def is_multipart(self): """Checks whether this request is a `multipart` request""" return self._content_type is not None and self._content_type.startswith("multipart") From 488eb1fac3738b09c261200ca96652933c8f59aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 6 Aug 2014 12:15:02 +0200 Subject: [PATCH 17/29] Also reset "otherRequestInProgress" if the request fails --- src/octoprint/static/js/app/viewmodels/files.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index aa838a217..c7d8678e6 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -118,6 +118,9 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { success: function(response) { self.fromResponse(response, filenameToFocus, locationToFocus); self._otherRequestInProgress = false; + }, + error: function() { + self._otherRequestInProgress = false; } }); }; From 86c6cda79a378e805d76f1abc19b0f7410eb0f65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 6 Aug 2014 16:21:32 +0200 Subject: [PATCH 18/29] Stop customized RequestHandler from sending another set of headers after the response This was causing the GET request for the list of files following directly after a successful response from an upload to get associated with the second empty response sent directly after the upload and such lead to a funny timing issue causing the file list not to update correctly since the response to THAT request -- while received by the client -- could then not be processed. See #455 --- src/octoprint/server/util/tornado.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 6837fbd5b..5da04a79f 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -134,8 +134,6 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): body-less request, just calls the `fallback` with an empty body and finishes the request. """ if self.request.method in UploadStorageFallbackHandler.BODY_METHODS: - print("### In UploadStorageFallbackHandler.prepare, processing body: %r" % self.request) - self._bytes_left = self.request.headers.get("Content-Length", 0) self._content_type = self.request.headers.get("Content-Type", None) @@ -158,8 +156,6 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): else: self._multipart_boundary = None else: - print("### In UploadStorageFallbackHandler.prepare, invoking fallback: %r" % self.request) - self._fallback(self.request, b"") self._finished = True @@ -178,9 +174,6 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): else: self._buffer = data - def on_finish(self): - pass - def is_multipart(self): """Checks whether this request is a `multipart` request""" return self._content_type is not None and self._content_type.startswith("multipart") @@ -373,6 +366,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): try: # call the configured fallback with request and body to use self._fallback(self.request, body) + self._headers_written = True finally: # make sure the temporary files are removed again for f in self._files: @@ -417,8 +411,6 @@ class WsgiInputContainer(object): :param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream """ - print("### In WsgiInputContainer.__call__: %r" % request) - data = {} response = [] From 02212bde21507d2fbcc5a15e33ecefc850ee0ed5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 7 Aug 2014 09:55:50 +0200 Subject: [PATCH 19/29] Made the navbar static instead of fixed to improve usability on mobile devices This is just a hack really, the proper approach would be to finally move to a real responsive design, but this should prove as a valid workaround until that is realized. Closes #257 for now. --- src/octoprint/static/css/octoprint.css | 2 +- src/octoprint/static/less/octoprint.less | 13 ++++++------- src/octoprint/templates/index.jinja2 | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/octoprint/static/css/octoprint.css b/src/octoprint/static/css/octoprint.css index 19769052b..aa71526a2 100644 --- a/src/octoprint/static/css/octoprint.css +++ b/src/octoprint/static/css/octoprint.css @@ -1 +1 @@ -.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{border-color:transparent;cursor:pointer;color:#08c;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}body{padding-top:60px}#navbar .navbar-inner{background-color:#ebebeb;background-image:-moz-linear-gradient(top,#fff,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#ccc));background-image:-webkit-linear-gradient(top,#fff,#ccc);background-image:-o-linear-gradient(top,#fff,#ccc);background-image:linear-gradient(to bottom,#fff,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffcccccc',GradientType=0)}#navbar .navbar-inner .brand,#navbar .navbar-inner .nav>li>a{text-shadow:0 1px 0 #fff;color:#333}#navbar .navbar-inner .brand .caret,#navbar .navbar-inner .nav>li>a .caret{border-bottom-color:#939393;border-top-color:#939393}#navbar .navbar-inner .brand:hover .caret,#navbar .navbar-inner .nav>li>a:hover .caret,#navbar .navbar-inner .brand:focus .caret,#navbar .navbar-inner .nav>li>a:focus .caret{border-bottom-color:#636363;border-top-color:#636363}#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.open.active>.dropdown-toggle{background-color:#e0e0e0;background-image:-moz-linear-gradient(top,#ccc,#fff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ccc),to(#fff));background-image:-webkit-linear-gradient(top,#ccc,#fff);background-image:-o-linear-gradient(top,#ccc,#fff);background-image:linear-gradient(to bottom,#ccc,#fff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffcccccc',endColorstr='#ffffffff',GradientType=0)}#navbar .navbar-inner.red{background-color:#e36565;background-image:-moz-linear-gradient(top,#f9a0a0,#c20c0c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9a0a0),to(#c20c0c));background-image:-webkit-linear-gradient(top,#f9a0a0,#c20c0c);background-image:-o-linear-gradient(top,#f9a0a0,#c20c0c);background-image:linear-gradient(to bottom,#f9a0a0,#c20c0c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9a0a0',endColorstr='#ffc20c0c',GradientType=0)}#navbar .navbar-inner.red .brand,#navbar .navbar-inner.red .nav>li>a{text-shadow:0 1px 0 #c20c0c;color:#f2f2f2}#navbar .navbar-inner.red .brand .caret,#navbar .navbar-inner.red .nav>li>a .caret{border-bottom-color:#f28d8d;border-top-color:#f28d8d}#navbar .navbar-inner.red .brand:hover .caret,#navbar .navbar-inner.red .nav>li>a:hover .caret,#navbar .navbar-inner.red .brand:focus .caret,#navbar .navbar-inner.red .nav>li>a:focus .caret{border-bottom-color:#f2c0c0;border-top-color:#f2c0c0}#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.red .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d84747;background-image:-moz-linear-gradient(top,#c20c0c,#f9a0a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c20c0c),to(#f9a0a0));background-image:-webkit-linear-gradient(top,#c20c0c,#f9a0a0);background-image:-o-linear-gradient(top,#c20c0c,#f9a0a0);background-image:linear-gradient(to bottom,#c20c0c,#f9a0a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc20c0c',endColorstr='#fff9a0a0',GradientType=0)}#navbar .navbar-inner.orange{background-color:#e39665;background-image:-moz-linear-gradient(top,#f9c3a0,#c2530c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9c3a0),to(#c2530c));background-image:-webkit-linear-gradient(top,#f9c3a0,#c2530c);background-image:-o-linear-gradient(top,#f9c3a0,#c2530c);background-image:linear-gradient(to bottom,#f9c3a0,#c2530c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9c3a0',endColorstr='#ffc2530c',GradientType=0)}#navbar .navbar-inner.orange .brand,#navbar .navbar-inner.orange .nav>li>a{text-shadow:0 1px 0 #f6a570;color:#333}#navbar .navbar-inner.orange .brand .caret,#navbar .navbar-inner.orange .nav>li>a .caret{border-bottom-color:#93552e;border-top-color:#93552e}#navbar .navbar-inner.orange .brand:hover .caret,#navbar .navbar-inner.orange .nav>li>a:hover .caret,#navbar .navbar-inner.orange .brand:focus .caret,#navbar .navbar-inner.orange .nav>li>a:focus .caret{border-bottom-color:#634430;border-top-color:#634430}#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.orange .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d88047;background-image:-moz-linear-gradient(top,#c2530c,#f9c3a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2530c),to(#f9c3a0));background-image:-webkit-linear-gradient(top,#c2530c,#f9c3a0);background-image:-o-linear-gradient(top,#c2530c,#f9c3a0);background-image:linear-gradient(to bottom,#c2530c,#f9c3a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2530c',endColorstr='#fff9c3a0',GradientType=0)}#navbar .navbar-inner.yellow{background-color:#e3d765;background-image:-moz-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9f0a0),to(#c2b00c));background-image:-webkit-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-o-linear-gradient(top,#f9f0a0,#c2b00c);background-image:linear-gradient(to bottom,#f9f0a0,#c2b00c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9f0a0',endColorstr='#ffc2b00c',GradientType=0)}#navbar .navbar-inner.yellow .brand,#navbar .navbar-inner.yellow .nav>li>a{text-shadow:0 1px 0 #f6e970;color:#333}#navbar .navbar-inner.yellow .brand .caret,#navbar .navbar-inner.yellow .nav>li>a .caret{border-bottom-color:#93892e;border-top-color:#93892e}#navbar .navbar-inner.yellow .brand:hover .caret,#navbar .navbar-inner.yellow .nav>li>a:hover .caret,#navbar .navbar-inner.yellow .brand:focus .caret,#navbar .navbar-inner.yellow .nav>li>a:focus .caret{border-bottom-color:#635e30;border-top-color:#635e30}#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.yellow .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d8ca47;background-image:-moz-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2b00c),to(#f9f0a0));background-image:-webkit-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-o-linear-gradient(top,#c2b00c,#f9f0a0);background-image:linear-gradient(to bottom,#c2b00c,#f9f0a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2b00c',endColorstr='#fff9f0a0',GradientType=0)}#navbar .navbar-inner.green{background-color:#98f064;background-image:-moz-linear-gradient(top,#c8ffa7,#50da00);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8ffa7),to(#50da00));background-image:-webkit-linear-gradient(top,#c8ffa7,#50da00);background-image:-o-linear-gradient(top,#c8ffa7,#50da00);background-image:linear-gradient(to bottom,#c8ffa7,#50da00);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8ffa7',endColorstr='#ff50da00',GradientType=0)}#navbar .navbar-inner.green .brand,#navbar .navbar-inner.green .nav>li>a{text-shadow:0 1px 0 #a7ff74;color:#333}#navbar .navbar-inner.green .brand .caret,#navbar .navbar-inner.green .nav>li>a .caret{border-bottom-color:#55992e;border-top-color:#55992e}#navbar .navbar-inner.green .brand:hover .caret,#navbar .navbar-inner.green .nav>li>a:hover .caret,#navbar .navbar-inner.green .brand:focus .caret,#navbar .navbar-inner.green .nav>li>a:focus .caret{border-bottom-color:#446630;border-top-color:#446630}#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.green .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.open.active>.dropdown-toggle{background-color:#80e943;background-image:-moz-linear-gradient(top,#50da00,#c8ffa7);background-image:-webkit-gradient(linear,0 0,0 100%,from(#50da00),to(#c8ffa7));background-image:-webkit-linear-gradient(top,#50da00,#c8ffa7);background-image:-o-linear-gradient(top,#50da00,#c8ffa7);background-image:linear-gradient(to bottom,#50da00,#c8ffa7);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff50da00',endColorstr='#ffc8ffa7',GradientType=0)}#navbar .navbar-inner.blue{background-color:#6498f0;background-image:-moz-linear-gradient(top,#a7c8ff,#0050da);background-image:-webkit-gradient(linear,0 0,0 100%,from(#a7c8ff),to(#0050da));background-image:-webkit-linear-gradient(top,#a7c8ff,#0050da);background-image:-o-linear-gradient(top,#a7c8ff,#0050da);background-image:linear-gradient(to bottom,#a7c8ff,#0050da);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa7c8ff',endColorstr='#ff0050da',GradientType=0)}#navbar .navbar-inner.blue .brand,#navbar .navbar-inner.blue .nav>li>a{text-shadow:0 1px 0 #74a7ff;color:#333}#navbar .navbar-inner.blue .brand .caret,#navbar .navbar-inner.blue .nav>li>a .caret{border-bottom-color:#2e5599;border-top-color:#2e5599}#navbar .navbar-inner.blue .brand:hover .caret,#navbar .navbar-inner.blue .nav>li>a:hover .caret,#navbar .navbar-inner.blue .brand:focus .caret,#navbar .navbar-inner.blue .nav>li>a:focus .caret{border-bottom-color:#304466;border-top-color:#304466}#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.blue .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.open.active>.dropdown-toggle{background-color:#4380e9;background-image:-moz-linear-gradient(top,#0050da,#a7c8ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#0050da),to(#a7c8ff));background-image:-webkit-linear-gradient(top,#0050da,#a7c8ff);background-image:-o-linear-gradient(top,#0050da,#a7c8ff);background-image:linear-gradient(to bottom,#0050da,#a7c8ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0050da',endColorstr='#ffa7c8ff',GradientType=0)}#navbar .navbar-inner.violet{background-color:#9864f0;background-image:-moz-linear-gradient(top,#c8a7ff,#5000da);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8a7ff),to(#5000da));background-image:-webkit-linear-gradient(top,#c8a7ff,#5000da);background-image:-o-linear-gradient(top,#c8a7ff,#5000da);background-image:linear-gradient(to bottom,#c8a7ff,#5000da);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8a7ff',endColorstr='#ff5000da',GradientType=0)}#navbar .navbar-inner.violet .brand,#navbar .navbar-inner.violet .nav>li>a{text-shadow:0 1px 0 #5000da;color:#f2f2f2}#navbar .navbar-inner.violet .brand .caret,#navbar .navbar-inner.violet .nav>li>a .caret{border-bottom-color:#b58df9;border-top-color:#b58df9}#navbar .navbar-inner.violet .brand:hover .caret,#navbar .navbar-inner.violet .nav>li>a:hover .caret,#navbar .navbar-inner.violet .brand:focus .caret,#navbar .navbar-inner.violet .nav>li>a:focus .caret{border-bottom-color:#d3c0f5;border-top-color:#d3c0f5}#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.violet .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.open.active>.dropdown-toggle{background-color:#8043e9;background-image:-moz-linear-gradient(top,#5000da,#c8a7ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5000da),to(#c8a7ff));background-image:-webkit-linear-gradient(top,#5000da,#c8a7ff);background-image:-o-linear-gradient(top,#5000da,#c8a7ff);background-image:linear-gradient(to bottom,#5000da,#c8a7ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5000da',endColorstr='#ffc8a7ff',GradientType=0)}#navbar .navbar-inner.black{background-color:#4f4f4f;background-image:-moz-linear-gradient(top,#787878,#121212);background-image:-webkit-gradient(linear,0 0,0 100%,from(#787878),to(#121212));background-image:-webkit-linear-gradient(top,#787878,#121212);background-image:-o-linear-gradient(top,#787878,#121212);background-image:linear-gradient(to bottom,#787878,#121212);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff787878',endColorstr='#ff121212',GradientType=0)}#navbar .navbar-inner.black .brand,#navbar .navbar-inner.black .nav>li>a{text-shadow:0 1px 0 #121212;color:#f2f2f2}#navbar .navbar-inner.black .brand .caret,#navbar .navbar-inner.black .nav>li>a .caret{border-bottom-color:#959595;border-top-color:#959595}#navbar .navbar-inner.black .brand:hover .caret,#navbar .navbar-inner.black .nav>li>a:hover .caret,#navbar .navbar-inner.black .brand:focus .caret,#navbar .navbar-inner.black .nav>li>a:focus .caret{border-bottom-color:#c4c4c4;border-top-color:#c4c4c4}#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.black .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.open.active>.dropdown-toggle{background-color:#3b3b3b;background-image:-moz-linear-gradient(top,#121212,#787878);background-image:-webkit-gradient(linear,0 0,0 100%,from(#121212),to(#787878));background-image:-webkit-linear-gradient(top,#121212,#787878);background-image:-o-linear-gradient(top,#121212,#787878);background-image:linear-gradient(to bottom,#121212,#787878);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff121212',endColorstr='#ff787878',GradientType=0)}#navbar .navbar-inner .brand span{background-size:20px 20px;background-position:left center;padding-left:24px;background-repeat:no-repeat}.octoprint-container .tab-content{padding:9px 15px;border-left:1px solid #DDD;border-right:1px solid #DDD;border-bottom:1px solid #DDD;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px}.octoprint-container .nav{margin-bottom:0}.octoprint-container .tab-content h1{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5;font-weight:normal}.octoprint-container .accordion-heading .accordion-heading-button{float:right}.octoprint-container .accordion-heading .accordion-heading-button a{display:inline-block;padding:8px 15px;font-size:14px;line-height:20px;color:#000;text-decoration:none;background:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.octoprint-container .accordion-heading a.accordion-toggle{display:inline-block}.octoprint-container .accordion-heading [class^="icon-"],.octoprint-container .accordion-heading [class*=" icon-"]{color:#000}.print-control .btn{padding-left:4px;padding-right:4px}.upload-buttons .btn{margin-right:0}table{table-layout:fixed}table .popover-title{text-overflow:ellipsis;word-break:break-all}table th,table td{overflow:hidden}table th.gcode_files_name,table td.gcode_files_name{text-overflow:ellipsis;white-space:nowrap;text-align:left}table th.gcode_files_action,table td.gcode_files_action{text-align:center;width:90px}table th.gcode_files_action a,table td.gcode_files_action a{text-decoration:none;color:#000}table th.gcode_files_action a.disabled,table td.gcode_files_action a.disabled{color:#ccc;cursor:default}table th.timelapse_files_name,table td.timelapse_files_name{text-overflow:ellipsis;text-align:left}table th.timelapse_files_size,table td.timelapse_files_size{text-align:right;width:55px}table th.timelapse_files_action,table td.timelapse_files_action{text-align:center;width:45px}table th.timelapse_files_action a,table td.timelapse_files_action a{text-decoration:none;color:#000}table th.timelapse_files_action a.disabled,table td.timelapse_files_action a.disabled{color:#ccc;cursor:default}table th.settings_users_name,table td.settings_users_name{text-overflow:ellipsis;text-align:left}table th.settings_users_active,table td.settings_users_active,table th.settings_users_admin,table td.settings_users_admin{text-align:center;width:55px}table th.settings_users_actions,table td.settings_users_actions{text-align:center;width:60px}table th.settings_users_actions a,table td.settings_users_actions a{text-decoration:none;color:#000}table th.settings_users_actions a.disabled,table td.settings_users_actions a.disabled{color:#ccc;cursor:default}table th.settings_logs_name,table td.settings_logs_name{text-overflow:ellipsis;text-align:left}table th.settings_logs_size,table td.settings_logs_size{text-align:right;width:70px}table th.settings_logs_date,table td.settings_logs_date{text-align:left;width:130px}table th.settings_logs_action,table td.settings_logs_action{text-align:center;width:70px}table th.settings_logs_action a,table td.settings_logs_action a{text-decoration:none;color:#000}table th.settings_logs_action a.disabled,table td.settings_logs_action a.disabled{color:#ccc;cursor:default}#temperature-graph{height:350px;width:100%;background-image:url("../img/graph-background.png");background-position:center;background-repeat:no-repeat}.tab-content,.tab-pane{overflow:visible}.tempInput{width:50px}#temp_newTemp,#temp_newBedTemp,#speed_innerWall,#speed_outerWall,#speed_fill,#speed_support,#webcam_timelapse_interval,#webcam_timelapse_postRoll{text-align:right}ul.dropdown-menu li a{cursor:pointer}#connection_ports,#connection_baudrates{width:100%}#offline_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#offline_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#offline_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#offline_overlay_wrapper .container{margin:auto}#webcam_container{width:100%}#webcam_container .flipH{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1)}#webcam_container .flipV{-webkit-transform:scaleY(-1);-moz-transform:scaleY(-1)}#webcam_container .flipH.flipV{-webkit-transform:scaleX(-1) scaleY(-1);-moz-transform:scaleX(-1) scaleY(-1)}#files .gcode_files{padding-right:7px}#files .gcode_files .entry{padding:5px;line-height:20px;border-bottom:1px solid #ddd;position:relative}#files .gcode_files .entry:hover{background-color:#f5f5f5}#files .gcode_files .entry .title{text-overflow:ellipsis;word-break:break-all}#files .gcode_files .entry .uploaded,#files .gcode_files .entry .size,#files .gcode_files .entry .additionalInfo{font-size:85%;color:#999}#files .gcode_files .entry .action-buttons{position:absolute;bottom:5px;right:5px}#files .gcode_files .entry .additionalInfo{padding-bottom:22px}#files .upload-buttons{margin-top:10px}#files .form-search{text-align:center;margin-bottom:5px!important}#control{overflow:hidden}#control .jog-panel{float:left;margin-right:19px}#control h1{text-align:left}#control .jog-panel>div{text-align:center}#control .jog-panel>div.distance{text-align:left}#control .box{width:30px;height:30px;margin-right:10px;margin-bottom:10px;padding-left:8px}#control .control-box{display:block;height:30px;margin-bottom:10px}#control .btn-group{margin-bottom:10px}#control .btn-group.distance>.btn{width:43px;padding:3px 0;height:30px}#gcode .progress{width:582px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode #gcode_layer_slider{height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}#term #terminal-output{min-height:340px}.footer ul{margin:0}.footer ul li{display:inline;margin-left:1em;font-size:85%}.footer ul li:first-child{margin-left:0}.footer ul li a{color:#555}.ui-pnotify .alert a{color:#c09853}.ui-pnotify .alert-error a,.ui-pnotify .alert-danger a{color:#b94a48}.ui-pnotify .alert-success a{color:#468847}.ui-pnotify .alert-info a{color:#3a87ad}.pnotify_additional_info .pnotify_more{font-size:85%}.text-right{text-align:right}.overflow_visible{overflow:visible!important}#drop_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#drop_overlay.in{display:block}#drop_overlay #drop_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#drop_overlay #drop_overlay_wrapper #drop,#drop_overlay #drop_overlay_wrapper #drop_background{position:absolute;top:50%;left:50%;margin-left:-200px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper #drop_locally,#drop_overlay #drop_overlay_wrapper #drop_locally_background{position:absolute;top:50%;left:50%;margin-left:-425px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper #drop_sd,#drop_overlay #drop_overlay_wrapper #drop_sd_background{position:absolute;top:50%;left:50%;margin-left:25px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper .dropzone{width:404px;height:404px;z-index:10001;color:#fff;font-size:30px}#drop_overlay #drop_overlay_wrapper .dropzone i{font-size:50px}#drop_overlay #drop_overlay_wrapper .dropzone .centered{display:table-cell;text-align:center;vertical-align:middle;width:400px;height:400px;line-height:40px;filter:alpha(opacity=100);-moz-opacity:1.0;-khtml-opacity:1.0;opacity:1.0}#drop_overlay #drop_overlay_wrapper .dropzone_background{width:400px;height:400px;border:2px dashed #eee;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;background-color:#000;filter:alpha(opacity=25);-moz-opacity:.25;-khtml-opacity:.25;opacity:.25}#drop_overlay #drop_overlay_wrapper .dropzone_background.hover{background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper .dropzone_background.fade{-webkit-transition:all .3s ease-out;-moz-transition:all .3s ease-out;-ms-transition:all .3s ease-out;-o-transition:all .3s ease-out;transition:all .3s ease-out;opacity:1}.icon-sd-black-14{background:url("../img/icon-sd-black-14.png") 0 3px no-repeat;width:11px;height:17px;display:inline-block!important}.center{float:none;margin-left:auto;margin-right:auto}.slider .slider-selection{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.slider .slider-selection:hover,.slider .slider-selection:focus,.slider .slider-selection:active,.slider .slider-selection.active,.slider .slider-selection.disabled,.slider .slider-selection[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.slider .slider-selection:active,.slider .slider-selection.active{background-color:#039 \9}.slider.slider-disabled .slider-selection{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-track{background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.slider.slider-disabled .slider-track{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);padding:0;margin-bottom:0;opacity:1;filter:alpha(opacity=100)}.slider .slider-handle:hover,.slider .slider-handle:focus,.slider .slider-handle:active,.slider .slider-handle.active,.slider .slider-handle.disabled,.slider .slider-handle[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.slider .slider-handle:active,.slider .slider-handle.active{background-color:#ccc \9}.slider .slider-handle:first-child{*margin-left:0}.slider .slider-handle:hover,.slider .slider-handle:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.slider .slider-handle:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.slider .slider-handle.active,.slider .slider-handle:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.slider .slider-handle.disabled,.slider .slider-handle[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle.hide{display:none}.slider .slider-handle.round{-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%} \ No newline at end of file +.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{border-color:transparent;cursor:pointer;color:#08c;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}#navbar .navbar-inner{background-color:#ebebeb;background-image:-moz-linear-gradient(top,#fff,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#ccc));background-image:-webkit-linear-gradient(top,#fff,#ccc);background-image:-o-linear-gradient(top,#fff,#ccc);background-image:linear-gradient(to bottom,#fff,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffcccccc',GradientType=0)}#navbar .navbar-inner .brand,#navbar .navbar-inner .nav>li>a{text-shadow:0 1px 0 #fff;color:#333}#navbar .navbar-inner .brand .caret,#navbar .navbar-inner .nav>li>a .caret{border-bottom-color:#939393;border-top-color:#939393}#navbar .navbar-inner .brand:hover .caret,#navbar .navbar-inner .nav>li>a:hover .caret,#navbar .navbar-inner .brand:focus .caret,#navbar .navbar-inner .nav>li>a:focus .caret{border-bottom-color:#636363;border-top-color:#636363}#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.open.active>.dropdown-toggle{background-color:#e0e0e0;background-image:-moz-linear-gradient(top,#ccc,#fff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ccc),to(#fff));background-image:-webkit-linear-gradient(top,#ccc,#fff);background-image:-o-linear-gradient(top,#ccc,#fff);background-image:linear-gradient(to bottom,#ccc,#fff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffcccccc',endColorstr='#ffffffff',GradientType=0)}#navbar .navbar-inner.red{background-color:#e36565;background-image:-moz-linear-gradient(top,#f9a0a0,#c20c0c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9a0a0),to(#c20c0c));background-image:-webkit-linear-gradient(top,#f9a0a0,#c20c0c);background-image:-o-linear-gradient(top,#f9a0a0,#c20c0c);background-image:linear-gradient(to bottom,#f9a0a0,#c20c0c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9a0a0',endColorstr='#ffc20c0c',GradientType=0)}#navbar .navbar-inner.red .brand,#navbar .navbar-inner.red .nav>li>a{text-shadow:0 1px 0 #c20c0c;color:#f2f2f2}#navbar .navbar-inner.red .brand .caret,#navbar .navbar-inner.red .nav>li>a .caret{border-bottom-color:#f28d8d;border-top-color:#f28d8d}#navbar .navbar-inner.red .brand:hover .caret,#navbar .navbar-inner.red .nav>li>a:hover .caret,#navbar .navbar-inner.red .brand:focus .caret,#navbar .navbar-inner.red .nav>li>a:focus .caret{border-bottom-color:#f2c0c0;border-top-color:#f2c0c0}#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.red .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d84747;background-image:-moz-linear-gradient(top,#c20c0c,#f9a0a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c20c0c),to(#f9a0a0));background-image:-webkit-linear-gradient(top,#c20c0c,#f9a0a0);background-image:-o-linear-gradient(top,#c20c0c,#f9a0a0);background-image:linear-gradient(to bottom,#c20c0c,#f9a0a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc20c0c',endColorstr='#fff9a0a0',GradientType=0)}#navbar .navbar-inner.orange{background-color:#e39665;background-image:-moz-linear-gradient(top,#f9c3a0,#c2530c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9c3a0),to(#c2530c));background-image:-webkit-linear-gradient(top,#f9c3a0,#c2530c);background-image:-o-linear-gradient(top,#f9c3a0,#c2530c);background-image:linear-gradient(to bottom,#f9c3a0,#c2530c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9c3a0',endColorstr='#ffc2530c',GradientType=0)}#navbar .navbar-inner.orange .brand,#navbar .navbar-inner.orange .nav>li>a{text-shadow:0 1px 0 #f6a570;color:#333}#navbar .navbar-inner.orange .brand .caret,#navbar .navbar-inner.orange .nav>li>a .caret{border-bottom-color:#93552e;border-top-color:#93552e}#navbar .navbar-inner.orange .brand:hover .caret,#navbar .navbar-inner.orange .nav>li>a:hover .caret,#navbar .navbar-inner.orange .brand:focus .caret,#navbar .navbar-inner.orange .nav>li>a:focus .caret{border-bottom-color:#634430;border-top-color:#634430}#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.orange .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d88047;background-image:-moz-linear-gradient(top,#c2530c,#f9c3a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2530c),to(#f9c3a0));background-image:-webkit-linear-gradient(top,#c2530c,#f9c3a0);background-image:-o-linear-gradient(top,#c2530c,#f9c3a0);background-image:linear-gradient(to bottom,#c2530c,#f9c3a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2530c',endColorstr='#fff9c3a0',GradientType=0)}#navbar .navbar-inner.yellow{background-color:#e3d765;background-image:-moz-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9f0a0),to(#c2b00c));background-image:-webkit-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-o-linear-gradient(top,#f9f0a0,#c2b00c);background-image:linear-gradient(to bottom,#f9f0a0,#c2b00c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9f0a0',endColorstr='#ffc2b00c',GradientType=0)}#navbar .navbar-inner.yellow .brand,#navbar .navbar-inner.yellow .nav>li>a{text-shadow:0 1px 0 #f6e970;color:#333}#navbar .navbar-inner.yellow .brand .caret,#navbar .navbar-inner.yellow .nav>li>a .caret{border-bottom-color:#93892e;border-top-color:#93892e}#navbar .navbar-inner.yellow .brand:hover .caret,#navbar .navbar-inner.yellow .nav>li>a:hover .caret,#navbar .navbar-inner.yellow .brand:focus .caret,#navbar .navbar-inner.yellow .nav>li>a:focus .caret{border-bottom-color:#635e30;border-top-color:#635e30}#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.yellow .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d8ca47;background-image:-moz-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2b00c),to(#f9f0a0));background-image:-webkit-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-o-linear-gradient(top,#c2b00c,#f9f0a0);background-image:linear-gradient(to bottom,#c2b00c,#f9f0a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2b00c',endColorstr='#fff9f0a0',GradientType=0)}#navbar .navbar-inner.green{background-color:#98f064;background-image:-moz-linear-gradient(top,#c8ffa7,#50da00);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8ffa7),to(#50da00));background-image:-webkit-linear-gradient(top,#c8ffa7,#50da00);background-image:-o-linear-gradient(top,#c8ffa7,#50da00);background-image:linear-gradient(to bottom,#c8ffa7,#50da00);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8ffa7',endColorstr='#ff50da00',GradientType=0)}#navbar .navbar-inner.green .brand,#navbar .navbar-inner.green .nav>li>a{text-shadow:0 1px 0 #a7ff74;color:#333}#navbar .navbar-inner.green .brand .caret,#navbar .navbar-inner.green .nav>li>a .caret{border-bottom-color:#55992e;border-top-color:#55992e}#navbar .navbar-inner.green .brand:hover .caret,#navbar .navbar-inner.green .nav>li>a:hover .caret,#navbar .navbar-inner.green .brand:focus .caret,#navbar .navbar-inner.green .nav>li>a:focus .caret{border-bottom-color:#446630;border-top-color:#446630}#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.green .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.open.active>.dropdown-toggle{background-color:#80e943;background-image:-moz-linear-gradient(top,#50da00,#c8ffa7);background-image:-webkit-gradient(linear,0 0,0 100%,from(#50da00),to(#c8ffa7));background-image:-webkit-linear-gradient(top,#50da00,#c8ffa7);background-image:-o-linear-gradient(top,#50da00,#c8ffa7);background-image:linear-gradient(to bottom,#50da00,#c8ffa7);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff50da00',endColorstr='#ffc8ffa7',GradientType=0)}#navbar .navbar-inner.blue{background-color:#6498f0;background-image:-moz-linear-gradient(top,#a7c8ff,#0050da);background-image:-webkit-gradient(linear,0 0,0 100%,from(#a7c8ff),to(#0050da));background-image:-webkit-linear-gradient(top,#a7c8ff,#0050da);background-image:-o-linear-gradient(top,#a7c8ff,#0050da);background-image:linear-gradient(to bottom,#a7c8ff,#0050da);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa7c8ff',endColorstr='#ff0050da',GradientType=0)}#navbar .navbar-inner.blue .brand,#navbar .navbar-inner.blue .nav>li>a{text-shadow:0 1px 0 #74a7ff;color:#333}#navbar .navbar-inner.blue .brand .caret,#navbar .navbar-inner.blue .nav>li>a .caret{border-bottom-color:#2e5599;border-top-color:#2e5599}#navbar .navbar-inner.blue .brand:hover .caret,#navbar .navbar-inner.blue .nav>li>a:hover .caret,#navbar .navbar-inner.blue .brand:focus .caret,#navbar .navbar-inner.blue .nav>li>a:focus .caret{border-bottom-color:#304466;border-top-color:#304466}#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.blue .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.open.active>.dropdown-toggle{background-color:#4380e9;background-image:-moz-linear-gradient(top,#0050da,#a7c8ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#0050da),to(#a7c8ff));background-image:-webkit-linear-gradient(top,#0050da,#a7c8ff);background-image:-o-linear-gradient(top,#0050da,#a7c8ff);background-image:linear-gradient(to bottom,#0050da,#a7c8ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0050da',endColorstr='#ffa7c8ff',GradientType=0)}#navbar .navbar-inner.violet{background-color:#9864f0;background-image:-moz-linear-gradient(top,#c8a7ff,#5000da);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8a7ff),to(#5000da));background-image:-webkit-linear-gradient(top,#c8a7ff,#5000da);background-image:-o-linear-gradient(top,#c8a7ff,#5000da);background-image:linear-gradient(to bottom,#c8a7ff,#5000da);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8a7ff',endColorstr='#ff5000da',GradientType=0)}#navbar .navbar-inner.violet .brand,#navbar .navbar-inner.violet .nav>li>a{text-shadow:0 1px 0 #5000da;color:#f2f2f2}#navbar .navbar-inner.violet .brand .caret,#navbar .navbar-inner.violet .nav>li>a .caret{border-bottom-color:#b58df9;border-top-color:#b58df9}#navbar .navbar-inner.violet .brand:hover .caret,#navbar .navbar-inner.violet .nav>li>a:hover .caret,#navbar .navbar-inner.violet .brand:focus .caret,#navbar .navbar-inner.violet .nav>li>a:focus .caret{border-bottom-color:#d3c0f5;border-top-color:#d3c0f5}#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.violet .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.open.active>.dropdown-toggle{background-color:#8043e9;background-image:-moz-linear-gradient(top,#5000da,#c8a7ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5000da),to(#c8a7ff));background-image:-webkit-linear-gradient(top,#5000da,#c8a7ff);background-image:-o-linear-gradient(top,#5000da,#c8a7ff);background-image:linear-gradient(to bottom,#5000da,#c8a7ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5000da',endColorstr='#ffc8a7ff',GradientType=0)}#navbar .navbar-inner.black{background-color:#4f4f4f;background-image:-moz-linear-gradient(top,#787878,#121212);background-image:-webkit-gradient(linear,0 0,0 100%,from(#787878),to(#121212));background-image:-webkit-linear-gradient(top,#787878,#121212);background-image:-o-linear-gradient(top,#787878,#121212);background-image:linear-gradient(to bottom,#787878,#121212);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff787878',endColorstr='#ff121212',GradientType=0)}#navbar .navbar-inner.black .brand,#navbar .navbar-inner.black .nav>li>a{text-shadow:0 1px 0 #121212;color:#f2f2f2}#navbar .navbar-inner.black .brand .caret,#navbar .navbar-inner.black .nav>li>a .caret{border-bottom-color:#959595;border-top-color:#959595}#navbar .navbar-inner.black .brand:hover .caret,#navbar .navbar-inner.black .nav>li>a:hover .caret,#navbar .navbar-inner.black .brand:focus .caret,#navbar .navbar-inner.black .nav>li>a:focus .caret{border-bottom-color:#c4c4c4;border-top-color:#c4c4c4}#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.black .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.open.active>.dropdown-toggle{background-color:#3b3b3b;background-image:-moz-linear-gradient(top,#121212,#787878);background-image:-webkit-gradient(linear,0 0,0 100%,from(#121212),to(#787878));background-image:-webkit-linear-gradient(top,#121212,#787878);background-image:-o-linear-gradient(top,#121212,#787878);background-image:linear-gradient(to bottom,#121212,#787878);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff121212',endColorstr='#ff787878',GradientType=0)}#navbar .navbar-inner .brand span{background-size:20px 20px;background-position:left center;padding-left:24px;background-repeat:no-repeat}.octoprint-container{margin-top:20px}.octoprint-container .tab-content{padding:9px 15px;border-left:1px solid #DDD;border-right:1px solid #DDD;border-bottom:1px solid #DDD;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px}.octoprint-container .nav{margin-bottom:0}.octoprint-container .tab-content h1{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5;font-weight:normal}.octoprint-container .accordion-heading .accordion-heading-button{float:right}.octoprint-container .accordion-heading .accordion-heading-button a{display:inline-block;padding:8px 15px;font-size:14px;line-height:20px;color:#000;text-decoration:none;background:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.octoprint-container .accordion-heading a.accordion-toggle{display:inline-block}.octoprint-container .accordion-heading [class^="icon-"],.octoprint-container .accordion-heading [class*=" icon-"]{color:#000}.print-control .btn{padding-left:4px;padding-right:4px}.upload-buttons .btn{margin-right:0}table{table-layout:fixed}table .popover-title{text-overflow:ellipsis;word-break:break-all}table th,table td{overflow:hidden}table th.gcode_files_name,table td.gcode_files_name{text-overflow:ellipsis;white-space:nowrap;text-align:left}table th.gcode_files_action,table td.gcode_files_action{text-align:center;width:90px}table th.gcode_files_action a,table td.gcode_files_action a{text-decoration:none;color:#000}table th.gcode_files_action a.disabled,table td.gcode_files_action a.disabled{color:#ccc;cursor:default}table th.timelapse_files_name,table td.timelapse_files_name{text-overflow:ellipsis;text-align:left}table th.timelapse_files_size,table td.timelapse_files_size{text-align:right;width:55px}table th.timelapse_files_action,table td.timelapse_files_action{text-align:center;width:45px}table th.timelapse_files_action a,table td.timelapse_files_action a{text-decoration:none;color:#000}table th.timelapse_files_action a.disabled,table td.timelapse_files_action a.disabled{color:#ccc;cursor:default}table th.settings_users_name,table td.settings_users_name{text-overflow:ellipsis;text-align:left}table th.settings_users_active,table td.settings_users_active,table th.settings_users_admin,table td.settings_users_admin{text-align:center;width:55px}table th.settings_users_actions,table td.settings_users_actions{text-align:center;width:60px}table th.settings_users_actions a,table td.settings_users_actions a{text-decoration:none;color:#000}table th.settings_users_actions a.disabled,table td.settings_users_actions a.disabled{color:#ccc;cursor:default}table th.settings_logs_name,table td.settings_logs_name{text-overflow:ellipsis;text-align:left}table th.settings_logs_size,table td.settings_logs_size{text-align:right;width:70px}table th.settings_logs_date,table td.settings_logs_date{text-align:left;width:130px}table th.settings_logs_action,table td.settings_logs_action{text-align:center;width:70px}table th.settings_logs_action a,table td.settings_logs_action a{text-decoration:none;color:#000}table th.settings_logs_action a.disabled,table td.settings_logs_action a.disabled{color:#ccc;cursor:default}#temperature-graph{height:350px;width:100%;background-image:url("../img/graph-background.png");background-position:center;background-repeat:no-repeat}.tab-content,.tab-pane{overflow:visible}.tempInput{width:50px}#temp_newTemp,#temp_newBedTemp,#speed_innerWall,#speed_outerWall,#speed_fill,#speed_support,#webcam_timelapse_interval,#webcam_timelapse_postRoll{text-align:right}ul.dropdown-menu li a{cursor:pointer}#connection_ports,#connection_baudrates{width:100%}#offline_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#offline_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#offline_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#offline_overlay_wrapper .container{margin:auto}#webcam_container{width:100%}#webcam_container .flipH{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1)}#webcam_container .flipV{-webkit-transform:scaleY(-1);-moz-transform:scaleY(-1)}#webcam_container .flipH.flipV{-webkit-transform:scaleX(-1) scaleY(-1);-moz-transform:scaleX(-1) scaleY(-1)}#files .gcode_files{padding-right:7px}#files .gcode_files .entry{padding:5px;line-height:20px;border-bottom:1px solid #ddd;position:relative}#files .gcode_files .entry:hover{background-color:#f5f5f5}#files .gcode_files .entry .title{text-overflow:ellipsis;word-break:break-all}#files .gcode_files .entry .uploaded,#files .gcode_files .entry .size,#files .gcode_files .entry .additionalInfo{font-size:85%;color:#999}#files .gcode_files .entry .action-buttons{position:absolute;bottom:5px;right:5px}#files .gcode_files .entry .additionalInfo{padding-bottom:22px}#files .upload-buttons{margin-top:10px}#files .form-search{text-align:center;margin-bottom:5px!important}#control{overflow:hidden}#control .jog-panel{float:left;margin-right:19px}#control h1{text-align:left}#control .jog-panel>div{text-align:center}#control .jog-panel>div.distance{text-align:left}#control .box{width:30px;height:30px;margin-right:10px;margin-bottom:10px;padding-left:8px}#control .control-box{display:block;height:30px;margin-bottom:10px}#control .btn-group{margin-bottom:10px}#control .btn-group.distance>.btn{width:43px;padding:3px 0;height:30px}#gcode .progress{width:582px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode #gcode_layer_slider{height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}#term #terminal-output{min-height:340px}.footer ul{margin:0}.footer ul li{display:inline;margin-left:1em;font-size:85%}.footer ul li:first-child{margin-left:0}.footer ul li a{color:#555}.ui-pnotify .alert a{color:#c09853}.ui-pnotify .alert-error a,.ui-pnotify .alert-danger a{color:#b94a48}.ui-pnotify .alert-success a{color:#468847}.ui-pnotify .alert-info a{color:#3a87ad}.pnotify_additional_info .pnotify_more{font-size:85%}.text-right{text-align:right}.overflow_visible{overflow:visible!important}#drop_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#drop_overlay.in{display:block}#drop_overlay #drop_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#drop_overlay #drop_overlay_wrapper #drop,#drop_overlay #drop_overlay_wrapper #drop_background{position:absolute;top:50%;left:50%;margin-left:-200px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper #drop_locally,#drop_overlay #drop_overlay_wrapper #drop_locally_background{position:absolute;top:50%;left:50%;margin-left:-425px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper #drop_sd,#drop_overlay #drop_overlay_wrapper #drop_sd_background{position:absolute;top:50%;left:50%;margin-left:25px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper .dropzone{width:404px;height:404px;z-index:10001;color:#fff;font-size:30px}#drop_overlay #drop_overlay_wrapper .dropzone i{font-size:50px}#drop_overlay #drop_overlay_wrapper .dropzone .centered{display:table-cell;text-align:center;vertical-align:middle;width:400px;height:400px;line-height:40px;filter:alpha(opacity=100);-moz-opacity:1.0;-khtml-opacity:1.0;opacity:1.0}#drop_overlay #drop_overlay_wrapper .dropzone_background{width:400px;height:400px;border:2px dashed #eee;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;background-color:#000;filter:alpha(opacity=25);-moz-opacity:.25;-khtml-opacity:.25;opacity:.25}#drop_overlay #drop_overlay_wrapper .dropzone_background.hover{background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper .dropzone_background.fade{-webkit-transition:all .3s ease-out;-moz-transition:all .3s ease-out;-ms-transition:all .3s ease-out;-o-transition:all .3s ease-out;transition:all .3s ease-out;opacity:1}.icon-sd-black-14{background:url("../img/icon-sd-black-14.png") 0 3px no-repeat;width:11px;height:17px;display:inline-block!important}.center{float:none;margin-left:auto;margin-right:auto}.slider .slider-selection{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.slider .slider-selection:hover,.slider .slider-selection:focus,.slider .slider-selection:active,.slider .slider-selection.active,.slider .slider-selection.disabled,.slider .slider-selection[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.slider .slider-selection:active,.slider .slider-selection.active{background-color:#039 \9}.slider.slider-disabled .slider-selection{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-track{background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.slider.slider-disabled .slider-track{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);padding:0;margin-bottom:0;opacity:1;filter:alpha(opacity=100)}.slider .slider-handle:hover,.slider .slider-handle:focus,.slider .slider-handle:active,.slider .slider-handle.active,.slider .slider-handle.disabled,.slider .slider-handle[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.slider .slider-handle:active,.slider .slider-handle.active{background-color:#ccc \9}.slider .slider-handle:first-child{*margin-left:0}.slider .slider-handle:hover,.slider .slider-handle:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.slider .slider-handle:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.slider .slider-handle.active,.slider .slider-handle:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.slider .slider-handle.disabled,.slider .slider-handle[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle.hide{display:none}.slider .slider-handle.round{-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%} \ No newline at end of file diff --git a/src/octoprint/static/less/octoprint.less b/src/octoprint/static/less/octoprint.less index 7a49001f4..e6e0dfd7b 100644 --- a/src/octoprint/static/less/octoprint.less +++ b/src/octoprint/static/less/octoprint.less @@ -6,7 +6,7 @@ // Body body { - padding-top: 60px; + //padding-top: 60px; } // Navigation bar @@ -113,9 +113,11 @@ body { } } -/** OctoPrint application tabs */ - .octoprint-container { + margin-top: 20px; + + /** OctoPrint application tabs */ + .tab-content { padding: 9px 15px; border-left: 1px solid #DDD; @@ -143,12 +145,9 @@ body { border-bottom: 1px solid #E5E5E5; font-weight: normal; } -} + /** Accordions */ -/** Accordions */ - -.octoprint-container { .accordion-heading { .accordion-heading-button { float: right; diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index 17255f91e..a7508680a 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -45,7 +45,7 @@ - +
+ +
+ +
+
From dffa00dc5e02d39f7d204c17b563e41dbc7db08d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 11 Aug 2014 18:26:33 +0200 Subject: [PATCH 29/29] If a tool did not extrude anything, skip it in the filament usage summary Also targets #539 --- src/octoprint/static/js/app/viewmodels/files.js | 4 +++- src/octoprint/static/js/app/viewmodels/printerstate.js | 10 ++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index c7d8678e6..77484a360 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -277,7 +277,9 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { } else { var i = 0; do { - output += "Filament (Tool " + i + "): " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + i]) + "
"; + if (filament["tool" + i].hasOwnProperty("length") && filament["tool" + i]["length"] > 0) { + output += "Filament (Tool " + i + "): " + formatFilament(filament["tool" + i]) + "
"; + } i++; } while (filament.hasOwnProperty("tool" + i)); } diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index 7dfad2971..98e17d135 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -133,10 +133,12 @@ function PrinterStateViewModel(loginStateViewModel) { var i = 0; do { var key = "tool" + i; - result[i] = { - name: ko.observable("Tool " + i), - data: ko.observable(data.filament[key]) - }; + if (data.filament[key].hasOwnProperty("length") && data.filament[key].length > 0) { + result.push({ + name: ko.observable("Tool " + i), + data: ko.observable(data.filament[key]) + }); + } i++; } while (data.filament.hasOwnProperty("tool" + i)); }