From bb2fcd5b00e2a4033d4f0403b6010c0a1a72da95 Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 20:25:04 -0500 Subject: [PATCH 01/80] Update flask, flask-{login,principal,babel,assets} versions to the latest, flask.ext. => flask_ --- setup.py | 10 ++--- src/octoprint/plugin/types.py | 2 +- .../plugins/announcements/__init__.py | 2 +- src/octoprint/plugins/corewizard/__init__.py | 2 +- .../plugins/pluginmanager/__init__.py | 2 +- .../plugins/softwareupdate/__init__.py | 4 +- src/octoprint/server/__init__.py | 8 ++-- src/octoprint/server/api/__init__.py | 4 +- src/octoprint/server/api/languages.py | 2 +- src/octoprint/server/api/system.py | 2 +- src/octoprint/server/api/users.py | 2 +- src/octoprint/server/util/flask.py | 42 +++++++++---------- src/octoprint/users.py | 4 +- 13 files changed, 43 insertions(+), 43 deletions(-) diff --git a/setup.py b/setup.py index 49b2cb9c7..eaa06d688 100644 --- a/setup.py +++ b/setup.py @@ -14,15 +14,15 @@ import octoprint_setuptools # Requirements for our application INSTALL_REQUIRES = [ - "flask>=0.9,<0.11", + "flask>=0.11,<0.12", "werkzeug>=0.8.3,<0.9", "tornado>=4.0.2,<4.1", "sockjs-tornado>=1.0.2,<1.1", "PyYAML>=3.10,<3.11", - "Flask-Login>=0.2.2,<0.3", - "Flask-Principal>=0.3.5,<0.4", - "Flask-Babel>=0.9,<0.10", - "Flask-Assets>=0.10,<0.11", + "Flask-Login>=0.3,<0.4", + "Flask-Principal>=0.4,<0.5", + "Flask-Babel>=0.11,<0.12", + "Flask-Assets>=0.12,<0.13", "markdown>=2.6.4,<2.7", "pyserial>=2.7,<2.8", "netaddr>=0.7.17,<0.8", diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 2bcc9f3bd..f9659e7d8 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1373,7 +1373,7 @@ class SettingsPlugin(OctoPrintPlugin): :return: the current settings of the plugin, as a dictionary """ - from flask.ext.login import current_user + from flask_login import current_user data = self._settings.get_all_data() if self.config_version_key in data: diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 890e82918..3cc03c10e 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -20,7 +20,7 @@ import flask from octoprint.server import admin_permission from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag -from flask.ext.babel import gettext +from flask_babel import gettext class AnnouncementPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.SettingsPlugin, diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 1a6b4e03f..41dc4a13a 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -9,7 +9,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import octoprint.plugin -from flask.ext.babel import gettext +from flask_babel import gettext class CoreWizardPlugin(octoprint.plugin.AssetPlugin, diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 51f002a87..c18ea2db1 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -15,7 +15,7 @@ from octoprint.server import admin_permission, VERSION from octoprint.util.pip import LocalPipCaller, UnknownPip from flask import jsonify, make_response -from flask.ext.babel import gettext +from flask_babel import gettext import logging import sarge diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 7a3ac351d..a156f4197 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -491,7 +491,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, ##~~ TemplatePlugin API def get_template_configs(self): - from flask.ext.babel import gettext + from flask_babel import gettext return [ dict(type="settings", name=gettext("Software Update")) ] @@ -806,7 +806,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, result = dict(check) if target == "octoprint": - from flask.ext.babel import gettext + from flask_babel import gettext result["displayName"] = check.get("displayName", gettext("OctoPrint")) result["displayVersion"] = check.get("displayVersion", "{octoprint_version}") diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 17308a269..aca269083 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -8,10 +8,10 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import uuid from sockjs.tornado import SockJSRouter from flask import Flask, g, request, session, Blueprint, Request, Response -from flask.ext.login import LoginManager, current_user -from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed -from flask.ext.babel import Babel, gettext, ngettext -from flask.ext.assets import Environment, Bundle +from flask_login import LoginManager, current_user +from flask_principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed +from flask_babel import Babel, gettext, ngettext +from flask_assets import Environment, Bundle from babel import Locale from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 6f6f37d5c..5e7afb358 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -10,8 +10,8 @@ import netaddr import sarge from flask import Blueprint, request, jsonify, abort, current_app, session, make_response, g -from flask.ext.login import login_user, logout_user, current_user -from flask.ext.principal import Identity, identity_changed, AnonymousIdentity +from flask_login import login_user, logout_user, current_user +from flask_principal import Identity, identity_changed, AnonymousIdentity import octoprint.util as util import octoprint.users diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index e0749658b..3d5f1f2c4 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -26,7 +26,7 @@ from octoprint.server.util.flask import restricted_access from octoprint.plugin import plugin_manager -from flask.ext.babel import Locale +from flask_babel import Locale @api.route("/languages", methods=["GET"]) @restricted_access diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index 8af7a24cc..fbdec959d 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -9,7 +9,7 @@ import logging import sarge from flask import request, make_response, jsonify, url_for -from flask.ext.babel import gettext +from flask_babel import gettext from octoprint.settings import settings as s diff --git a/src/octoprint/server/api/users.py b/src/octoprint/server/api/users.py index 73233f5e0..8335315ff 100644 --- a/src/octoprint/server/api/users.py +++ b/src/octoprint/server/api/users.py @@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from flask import request, jsonify, abort, make_response from werkzeug.exceptions import BadRequest -from flask.ext.login import current_user +from flask_login import current_user import octoprint.users as users diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index f4281ee13..ee7fe8833 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -8,9 +8,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import tornado.web import flask -import flask.ext.login -import flask.ext.principal -import flask.ext.assets +import flask_login +import flask_principal +import flask_assets import webassets.updater import webassets.utils import functools @@ -40,7 +40,7 @@ def enable_additional_translations(default_locale="en", additional_folders=None) import os from flask import _request_ctx_stack from babel import support, Locale - import flask.ext.babel + import flask_babel if additional_folders is None: additional_folders = [] @@ -85,7 +85,7 @@ def enable_additional_translations(default_locale="en", additional_folders=None) return None translations = getattr(ctx, 'babel_translations', None) if translations is None: - locale = flask.ext.babel.get_locale() + locale = flask_babel.get_locale() translations = support.Translations() if str(locale) != default_locale: @@ -123,8 +123,8 @@ def enable_additional_translations(default_locale="en", additional_folders=None) ctx.babel_translations = translations return translations - flask.ext.babel.Babel.list_translations = fixed_list_translations - flask.ext.babel.get_translations = fixed_get_translations + flask_babel.Babel.list_translations = fixed_list_translations + flask_babel.get_translations = fixed_get_translations def fix_webassets_cache(): from webassets import cache @@ -426,12 +426,12 @@ class OctoPrintFlaskResponse(flask.Response): def passive_login(): if octoprint.server.userManager.enabled: - user = octoprint.server.userManager.login_user(flask.ext.login.current_user) + user = octoprint.server.userManager.login_user(flask_login.current_user) else: - user = flask.ext.login.current_user + user = flask_login.current_user - if user is not None and not user.is_anonymous(): - flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id())) + if user is not None and not user.is_anonymous: + flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) if hasattr(user, "get_session"): flask.session["usersession.id"] = user.get_session() flask.g.user = user @@ -453,8 +453,8 @@ def passive_login(): user = octoprint.server.userManager.login_user(user) flask.session["usersession.id"] = user.get_session() flask.g.user = user - flask.ext.login.login_user(user) - flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id())) + flask_login.login_user(user) + flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) return flask.jsonify(user.asDict()) except: logger = logging.getLogger(__name__) @@ -999,14 +999,14 @@ def _get_flask_user_from_request(request): :return: the user or None if no user could be determined """ import octoprint.server.util - import flask.ext.login + import flask_login from octoprint.settings import settings apikey = octoprint.server.util.get_api_key(request) if settings().getBoolean(["api", "enabled"]) and apikey is not None: user = octoprint.server.util.get_user_for_apikey(apikey) else: - user = flask.ext.login.current_user + user = flask_login.current_user return user @@ -1061,7 +1061,7 @@ def restricted_access(func): apikey = octoprint.server.util.get_api_key(flask.request) if apikey == octoprint.server.UI_API_KEY: # UI API key => call regular login_required decorator, we are using browser sessions here - return flask.ext.login.login_required(func)(*args, **kwargs) + return flask_login.login_required(func)(*args, **kwargs) # try to determine user for key user = octoprint.server.util.get_user_for_apikey(apikey) @@ -1069,11 +1069,11 @@ def restricted_access(func): # no user or no key => go away return flask.make_response("Invalid API key", 401) - if not flask.ext.login.login_user(user, remember=False): + if not flask_login.login_user(user, remember=False): # user for API key could not be logged in => go away return flask.make_response("Invalid API key", 401) - flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id())) + flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) return func(*args, **kwargs) return decorated_view @@ -1172,7 +1172,7 @@ def get_json_command_from_request(request, valid_commands): ##~~ Flask-Assets resolver with plugin asset support -class PluginAssetResolver(flask.ext.assets.FlaskResolver): +class PluginAssetResolver(flask_assets.FlaskResolver): def split_prefix(self, ctx, item): app = ctx.environment._app @@ -1181,14 +1181,14 @@ class PluginAssetResolver(flask.ext.assets.FlaskResolver): prefix, plugin, name = item.split("/", 2) blueprint = prefix + "." + plugin - directory = flask.ext.assets.get_static_folder(app.blueprints[blueprint]) + directory = flask_assets.get_static_folder(app.blueprints[blueprint]) item = name endpoint = blueprint + ".static" return directory, item, endpoint except (ValueError, KeyError): pass - return flask.ext.assets.FlaskResolver.split_prefix(self, ctx, item) + return flask_assets.FlaskResolver.split_prefix(self, ctx, item) def resolve_output_to_path(self, ctx, target, bundle): import os diff --git a/src/octoprint/users.py b/src/octoprint/users.py index a615d222a..e5761773b 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -5,8 +5,8 @@ __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.ext.login import UserMixin -from flask.ext.principal import Identity +from flask_login import UserMixin +from flask_principal import Identity from werkzeug.local import LocalProxy import hashlib import os From 87d65c150b043efa20a666f7bbf326492abd5ee9 Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 20:30:12 -0500 Subject: [PATCH 02/80] Update werkzeug --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index eaa06d688..950f4b287 100644 --- a/setup.py +++ b/setup.py @@ -15,7 +15,7 @@ import octoprint_setuptools # Requirements for our application INSTALL_REQUIRES = [ "flask>=0.11,<0.12", - "werkzeug>=0.8.3,<0.9", + "werkzeug>=0.11.1,<0.12", "tornado>=4.0.2,<4.1", "sockjs-tornado>=1.0.2,<1.1", "PyYAML>=3.10,<3.11", From fbb881bb426d6cd398fa039731545901dc8f59f4 Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 21:00:14 -0500 Subject: [PATCH 03/80] Update Tornado, adapt CustomHTTPServer to new usage --- setup.py | 2 +- src/octoprint/server/util/tornado.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 950f4b287..26c473d66 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ import octoprint_setuptools INSTALL_REQUIRES = [ "flask>=0.11,<0.12", "werkzeug>=0.11.1,<0.12", - "tornado>=4.0.2,<4.1", + "tornado>=4.4.2,<4.5", "sockjs-tornado>=1.0.2,<1.1", "PyYAML>=3.10,<3.11", "Flask-Login>=0.3,<0.4", diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 12ba3b9b8..54eb09553 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -672,8 +672,10 @@ class CustomHTTPServer(tornado.httpserver.HTTPServer): ``default_max_body_size`` is the default maximum body size to apply if no specific one from ``max_body_sizes`` matches. """ + def __init__(self, *args, **kwargs): + pass - def __init__(self, request_callback, no_keep_alive=False, io_loop=None, + def initialize(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, From 9a6da3f46f65462a26349bfea8671733772ef07b Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 21:03:29 -0500 Subject: [PATCH 04/80] Update PyYAML --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 26c473d66..0a9ae65ed 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ INSTALL_REQUIRES = [ "werkzeug>=0.11.1,<0.12", "tornado>=4.4.2,<4.5", "sockjs-tornado>=1.0.2,<1.1", - "PyYAML>=3.10,<3.11", + "PyYAML>=3.12,<3.13", "Flask-Login>=0.3,<0.4", "Flask-Principal>=0.4,<0.5", "Flask-Babel>=0.11,<0.12", From 23a28012841baf3f21302ba97757f546b2a3270e Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 21:08:45 -0500 Subject: [PATCH 05/80] Update pyserial --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 0a9ae65ed..3ada20565 100644 --- a/setup.py +++ b/setup.py @@ -24,7 +24,7 @@ INSTALL_REQUIRES = [ "Flask-Babel>=0.11,<0.12", "Flask-Assets>=0.12,<0.13", "markdown>=2.6.4,<2.7", - "pyserial>=2.7,<2.8", + "pyserial>=3.1.1,<3.2", "netaddr>=0.7.17,<0.8", "watchdog>=0.8.3,<0.9", "sarge>=0.1.4,<0.2", From e15ca55558324f6af5084291ca65883a56ce9491 Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 21:11:33 -0500 Subject: [PATCH 06/80] Update rsa --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 3ada20565..ca0091e94 100644 --- a/setup.py +++ b/setup.py @@ -30,7 +30,7 @@ INSTALL_REQUIRES = [ "sarge>=0.1.4,<0.2", "netifaces>=0.10,<0.11", "pylru>=1.0.9,<1.1", - "rsa>=3.2,<3.3", + "rsa>=3.4,<3.5", "pkginfo>=1.2.1,<1.3", "requests>=2.7,<2.8", "semantic_version>=2.4.2,<2.5", From e998edd083bf2715706339e3b35f3a9c4f8353eb Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 21:12:46 -0500 Subject: [PATCH 07/80] Update pkginfo --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index ca0091e94..bd8a68419 100644 --- a/setup.py +++ b/setup.py @@ -31,7 +31,7 @@ INSTALL_REQUIRES = [ "netifaces>=0.10,<0.11", "pylru>=1.0.9,<1.1", "rsa>=3.4,<3.5", - "pkginfo>=1.2.1,<1.3", + "pkginfo>=1.3.2,<1.4", "requests>=2.7,<2.8", "semantic_version>=2.4.2,<2.5", "psutil>=3.2.1,<3.3", From 599e24634cf5e7c5f14df8729cfe51f16957066f Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 21:16:31 -0500 Subject: [PATCH 08/80] Update requests --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index bd8a68419..0cd0ac2bc 100644 --- a/setup.py +++ b/setup.py @@ -32,7 +32,7 @@ INSTALL_REQUIRES = [ "pylru>=1.0.9,<1.1", "rsa>=3.4,<3.5", "pkginfo>=1.3.2,<1.4", - "requests>=2.7,<2.8", + "requests>=2.11.1,<2.12", "semantic_version>=2.4.2,<2.5", "psutil>=3.2.1,<3.3", "Click>=6.2,<6.3", From 7d091d18ee552e1124367352c30d14944f10351d Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 21:19:54 -0500 Subject: [PATCH 09/80] Update semantic_version --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 0cd0ac2bc..4c7d48941 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ INSTALL_REQUIRES = [ "rsa>=3.4,<3.5", "pkginfo>=1.3.2,<1.4", "requests>=2.11.1,<2.12", - "semantic_version>=2.4.2,<2.5", + "semantic_version>=2.6.0,<2.7", "psutil>=3.2.1,<3.3", "Click>=6.2,<6.3", "awesome-slugify>=1.6.5,<1.7", From bc54ddf19f26e0cf0526d25d5a654a7eb67d6e08 Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 21:25:48 -0500 Subject: [PATCH 10/80] Update psutil --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 4c7d48941..52965618c 100644 --- a/setup.py +++ b/setup.py @@ -34,7 +34,7 @@ INSTALL_REQUIRES = [ "pkginfo>=1.3.2,<1.4", "requests>=2.11.1,<2.12", "semantic_version>=2.6.0,<2.7", - "psutil>=3.2.1,<3.3", + "psutil>=4.3.1,<4.4", "Click>=6.2,<6.3", "awesome-slugify>=1.6.5,<1.7", "feedparser>=5.2.1,<5.3", From 943d7ce31a02f3cec8894e92b5797c58b1b766dc Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 6 Oct 2016 21:35:43 -0500 Subject: [PATCH 11/80] Update Click --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 52965618c..41e9a56d3 100644 --- a/setup.py +++ b/setup.py @@ -35,7 +35,7 @@ INSTALL_REQUIRES = [ "requests>=2.11.1,<2.12", "semantic_version>=2.6.0,<2.7", "psutil>=4.3.1,<4.4", - "Click>=6.2,<6.3", + "Click>=6.6,<6.7", "awesome-slugify>=1.6.5,<1.7", "feedparser>=5.2.1,<5.3", "chainmap>=1.0.2,<1.1", From 37f51ef983fb38ebc6f761842add961c446cdee0 Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Fri, 7 Oct 2016 11:37:36 -0500 Subject: [PATCH 12/80] Botched the initial Flask-Login update -- is_active(), is_authenticated(), and is_anonymous() got converted into properties, so we should do the same --- src/octoprint/plugin/types.py | 4 ++-- src/octoprint/server/__init__.py | 4 ++-- src/octoprint/server/api/__init__.py | 4 ++-- src/octoprint/server/api/users.py | 12 ++++++------ src/octoprint/server/util/flask.py | 4 ++-- src/octoprint/users.py | 13 ++++++++----- 6 files changed, 22 insertions(+), 19 deletions(-) diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index f9659e7d8..dd17d7a77 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1400,8 +1400,8 @@ class SettingsPlugin(OctoPrintPlugin): if key in node: node[key] = None - conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous(), - admin=lambda: current_user is not None and not current_user.is_anonymous() and current_user.is_admin(), + conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous, + admin=lambda: current_user is not None and not current_user.is_anonymous and current_user.is_admin, never=lambda: False) for level, condition in conditions.items(): diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index aca269083..bbedc609e 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -86,9 +86,9 @@ def on_identity_loaded(sender, identity): return identity.provides.add(UserNeed(user.get_id())) - if user.is_user(): + if user.is_user: identity.provides.add(RoleNeed("user")) - if user.is_admin(): + if user.is_admin: identity.provides.add(RoleNeed("admin")) def load_user(id): diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 5e7afb358..7602ae18e 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -60,7 +60,7 @@ def pluginData(name): return make_response("More than one api provider registered for {name}, can't proceed".format(name=name), 500) api_plugin = api_plugins[0] - if api_plugin.is_api_adminonly() and not current_user.is_admin(): + if api_plugin.is_api_adminonly() and not current_user.is_admin: return make_response("Forbidden", 403) response = api_plugin.on_api_get(request) @@ -87,7 +87,7 @@ def pluginCommand(name): if valid_commands is None: return make_response("Method not allowed", 405) - if api_plugin.is_api_adminonly() and not current_user.is_admin(): + if api_plugin.is_api_adminonly() and not current_user.is_admin: return make_response("Forbidden", 403) command, data, response = get_json_command_from_request(request, valid_commands) diff --git a/src/octoprint/server/api/users.py b/src/octoprint/server/api/users.py index 8335315ff..fbee5c168 100644 --- a/src/octoprint/server/api/users.py +++ b/src/octoprint/server/api/users.py @@ -72,7 +72,7 @@ def getUser(username): if not userManager.enabled: return jsonify(SUCCESS) - if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()): + if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin): user = userManager.findUser(username) if user is not None: return jsonify(user.asDict()) @@ -133,7 +133,7 @@ def changePasswordForUser(username): if not userManager.enabled: return jsonify(SUCCESS) - if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()): + if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin): if not "application/json" in request.headers["Content-Type"]: return make_response("Expected content-type JSON", 400) @@ -161,7 +161,7 @@ def getSettingsForUser(username): if not userManager.enabled: return jsonify(SUCCESS) - if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()): + if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.is_admin): return make_response("Forbidden", 403) try: @@ -175,7 +175,7 @@ def changeSettingsForUser(username): if not userManager.enabled: return jsonify(SUCCESS) - if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()): + if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.is_admin): return make_response("Forbidden", 403) try: @@ -195,7 +195,7 @@ def deleteApikeyForUser(username): if not userManager.enabled: return jsonify(SUCCESS) - if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()): + if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin): try: userManager.deleteApikey(username) except users.UnknownUser: @@ -211,7 +211,7 @@ def generateApikeyForUser(username): if not userManager.enabled: return jsonify(SUCCESS) - if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()): + if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin): try: apikey = userManager.generateApiKey(username) except users.UnknownUser: diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index ee7fe8833..d7aca0947 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -971,7 +971,7 @@ def admin_validator(request): """ user = _get_flask_user_from_request(request) - if user is None or not user.is_authenticated() or not user.is_admin(): + if user is None or not user.is_authenticated or not user.is_admin: raise tornado.web.HTTPError(403) @@ -986,7 +986,7 @@ def user_validator(request): """ user = _get_flask_user_from_request(request) - if user is None or not user.is_authenticated(): + if user is None or not user.is_authenticated: raise tornado.web.HTTPError(403) diff --git a/src/octoprint/users.py b/src/octoprint/users.py index e5761773b..1ce377a0a 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -428,9 +428,9 @@ class User(UserMixin): def asDict(self): return { "name": self._username, - "active": self.is_active(), - "admin": self.is_admin(), - "user": self.is_user(), + "active": self.is_active, + "admin": self.is_admin, + "user": self.is_user, "apikey": self._apikey, "settings": self._settings } @@ -444,12 +444,15 @@ class User(UserMixin): def get_name(self): return self._username + @property def is_active(self): return self._active + @property def is_user(self): return "user" in self._roles + @property def is_admin(self): return "admin" in self._roles @@ -496,7 +499,7 @@ class User(UserMixin): return True def __repr__(self): - return "User(id=%s,name=%s,active=%r,user=%r,admin=%r)" % (self.get_id(), self.get_name(), self.is_active(), self.is_user(), self.is_admin()) + return "User(id=%s,name=%s,active=%r,user=%r,admin=%r)" % (self.get_id(), self.get_name(), self.is_active, self.is_user, self.is_admin) class SessionUser(User): def __init__(self, user): @@ -526,7 +529,7 @@ class SessionUser(User): return self._session def __repr__(self): - return "SessionUser(id=%s,name=%s,active=%r,user=%r,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), self.is_active(), self.is_user(), self.is_admin(), self._session, self._created) + return "SessionUser(id=%s,name=%s,active=%r,user=%r,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), self.is_active, self.is_user, self.is_admin, self._session, self._created) ##~~ DummyUser object to use when accessControl is disabled From 35d480bc482333e99f1785aca7259d7799dd4537 Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Tue, 25 Oct 2016 21:36:47 -0500 Subject: [PATCH 13/80] Clean up bogus whitespace changes/inconsistency --- src/octoprint/server/util/flask.py | 2 +- src/octoprint/server/util/tornado.py | 4 ++-- src/octoprint/users.py | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index d7aca0947..a0292ad11 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -426,7 +426,7 @@ class OctoPrintFlaskResponse(flask.Response): def passive_login(): if octoprint.server.userManager.enabled: - user = octoprint.server.userManager.login_user(flask_login.current_user) + user = octoprint.server.userManager.login_user(flask_login.current_user) else: user = flask_login.current_user diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 54eb09553..e599d1510 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -672,8 +672,8 @@ class CustomHTTPServer(tornado.httpserver.HTTPServer): ``default_max_body_size`` is the default maximum body size to apply if no specific one from ``max_body_sizes`` matches. """ - def __init__(self, *args, **kwargs): - pass + def __init__(self, *args, **kwargs): + pass def initialize(self, request_callback, no_keep_alive=False, io_loop=None, xheaders=False, ssl_options=None, protocol=None, diff --git a/src/octoprint/users.py b/src/octoprint/users.py index 1ce377a0a..d7d4d1e49 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -444,15 +444,15 @@ class User(UserMixin): def get_name(self): return self._username - @property + @property def is_active(self): return self._active - @property + @property def is_user(self): return "user" in self._roles - @property + @property def is_admin(self): return "admin" in self._roles From f318cc5e284ef437e80350a61b137ae172eceadd Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Thu, 10 Nov 2016 13:12:02 -0600 Subject: [PATCH 14/80] Update 970880d, flask.ext.login -> flask_login --- src/octoprint/server/api/settings.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index b4d862aeb..0225ad81c 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging from flask import request, jsonify, make_response -from flask.ext.login import current_user +from flask_login import current_user from werkzeug.exceptions import BadRequest from octoprint.events import eventManager, Events @@ -32,7 +32,7 @@ def _etag(lm=None): connection_options = printer.__class__.get_connection_options() plugins = sorted(octoprint.plugin.plugin_manager().enabled_plugins) - if current_user is not None and not current_user.is_anonymous(): + if current_user is not None and not current_user.is_anonymous: roles = sorted(current_user.roles) else: roles = [] From 153b5de1d43661408af96e6ff8588b6263f4d36c Mon Sep 17 00:00:00 2001 From: Juha-Jarmo Heinonen Date: Mon, 19 Dec 2016 20:35:04 +0200 Subject: [PATCH 15/80] Added /dev/ttyS* into serial ports to find. OctoPrint was unable to find any of the serial ports on my CubieBoard, which are all ttyS devices; this fixes that issue. --- AUTHORS.md | 1 + src/octoprint/util/comm.py | 1 + 2 files changed, 2 insertions(+) diff --git a/AUTHORS.md b/AUTHORS.md index a85ff3f29..4ff4458df 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -74,6 +74,7 @@ date of first contribution): * [Mathias Rangel Wulff](https://github.com/mathiasrw) * [Clemens Niemeyer](https://github.com/clemniem) * ["I-am-me"](https://github.com/I-am-me) + * [J-J Heinonen](https://github.com/jammi) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index dd0ab9c6a..71cc3fd5a 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -144,6 +144,7 @@ def serialList(): + glob.glob("/dev/tty.usb*") \ + glob.glob("/dev/cu.*") \ + glob.glob("/dev/cuaU*") \ + + glob.glob("/dev/ttyS*") \ + glob.glob("/dev/rfcomm*") additionalPorts = settings().get(["serial", "additionalPorts"]) From 8a8b88af13bb86fc8391e80cd7bcf9a035d2fbd1 Mon Sep 17 00:00:00 2001 From: Marc Hannappel Date: Wed, 21 Dec 2016 09:44:24 +0100 Subject: [PATCH 16/80] Fix folders doesn't get listed when performing a filtering in file section, issue #1667 --- src/octoprint/static/js/app/viewmodels/files.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 24695b2dd..2563ebe87 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -708,11 +708,12 @@ $(function() { return false; } - if (entry["type"] == "folder" && entry["children"]) { + var success = entry["name"].toLocaleLowerCase().indexOf(query) > -1; + if (!success && entry["type"] == "folder" && entry["children"]) { return _.any(entry["children"], recursiveSearch); - } else { - return entry["name"].toLocaleLowerCase().indexOf(query) > -1; } + + return success; }; self.listHelper.changeSearchFunction(recursiveSearch); From bcb74d01b63ba18ddf071320ed1007c1a4ef9da8 Mon Sep 17 00:00:00 2001 From: Marc Hannappel Date: Wed, 21 Dec 2016 10:51:19 +0100 Subject: [PATCH 17/80] Added active tab using hash from URL feature, as requested in issue #203 --- src/octoprint/static/js/app/main.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 86221ca40..d762f1e5c 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -478,6 +478,15 @@ $(function() { // reload overlay $("#reloadui_overlay_reload").click(function() { location.reload(); }); + var changeTab = function() + { + var hashtag = window.location.hash; + + var tab = $('#tabs a[href="' + hashtag + '"]'); + tab.tab("show"); + onTabChange(hashtag); + } + //~~ view model binding var bindViewModels = function() { @@ -566,6 +575,15 @@ $(function() { callViewModels(allViewModels, "onBrowserTabVisibilityChange", [status]); }); + $(window).on("hashchange", function() { + changeTab(); + }); + + if (window.location.hash != "") + { + changeTab(); + } + log.info("Application startup complete"); }; From b3f35c579b37bbfd7e02671a7572e26289fe2f2c Mon Sep 17 00:00:00 2001 From: Marc Hannappel Date: Wed, 21 Dec 2016 10:56:11 +0100 Subject: [PATCH 18/80] Little update to the active tab using hash from URL, forgot to add a check if the hash is valid, fixed this now --- src/octoprint/static/js/app/main.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index d762f1e5c..80b1701ec 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -481,10 +481,12 @@ $(function() { var changeTab = function() { var hashtag = window.location.hash; - var tab = $('#tabs a[href="' + hashtag + '"]'); - tab.tab("show"); - onTabChange(hashtag); + if (tab.length) + { + tab.tab("show"); + onTabChange(hashtag); + } } //~~ view model binding From 639619ff939c00befadbc5ded213200cae431a9c Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Mon, 9 Jan 2017 08:51:52 -0600 Subject: [PATCH 19/80] Partially revert 57de36a --- src/octoprint/server/__init__.py | 3 +-- src/octoprint/server/util/tornado.py | 30 ---------------------------- 2 files changed, 1 insertion(+), 32 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 4c60edc94..e9a432c70 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -168,8 +168,7 @@ class Server(object): self._logger = logging.getLogger(__name__) pluginManager = self._plugin_manager - # monkey patch a bunch of stuff - util.tornado.fix_ioloop_scheduling() + # monkey patch some stuff util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")]) # setup app diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index e599d1510..8325bcaf5 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -29,36 +29,6 @@ import tornado.util import octoprint.util -#~~ Monkey patching - - -def fix_ioloop_scheduling(): - """ - This monkey patches tornado's :meth:``tornado.ioloop.PeriodicCallback._schedule_next`` method so it no longer - blocks for long times on slow machines (RPi) when the system time happens to change by a large amount (e.g. due to - the first ever contact to an NTP server). - - Patch by @nosyjoe on Github. See this PR against tornado: https://github.com/tornadoweb/tornado/pull/1290 - """ - - import math - - # patched implementation taken from PR - def _schedule_next(self): - if self._running: - current_time = self.io_loop.time() - - if self._next_timeout <= current_time: - callback_time_sec = self.callback_time / 1000.0 - self._next_timeout += (math.floor((current_time - self._next_timeout) / callback_time_sec) + 1) * callback_time_sec - - self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) - - # replace original implementation with patched version - import tornado.ioloop - tornado.ioloop.PeriodicCallback._schedule_next = _schedule_next - - #~~ WSGI middleware From 72f3fa6eda99121169b279d79ec28ef936996902 Mon Sep 17 00:00:00 2001 From: Noah Martin Date: Tue, 10 Jan 2017 23:36:55 -0800 Subject: [PATCH 20/80] Changed old comments to not claim a method does more than it really does, because comments are there to clear up confusion, might as well start here. poll_temperature and poll_sd_status are called by a RepeatedTimer now, the methods don't re-enqueue themselves. --- src/octoprint/util/comm.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 71cc3fd5a..fb1e1118a 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -1545,7 +1545,7 @@ class MachineCom(object): def _poll_temperature(self): """ - Polls the temperature after the temperature timeout, re-enqueues itself. + Polls the temperature. If the printer is not operational, closing the connection, not printing from sd, busy with a long running command or heating, no poll will be done. @@ -1556,7 +1556,7 @@ class MachineCom(object): def _poll_sd_status(self): """ - Polls the sd printing status after the sd status timeout, re-enqueues itself. + Polls the sd printing status. If the printer is not operational, closing the connection, not printing from sd, busy with a long running command or heating, no poll will be done. From ce38ef628908db0b40071f17f834a6687dc182f4 Mon Sep 17 00:00:00 2001 From: Eyal Soha Date: Thu, 2 Feb 2017 10:47:41 +0200 Subject: [PATCH 21/80] add same device to the slicing API --- src/octoprint/server/api/slicing.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 3aa8a33dc..824faf023 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -72,6 +72,7 @@ def slicingListAll(): result[slicer] = dict( key=slicer, displayName=slicer_impl.get_slicer_properties()["name"], + sameDevice=slicer_impl.get_slicer_properties()["same_device"], default=default_slicer == slicer, configured=slicer_impl.is_slicer_configured(), profiles=_getSlicingProfilesData(slicer), From fea07917fae2079c02f43adf1215877e0f94c534 Mon Sep 17 00:00:00 2001 From: Eyal Soha Date: Sun, 12 Feb 2017 12:35:57 +0200 Subject: [PATCH 22/80] add sameDevice to SlicingViewModel --- src/octoprint/static/js/app/viewmodels/slicing.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/octoprint/static/js/app/viewmodels/slicing.js b/src/octoprint/static/js/app/viewmodels/slicing.js index 8e39b5066..ae98bed74 100644 --- a/src/octoprint/static/js/app/viewmodels/slicing.js +++ b/src/octoprint/static/js/app/viewmodels/slicing.js @@ -204,7 +204,8 @@ $(function() { name: name, configured: slicer.configured, sourceExtensions: slicer.extensions.source, - destinationExtensions: slicer.extensions.destination + destinationExtensions: slicer.extensions.destination, + sameDevice: slicer.sameDevice }; self.slicers.push(props); }); From e82efd24d347d04806b01dac0394b797a06e5794 Mon Sep 17 00:00:00 2001 From: Greg Hulands Date: Mon, 20 Feb 2017 11:02:07 -0800 Subject: [PATCH 23/80] Issue #1780: Safari Webcam Fix. --- .../static/js/app/viewmodels/control.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index 3879cd6c9..d878eef56 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -362,9 +362,21 @@ $(function() { self.onSettingsBeforeSave = self.updateRotatorWidth; + self._isSafari = function() { + var is_chrome = navigator.userAgent.indexOf('Chrome') > -1; + var is_safari = navigator.userAgent.indexOf("Safari") > -1; + return is_safari && !is_chrome; + } + self._disableWebcam = function() { // only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause // more load by the constant connection creation than by the actual webcam stream + + // safari bug doesn't release the mjpeg stream, so we just disable this for safari. + if (self._isSafari()) { + return; + } + self.webcamDisableTimeout = setTimeout(function () { $("#webcam_image").attr("src", ""); }, 5000); @@ -380,6 +392,12 @@ $(function() { } var webcamImage = $("#webcam_image"); var currentSrc = webcamImage.attr("src"); + + // safari bug doesn't release the mjpeg stream, so we just set it up the once + if (self._isSafari() && currentSrc != undefined) { + return; + } + var newSrc = self.settings.webcam_streamUrl(); if (currentSrc != newSrc) { if (newSrc.lastIndexOf("?") > -1) { From 0adb62b485033b154f86891a59bf5b2d8eda3888 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Feb 2017 11:55:35 +0100 Subject: [PATCH 24/80] Compatibility layer for plugins depending on flask.ext Logs a deprecation warning when anything from flask.ext is accessed, imports flask_ instead and returns it. To be removed again in OctoPrint 1.5.0 --- src/octoprint/server/__init__.py | 4 +++- src/octoprint/server/util/flask.py | 26 +++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index abc717ff4..5adbcf2e9 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -609,7 +609,9 @@ class Server(object): return Locale.parse(request.accept_languages.best_match(LANGUAGES)) def _setup_app(self, app): - from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse + from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse, deprecate_flaskext + + deprecate_flaskext() # TODO: remove in OctoPrint 1.5.0 s = settings() diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 9fc0defd1..328bb6fa7 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -229,6 +229,27 @@ def fix_webassets_filtertool(): FilterTool._wrap_cache = fixed_wrap_cache +# TODO: Remove compatibility layer in OctoPrint 1.5.0 +def deprecate_flaskext(): + import flask + import importlib + + class FlaskExtDeprecator(object): + + def __getattr__(self, item): + old_name = "flask.ext.{}".format(item) + new_name = "flask_{}".format(item) + module = importlib.import_module(new_name) + + from warnings import warn + message = "The {old} import is deprecated in Flask versions >= 0.11, which OctoPrint now uses. " + \ + "Import {new} instead. This compatibility layer will be removed in OctoPrint 1.5.0." + warn(DeprecationWarning(message.format(old=old_name, new=new_name)), stacklevel=2) + + return module + + flask.ext = FlaskExtDeprecator() + #~~ WSGI environment wrapper for reverse proxying class ReverseProxiedEnvironment(object): @@ -1188,7 +1209,10 @@ def get_json_command_from_request(request, valid_commands): if content_type is None or not "application/json" in content_type: return None, None, make_response("Expected content-type JSON", 400) - data = request.json + data = request.get_json() + if data is None: + return make_response("Malformed JSON body in request", 400) + if not "command" in data.keys() or not data["command"] in valid_commands.keys(): return None, None, make_response("Expected valid command", 400) From b7a0f5bee56ab9fb39df45167322582a10ddf8e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Feb 2017 12:00:51 +0100 Subject: [PATCH 25/80] Compatibility layer for plugins depending on user.is_anonymous() etc Logs a deprecation warning when any of the made-property fields is accessed as a getter and return value. Implements __eq__, __ne__, __bool__ and __nonzero__ to allow things like "user.is_anonymous == True" or "not user.is_anonymous" is used. Careful with serialization to json, needs "bool(...)" wrapper to not cause an exception (or inclusion in a custom serializer). Affected fields: * is_anonymous * is_authenticated * is_active * is_user * is_admin To be removed again in OctoPrint 1.5.0 --- src/octoprint/server/__init__.py | 1 + src/octoprint/users.py | 97 +++++++++++++++++++++++++++++--- 2 files changed, 91 insertions(+), 7 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 5adbcf2e9..a574776bd 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -336,6 +336,7 @@ class Server(object): loginManager = LoginManager() loginManager.session_protection = "strong" loginManager.user_callback = load_user + loginManager.anonymous_user = users.AnonymousUser # TODO: remove in 1.5.0 if not userManager.enabled: loginManager.anonymous_user = users.DummyUser principals.identity_loaders.appendleft(users.dummy_identity_loader) diff --git a/src/octoprint/users.py b/src/octoprint/users.py index 1803104ba..fb3fc83db 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -5,7 +5,7 @@ __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_login import UserMixin +from flask_login import UserMixin, AnonymousUserMixin from flask_principal import Identity from werkzeug.local import LocalProxy import hashlib @@ -413,6 +413,65 @@ class UnknownRole(Exception): ##~~ User object +class MethodReplacedByBooleanProperty(object): + + def __init__(self, name, message, getter): + self._name = name + self._message = message + self._getter = getter + + @property + def _attr(self): + return self._getter() + + def __call__(self): + from warnings import warn + warn(DeprecationWarning(self._message.format(name=self._name)), stacklevel=2) + return self._attr + + def __eq__(self, other): + return self._attr == other + + def __ne__(self, other): + return self._attr != other + + def __bool__(self): + # Python 3 + return self._attr + + def __nonzero__(self): + # Python 2 + return self._attr + + def __hash__(self): + return hash(self._attr) + + def __repr__(self): + return "MethodReplacedByProperty({}, {}, {})".format(self._name, self._message, self._getter) + + def __str__(self): + return str(self._attr) + + +# TODO: Remove compatibility layer in OctoPrint 1.5.0 +class FlaskLoginMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty): + + def __init__(self, name, getter): + message = "{name} is now a property in Flask-Login versions >= 0.3.0, which OctoPrint now uses. " + \ + "Use {name} instead of {name}(). This compatibility layer will be removed in OctoPrint 1.5.0." + MethodReplacedByBooleanProperty.__init__(self, name, message, getter) + + +# TODO: Remove compatibility layer in OctoPrint 1.5.0 +class OctoPrintUserMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty): + + def __init__(self, name, getter): + message = "{name} is now a property for consistency reasons with Flask-Login versions >= 0.3.0, which " + \ + "OctoPrint now uses. Use {name} instead of {name}(). This compatibility layer will be removed " + \ + "in OctoPrint 1.5.0." + MethodReplacedByBooleanProperty.__init__(self, name, message, getter) + + class User(UserMixin): def __init__(self, username, passwordHash, active, roles, apikey=None, settings=None): self._username = username @@ -428,9 +487,9 @@ class User(UserMixin): def asDict(self): return { "name": self._username, - "active": self.is_active, - "admin": self.is_admin, - "user": self.is_user, + "active": bool(self.is_active), + "admin": bool(self.is_admin), + "user": bool(self.is_user), "apikey": self._apikey, "settings": self._settings } @@ -444,17 +503,25 @@ class User(UserMixin): def get_name(self): return self._username + @property + def is_anonymous(self): + return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: False) + + @property + def is_authenticated(self): + return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: True) + @property def is_active(self): - return self._active + return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: self._active) @property def is_user(self): - return "user" in self._roles + return OctoPrintUserMethodReplacedByBooleanProperty("is_user", lambda: "user" in self._roles) @property def is_admin(self): - return "admin" in self._roles + return OctoPrintUserMethodReplacedByBooleanProperty("is_admin", lambda: "admin" in self._roles) def get_all_settings(self): return self._settings @@ -505,6 +572,22 @@ class User(UserMixin): def __repr__(self): return "User(id=%s,name=%s,active=%r,user=%r,admin=%r)" % (self.get_id(), self.get_name(), self.is_active, self.is_user, self.is_admin) + +class AnonymousUser(AnonymousUserMixin): + + @property + def is_anonymous(self): + return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: True) + + @property + def is_authenticated(self): + return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: False) + + @property + def is_active(self): + return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: False) + + class SessionUser(User): def __init__(self, user): self._user = user From dbe4acd47d7189bcb27f8417d9291fb2a5bb9777 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Feb 2017 13:18:59 +0100 Subject: [PATCH 26/80] flask.request.json => flask.request.get_json() Old property is deprecated as of Flask 0.11 --- src/octoprint/plugins/corewizard/__init__.py | 6 +++--- .../plugins/softwareupdate/__init__.py | 4 +++- src/octoprint/server/api/__init__.py | 11 ++++++---- src/octoprint/server/api/printer.py | 5 ++++- src/octoprint/server/api/printer_profiles.py | 10 ++++++++-- src/octoprint/server/api/settings.py | 5 ++++- src/octoprint/server/api/slicing.py | 10 ++++++++-- src/octoprint/server/api/system.py | 6 +++--- src/octoprint/server/api/timelapse.py | 6 +++--- src/octoprint/server/api/users.py | 20 +++++++++++++++---- src/octoprint/server/apps/__init__.py | 5 ++++- 11 files changed, 63 insertions(+), 25 deletions(-) diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index f5475239e..787300b6d 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -87,9 +87,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, from flask import request from octoprint.server.api import valid_boolean_trues, NO_CONTENT - data = request.values - if hasattr(request, "json") and request.json: - data = request.json + data = request.get_json() + if data is None: + data = request.values if "ac" in data and data["ac"] in valid_boolean_trues and \ "user" in data.keys() and "pass1" in data.keys() and \ diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 615587185..fccd2214b 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -495,7 +495,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, if not "application/json" in flask.request.headers["Content-Type"]: return flask.make_response("Expected content-type JSON", 400) - json_data = flask.request.json + json_data = flask.request.get_json(silent=True) + if json_data is None: + return flask.make_response("Invalid JSON", 400) if "check" in json_data: check_targets = map(lambda x: x.strip(), json_data["check"]) diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 6d056fe09..ecad3e93d 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -134,10 +134,13 @@ def wizardFinish(): data = dict() try: - data = request.json + data = request.get_json() except: abort(400) + if data is None: + abort(400) + if not "handled" in data: abort(400) handled = data["handled"] @@ -186,9 +189,9 @@ def apiVersion(): @api.route("/login", methods=["POST"]) def login(): - data = request.values - if hasattr(request, "json") and request.json: - data = request.json + data = request.get_json() + if data is None: + data = request.values if octoprint.server.userManager.enabled and "user" in data and "pass" in data: username = data["user"] diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index b6e81b220..68d69146c 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -326,10 +326,13 @@ def printerCommand(): return make_response("Expected content type JSON", 400) try: - data = request.json + data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) + if "command" in data and "commands" in data: return make_response("'command' and 'commands' are mutually exclusive", 400) elif ("command" in data or "commands" in data) and "script" in data: diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py index bc9f6f2c6..6e3d5dcde 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -50,10 +50,13 @@ def printerProfilesAdd(): return make_response("Expected content-type JSON", 400) try: - json_data = request.json + json_data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if json_data is None: + return make_response("Malformed JSON body in request", 400) + if not "profile" in json_data: return make_response("No profile included in request", 400) @@ -117,10 +120,13 @@ def printerProfilesUpdate(identifier): return make_response("Expected content-type JSON", 400) try: - json_data = request.json + json_data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if json_data is None: + return make_response("Malformed JSON body in request", 400) + if not "profile" in json_data: return make_response("No profile included in request", 400) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 7ef37a355..645a4ef76 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -251,10 +251,13 @@ def setSettings(): return make_response("Expected content-type JSON", 400) try: - data = request.json + data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) + _saveSettings(data) return getSettings() diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 824faf023..6644024e2 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -118,10 +118,13 @@ def slicingAddSlicerProfile(slicer, name): return make_response("Expected content-type JSON", 400) try: - json_data = request.json + json_data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if json_data is None: + return make_response("Malformed JSON body in request", 400) + data = dict() display_name = None description = None @@ -157,10 +160,13 @@ def slicingPatchSlicerProfile(slicer, name): return make_response("Profile {name} for slicer {slicer} not found".format(**locals()), 404) try: - json_data = request.json + json_data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if json_data is None: + return make_response("Malformed JSON body in request", 400) + data = dict() display_name = None description = None diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index 14a0e0844..24b0ae527 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -24,9 +24,9 @@ from octoprint.server.util.flask import restricted_access, get_remote_address def performSystemAction(): logging.getLogger(__name__).warn("Deprecated API call to /api/system made by {}, should be migrated to use /system/commands/custom/".format(get_remote_address(request))) - data = request.values - if hasattr(request, "json") and request.json: - data = request.json + data = request.get_json(silent=True) + if data is None: + data = request.values if not "action" in data: return make_response("action to perform is not defined", 400) diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index e7272eb62..a108fad4c 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -162,9 +162,9 @@ def processUnrenderedTimelapseCommand(name): @api.route("/timelapse", methods=["POST"]) @restricted_access def setTimelapseConfig(): - data = request.values - if hasattr(request, "json") and request.json: - data = request.json + data = request.get_json(silent=True) + if data is None: + data = request.values if "type" in data: config = { diff --git a/src/octoprint/server/api/users.py b/src/octoprint/server/api/users.py index fbee5c168..b907e5608 100644 --- a/src/octoprint/server/api/users.py +++ b/src/octoprint/server/api/users.py @@ -40,10 +40,13 @@ def addUser(): return make_response("Expected content-type JSON", 400) try: - data = request.json + data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) + if not "name" in data: return make_response("Missing mandatory name field", 400) if not "password" in data: @@ -95,10 +98,13 @@ def updateUser(username): return make_response("Expected content-type JSON", 400) try: - data = request.json + data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) + # change roles roles = ["user"] if "admin" in data and data["admin"] in valid_boolean_trues: @@ -138,10 +144,13 @@ def changePasswordForUser(username): return make_response("Expected content-type JSON", 400) try: - data = request.json + data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) + if not "password" in data or not data["password"]: return make_response("password is missing from request", 400) @@ -179,10 +188,13 @@ def changeSettingsForUser(username): return make_response("Forbidden", 403) try: - data = request.json + data = request.get_json() except BadRequest: return make_response("Malformed JSON body in request", 400) + if data is None: + return make_response("Malformed JSON body in request", 400) + try: userManager.changeUserSettings(username, data) return jsonify(SUCCESS) diff --git a/src/octoprint/server/apps/__init__.py b/src/octoprint/server/apps/__init__.py index f5e9e3286..b98d11e17 100644 --- a/src/octoprint/server/apps/__init__.py +++ b/src/octoprint/server/apps/__init__.py @@ -29,7 +29,10 @@ def verifySessionKey(): if not "application/json" in request.headers["Content-Type"]: return None, None, make_response("Expected content-type JSON", 400) - data = request.json + data = request.get_json() + if data is None: + return make_response("Malformed JSON body in request", 400) + for key in ("appid", "key", "_sig"): if not key in data: return make_response("Missing argument: {key}".format(key=key), 400) From cf20b3a3c38da8effa1a99d4a843ea60d87e4769 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Feb 2017 13:19:44 +0100 Subject: [PATCH 27/80] flask.ext.foo => flask_foo for things new on devel --- src/octoprint/server/util/__init__.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 5d202d16b..cd95e76ea 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -13,6 +13,8 @@ from octoprint.users import ApiUser from octoprint.util import deprecated import flask as _flask +import flask_login +import flask_principal from . import flask from . import sockjs @@ -58,9 +60,9 @@ def loginFromApiKeyRequestHandler(): if apikey and apikey != octoprint.server.UI_API_KEY and not octoprint.server.appSessionManager.validate(apikey): user = get_user_for_apikey(apikey) - if user is not None and _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())) + if user is not None and not user.is_anonymous() and flask_login.login_user(user, remember=False): + flask_principal.identity_changed.send(_flask.current_app._get_current_object(), + identity=flask_principal.Identity(user.get_id())) else: return _flask.make_response("Invalid API key", 401) From 5d07c5a0b2898f836a4602dac259fe95f6d6636c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Feb 2017 13:21:18 +0100 Subject: [PATCH 28/80] Updated mirrored methods of custom tornado http server Should now be up to date with stock implementation again. --- src/octoprint/server/util/tornado.py | 123 ++++++++++++++------------- 1 file changed, 63 insertions(+), 60 deletions(-) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 8325bcaf5..d25fe343e 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -7,11 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import os -import datetime -import stat import mimetypes -import email -import time import re import tornado @@ -530,7 +526,8 @@ class WsgiInputContainer(object): if not data: raise Exception("WSGI app did not call start_response") - status_code = int(data["status"].split()[0]) + status_code, reason = data["status"].split(" ", 1) + status_code = int(status_code) headers = data["headers"] header_set = set(k.lower() for (k, v) in headers) body = tornado.escape.utf8(body) @@ -542,13 +539,12 @@ class WsgiInputContainer(object): if "server" not in header_set: headers.append(("Server", "TornadoServer/%s" % tornado.version)) - parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")] + start_line = tornado.httputil.ResponseStartLine("HTTP/1.1", status_code, reason) + header_obj = tornado.httputil.HTTPHeaders() 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() + header_obj.add(key, value) + request.connection.write_headers(start_line, header_obj, chunk=body) + request.connection.finish() self._log(status_code, request) @staticmethod @@ -583,22 +579,22 @@ class WsgiInputContainer(object): 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, + "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") @@ -619,7 +615,7 @@ class WsgiInputContainer(object): log_method = access_log.error request_time = 1000.0 * request.request_time() summary = request.method + " " + request.uri + " (" + \ - request.remote_ip + ")" + request.remote_ip + ")" log_method("%d %s %.2fms", status_code, summary, request_time) @@ -645,35 +641,21 @@ class CustomHTTPServer(tornado.httpserver.HTTPServer): def __init__(self, *args, **kwargs): pass - def initialize(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 initialize(self, *args, **kwargs): + default_max_body_size = kwargs.pop("default_max_body_size", None) + max_body_sizes = kwargs.pop("max_body_sizes", None) + + tornado.httpserver.HTTPServer.initialize(self, *args, **kwargs) + + additional = dict(default_max_body_size=default_max_body_size, + max_body_sizes=max_body_sizes) + self.conn_params = CustomHTTP1ConnectionParameters.from_stock_params(self.conn_params, **additional) def handle_stream(self, stream, address): context = tornado.httpserver._HTTPRequestContext(stream, address, - self.protocol) - conn = CustomHTTP1ServerConnection( - stream, self.conn_params, context) + self.protocol) + conn = CustomHTTP1ServerConnection(stream, self.conn_params, context) self._connections.add(conn) conn.start_serving(self) @@ -690,7 +672,7 @@ class CustomHTTP1ServerConnection(tornado.http1connection.HTTP1ServerConnection) try: while True: conn = CustomHTTP1Connection(self.stream, False, - self.params, self.context) + self.params, self.context) request_delegate = delegate.start_request(self, conn) try: ret = yield conn.read_response(request_delegate) @@ -734,8 +716,13 @@ class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection): 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" in headers: + if "Transfer-Encoding" in headers: + # Response cannot contain both Content-Length and + # Transfer-Encoding headers. + # http://tools.ietf.org/html/rfc7230#section-3.3.3 + raise tornado.httputil.HTTPInputError( + "Response with both Transfer-Encoding and Content-Length") if "," in headers["Content-Length"]: # Proxies sometimes cause Content-Length headers to get # duplicated. If all the values are identical then we can @@ -746,9 +733,14 @@ class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection): "Multiple unequal Content-Lengths: %r" % headers["Content-Length"]) headers["Content-Length"] = pieces[0] - content_length = int(headers["Content-Length"]) - content_length = int(content_length) + try: + content_length = int(headers["Content-Length"]) + except ValueError: + # Handles non-integer Content-Length value. + raise tornado.httputil.HTTPInputError( + "Only integer Content-Length is allowed: %s" % headers["Content-Length"]) + max_content_length = self._get_max_content_length(self._request_start_line.method, self._request_start_line.path) if max_content_length is not None and 0 <= max_content_length < content_length: raise tornado.httputil.HTTPInputError("Content-Length too long") @@ -800,9 +792,20 @@ class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionPar """ 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 list() - self.default_max_body_size = kwargs["default_max_body_size"] if "default_max_body_size" in kwargs else None + max_body_sizes = kwargs.pop("max_body_sizes", list()) + default_max_body_size = kwargs.pop("default_max_body_size", None) + + tornado.http1connection.HTTP1ConnectionParameters.__init__(self, *args, **kwargs) + + self.max_body_sizes = max_body_sizes + self.default_max_body_size = default_max_body_size + + @classmethod + def from_stock_params(cls, other, **additional): + kwargs = dict(other.__dict__) + for key, value in additional.items(): + kwargs[key] = value + return cls(**kwargs) #~~ customized large response handler From 0cd4fc86556586747f8eab3658570a29686bef19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Feb 2017 13:21:42 +0100 Subject: [PATCH 29/80] Enable template auto reload by default We have our own cache, and that would get confused by not allowing a reload of the templates at runtime, which Flask 0.11+ will not allow anymore unless this setting is set to True. --- src/octoprint/server/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index a574776bd..4f6f2cc33 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -617,6 +617,7 @@ class Server(object): s = settings() app.debug = self._debug + app.config["TEMPLATES_AUTO_RELOAD"] = True secret_key = s.get(["server", "secretKey"]) if not secret_key: From 9884c52c4e1831bcb3160b357c7e0908d0d9ba40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Feb 2017 13:23:52 +0100 Subject: [PATCH 30/80] Upgrade to current versions again --- setup.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/setup.py b/setup.py index d2c98c6ad..5cf2ad466 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ import octoprint_setuptools # Requirements for our application INSTALL_REQUIRES = [ - "flask>=0.11,<0.12", + "flask>=0.12,<0.13", "werkzeug>=0.11.1,<0.12", "tornado>=4.4.2,<4.5", "Jinja2>=2.8,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't @@ -22,23 +22,23 @@ INSTALL_REQUIRES = [ # version, hence we need to pin to a lower version for now. See #1697 "sockjs-tornado>=1.0.2,<1.1", "PyYAML>=3.12,<3.13", - "Flask-Login>=0.3,<0.4", + "Flask-Login>=0.4,<0.5", "Flask-Principal>=0.4,<0.5", "Flask-Babel>=0.11,<0.12", "Flask-Assets>=0.12,<0.13", "markdown>=2.6.4,<2.7", - "pyserial>=3.1.1,<3.2", + "pyserial>=3.2.1,<3.3", "netaddr>=0.7.17,<0.8", "watchdog>=0.8.3,<0.9", "sarge>=0.1.4,<0.2", "netifaces>=0.10,<0.11", "pylru>=1.0.9,<1.1", "rsa>=3.4,<3.5", - "pkginfo>=1.3.2,<1.4", - "requests>=2.11.1,<2.12", + "pkginfo>=1.4.1,<1.5", + "requests>=2.13.0,<2.14", "semantic_version>=2.6.0,<2.7", - "psutil>=4.3.1,<4.4", - "Click>=6.6,<6.7", + "psutil>=5.1.3,<5.2", + "Click>=6.7,<6.8", "awesome-slugify>=1.6.5,<1.7", "feedparser>=5.2.1,<5.3", "chainmap>=1.0.2,<1.1", @@ -55,7 +55,7 @@ EXTRA_REQUIRES = dict( # Dependencies for developing OctoPrint develop=[ # Testing dependencies - "mock>=1.0.1,<1.1", + "mock>=2.0,<2.1", "nose>=1.3.0,<1.4", "ddt", @@ -70,7 +70,7 @@ EXTRA_REQUIRES = dict( # Dependencies for developing OctoPrint plugins plugins=[ - "cookiecutter>=1.4,<1.5" + "cookiecutter>=1.5,<1.6" ] ) From 49583533355a947e788b3ce2381254c98e4c3e34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Feb 2017 14:00:50 +0100 Subject: [PATCH 31/80] Fix repr for User and SessionUser --- src/octoprint/users.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/users.py b/src/octoprint/users.py index fb3fc83db..47a2d28a4 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -570,7 +570,7 @@ class User(UserMixin): return True def __repr__(self): - return "User(id=%s,name=%s,active=%r,user=%r,admin=%r)" % (self.get_id(), self.get_name(), self.is_active, self.is_user, self.is_admin) + return "User(id=%s,name=%s,active=%r,user=%r,admin=%r)" % (self.get_id(), self.get_name(), bool(self.is_active), bool(self.is_user), bool(self.is_admin)) class AnonymousUser(AnonymousUserMixin): @@ -616,7 +616,7 @@ class SessionUser(User): return self._session def __repr__(self): - return "SessionUser(id=%s,name=%s,active=%r,user=%r,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), self.is_active, self.is_user, self.is_admin, self._session, self._created) + return "SessionUser(id=%s,name=%s,active=%r,user=%r,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), bool(self.is_user), bool(self.is_admin), self._session, self._created) ##~~ DummyUser object to use when accessControl is disabled From 814b02900bf286d4a4fb3636851c17c177a71071 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Feb 2017 16:39:30 +0100 Subject: [PATCH 32/80] Fixed a test left-over Thanks for the heads-up @kevans91 --- src/octoprint/server/util/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index cd95e76ea..c04e21d87 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -60,7 +60,7 @@ def loginFromApiKeyRequestHandler(): if apikey and apikey != octoprint.server.UI_API_KEY and not octoprint.server.appSessionManager.validate(apikey): user = get_user_for_apikey(apikey) - if user is not None and not user.is_anonymous() and flask_login.login_user(user, remember=False): + if user is not None and not user.is_anonymous and flask_login.login_user(user, remember=False): flask_principal.identity_changed.send(_flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id())) else: From b75b53d05af04b4b6c049dc76380c6bfc16d6870 Mon Sep 17 00:00:00 2001 From: Andy Werner Date: Tue, 7 Mar 2017 10:35:33 +0100 Subject: [PATCH 33/80] Fix an issue in user settings * UserSettings: crashed if overwrite an existing key with primitive value by same key with complex value. Also reduced number of calls to user.get_setting() * Updated tests --- AUTHORS.md | 1 + src/octoprint/users.py | 9 ++++----- tests/users/test_user.py | 4 +++- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index 9a2f67442..e7fbcc557 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -78,6 +78,7 @@ date of first contribution): * [Noah Martin](https://github.com/noahsmartin) * [Eyal Soha](https://github.com/eyal0) * [Greg Hulands](https://github.com/ghulands) + * [Andreas Werner](https://github.com/gallore) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/src/octoprint/users.py b/src/octoprint/users.py index 47a2d28a4..e1c8edc9e 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -310,9 +310,8 @@ class FilebasedUserManager(UserManager): raise UnknownUser(username) user = self._users[username] - current = user.get_setting(key) - if not current or current != value: - old_value = user.get_setting(key) + old_value = user.get_setting(key) + if not old_value or old_value != value: user.set_setting(key, value) self._dirty = self._dirty or old_value != value self._save() @@ -548,7 +547,7 @@ class User(UserMixin): def _get_setting(self, path): s = self._settings for p in path: - if p in s: + if isinstance(s, dict) and p in s: s = s[p] else: return None @@ -561,7 +560,7 @@ class User(UserMixin): s[p] = dict() if not isinstance(s[p], dict): - return False + s[p] = dict() s = s[p] diff --git a/tests/users/test_user.py b/tests/users/test_user.py index 4665a2153..e827d3e89 100644 --- a/tests/users/test_user.py +++ b/tests/users/test_user.py @@ -63,7 +63,9 @@ class UserTestCase(unittest.TestCase): (["sub", "othersubkey"], "othersubvalue", dict(sub=dict(othersubkey="othersubvalue")), True), ("booleankey", True, dict(booleankey=True), True), (["newsub", "newsubkey"], "newsubvalue", dict(newsub=dict(newsubkey="newsubvalue")), True), - (["sub", "subkey", "wontwork"], "wontwork", dict(), False) + # ["sub", "subkey"] is already existing and gets overwritten + (["sub", "subkey", "subsubkey"], "42", dict(sub=dict(subkey=dict(subsubkey="42"))), True), + (["sub"], "overwrite", dict(sub="overwrite"), True) ) @ddt.unpack def test_set_setting_string(self, key, value, update, expected_returnvalue): From 5c8183341525126e1e668b28c2c977e8d140fa21 Mon Sep 17 00:00:00 2001 From: Shawn Bruce Date: Wed, 8 Mar 2017 14:16:17 -0500 Subject: [PATCH 34/80] Only reset scroll position for settings content. (Fixes #1812) --- src/octoprint/static/js/app/viewmodels/settings.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 5f1241f4d..4706cb7f8 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -814,7 +814,7 @@ $(function() { }; self._resetScrollPosition = function() { - $('.scrollable', self.settingsDialog).scrollTop(0); + $('#settings_dialog_content', self.settingsDialog).scrollTop(0); }; self.selectTab = function(tab) { From d1d94624236153c7a2cc7072d0527c6516f0daf7 Mon Sep 17 00:00:00 2001 From: Shawn Bruce Date: Tue, 11 Apr 2017 12:29:52 -0400 Subject: [PATCH 35/80] Add octoprint.timelapse.capture.[pre/post] hooks (#1854) * Add octoprint.timelapse.capture.pre and octoprint.timelapse.capture.post hooks * Adjust underline length --- docs/plugins/hooks.rst | 32 ++++++++++++++++++++++++++++++++ src/octoprint/timelapse.py | 37 ++++++++++++++++++++++++++++++++----- 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index cfdf3800f..0d9172285 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -922,3 +922,35 @@ octoprint.ui.web.templatetypes :param dict template_sorting: read-only dictionary of currently configured template sorting specifications :return: a list of 3-tuples (template type, rule, sorting spec) :rtype: list + +.. _sec-plugins-hook-timelapse-capture-pre: + +octoprint.timelapse.capture.pre +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: capture_pre_hook(filename) + + Perform specific actions prior to capturing a timelapse frame. + + ``filename`` will be the future path of the frame to be saved. + + :param str filename: The future path of the frame to be saved. + :return: None + :rtype: None + +.. _sec-plugins-hook-timelapse-capture-post: + +octoprint.timelapse.capture.post +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: capture_post_hook(filename, success) + + Perform specific actions after capturing a timelapse frame. + + ``filename`` will be the path of the frame that should have been saved. + ``sucesss`` indicates whether the capture was successful or not. + + :param str filename: The path of the frame that should have been saved. + :param boolean success: Indicates whether the capture was successful or not. + :return: None + :rtype: None \ No newline at end of file diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 5ea73db64..8ded0bc90 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -17,6 +17,7 @@ except ImportError: import Queue as queue import requests +import octoprint.plugin import octoprint.util as util from octoprint.settings import settings @@ -344,6 +345,11 @@ class Timelapse(object): self._fps = fps + + self._pluginManager = octoprint.plugin.plugin_manager() + self._pre_capture_hooks = self._pluginManager.get_hooks("octoprint.timelapse.capture.pre") + self._post_capture_hooks = self._pluginManager.get_hooks("octoprint.timelapse.capture.post") + self._capture_mutex = threading.Lock() self._capture_queue = queue.Queue() self._capture_queue_active = True @@ -553,6 +559,13 @@ class Timelapse(object): entry["callback"](*args, **kwargs) def _perform_capture(self, filename, onerror=None): + # pre-capture hook + for name, hook in self._pre_capture_hooks.items(): + try: + hook(filename) + except: + self._logger.exception("Error while processing hook {name}.".format(**locals())) + eventManager().fire(Events.CAPTURE_START, dict(file=filename)) try: self._logger.debug("Going to capture {} from {}".format(filename, self._snapshot_url)) @@ -568,17 +581,31 @@ class Timelapse(object): self._logger.debug("Image {} captured from {}".format(filename, self._snapshot_url)) except Exception as e: self._logger.exception("Could not capture image {} from {}".format(filename, self._snapshot_url)) + self._capture_errors += 1 + success = False + else: + self._capture_success += 1 + success = True + + # post-capture hook + for name, hook in self._post_capture_hooks.items(): + try: + hook(filename, success) + except: + self._logger.exception("Error while processing hook {name}.".format(**locals())) + + # handle events and onerror call + if success: + eventManager().fire(Events.CAPTURE_DONE, dict(file=filename)) + return True + else: if callable(onerror): onerror() eventManager().fire(Events.CAPTURE_FAILED, dict(file=filename, error=str(e), url=self._snapshot_url)) - self._capture_errors += 1 return False - else: - eventManager().fire(Events.CAPTURE_DONE, dict(file=filename)) - self._capture_success += 1 - return True + def _copying_postroll(self): with self._capture_mutex: From c4fcc59efdd7eb50092098123463ded70642be38 Mon Sep 17 00:00:00 2001 From: Mark Walker Date: Tue, 30 May 2017 00:29:30 -0700 Subject: [PATCH 36/80] Fix typo: TRANFERING_FILE --- src/octoprint/printer/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index 8e4b1e3c3..3fb95b5ac 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -367,7 +367,7 @@ class PrinterInterface(object): * CLOSED * ERROR * CLOSED_WITH_ERROR - * TRANFERING_FILE + * TRANSFERING_FILE * OFFLINE * UNKNOWN * NONE From 312760f86a71c07cde049d2099a2ca918b25aada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Nov 2017 11:33:55 +0100 Subject: [PATCH 37/80] flask.ext.babel => flask_babel --- src/octoprint/plugins/octopi_support/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/octopi_support/__init__.py b/src/octoprint/plugins/octopi_support/__init__.py index ab1dc79b8..7e814e663 100644 --- a/src/octoprint/plugins/octopi_support/__init__.py +++ b/src/octoprint/plugins/octopi_support/__init__.py @@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms import flask import os -from flask.ext.babel import gettext +from flask_babel import gettext import octoprint.plugin From a77fbfe0c252472a52b3171aae3c56eb3bef6d56 Mon Sep 17 00:00:00 2001 From: tedder Date: Wed, 27 Dec 2017 19:53:54 -0800 Subject: [PATCH 38/80] grammatical fix in text [It's a common error](https://brians.wsu.edu/2016/05/31/setup-set-up/); I'm not sure if it needs to be fixed in all three places or perhaps only in the .pot file. --- src/octoprint/templates/dialogs/wizard/firstrun_start.jinja2 | 2 +- src/octoprint/translations/de/LC_MESSAGES/messages.po | 2 +- translations/messages.pot | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/octoprint/templates/dialogs/wizard/firstrun_start.jinja2 b/src/octoprint/templates/dialogs/wizard/firstrun_start.jinja2 index bb8dd358c..a51e3a4c2 100644 --- a/src/octoprint/templates/dialogs/wizard/firstrun_start.jinja2 +++ b/src/octoprint/templates/dialogs/wizard/firstrun_start.jinja2 @@ -4,6 +4,6 @@ Thank you for installing OctoPrint! {% endtrans %}

{% trans %} - This wizard will guide you through the final steps to get your OctoPrint instance all setup and ready to go. We'll + This wizard will guide you through the final steps to get your OctoPrint instance all set up and ready to go. We'll get you printing in no time! {% endtrans %}

diff --git a/src/octoprint/translations/de/LC_MESSAGES/messages.po b/src/octoprint/translations/de/LC_MESSAGES/messages.po index ab1929635..8220bcd44 100644 --- a/src/octoprint/translations/de/LC_MESSAGES/messages.po +++ b/src/octoprint/translations/de/LC_MESSAGES/messages.po @@ -3588,7 +3588,7 @@ msgstr "Danke, dass du OctoPrint installiert hast!\n" #: src/octoprint/templates/dialogs/wizard/firstrun_start.jinja2:6 msgid "\n" -" This wizard will guide you through the final steps to get your OctoPrint instance all setup and ready to go. We'll\n" +" This wizard will guide you through the final steps to get your OctoPrint instance all set up and ready to go. We'll\n" " get you printing in no time!\n" msgstr "Dieser Wizard wird dich nun durch die letzten Schritte begleiten, um deine OctoPrint Instanz fertig einzurichten.\n" diff --git a/translations/messages.pot b/translations/messages.pot index ea78e9301..4a3cef5ce 100644 --- a/translations/messages.pot +++ b/translations/messages.pot @@ -4008,7 +4008,7 @@ msgstr "" msgid "" "\n" " This wizard will guide you through the final steps to get your " -"OctoPrint instance all setup and ready to go. We'll\n" +"OctoPrint instance all set up and ready to go. We'll\n" " get you printing in no time!\n" msgstr "" From 066e7d1e39338f5ca995363d09a6fde01b494426 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 20 Feb 2018 13:15:30 +0100 Subject: [PATCH 39/80] flask.ext.foo => flask_foo --- src/octoprint/plugins/corewizard/subwizards.py | 2 +- src/octoprint/server/util/__init__.py | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py index d30d8853b..550b701a2 100644 --- a/src/octoprint/plugins/corewizard/subwizards.py +++ b/src/octoprint/plugins/corewizard/subwizards.py @@ -8,7 +8,7 @@ import octoprint.plugin import sys import inspect -from flask.ext.babel import gettext +from flask_babel import gettext # noinspection PyUnresolvedReferences,PyMethodMayBeStatic diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 30f13d2fc..9aa0efc63 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -16,6 +16,9 @@ from octoprint.util import deprecated from octoprint.plugin import plugin_manager import flask as _flask +import flask_login +import flask_principal + import logging from . import flask @@ -95,9 +98,9 @@ def loginUser(user, remember=False): Returns: (bool) True if the login succeeded, False otherwise """ - if user is not None and user.is_active() and _flask.ext.login.login_user(user, remember=remember): - _flask.ext.principal.identity_changed.send(_flask.current_app._get_current_object(), - identity=_flask.ext.principal.Identity(user.get_id())) + if user is not None and user.is_active() and flask_login.login_user(user, remember=remember): + flask_principal.identity_changed.send(_flask.current_app._get_current_object(), + identity=flask_principal.Identity(user.get_id())) return True return False From 4f1cd6b3a2cbab72873d5b06056ceb949961db9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 19 Mar 2018 17:19:38 +0100 Subject: [PATCH 40/80] maintenance is now 1.3.8.dev --- .versioneer-lookup | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.versioneer-lookup b/.versioneer-lookup index 44d9f682c..c5b025946 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -17,11 +17,11 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.3.7 +# maintenance is currently the branch for preparation of maintenance release 1.3.8 # so are any fix/... and improve/... branches -maintenance 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev -fix/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev -improve/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev +maintenance 1.3.8 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +fix/.* 1.3.8 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +improve/.* 1.3.8 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev # staging/maintenance is currently the branch for preparation of 1.3.7rc2 # so is regressionfix/... From 1c43e193ba1b384c069c3b7c39b42d48220551b0 Mon Sep 17 00:00:00 2001 From: Daniele Forsi Date: Mon, 19 Mar 2018 18:55:14 +0100 Subject: [PATCH 41/80] Remove unneeded format() filter --- .../templates/dialogs/settings/serialconnection.jinja2 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 index 9cfd52039..52c90663b 100644 --- a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 +++ b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 @@ -40,7 +40,7 @@
- {{ _('Use this to define additional serial port baud rates to list for connecting with, e.g. 123456. Comma separated.')|format(glob_url="http://docs.python.org/2/library/glob.html") }} + {{ _('Use this to define additional serial port baud rates to list for connecting with, e.g. 123456. Comma separated.') }}
From 819d4d0fdffcd352288bd5adc293450b3d44d19e Mon Sep 17 00:00:00 2001 From: Daniele Forsi Date: Tue, 20 Mar 2018 16:12:49 +0100 Subject: [PATCH 42/80] Expand the description of custom system commands Fixes #2487 --- docs/configuration/config_yaml.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 790702fd1..7d4107174 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -1092,7 +1092,12 @@ System Use the following settings to add custom system commands to the "System" dropdown within OctoPrint's top bar. -Commands consist of a name, an action identifier, the commandline to execute and an optional confirmation message to +Commands consist of a ``name`` shown to the user, an ``action`` identifier used by the code and the actual +``command`` including any argument needed for its execution. +By default OctoPrint blocks until the command has returned so that the exit code can be used to show a success +or failure message; use the flag ``async: true`` for commands that don't return. + +Optionally you can add a confirmation message to display before actually executing the command (should be set to False if a confirmation dialog is not desired). The following example defines a command for shutting down the system under Linux. It assumes that the user under which From cb18d3fe32cebd70e6cedc22a1a7484da362e41b Mon Sep 17 00:00:00 2001 From: Daniele Forsi Date: Wed, 21 Mar 2018 12:52:05 +0100 Subject: [PATCH 43/80] Fix some invalid HTML Fixes 4 kinds of errors found with https://validator.w3.org/nu/#textarea Bad value javascript for attribute lang on element script Bad character after < . Probable cause: Unescaped < . Try escaping it as < . The element label must not appear as a descendant of the label element. Element legend not allowed as child of element form in this context. Note: the change related to seems big because of the increased indent of the existing code (use "git diff --ignore-all-space" or "git log --patch --ignore-all-space" to see the lines actually added). --- .../templates/pluginmanager_settings.jinja2 | 91 ++++++++++--------- .../dialogs/settings/serialconnection.jinja2 | 2 +- src/octoprint/templates/initscript.jinja2 | 2 +- .../templates/tabs/gcodeviewer.jinja2 | 4 +- 4 files changed, 53 insertions(+), 46 deletions(-) diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 6541c2b58..f66f9f35b 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -245,57 +245,64 @@

{% trans %}You should normally not have to change any of the following settings, they are purely provided for convenience here.{% endtrans %}

- {{ _('Plugin repository configuration') }} +
+ {{ _('Plugin repository configuration') }} -
- -
- -
-
-
- -
-
- - min +
+ +
+
-
- - {{ _('Notices configuration') }} - -
- -
- -
-
-
- -
-
- - min +
+ +
+
+ + min +
-
+
- {{ _('pip configuration') }} +
+ {{ _('Notices configuration') }} -
- -
- +
+ +
+ +
-
-
-
- +
+ +
+
+ + min +
+
-
+
+ +
+ {{ _('pip configuration') }} + +
+ +
+ +
+
+
+
+ +
+
+
+
diff --git a/src/octoprint/templates/initscript.jinja2 b/src/octoprint/templates/initscript.jinja2 index 722830bf3..7ffa07a26 100644 --- a/src/octoprint/templates/initscript.jinja2 +++ b/src/octoprint/templates/initscript.jinja2 @@ -1,4 +1,4 @@ - + + + +

Don't panic!

+

This is a SockJS hidden iframe. It's used for cross domain magic.

+ +'''.strip() + + +class IFrameHandler(BaseHandler): + """SockJS IFrame page handler""" + def get(self): + data = str_to_bytes(IFRAME_TEXT % self.server.settings['sockjs_url']) + + hsh = hashlib.md5(data).hexdigest() + + value = self.request.headers.get('If-None-Match') + if value: + if value.find(hsh) != -1: + # TODO: Fix me? Right now it is a hack to remove content-type + # header + self.clear() + del self._headers['Content-Type'] + + self.set_status(304) + return + + self.enable_cache() + + self.set_header('Etag', hsh) + self.write(data) + + +class GreetingsHandler(BaseHandler): + """SockJS greetings page handler""" + + def initialize(self, server): + self.server = server + + def get(self): + self.enable_cache() + + self.set_header('Content-Type', 'text/plain; charset=UTF-8') + self.write('Welcome to SockJS!\n') + + +class ChunkingTestHandler(PreflightHandler): + """SockJS chunking test handler""" + + # Step timeouts according to sockjs documentation + steps = [0.005, 0.025, 0.125, 0.625, 3.125] + + def initialize(self, server): + self.server = server + self.step = 0 + self.io_loop = server.io_loop + + @asynchronous + def post(self): + self.preflight() + self.set_header('Content-Type', 'application/javascript; charset=UTF-8') + + # Send one 'h' immediately + self.write('h\n') + self.flush() + + # Send 2048 spaces followed by 'h' + self.write(' ' * 2048 + 'h\n') + self.flush() + + # Send 'h' with different timeouts + def run_step(): + try: + self.write('h\n') + self.flush() + + self.step += 1 + if self.step < len(self.steps): + self.io_loop.add_timeout(time.time() + self.steps[self.step], + run_step) + else: + self.finish() + except IOError: + pass + + self.io_loop.add_timeout(time.time() + self.steps[0], run_step) + + +class InfoHandler(PreflightHandler): + """SockJS 0.2+ /info handler""" + def initialize(self, server): + self.server = server + self.access_methods = 'OPTIONS, GET' + + def get(self): + self.preflight() + self.disable_cache() + self.set_header('Content-Type', 'application/json; charset=UTF-8') + + options = dict(websocket=self.server.websockets_enabled, + cookie_needed=self.server.cookie_needed, + origins=['*:*'], + entropy=random.randint(0, MAXSIZE)) + + self.write(json_encode(options)) diff --git a/src/octoprint/vendor/sockjs/tornado/stats.py b/src/octoprint/vendor/sockjs/tornado/stats.py new file mode 100644 index 000000000..33f1fd509 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/stats.py @@ -0,0 +1,123 @@ +from collections import deque + +from tornado import ioloop + + +class MovingAverage(object): + """Moving average class implementation""" + def __init__(self, period=10): + """Constructor. + + `period` + Moving window size. Average will be calculated + from the data in the window. + """ + self.period = period + self.stream = deque() + self.sum = 0 + self.accumulator = 0 + self.last_average = 0 + + def add(self, n): + """Add value to the current accumulator + + `n` + Value to add + """ + self.accumulator += n + + def flush(self): + """Add accumulator to the moving average queue + and reset it. For example, called by the StatsCollector + once per second to calculate per-second average. + """ + n = self.accumulator + self.accumulator = 0 + + stream = self.stream + stream.append(n) + self.sum += n + + streamlen = len(stream) + + if streamlen > self.period: + self.sum -= stream.popleft() + streamlen -= 1 + + if streamlen == 0: + self.last_average = 0 + else: + self.last_average = self.sum / float(streamlen) + + +class StatsCollector(object): + def __init__(self, io_loop): + # Sessions + self.sess_active = 0 + + # Avoid circular reference + self.sess_transports = dict() + + # Connections + self.conn_active = 0 + self.conn_ps = MovingAverage() + + # Packets + self.pack_sent_ps = MovingAverage() + self.pack_recv_ps = MovingAverage() + + self._callback = ioloop.PeriodicCallback(self._update, + 1000) + self._callback.start() + + def _update(self): + self.conn_ps.flush() + + self.pack_sent_ps.flush() + self.pack_recv_ps.flush() + + def dump(self): + """Return dictionary with current statistical information""" + data = dict( + # Sessions + sessions_active=self.sess_active, + + # Connections + connections_active=self.conn_active, + connections_ps=self.conn_ps.last_average, + + # Packets + packets_sent_ps=self.pack_sent_ps.last_average, + packets_recv_ps=self.pack_recv_ps.last_average + ) + + for k, v in self.sess_transports.items(): + data['transp_' + k] = v + + return data + + # Various event callbacks + def on_sess_opened(self, transport): + self.sess_active += 1 + + if transport not in self.sess_transports: + self.sess_transports[transport] = 0 + + self.sess_transports[transport] += 1 + + def on_sess_closed(self, transport): + self.sess_active -= 1 + self.sess_transports[transport] -= 1 + + def on_conn_opened(self): + self.conn_active += 1 + self.conn_ps.add(1) + + def on_conn_closed(self): + self.conn_active -= 1 + + def on_pack_sent(self, num): + self.pack_sent_ps.add(num) + + def on_pack_recv(self, num): + self.pack_recv_ps.add(num) diff --git a/src/octoprint/vendor/sockjs/tornado/transports/__init__.py b/src/octoprint/vendor/sockjs/tornado/transports/__init__.py new file mode 100644 index 000000000..f6824a7c7 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/__init__.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +import octoprint.vendor.sockjs.tornado.transports.pollingbase + +from .xhr import XhrPollingTransport, XhrSendHandler +from .jsonp import JSONPTransport, JSONPSendHandler +from .websocket import WebSocketTransport +from .xhrstreaming import XhrStreamingTransport +from .eventsource import EventSourceTransport +from .htmlfile import HtmlFileTransport +from .rawwebsocket import RawWebSocketTransport diff --git a/src/octoprint/vendor/sockjs/tornado/transports/base.py b/src/octoprint/vendor/sockjs/tornado/transports/base.py new file mode 100644 index 000000000..6ab8a360f --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/base.py @@ -0,0 +1,22 @@ +from octoprint.vendor.sockjs.tornado import session + + +class BaseTransportMixin(object): + """Base transport. + + Implements few methods that session expects to see in each transport. + """ + + name = 'override_me_please' + + def get_conn_info(self): + """Return `ConnectionInfo` object from current transport""" + return session.ConnectionInfo(self.request.remote_ip, + self.request.cookies, + self.request.arguments, + self.request.headers, + self.request.path) + + def session_closed(self): + """Called by the session, when it gets closed""" + pass diff --git a/src/octoprint/vendor/sockjs/tornado/transports/eventsource.py b/src/octoprint/vendor/sockjs/tornado/transports/eventsource.py new file mode 100644 index 000000000..ed6ecbee4 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/eventsource.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.eventsource + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + EventSource transport implementation. +""" + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado.transports import streamingbase + + +class EventSourceTransport(streamingbase.StreamingTransportBase): + name = 'eventsource' + + @asynchronous + def get(self, session_id): + # Start response + self.preflight() + self.handle_session_cookie() + self.disable_cache() + + self.set_header('Content-Type', 'text/event-stream; charset=UTF-8') + self.write('\r\n') + self.flush() + + if not self._attach_session(session_id): + self.finish() + return + + if self.session: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for EventSourceTransport') + + msg = 'data: %s\r\n\r\n' % message + + self.active = False + + try: + self.notify_sent(len(msg)) + + self.write(msg) + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + self._detach() diff --git a/src/octoprint/vendor/sockjs/tornado/transports/htmlfile.py b/src/octoprint/vendor/sockjs/tornado/transports/htmlfile.py new file mode 100644 index 000000000..fbea68fff --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/htmlfile.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.htmlfile + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + HtmlFile transport implementation. +""" + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado import proto +from octoprint.vendor.sockjs.tornado.transports import streamingbase + +# HTMLFILE template +HTMLFILE_HEAD = r''' + + + + +

Don't panic!

+ +'''.strip() +HTMLFILE_HEAD += ' ' * (1024 - len(HTMLFILE_HEAD) + 14) +HTMLFILE_HEAD += '\r\n\r\n' + + +class HtmlFileTransport(streamingbase.StreamingTransportBase): + name = 'htmlfile' + + def initialize(self, server): + super(HtmlFileTransport, self).initialize(server) + + @asynchronous + def get(self, session_id): + # Start response + self.preflight() + self.handle_session_cookie() + self.disable_cache() + self.set_header('Content-Type', 'text/html; charset=UTF-8') + + # Grab callback parameter + callback = self.get_argument('c', None) + if not callback: + self.write('"callback" parameter required') + self.set_status(500) + self.finish() + return + + # TODO: Fix me - use parameter + self.write(HTMLFILE_HEAD % callback) + self.flush() + + # Now try to attach to session + if not self._attach_session(session_id): + self.finish() + return + + # Flush any pending messages + if self.session: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for HtmlFileTransport') + + # TODO: Just do escaping + msg = '\r\n' % proto.json_encode(message) + + self.active = False + + try: + self.notify_sent(len(message)) + + self.write(msg) + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + self._detach() diff --git a/src/octoprint/vendor/sockjs/tornado/transports/jsonp.py b/src/octoprint/vendor/sockjs/tornado/transports/jsonp.py new file mode 100644 index 000000000..d63ef2322 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/jsonp.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.jsonp + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + JSONP transport implementation. +""" +import logging + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado import proto +from octoprint.vendor.sockjs.tornado.transports import pollingbase +from octoprint.vendor.sockjs.tornado.util import bytes_to_str, unquote_plus + +LOG = logging.getLogger("tornado.general") + +class JSONPTransport(pollingbase.PollingTransportBase): + name = 'jsonp' + + @asynchronous + def get(self, session_id): + # Start response + self.handle_session_cookie() + self.disable_cache() + + # Grab callback parameter + self.callback = self.get_argument('c', None) + if not self.callback: + self.write('"callback" parameter required') + self.set_status(500) + self.finish() + return + + # Get or create session without starting heartbeat + if not self._attach_session(session_id, False): + return + + # Might get already detached because connection was closed in on_open + if not self.session: + return + + if not self.session.send_queue: + self.session.start_heartbeat() + else: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for JSONPTransport') + + self.active = False + + try: + # TODO: Just escape + msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message)) + + self.set_header('Content-Type', 'application/javascript; charset=UTF-8') + self.set_header('Content-Length', len(msg)) + + # TODO: Fix me + self.set_header('Etag', 'dummy') + + self.write(msg) + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + + +class JSONPSendHandler(pollingbase.PollingTransportBase): + def post(self, session_id): + self.preflight() + self.handle_session_cookie() + self.disable_cache() + + session = self._get_session(session_id) + + if session is None or session.is_closed: + self.set_status(404) + return + + data = bytes_to_str(self.request.body) + + ctype = self.request.headers.get('Content-Type', '').lower() + if ctype == 'application/x-www-form-urlencoded': + if not data.startswith('d='): + LOG.exception('jsonp_send: Invalid payload.') + + self.write("Payload expected.") + self.set_status(500) + return + + data = unquote_plus(data[2:]) + + if not data: + LOG.debug('jsonp_send: Payload expected.') + + self.write("Payload expected.") + self.set_status(500) + return + + try: + messages = proto.json_decode(data) + except: + # TODO: Proper error handling + LOG.debug('jsonp_send: Invalid json encoding') + + self.write("Broken JSON encoding.") + self.set_status(500) + return + + try: + session.on_messages(messages) + except Exception: + LOG.exception('jsonp_send: on_message() failed') + + session.close() + + self.write('Message handler failed.') + self.set_status(500) + return + + self.write('ok') + self.set_header('Content-Type', 'text/plain; charset=UTF-8') + self.set_status(200) diff --git a/src/octoprint/vendor/sockjs/tornado/transports/pollingbase.py b/src/octoprint/vendor/sockjs/tornado/transports/pollingbase.py new file mode 100644 index 000000000..9c01782a8 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/pollingbase.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.pollingbase + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Polling transports base +""" + +from octoprint.vendor.sockjs.tornado import basehandler +from octoprint.vendor.sockjs.tornado.transports import base + + +class PollingTransportBase(basehandler.PreflightHandler, base.BaseTransportMixin): + """Polling transport handler base class""" + def initialize(self, server): + super(PollingTransportBase, self).initialize(server) + + self.session = None + self.active = True + + def _get_session(self, session_id): + return self.server.get_session(session_id) + + def _attach_session(self, session_id, start_heartbeat=False): + session = self._get_session(session_id) + + if session is None: + session = self.server.create_session(session_id) + + # Try to attach to the session + if not session.set_handler(self, start_heartbeat): + return False + + self.session = session + + # Verify if session is properly opened + session.verify_state() + + return True + + def _detach(self): + """Detach from the session""" + if self.session: + self.session.remove_handler(self) + self.session = None + + def check_xsrf_cookie(self): + pass + + def send_message(self, message, binary=False): + """Called by the session when some data is available""" + raise NotImplementedError() + + def session_closed(self): + """Called by the session when it was closed""" + self._detach() + self.safe_finish() + + def on_connection_close(self): + # If connection was dropped by the client, close session. + # In all other cases, connection will be closed by the server. + if self.session is not None: + self.session.close(1002, 'Connection interrupted') + + super(PollingTransportBase, self).on_connection_close() + + def send_complete(self): + self._detach() + + # Avoid race condition when waiting for write callback and session getting closed in between + if not self._finished: + self.safe_finish() diff --git a/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py b/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py new file mode 100644 index 000000000..d5dd6efc7 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.rawwebsocket + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Raw websocket transport implementation +""" +import logging +import socket + +from octoprint.vendor.sockjs.tornado import websocket, session +from octoprint.vendor.sockjs.tornado.transports import base + +LOG = logging.getLogger("tornado.general") + +class RawSession(session.BaseSession): + """Raw session without any sockjs protocol encoding/decoding. Simply + works as a proxy between `SockJSConnection` class and `RawWebSocketTransport`.""" + def send_message(self, msg, stats=True, binary=False): + self.handler.send_pack(msg, binary) + + def on_message(self, msg): + self.conn.on_message(msg) + + +class RawWebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin): + """Raw Websocket transport""" + name = 'rawwebsocket' + + def initialize(self, server): + self.server = server + self.session = None + self.active = True + + def open(self): + # Stats + self.server.stats.on_conn_opened() + + # Disable nagle if needed + if self.server.settings['disable_nagle']: + self.stream.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) + + # Create and attach to session + self.session = RawSession(self.server.get_connection_class(), self.server) + self.session.set_handler(self) + self.session.verify_state() + + def _detach(self): + if self.session is not None: + self.session.remove_handler(self) + self.session = None + + def on_message(self, message): + # SockJS requires that empty messages should be ignored + if not message or not self.session: + return + + try: + self.session.on_message(message) + except Exception: + LOG.exception('RawWebSocket') + + # Close running connection + self.abort_connection() + + def on_close(self): + # Close session if websocket connection was closed + if self.session is not None: + # Stats + self.server.stats.on_conn_closed() + + session = self.session + self._detach() + session.close() + + def send_pack(self, message, binary=False): + # Send message + try: + self.write_message(message, binary) + except IOError: + self.server.io_loop.add_callback(self.on_close) + + def session_closed(self): + try: + self.close(*self.session.get_close_reason()) + except IOError: + pass + finally: + self._detach() + + # Websocket overrides + def allow_draft76(self): + return True diff --git a/src/octoprint/vendor/sockjs/tornado/transports/streamingbase.py b/src/octoprint/vendor/sockjs/tornado/transports/streamingbase.py new file mode 100644 index 000000000..4172401c2 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/streamingbase.py @@ -0,0 +1,47 @@ +from octoprint.vendor.sockjs.tornado.transports import pollingbase + + +class StreamingTransportBase(pollingbase.PollingTransportBase): + def initialize(self, server): + super(StreamingTransportBase, self).initialize(server) + + self.amount_limit = self.server.settings['response_limit'] + + # HTTP 1.0 client might send keep-alive + if hasattr(self.request, 'connection') and not self.request.supports_http_1_1(): + self.request.connection.no_keep_alive = True + + def notify_sent(self, data_len): + """ + Update amount of data sent + """ + self.amount_limit -= data_len + + def should_finish(self): + """ + Check if transport should close long running connection after + sending X bytes to the client. + + `data_len` + Amount of data that was sent + """ + if self.amount_limit <= 0: + return True + + return False + + def send_complete(self): + """ + Verify if connection should be closed based on amount of data that was sent. + """ + self.active = True + + if self.should_finish(): + self._detach() + + # Avoid race condition when waiting for write callback and session getting closed in between + if not self._finished: + self.safe_finish() + else: + if self.session: + self.session.flush() diff --git a/src/octoprint/vendor/sockjs/tornado/transports/websocket.py b/src/octoprint/vendor/sockjs/tornado/transports/websocket.py new file mode 100644 index 000000000..8df3a2901 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/websocket.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.websocket + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Websocket transport implementation +""" +import logging +import socket + +from octoprint.vendor.sockjs.tornado import proto, websocket +from octoprint.vendor.sockjs.tornado.transports import base +from octoprint.vendor.sockjs.tornado.util import bytes_to_str + +LOG = logging.getLogger("tornado.general") + +class WebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin): + """Websocket transport""" + name = 'websocket' + + def initialize(self, server): + self.server = server + self.session = None + self.active = True + + def open(self, session_id): + # Stats + self.server.stats.on_conn_opened() + + # Disable nagle + if self.server.settings['disable_nagle']: + self.stream.set_nodelay(True) + + # Handle session + self.session = self.server.create_session(session_id, register=False) + + if not self.session.set_handler(self): + self.close() + return + + self.session.verify_state() + + if self.session: + self.session.flush() + + def _detach(self): + if self.session is not None: + self.session.remove_handler(self) + self.session = None + + def on_message(self, message): + # SockJS requires that empty messages should be ignored + if not message or not self.session: + return + + try: + msg = proto.json_decode(bytes_to_str(message)) + + if isinstance(msg, list): + self.session.on_messages(msg) + else: + self.session.on_messages((msg,)) + except Exception: + LOG.exception('WebSocket') + + # Close session on exception + #self.session.close() + + # Close running connection + self.abort_connection() + + def on_close(self): + # Close session if websocket connection was closed + if self.session is not None: + # Stats + self.server.stats.on_conn_closed() + + # Detach before closing session + session = self.session + self._detach() + session.close() + + def send_pack(self, message, binary=False): + # Send message + try: + self.write_message(message, binary) + except IOError: + self.server.io_loop.add_callback(self.on_close) + + def session_closed(self): + # If session was closed by the application, terminate websocket + # connection as well. + try: + self.close() + except IOError: + pass + finally: + self._detach() + + # Websocket overrides + def allow_draft76(self): + return True + + def auto_decode(self): + return False diff --git a/src/octoprint/vendor/sockjs/tornado/transports/xhr.py b/src/octoprint/vendor/sockjs/tornado/transports/xhr.py new file mode 100644 index 000000000..01e01b21c --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/xhr.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.xhr + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Xhr-Polling transport implementation +""" +import logging + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado import proto +from octoprint.vendor.sockjs.tornado.transports import pollingbase +from octoprint.vendor.sockjs.tornado.util import bytes_to_str + +LOG = logging.getLogger("tornado.general") + +class XhrPollingTransport(pollingbase.PollingTransportBase): + """xhr-polling transport implementation""" + name = 'xhr' + + @asynchronous + def post(self, session_id): + # Start response + self.preflight() + self.handle_session_cookie() + self.disable_cache() + + # Get or create session without starting heartbeat + if not self._attach_session(session_id, False): + return + + # Might get already detached because connection was closed in on_open + if not self.session: + return + + if not self.session.send_queue: + self.session.start_heartbeat() + else: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for XhrPollingTransport') + + self.active = False + + try: + self.set_header('Content-Type', 'application/javascript; charset=UTF-8') + self.set_header('Content-Length', len(message) + 1) + self.write(message + '\n') + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + + +class XhrSendHandler(pollingbase.PollingTransportBase): + def post(self, session_id): + self.preflight() + self.handle_session_cookie() + self.disable_cache() + + session = self._get_session(session_id) + + if session is None or session.is_closed: + self.set_status(404) + return + + data = self.request.body + if not data: + self.write("Payload expected.") + self.set_status(500) + return + + try: + messages = proto.json_decode(bytes_to_str(data)) + except: + # TODO: Proper error handling + self.write("Broken JSON encoding.") + self.set_status(500) + return + + try: + session.on_messages(messages) + except Exception: + LOG.exception('XHR incoming') + session.close() + + self.set_status(500) + return + + self.set_status(204) + self.set_header('Content-Type', 'text/plain; charset=UTF-8') diff --git a/src/octoprint/vendor/sockjs/tornado/transports/xhrstreaming.py b/src/octoprint/vendor/sockjs/tornado/transports/xhrstreaming.py new file mode 100644 index 000000000..be8329c25 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/xhrstreaming.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.xhrstreaming + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Xhr-Streaming transport implementation +""" + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado.transports import streamingbase + + +class XhrStreamingTransport(streamingbase.StreamingTransportBase): + name = 'xhr_streaming' + + @asynchronous + def post(self, session_id): + # Handle cookie + self.preflight() + self.handle_session_cookie() + self.disable_cache() + self.set_header('Content-Type', 'application/javascript; charset=UTF-8') + + # Send prelude and flush any pending messages + self.write('h' * 2048 + '\n') + self.flush() + + if not self._attach_session(session_id, False): + self.finish() + return + + if self.session: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for XhrStreamingTransport') + + self.active = False + + try: + self.notify_sent(len(message)) + + self.write(message + '\n') + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + self._detach() diff --git a/src/octoprint/vendor/sockjs/tornado/util.py b/src/octoprint/vendor/sockjs/tornado/util.py new file mode 100644 index 000000000..0911258ac --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/util.py @@ -0,0 +1,50 @@ +import sys + +PY3 = sys.version_info[0] == 3 + +if PY3: + MAXSIZE = sys.maxsize + + def bytes_to_str(b): + if isinstance(b, bytes): + return str(b, 'utf8') + return b + + def str_to_bytes(s): + if isinstance(s, bytes): + return s + return s.encode('utf8') + + import urllib.parse + unquote_plus = urllib.parse.unquote_plus +else: + if sys.platform == "java": + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + del X + + def bytes_to_str(s): + if isinstance(s, unicode): + return s.encode('utf-8') + return s + + def str_to_bytes(s): + if isinstance(s, unicode): + return s.encode('utf8') + return s + + import urllib + unquote_plus = urllib.unquote_plus diff --git a/src/octoprint/vendor/sockjs/tornado/websocket.py b/src/octoprint/vendor/sockjs/tornado/websocket.py new file mode 100644 index 000000000..6dc450fca --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/websocket.py @@ -0,0 +1,36 @@ +import tornado +from tornado import escape, gen, websocket + +try: + from urllib.parse import urlparse # py3 +except ImportError: + from urlparse import urlparse # py2 + + +class SockJSWebSocketHandler(websocket.WebSocketHandler): + if tornado.version_info[0] == 4 and tornado.version_info[1] > 1: + def get_compression_options(self): + # let tornado use compression when Sec-WebSocket-Extensions:permessage-deflate is provided + return {} + + SUPPORTED_METHODS = ('GET',) + + def check_origin(self, origin): + # let tornado first check if connection from the same domain + same_domain = super(SockJSWebSocketHandler, self).check_origin(origin) + if same_domain: + return True + + # this is cross-origin connection - check using SockJS server settings + allow_origin = self.server.settings.get("websocket_allow_origin", "*") + if allow_origin == "*": + return True + else: + parsed_origin = urlparse(origin) + origin = parsed_origin.netloc + origin = origin.lower() + return origin in allow_origin + + def abort_connection(self): + if self.ws_connection: + self.ws_connection._abort() From 75de062b55c3aef7b250bf71c2ca5747860c3330 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 10 Apr 2018 18:09:55 +0200 Subject: [PATCH 70/80] Safety Plugin: Add detection of Anycubic Mega Identified by "Author: (Jolly, xxxxxxxx.CO.)" in startup messages. --- .../plugins/printer_safety_check/__init__.py | 44 ++++++++++++++----- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 431892cf6..0d28f1d88 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -23,8 +23,14 @@ Learn more at https://faq.octoprint.org/warning-{warning_type} """ +ANETA8_FIRMWARE_NAME = "ANET_A8_".lower() +ANYCUBIC_AUTHOR = "| Author: (Jolly, xxxxxxxx.CO.)".lower() + SAFETY_CHECKS = { - "firmware-unsafe": (lambda name, data: name and name.lower().startswith("anet_a8_"),) + "firmware-unsafe": dict(m115=(lambda name, data: name and name.lower().startswith(ANETA8_FIRMWARE_NAME),), + received=(lambda line: line and ANYCUBIC_AUTHOR in line.lower(),), + message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ + u"thermal runaway protection). This is a fire risk.") } class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, @@ -35,6 +41,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, # noinspection PyMissingConstructor def __init__(self): self._warnings = dict() + self._scan_received = True ##~~ TemplatePlugin API @@ -58,7 +65,8 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, def on_event(self, event, payload): if event == Events.FIRMWARE_DATA: - self._analyze_firmware_data(payload.get("name"), payload.get("data")) + self._run_checks("m115", payload.get("name"), payload.get("data")) + self._scan_received = False elif event == Events.DISCONNECTED: self._reset_warnings() @@ -69,23 +77,36 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, return flask.make_response("Insufficient rights", 403) return flask.jsonify(self._warnings) + ##~~ GCODE received hook handler + + def on_gcode_received(self, comm_instance, line, *args, **kwargs): + if self._scan_received: + self._run_checks("received", line) + return line + ##~~ Helpers - def _analyze_firmware_data(self, name, data): + def _run_checks(self, check_type, *args, **kwargs): changes = False - for warning_type, checks in SAFETY_CHECKS.items(): - if any(x(name, data) for x in checks): - message = u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ - u"thermal runaway protection). This is a fire risk." - self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)), - warning_type=warning_type)) - self._warnings[warning_type] = message + for warning_type, check_data in SAFETY_CHECKS.items(): + checks = check_data.get(check_type) + message = check_data.get("message") + if not checks or not message: + continue + + if any(x(*args, **kwargs) for x in checks): + self._register_warning(warning_type, message) changes = True if changes: self._ping_clients() + def _register_warning(self, warning_type, message): + self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)), + warning_type=warning_type)) + self._warnings[warning_type] = message + def _reset_warnings(self): self._warnings.clear() self._ping_clients() @@ -107,4 +128,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will n "issue and inform you about that fact.") __plugin_license__ = "AGPLv3" __plugin_implementation__ = PrinterSafetyCheckPlugin() +__plugin_hooks__ = { + "octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received +} From 58bbbc2ad94f4b9d8a0321087a49ad1ce3023a83 Mon Sep 17 00:00:00 2001 From: Vitor de Miranda Henrique Date: Tue, 10 Apr 2018 16:19:55 -0500 Subject: [PATCH 71/80] Update hooks.rst Fix Software Update plugin link, it was pointing to an old github page --> https://github.com/OctoPrint/OctoPrint-SoftwareUpdate instead of the bundled plugin--> https://github.com/foosel/OctoPrint/tree/master/src/octoprint/plugins/softwareupdate --- docs/plugins/hooks.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 18d63f75f..f3a5607f5 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -66,7 +66,7 @@ the general type of script for which to look for additions ("gcode") and the scr return a 2-tuple of prefix and postfix if has something for either of those, otherwise ``None``. OctoPrint will then take care to add prefix and suffix as necessary after a small round of preprocessing. -Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_ +Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_ declares a custom hook "octoprint.plugin.softwareupdate.check_config" which other plugins can add handlers for in order to register themselves with the Software Update Plugin by returning their own update check configuration. From 6f224bd825f4c9bab1d3eb109540420ca564532f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 11:12:56 +0200 Subject: [PATCH 72/80] Workaround for typo & whitespace in Malyan M115 responses NAME. instead of NAME:, whitespace between key and value component. --- src/octoprint/util/comm.py | 18 ++++++++++++++---- tests/util/test_comm_helpers.py | 15 ++++++++++++++- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index d4cbc4799..7737b7dc8 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -192,7 +192,7 @@ Groups will be as follows: * ``value``: reported position value """ -regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):") +regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):\s*") """Regex to use for splitting M115 responses.""" regex_resend_linenumber = re.compile("(N|N:)?(?P%s)" % regex_int_pattern) @@ -1662,7 +1662,7 @@ class MachineCom(object): pass ##~~ firmware name & version - elif "NAME:" in line: + elif "NAME:" in line or line.startswith("NAME."): # looks like a response to M115 data = parse_firmware_line(line) firmware_name = data.get("FIRMWARE_NAME") @@ -1672,7 +1672,11 @@ class MachineCom(object): # report its firmware name properly in response to M115. Wonderful - why stick to established # protocol when you can do your own thing, right? # - # Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02 + # Examples: + # + # NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02 + # NAME. Malyan VER: 3.8 MODEL: M100 HW: HB02 + # NAME. Malyan VER: 3.7 MODEL: M300 HW: HG01 # # We do a bit of manual fiddling around here to circumvent that issue and get ourselves a # reliable firmware name (NAME + VER) out of the Malyan M115 response. @@ -4013,10 +4017,16 @@ def parse_firmware_line(line): dict: a dictionary with the parsed data """ + if line.startswith("NAME."): + # Good job Malyan. Why use a : when you can also just use a ., right? Let's revert that. + line = list(line) + line[4] = ":" + line = "".join(line) + result = dict() split_line = regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string for key, value in chunks(split_line, 2): - result[key] = value + result[key] = value.strip() return result def parse_capability_line(line): diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py index 10ab72122..119ff406d 100644 --- a/tests/util/test_comm_helpers.py +++ b/tests/util/test_comm_helpers.py @@ -259,7 +259,20 @@ class TestCommHelpers(unittest.TestCase): @data( ("KEY1:Value 1 FIRMWARE_NAME:Some Firmware With Spaces KEY2:Value 2", - dict(KEY1="Value 1", KEY2="Value 2", FIRMWARE_NAME="Some Firmware With Spaces")) + dict(KEY1="Value 1", KEY2="Value 2", FIRMWARE_NAME="Some Firmware With Spaces")), + ("NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02", + dict(NAME="Malyan", VER="2.9", MODEL="M200", HW="HA02")), + ("NAME. Malyan VER: 3.8 MODEL: M100 HW: HB02", + dict(NAME="Malyan", VER="3.8", MODEL="M100", HW="HB02")), + ("NAME. Malyan VER: 3.7 MODEL: M300 HW: HG01", + dict(NAME="Malyan", VER="3.7", MODEL="M300", HW="HG01")), + ("FIRMWARE_NAME:Marlin 1.1.0 From Archive SOURCE_CODE_URL:http:// ... PROTOCOL_VERSION:1.0 MACHINE_TYPE:www.cxsw3d.com EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000", + dict(FIRMWARE_NAME="Marlin 1.1.0 From Archive", + SOURCE_CODE_URL="http:// ...", + PROTOCOL_VERSION="1.0", + MACHINE_TYPE="www.cxsw3d.com", + EXTRUDER_COUNT="1", + UUID="00000000-0000-0000-0000-000000000000")) ) @unpack def test_parse_firmware_line(self, line, expected): From f3128a15d916610446ce1559b64d7cc5c819d1e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 11:15:18 +0200 Subject: [PATCH 73/80] Safety Plugin: Add Malyan M200 & CR-10S Malyan M200 identified by firmware name "Malyan" and model "M200". Printer also known as Monoprice Select Mini, see also ID strings in #2271. CR-10S identified by "Author: (CR-10Slanguage)". --- .../plugins/printer_safety_check/__init__.py | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 0d28f1d88..3d563d806 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -23,12 +23,24 @@ Learn more at https://faq.octoprint.org/warning-{warning_type} """ -ANETA8_FIRMWARE_NAME = "ANET_A8_".lower() -ANYCUBIC_AUTHOR = "| Author: (Jolly, xxxxxxxx.CO.)".lower() +# Anet A8 +ANETA8_M115_TEST = lambda name, data: name and name.lower().startswith("anet_a8_") + +# Anycubic MEGA +ANYCUBIC_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower() +ANYCUBIC_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower() +ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower()) + +# Creality CR-10s +CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower() +CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower() + +# Malyan M200 aka Monoprice Select Mini +MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" SAFETY_CHECKS = { - "firmware-unsafe": dict(m115=(lambda name, data: name and name.lower().startswith(ANETA8_FIRMWARE_NAME),), - received=(lambda line: line and ANYCUBIC_AUTHOR in line.lower(),), + "firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST), + received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST), message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ u"thermal runaway protection). This is a fire risk.") } From c4d8e344d13581f7ee47241f7543c6bf7383b721 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 11:15:46 +0200 Subject: [PATCH 74/80] Remove wrongly placed whitespace --- src/octoprint/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 9e6f13a04..492f1b810 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -403,7 +403,7 @@ default_settings = { "resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'], "preparedOks": [], "okFormatString": "ok", - "m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0", + "m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0", "m115ReportCapabilities": False, "capabilities": { "AUTOREPORT_TEMP": True, From 258f3725bf3b565e00aab30df9aa84b2c299b771 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 18:43:23 +0200 Subject: [PATCH 75/80] Minor adjustments for Tornado 5 --- src/octoprint/server/__init__.py | 6 ++++-- src/octoprint/vendor/sockjs/tornado/router.py | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index f727db996..3cc9bdde8 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -490,7 +490,7 @@ class Server(object): ## Tornado initialization starts here ioloop = IOLoop() - ioloop.install() + ioloop.make_current() self._router = SockJSRouter(self._create_socket_connection, "/sockjs", session_kls=util.sockjs.ThreadSafeSession) @@ -760,7 +760,9 @@ class Server(object): except (KeyboardInterrupt, SystemExit): pass except: - self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!") + self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report " + "this including reproduction steps, octoprint.log and the stacktrace below in " + "OctoPrint's bugtracker. Thanks!") self._logger.exception("Stacktrace follows:") def _create_socket_connection(self, session): diff --git a/src/octoprint/vendor/sockjs/tornado/router.py b/src/octoprint/vendor/sockjs/tornado/router.py index e20619e89..103c346ad 100644 --- a/src/octoprint/vendor/sockjs/tornado/router.py +++ b/src/octoprint/vendor/sockjs/tornado/router.py @@ -91,7 +91,7 @@ class SockJSRouter(object): self._connection = connection # Initialize io_loop - self.io_loop = io_loop or ioloop.IOLoop.instance() + self.io_loop = io_loop or ioloop.IOLoop.current() # Settings self.settings = DEFAULT_SETTINGS.copy() From a5d541dafccff41fcfb0bc7cd0485e2dda2d40cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 18:47:08 +0200 Subject: [PATCH 76/80] Fix sockjs not working behind haproxy For some reason the websocket connection runs into a timeout, the xhr transport doesn't properly take over, and then stuff takes ages to realign again. Only happens under Tornado 5, doesn't happen under Tornado 4.5 Increasing the timeout for now instead of pinning to Tornado 4.5 in the hopes that might still be figured out. Incredibly weird though. --- src/octoprint/static/js/lib/sockjs.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/static/js/lib/sockjs.js b/src/octoprint/static/js/lib/sockjs.js index f168d5f7b..52431ec9e 100644 --- a/src/octoprint/static/js/lib/sockjs.js +++ b/src/octoprint/static/js/lib/sockjs.js @@ -818,7 +818,7 @@ SockJS.prototype._connect = function() { } // calculate timeout based on RTO and round trips. Default to 5s - var timeoutMs = (this._rto * Transport.roundTrips) || 5000; + var timeoutMs = (this._rto * Transport.roundTrips * 2) || 5000; this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs); debug('using timeout', timeoutMs); From a33b037364d3adc624ba3733fe6d4723c92b324d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 12 Apr 2018 11:55:14 +0200 Subject: [PATCH 77/80] Fix ItemListHelper throwing an error on undefined items Just fall back to an empty list. Fixed #2572 (at least the bit that isn't a broken nginx config) --- src/octoprint/static/js/app/helpers.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 98a1e5741..7517ad1e2 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -27,6 +27,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor }; self.updateItems = function(items) { + if (items === undefined) items = []; self.allItems = items; self.allSize(items.length); self._updateItems(); From 132614045c82e0ed684b510e3c02b84a5ed87c96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 12 Apr 2018 12:08:19 +0200 Subject: [PATCH 78/80] Early detection & logging of broken files response Fixes #2572 --- .../static/js/app/viewmodels/files.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 1ffcd1eb4..8d3a0afb9 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -276,6 +276,20 @@ $(function() { self.allItems(files); + // Sanity check file list - see #2572 + var nonrecursive = false; + _.each(files, function(file) { + if (file.type === "folder" && file.children === undefined) { + nonrecursive = true; + } + }); + if (nonrecursive) { + log.error("At least one folder doesn't have a 'children' element defined. That means the file list request " + + "wasn't actually made with 'recursive=true' in the query.\n\n" + + "This can happen on wrong reverse proxy configs that " + + "swallow up query parameters, see https://github.com/foosel/OctoPrint/issues/2572"); + } + if (!switchToPath) { var currentPath = self.currentPath(); if (currentPath === undefined) { @@ -318,6 +332,11 @@ $(function() { }; self.changeFolder = function(data) { + if (data.children === undefined) { + log.error("Can't switch to folder '" + data.path + "', no children available"); + return; + } + self.currentPath(data.path); self.listHelper.updateItems(data.children); self.highlightCurrentFilename(); From 9c923be5f05f433a1bd3d050f6cd83e3eb5d0ae2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 12 Apr 2018 13:19:02 +0200 Subject: [PATCH 79/80] Better solution for the Tornado 5 + SockJS + haproxy issue Looks like Nagle's algorithm was the cause. Adding option http-no-delay to haproxy.cfg solves the problem without modification of the timeout, however that is not an option for the thousands of instances already deployed in the field. So instead we add 300ms to the roundtrip based connection timeout, that should hopefully get around any Nagle-induced delays (usually between 40 and 200ms according to various sites on the net). --- src/octoprint/static/js/lib/sockjs.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/static/js/lib/sockjs.js b/src/octoprint/static/js/lib/sockjs.js index 52431ec9e..dff4b42c7 100644 --- a/src/octoprint/static/js/lib/sockjs.js +++ b/src/octoprint/static/js/lib/sockjs.js @@ -817,8 +817,8 @@ SockJS.prototype._connect = function() { } } - // calculate timeout based on RTO and round trips. Default to 5s - var timeoutMs = (this._rto * Transport.roundTrips * 2) || 5000; + // calculate timeout based on RTO and round trips, compensate for potential nagle. Default to 5s. + var timeoutMs = (this._rto * Transport.roundTrips + 300) || 5000; this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs); debug('using timeout', timeoutMs); From 6a8a1c31e353996fced57afa63d0f2ab3a79f95b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 13 Apr 2018 17:08:19 +0200 Subject: [PATCH 80/80] maintenance is now 1.3.9.dev --- .versioneer-lookup | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.versioneer-lookup b/.versioneer-lookup index 6169322c5..acbff62a1 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,11 +18,11 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.3.8 +# maintenance is currently the branch for preparation of maintenance release 1.3.9 # so are any fix/... and improve/... branches -maintenance 1.3.8 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev -fix/.* 1.3.8 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev -improve/.* 1.3.8 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev # staging/maintenance is currently the branch for preparation of 1.3.7rc5 # so is regressionfix/...