id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
21,800
notification_contact_add.py
tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notification_contact_add.py
from yowsup.structs import ProtocolTreeNode from .notification_contact import ContactNotificationProtocolEntity class AddContactNotificationProtocolEntity(ContactNotificationProtocolEntity): ''' <notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="contacts" t="{{TIMESTAMP}}" from="{{SENDER_JID}}"> <add jid="{{SET_JID}}"> </add> </notification> ''' def __init__(self, _id, _from, timestamp, notify, offline, contactJid): super(AddContactNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline) self.setData(contactJid) def setData(self, jid): self.contactJid = jid def toProtocolTreeNode(self): node = super(AddContactNotificationProtocolEntity, self).toProtocolTreeNode() removeNode = ProtocolTreeNode("add", {"jid": self.contactJid}, None, None) node.addChild(removeNode) return node @staticmethod def fromProtocolTreeNode(node): entity = ContactNotificationProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = AddContactNotificationProtocolEntity removeNode = node.getChild("add") entity.setData(removeNode.getAttributeValue("jid")) return entity
1,271
Python
.tac
26
41.884615
106
0.706119
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,801
notification_contact_remove.py
tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notification_contact_remove.py
from yowsup.structs import ProtocolTreeNode from .notification_contact import ContactNotificationProtocolEntity class RemoveContactNotificationProtocolEntity(ContactNotificationProtocolEntity): ''' <notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="contacts" t="{{TIMESTAMP}}" from="{{SENDER_JID}}"> <remove jid="{{SET_JID}}"> </remove> </notification> ''' def __init__(self, _id, _from, timestamp, notify, offline, contactJid): super(RemoveContactNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline) self.setData(contactJid) def setData(self, jid): self.contactJid = jid def toProtocolTreeNode(self): node = super(RemoveContactNotificationProtocolEntity, self).toProtocolTreeNode() removeNode = ProtocolTreeNode("remove", {"jid": self.contactJid}, None, None) node.addChild(removeNode) return node @staticmethod def fromProtocolTreeNode(node): entity = ContactNotificationProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = RemoveContactNotificationProtocolEntity removeNode = node.getChild("remove") entity.setData(removeNode.getAttributeValue("jid")) return entity
1,295
Python
.tac
26
42.807692
109
0.71169
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,802
test_notification_contact_update.py
tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/test_notification_contact_update.py
from yowsup.layers.protocol_contacts.protocolentities import UpdateContactNotificationProtocolEntity from yowsup.structs.protocolentity import ProtocolEntityTest import time import unittest entity = UpdateContactNotificationProtocolEntity("1234", "jid@s.whatsapp.net", int(time.time()), "notify", False,"contactjid@s.whatsapp.net") class UpdateContactNotificationProtocolEntityTest(ProtocolEntityTest, unittest.TestCase): def setUp(self): self.ProtocolEntity = UpdateContactNotificationProtocolEntity self.node = entity.toProtocolTreeNode()
612
Python
.tac
10
53.1
111
0.771667
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,803
notification_contact.py
tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notification_contact.py
from yowsup.structs import ProtocolEntity, ProtocolTreeNode from yowsup.layers.protocol_notifications.protocolentities import NotificationProtocolEntity class ContactNotificationProtocolEntity(NotificationProtocolEntity): ''' <notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="contacts" t="{{TIMESTAMP}}" from="{{SENDER_JID}}"> </notification> ''' def __init__(self, _id, _from, timestamp, notify, offline = False): super(ContactNotificationProtocolEntity, self).__init__("contacts", _id, _from, timestamp, notify, offline) @staticmethod def fromProtocolTreeNode(node): entity = NotificationProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = ContactNotificationProtocolEntity return entity
812
Python
.tac
15
47.8
115
0.731646
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,804
test_notification_contact_remove.py
tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/test_notification_contact_remove.py
from yowsup.layers.protocol_contacts.protocolentities import RemoveContactNotificationProtocolEntity from yowsup.structs.protocolentity import ProtocolEntityTest import time import unittest entity = RemoveContactNotificationProtocolEntity("1234", "jid@s.whatsapp.net", int(time.time()), "notify", False, "contactjid@s.whatsapp.net") class RemoveContactNotificationProtocolEntityTest(ProtocolEntityTest, unittest.TestCase): def setUp(self): self.ProtocolEntity = RemoveContactNotificationProtocolEntity self.node = entity.toProtocolTreeNode()
613
Python
.tac
10
53.2
112
0.770383
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,805
notification_contact_update.py
tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notification_contact_update.py
from yowsup.structs import ProtocolTreeNode from .notification_contact import ContactNotificationProtocolEntity class UpdateContactNotificationProtocolEntity(ContactNotificationProtocolEntity): ''' <notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="contacts" t="{{TIMESTAMP}}" from="{{SENDER_JID}}"> <update jid="{{SET_JID}}"> </update> </notification> ''' def __init__(self, _id, _from, timestamp, notify, offline, contactJid): super(UpdateContactNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline) self.setData(contactJid) def setData(self, jid): self.contactJid = jid def toProtocolTreeNode(self): node = super(UpdateContactNotificationProtocolEntity, self).toProtocolTreeNode() removeNode = ProtocolTreeNode("update", {"jid": self.contactJid}, None, None) node.addChild(removeNode) return node @staticmethod def fromProtocolTreeNode(node): entity = ContactNotificationProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = UpdateContactNotificationProtocolEntity removeNode = node.getChild("update") entity.setData(removeNode.getAttributeValue("jid")) return entity
1,295
Python
.tac
26
42.807692
109
0.71169
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,806
notificiation_contacts_sync.py
tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notificiation_contacts_sync.py
from yowsup.structs import ProtocolTreeNode from .notification_contact import ContactNotificationProtocolEntity class ContactsSyncNotificationProtocolEntity(ContactNotificationProtocolEntity): ''' <notification from="4917667738517@s.whatsapp.net" t="1437251557" offline="0" type="contacts" id="4174521704"> <sync after="1437251557"></sync> </notification> ''' def __init__(self, _id, _from, timestamp, notify, offline, after): super(ContactsSyncNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline) self.setData(after) def setData(self, after): self.after = int(after) def toProtocolTreeNode(self): node = super(ContactsSyncNotificationProtocolEntity, self).toProtocolTreeNode() syncNode = ProtocolTreeNode("sync", {"after": str(self.after)}, None, None) node.addChild(syncNode) return node @staticmethod def fromProtocolTreeNode(node): entity = ContactNotificationProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = ContactsSyncNotificationProtocolEntity syncNode = node.getChild("sync") entity.setData(syncNode.getAttributeValue("after")) return entity
1,237
Python
.tac
25
42.76
113
0.72622
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,807
stack.py
tgalal_yowsup/yowsup/demos/contacts/stack.py
from .layer import SyncLayer from yowsup.stacks import YowStackBuilder from yowsup.layers import YowLayerEvent from yowsup.layers.auth import YowAuthenticationProtocolLayer from yowsup.layers.network import YowNetworkLayer class YowsupSyncStack(object): def __init__(self, profile, contacts): """ :param profile: :param contacts: list of [jid ] :return: """ stackBuilder = YowStackBuilder() self._stack = stackBuilder \ .pushDefaultLayers() \ .push(SyncLayer) \ .build() self._stack.setProp(SyncLayer.PROP_CONTACTS, contacts) self._stack.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True) self._stack.setProfile(profile) def set_prop(self, key, val): self._stack.setProp(key, val) def start(self): self._stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) self._stack.loop()
964
Python
.tac
25
31.2
86
0.684549
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,808
stack.py
tgalal_yowsup/yowsup/demos/echoclient/stack.py
from yowsup.stacks import YowStackBuilder from .layer import EchoLayer from yowsup.layers import YowLayerEvent from yowsup.layers.network import YowNetworkLayer class YowsupEchoStack(object): def __init__(self, profile): stackBuilder = YowStackBuilder() self._stack = stackBuilder\ .pushDefaultLayers()\ .push(EchoLayer)\ .build() self._stack.setProfile(profile) def set_prop(self, key, val): self._stack.setProp(key, val) def start(self): self._stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) self._stack.loop()
641
Python
.tac
17
30.705882
86
0.692557
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,809
stack.py
tgalal_yowsup/yowsup/demos/sendclient/stack.py
from yowsup.stacks import YowStackBuilder from .layer import SendLayer from yowsup.layers import YowLayerEvent from yowsup.layers.auth import YowAuthenticationProtocolLayer from yowsup.layers.network import YowNetworkLayer class YowsupSendStack(object): def __init__(self, profile, messages): """ :param profile: :param messages: list of (jid, message) tuples :return: """ stackBuilder = YowStackBuilder() self._stack = stackBuilder\ .pushDefaultLayers()\ .push(SendLayer)\ .build() self._stack.setProp(SendLayer.PROP_MESSAGES, messages) self._stack.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True) self._stack.setProfile(profile) def set_prop(self, key, val): self._stack.setProp(key, val) def start(self): self._stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) self._stack.loop()
975
Python
.tac
25
31.68
86
0.689619
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,810
stack.py
tgalal_yowsup/yowsup/demos/cli/stack.py
from yowsup.stacks import YowStackBuilder from .layer import YowsupCliLayer from yowsup.layers import YowLayerEvent from yowsup.layers.axolotl.props import PROP_IDENTITY_AUTOTRUST import sys class YowsupCliStack(object): def __init__(self, profile): stackBuilder = YowStackBuilder() self._stack = stackBuilder\ .pushDefaultLayers()\ .push(YowsupCliLayer)\ .build() self._stack.setProfile(profile) self._stack.setProp(PROP_IDENTITY_AUTOTRUST, True) def set_prop(self, prop, val): self._stack.setProp(prop, val) def start(self): print("Yowsup Cli client\n==================\nType /help for available commands\n") self._stack.broadcastEvent(YowLayerEvent(YowsupCliLayer.EVENT_START)) try: self._stack.loop() except KeyboardInterrupt: print("\nYowsdown") sys.exit(0)
927
Python
.tac
24
30.833333
91
0.659598
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,811
stack.py
tgalal_yowsup/yowsup/demos/mediasink/stack.py
from yowsup.stacks import YowStackBuilder from .layer import MediaSinkLayer from yowsup.layers import YowLayerEvent from yowsup.layers.network import YowNetworkLayer class MediaSinkStack(object): def __init__(self, profile, storage_dir=None): stackBuilder = YowStackBuilder() self._stack = stackBuilder\ .pushDefaultLayers()\ .push(MediaSinkLayer)\ .build() self._stack.setProp(MediaSinkLayer.PROP_STORAGE_DIR, storage_dir) self._stack.setProfile(profile) def set_prop(self, key, val): self._stack.setProp(key, val) def start(self): self._stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) self._stack.loop()
741
Python
.tac
18
34.111111
86
0.703343
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,812
setup.py
OctoPrint_OctoPrint/setup.py
# -*- coding: utf-8 -*- ### NOTE ################################################################################# # This file has to stay format compatible to Python 2, or pip under Python 2 will # not be able to detect that OctoPrint requires Python 3 but instead fail with a # syntax error. # # So, no f-strings, no walrus operators, no pyupgrade or codemods. ########################################################################################## import os import sys sys.path.insert(0, os.path.dirname(__file__)) import setuptools # noqa: F401,E402 try: import octoprint_setuptools # noqa: F401,E402 except ImportError: octoprint_setuptools = None # ---------------------------------------------------------------------------------------- # Supported python versions PYTHON_REQUIRES = ">=3.7, <3.13" # Requirements for setup.py SETUP_REQUIRES = [] # Requirements for our application bundled_plugins = [ "OctoPrint-FileCheck>=2021.2.23", "OctoPrint-FirmwareCheck>=2021.10.11", "OctoPrint-PiSupport>=2023.10.10", ] core_deps = [ "argon2-cffi>=23.1.0", "Babel>=2.12.1,<2.13", # breaking changes can happen on minor version increases "cachelib>=0.10.2,<0.11", "Click>=8.1.7,<9", "colorlog>=6.7.0,<7", "emoji>=2.10.1,<3", "feedparser>=6.0.11,<7", "filetype>=1.2.0,<2", "Flask-Assets>=2.1.0,<3", "Flask-Babel>=3.1.0,<4", "Flask-Login>=0.6.3,<0.7", # breaking changes can happen on minor version increases "Flask-Limiter>=3.5.0,<4", "flask>=2.2.3,<2.3", # breaking changes can happen on minor version increases (with deprecation warnings) "frozendict>=2.4.0,<3", "future>=0.18.3,<1", # not really needed anymore, but leaving in for py2/3 compat plugins "markdown>=3.4.4,<3.5", # later versions require Python 3.8+ "netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases # "netifaces2>=0.0.21,<0.1", # fork of netifaces in Rust, use rolled back due to build issues in some environments "netifaces>=0.11.0,<0.12", "passlib>=1.7.4,<2", "pathvalidate>=2.5.2,<3", "pkginfo>=1.9.6,<2", "psutil>=5.9.8,<6", "pydantic==1.10.16", # to be kept pinned until https://github.com/pydantic/pydantic/issues/7689 is resolved "pylru>=1.2.1,<2", "pyserial>=3.5,<4", "pytz", "PyYAML>=6.0.1,<7", # changelog at https://github.com/yaml/pyyaml/blob/master/CHANGES "requests>=2.31.0,<3", "sarge==0.1.7.post1", "semantic_version>=2.10.0,<3", "sentry-sdk>=1.40.0,<2", "setuptools", "tornado>=6.2,<6.3", # later versions require Python 3.8+ "watchdog>=2.3.1,<3", "websocket-client==1.6.1", # later versions require Python 3.8+, breaking changes can happen on patch version increases, changelog incomplete "werkzeug>=2.2.3,<2.3", # breaking changes can happen on minor version increases "wrapt>=1.15,<1.16", "zeroconf~=0.127", # breaking changes can happen on minor version increases (despite semantic versioning) "zipstream-ng>=1.7.1,<2.0.0", ] vendored_deps = [ "blinker>=1.6.3,<1.7.0", # dependency of flask_principal, later versions require Python 3.8+ "class-doc>=0.2.6,<0.3", # dependency of with_attrs_docs "regex", # dependency of awesome-slugify "unidecode", # dependency of awesome-slugify ] plugin_deps = [ # "OctoPrint-Setuptools>=1.0.3", # makes sure plugins can import this on setup.py based install "wheel", # makes sure plugins can be built as wheels in OctoPrint's venv, see #4682 ] INSTALL_REQUIRES = bundled_plugins + core_deps + vendored_deps + plugin_deps # Additional requirements for optional install options and/or OS-specific dependencies EXTRA_REQUIRES = { # Dependencies for OSX ":sys_platform == 'darwin'": [ "appdirs>=1.4.4,<2", ], # Dependencies for core development "develop": [ # Testing dependencies "ddt", "mock>=5.1.0,<6", "pytest-doctest-custom>=1.0.0,<2", "pytest>=7.3.0,<8", # pre-commit "pre-commit", # profiler "pyinstrument", ], # Dependencies for developing OctoPrint plugins "plugins": ["cookiecutter>=2.5.0,<3"], # update plugin tutorial when updating this # Dependencies for building the documentation "docs": [ "sphinx", "sphinxcontrib-httpdomain", "sphinxcontrib-mermaid", "sphinx_rtd_theme", "readthedocs-sphinx-ext", ], } # ---------------------------------------------------------------------------------------- # Anything below here is just command setup and general setup configuration here = os.path.abspath(os.path.dirname(__file__)) def read_file_contents(path): import io with io.open(path, encoding="utf-8") as f: return f.read() def copy_files_build_py_factory(files, baseclass): class copy_files_build_py(baseclass): files = {} def run(self): print("RUNNING copy_files_build_py") if not self.dry_run: import shutil for directory, files in self.files.items(): target_dir = os.path.join(self.build_lib, directory) self.mkpath(target_dir) for entry in files: if isinstance(entry, tuple): if len(entry) != 2: continue source, dest = entry[0], os.path.join(target_dir, entry[1]) else: source = entry dest = os.path.join(target_dir, source) print("Copying {} to {}".format(source, dest)) shutil.copy2(source, dest) baseclass.run(self) return type(copy_files_build_py)( copy_files_build_py.__name__, (copy_files_build_py,), {"files": files} ) class ScanDepsCommand(setuptools.Command): description = "Scan dependencies for updates" user_options = [] PYPI = "https://pypi.org/simple/{package}/" def initialize_options(self): pass def finalize_options(self): pass def run(self): from collections import namedtuple import pkg_resources import requests from packaging.version import parse as parse_version Update = namedtuple("Update", ["name", "spec", "current", "latest"]) update_lower_bounds = [] update_bounds = [] all_requires = list(INSTALL_REQUIRES) for value in EXTRA_REQUIRES.values(): all_requires += value for r in all_requires: requirement = pkg_resources.Requirement.parse(r) resp = requests.get( self.PYPI.format(package=requirement.project_name), headers={"Accept": "application/vnd.pypi.simple.v1+json"}, ) resp.raise_for_status() def safe_parse_version(version): try: return parse_version(version) except ValueError: return None data = resp.json() versions = list( filter( lambda x: x and not x.is_prerelease and not x.is_devrelease, map(lambda x: safe_parse_version(x), data.get("versions", [])), ) ) if not versions: continue lower = None for spec in requirement.specs: if spec[0] == ">=": lower = spec[1] break latest = versions[-1] update = Update(requirement.project_name, str(requirement), lower, latest) if str(latest) not in requirement: update_bounds.append(update) elif lower and parse_version(lower) < latest: update_lower_bounds.append(update) def print_update(update): print( f"{update.spec}: latest {update.latest}, pypi: https://pypi.org/project/{update.name}/" ) print("") print("The following dependencies can get their lower bounds updated:") print("") for update in update_lower_bounds: print_update(update) print("") print("The following dependencies should get looked at for a full update:") print("") for update in update_bounds: print_update(update) def get_version_and_cmdclass(pkg_path): import os from importlib.util import module_from_spec, spec_from_file_location spec = spec_from_file_location("version", os.path.join(pkg_path, "_version.py")) module = module_from_spec(spec) spec.loader.exec_module(module) data = module.get_data() return data["version"], module.get_cmdclass(pkg_path) def get_cmdclass(cmdclass): # make sure these are always available, even when run by dependabot global octoprint_setuptools, md_to_html_build_py_factory from setuptools.command.build_py import build_py as _build_py if octoprint_setuptools: # add clean command cmdclass.update( { "clean": octoprint_setuptools.CleanCommand.for_options( source_folder="src", eggs=["OctoPrint*.egg-info"] ) } ) # add translation commands translation_dir = "translations" pot_file = os.path.join(translation_dir, "messages.pot") bundled_dir = os.path.join("src", "octoprint", "translations") cmdclass.update( octoprint_setuptools.get_babel_commandclasses( pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir, ) ) cmdclass["build_py"] = copy_files_build_py_factory( { "octoprint/templates/_data": [ "AUTHORS.md", "SUPPORTERS.md", "THIRDPARTYLICENSES.md", ] }, cmdclass.get("build_py", _build_py), ) cmdclass["scan_deps"] = ScanDepsCommand return cmdclass def package_data_dirs(source, sub_folders): dirs = [] for d in sub_folders: folder = os.path.join(source, d) if not os.path.exists(folder): continue for dirname, _, files in os.walk(folder): dirname = os.path.relpath(dirname, source) for f in files: dirs.append(os.path.join(dirname, f)) return dirs if __name__ == "__main__": version, cmdclass = get_version_and_cmdclass(os.path.join("src", "octoprint")) setuptools.setup( name="OctoPrint", version=version, cmdclass=get_cmdclass(cmdclass), description="The snappy web interface for your 3D printer", long_description=read_file_contents(os.path.join(here, "README.md")), long_description_content_type="text/markdown", python_requires=PYTHON_REQUIRES, setup_requires=SETUP_REQUIRES, install_requires=INSTALL_REQUIRES, extras_require=EXTRA_REQUIRES, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Flask", "Intended Audience :: Developers", "Intended Audience :: Education", "Intended Audience :: End Users/Desktop", "Intended Audience :: Manufacturing", "Intended Audience :: Other Audience", "Intended Audience :: Science/Research", "License :: OSI Approved :: GNU Affero General Public License v3", "Natural Language :: English", "Natural Language :: German", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: JavaScript", "Topic :: Printing", "Topic :: System :: Monitoring", ], author="Gina Häußge", author_email="gina@octoprint.org", url="https://octoprint.org", license="GNU Affero General Public License v3", keywords="3dprinting 3dprinter 3d-printing 3d-printer octoprint", project_urls={ "Community Forum": "https://community.octoprint.org", "Bug Reports": "https://github.com/OctoPrint/OctoPrint/issues", "Source": "https://github.com/OctoPrint/OctoPrint", "Funding": "https://support.octoprint.org", }, packages=setuptools.find_packages(where="src"), package_dir={"": "src"}, package_data={ "octoprint": package_data_dirs( "src/octoprint", ["static", "templates", "plugins", "translations"] ) + ["util/piptestballoon/setup.py"] }, include_package_data=True, zip_safe=False, entry_points={"console_scripts": ["octoprint = octoprint:main"]}, )
13,633
Python
.py
326
32.509202
146
0.579369
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,813
__init__.py
OctoPrint_OctoPrint/src/octoprint_setuptools/__init__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals ### NOTE ################################################################################# # This file has to stay format compatible to Python 2, or pip under Python 2 will # not be able to detect that OctoPrint requires Python 3 but instead fail with a # syntax error. # # So, no f-strings, no walrus operators, no pyupgrade or codemods. ########################################################################################## __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import glob import os import shutil from distutils.command.clean import clean as _clean from setuptools import Command def package_data_dirs(source, sub_folders): dirs = [] for d in sub_folders: folder = os.path.join(source, d) if not os.path.exists(folder): continue for dirname, _, files in os.walk(folder): dirname = os.path.relpath(dirname, source) for f in files: dirs.append(os.path.join(dirname, f)) return dirs def recursively_handle_files( directory, file_matcher, folder_matcher=None, folder_handler=None, file_handler=None ): applied_handler = False for filename in os.listdir(directory): path = os.path.join(directory, filename) if file_handler is not None and file_matcher(filename): file_handler(path) applied_handler = True elif os.path.isdir(path) and ( folder_matcher is None or folder_matcher(directory, filename, path) ): sub_applied_handler = recursively_handle_files( path, file_matcher, folder_handler=folder_handler, file_handler=file_handler, ) if sub_applied_handler: applied_handler = True if folder_handler is not None: folder_handler(path, sub_applied_handler) return applied_handler def has_requirement(requirement, requirements): if requirement is None or requirements is None: return False requirement = requirement.lower() requirements = [r.lower() for r in requirements] compat = [ requirement.lower() + c for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===") ] return requirement in requirements or any( any(r.startswith(c) for c in compat) for r in requirements ) class CleanCommand(_clean): user_options = _clean.user_options + [ ("orig", None, "behave like original clean command"), ("noeggs", None, "don't clean up eggs"), ("nopyc", None, "don't clean up pyc files"), ] boolean_options = _clean.boolean_options + ["orig", "noeggs", "nopyc"] source_folder = "src" eggs = None @classmethod def for_options(cls, source_folder="src", eggs=None): if eggs is None: eggs = [] return type(cls)( cls.__name__, (cls,), {"source_folder": source_folder, "eggs": eggs} ) def initialize_options(self): _clean.initialize_options(self) self.orig = None self.noeggs = None self.nopyc = None def finalize_options(self): _clean.finalize_options(self) if not self.orig: self.all = True def run(self): _clean.run(self) if self.orig: return # eggs if not self.noeggs: for egg in self.eggs: globbed_eggs = glob.glob(egg) for globbed_egg in globbed_eggs: print("deleting '%s' egg" % globbed_egg) if not self.dry_run: shutil.rmtree(globbed_egg) # pyc files if not self.nopyc: def delete_folder_if_empty(path, applied_handler): if not applied_handler: return if len(os.listdir(path)) == 0: if not self.dry_run: shutil.rmtree(path) print( "removed %s since it was empty" % path[len(self.source_folder) :] ) def delete_file(path): print("removing '%s'" % path[len(self.source_folder) :]) if not self.dry_run: os.remove(path) import fnmatch print("recursively removing *.pyc from '%s'" % self.source_folder) recursively_handle_files( os.path.abspath(self.source_folder), lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"), folder_matcher=lambda dir, name, path: name != ".git", folder_handler=delete_folder_if_empty, file_handler=delete_file, ) def _normalize_locale(l): from babel.core import Locale return str(Locale.parse(l)) class NewTranslation(Command): description = "create a new translation" user_options = [ ("locale=", "l", "locale for the new translation"), ] boolean_options = [] pot_file = None output_dir = None @classmethod def for_options(cls, pot_file=None, output_dir=None): if pot_file is None: raise ValueError("pot_file must not be None") if output_dir is None: raise ValueError("output_dir must not be None") return type(cls)( cls.__name__, (cls,), {"pot_file": pot_file, "output_dir": output_dir} ) def __init__(self, dist, **kw): from babel.messages import frontend as babel self.babel_init_messages = babel.init_catalog(dist) Command.__init__(self, dist, **kw) def initialize_options(self): self.locale = None self.babel_init_messages.initialize_options() def finalize_options(self): self.babel_init_messages.locale = _normalize_locale(self.locale) self.babel_init_messages.input_file = self.__class__.pot_file self.babel_init_messages.output_dir = self.__class__.output_dir self.babel_init_messages.finalize_options() def run(self): self.babel_init_messages.run() class ExtractTranslation(Command): description = "extract translations" user_options = [] boolean_options = [] mail_address = "i18n@octoprint.org" copyright_holder = "The OctoPrint Project" mapping_file = None pot_file = None input_dirs = None @classmethod def for_options( cls, mail_address="i18n@octoprint.org", copyright_holder="The OctoPrint Project", mapping_file=None, pot_file=None, input_dirs=None, ): if mapping_file is None: raise ValueError("mapping_file must not be None") if pot_file is None: raise ValueError("pot_file must not be None") if input_dirs is None: raise ValueError("input_dirs must not be None") return type(cls)( cls.__name__, (cls,), { "mapping_file": mapping_file, "pot_file": pot_file, "input_dirs": input_dirs, "mail_address": mail_address, "copyright_holder": copyright_holder, }, ) def __init__(self, dist, **kw): from babel.messages import frontend as babel self.babel_extract_messages = babel.extract_messages(dist) Command.__init__(self, dist, **kw) def initialize_options(self): self.babel_extract_messages.initialize_options() def finalize_options(self): self.babel_extract_messages.mapping_file = self.__class__.mapping_file self.babel_extract_messages.output_file = self.__class__.pot_file self.babel_extract_messages.input_dirs = self.__class__.input_dirs self.babel_extract_messages.msgid_bugs_address = self.__class__.mail_address self.babel_extract_messages.copyright_holder = self.__class__.copyright_holder self.babel_extract_messages.finalize_options() def run(self): self.babel_extract_messages.run() class RefreshTranslation(Command): description = "refresh translations" user_options = [ ("locale=", "l", "locale for the translation to refresh"), ] boolean_options = [] mail_address = "i18n@octoprint.org" copyright_holder = "The OctoPrint Project" mapping_file = None pot_file = None input_dirs = None output_dir = None @classmethod def for_options( cls, mail_address="i18n@octoprint.org", copyright_holder="The OctoPrint Project", mapping_file=None, pot_file=None, input_dirs=None, output_dir=None, ): if mapping_file is None: raise ValueError("mapping_file must not be None") if pot_file is None: raise ValueError("pot_file must not be None") if input_dirs is None: raise ValueError("input_dirs must not be None") if output_dir is None: raise ValueError("output_dir must not be None") return type(cls)( cls.__name__, (cls,), { "mapping_file": mapping_file, "pot_file": pot_file, "input_dirs": input_dirs, "mail_address": mail_address, "copyright_holder": copyright_holder, "output_dir": output_dir, }, ) def __init__(self, dist, **kw): from babel.messages import frontend as babel self.babel_extract_messages = babel.extract_messages(dist) self.babel_update_messages = babel.update_catalog(dist) Command.__init__(self, dist, **kw) def initialize_options(self): self.locale = None self.babel_extract_messages.initialize_options() self.babel_update_messages.initialize_options() def finalize_options(self): self.babel_extract_messages.mapping_file = self.__class__.mapping_file self.babel_extract_messages.output_file = self.__class__.pot_file self.babel_extract_messages.input_dirs = self.__class__.input_dirs self.babel_extract_messages.msgid_bugs_address = self.__class__.mail_address self.babel_extract_messages.copyright_holder = self.__class__.copyright_holder self.babel_extract_messages.finalize_options() self.babel_update_messages.input_file = self.__class__.pot_file self.babel_update_messages.output_dir = self.__class__.output_dir if self.locale: self.babel_update_messages.locale = _normalize_locale(self.locale) self.babel_update_messages.finalize_options() def run(self): self.babel_extract_messages.run() self.babel_update_messages.run() class CompileTranslation(Command): description = "compile translations" user_options = [] boolean_options = [] output_dir = None @classmethod def for_options(cls, output_dir=None): if output_dir is None: raise ValueError("output_dir must not be None") return type(cls)(cls.__name__, (cls,), {"output_dir": output_dir}) def __init__(self, dist, **kw): from babel.messages import frontend as babel self.babel_compile_messages = babel.compile_catalog(dist) Command.__init__(self, dist, **kw) def initialize_options(self): self.babel_compile_messages.initialize_options() def finalize_options(self): self.babel_compile_messages.directory = self.__class__.output_dir self.babel_compile_messages.finalize_options() def run(self): self.babel_compile_messages.run() class BundleTranslation(Command): description = "bundles translations" user_options = [("locale=", "l", "locale for the translation to bundle")] boolean_options = [] source_dir = None target_dir = None @classmethod def for_options(cls, source_dir=None, target_dir=None): if source_dir is None: raise ValueError("source_dir must not be None") if target_dir is None: raise ValueError("target_dir must not be None") return type(cls)( cls.__name__, (cls,), {"source_dir": source_dir, "target_dir": target_dir} ) def initialize_options(self): self.locale = None def finalize_options(self): pass def run(self): locale = _normalize_locale(self.locale) source_path = os.path.join(self.__class__.source_dir, locale) target_path = os.path.join(self.__class__.target_dir, locale) if not os.path.exists(source_path): raise RuntimeError("source path " + source_path + " does not exist") if os.path.exists(target_path): if not os.path.isdir(target_path): raise RuntimeError( "target path " + target_path + " exists and is not a directory" ) shutil.rmtree(target_path) print( "Copying translations for locale {locale} from {source_path} to {target_path}...".format( **locals() ) ) shutil.copytree(source_path, target_path) class PackTranslation(Command): description = "creates language packs for translations" user_options = [ ("locale=", "l", "locale for the translation to pack"), ("author=", "a", "author of the translation"), ("target=", "t", "target folder for the pack"), ] boolean_options = [] source_dir = None pack_name_prefix = None pack_path_prefix = None @classmethod def for_options(cls, source_dir=None, pack_name_prefix=None, pack_path_prefix=None): if source_dir is None: raise ValueError("source_dir must not be None") if pack_name_prefix is None: raise ValueError("pack_name_prefix must not be None") if pack_path_prefix is None: raise ValueError("pack_path_prefix must not be None") return type(cls)( cls.__name__, (cls,), { "source_dir": source_dir, "pack_name_prefix": pack_name_prefix, "pack_path_prefix": pack_path_prefix, }, ) def initialize_options(self): self.locale = None self.author = None self.target = None def finalize_options(self): if self.locale is None: raise ValueError("locale must be provided") def run(self): locale = _normalize_locale(self.locale) locale_dir = os.path.join(self.__class__.source_dir, locale) if not os.path.isdir(locale_dir): raise RuntimeError("translation does not exist, please create it first") import datetime now = datetime.datetime.utcnow().replace(microsecond=0) if self.target is None: self.target = self.__class__.source_dir zip_path = os.path.join( self.target, "{prefix}{locale}_{date}.zip".format( prefix=self.__class__.pack_name_prefix, locale=locale, date=now.strftime("%Y%m%d%H%M%S"), ), ) print("Packing translation to {zip_path}".format(**locals())) def add_recursively(zip, path, prefix): if not os.path.isdir(path): return for entry in os.listdir(path): entry_path = os.path.join(path, entry) new_prefix = prefix + "/" + entry if os.path.isdir(entry_path): add_recursively(zip, entry_path, new_prefix) elif os.path.isfile(entry_path): print("Adding {entry_path} as {new_prefix}".format(**locals())) zip.write(entry_path, new_prefix) meta_str = "last_update: {date}\n".format(date=now.isoformat()) if self.author: meta_str += "author: {author}\n".format(author=self.author) zip_locale_root = self.__class__.pack_path_prefix + locale import zipfile with zipfile.ZipFile(zip_path, "w") as zip: add_recursively(zip, locale_dir, zip_locale_root) print("Adding meta.yaml as {zip_locale_root}/meta.yaml".format(**locals())) zip.writestr(zip_locale_root + "/meta.yaml", meta_str) def get_babel_commandclasses( pot_file=None, mapping_file="babel.cfg", input_dirs=".", output_dir=None, pack_name_prefix=None, pack_path_prefix=None, bundled_dir=None, mail_address="i18n@octoprint.org", copyright_holder="The OctoPrint Project", ): try: import babel except ImportError: return {} result = { "babel_new": NewTranslation.for_options(pot_file=pot_file, output_dir=output_dir), "babel_extract": ExtractTranslation.for_options( mapping_file=mapping_file, pot_file=pot_file, input_dirs=input_dirs, mail_address=mail_address, copyright_holder=copyright_holder, ), "babel_refresh": RefreshTranslation.for_options( mapping_file=mapping_file, pot_file=pot_file, input_dirs=input_dirs, output_dir=output_dir, mail_address=mail_address, copyright_holder=copyright_holder, ), "babel_compile": CompileTranslation.for_options(output_dir=output_dir), "babel_pack": PackTranslation.for_options( source_dir=output_dir, pack_name_prefix=pack_name_prefix, pack_path_prefix=pack_path_prefix, ), } if bundled_dir is not None: result["babel_bundle"] = BundleTranslation.for_options( source_dir=output_dir, target_dir=bundled_dir ) return result def create_plugin_setup_parameters( identifier="todo", name="TODO", version="0.1", description="TODO", author="TODO", mail="todo@example.com", url="TODO", license="AGPLv3", source_folder=".", additional_data=None, additional_packages=None, ignored_packages=None, requires=None, extra_requires=None, cmdclass=None, eggs=None, package=None, dependency_links=None, ): import pkg_resources if package is None: package = "octoprint_{identifier}".format(**locals()) if additional_data is None: additional_data = list() if additional_packages is None: additional_packages = list() if ignored_packages is None: ignored_packages = list() if dependency_links is None: dependency_links = list() if requires is None: requires = ["OctoPrint"] if not isinstance(requires, list): raise ValueError("requires must be a list") if not has_requirement("OctoPrint", requires): requires = ["OctoPrint"] + list(requires) if extra_requires is None: extra_requires = {} if not isinstance(extra_requires, dict): raise ValueError("extra_requires must be a dict") if cmdclass is None: cmdclass = {} if not isinstance(cmdclass, dict): raise ValueError("cmdclass must be a dict") if eggs is None: eggs = [] if not isinstance(eggs, list): raise ValueError("eggs must be a list") egg = "{name}*.egg-info".format( name=pkg_resources.to_filename(pkg_resources.safe_name(name)) ) if egg not in eggs: eggs = [egg] + eggs cmdclass.update( { "clean": CleanCommand.for_options( source_folder=os.path.join(source_folder, package), eggs=eggs ) } ) translation_dir = os.path.join(source_folder, "translations") pot_file = os.path.join(translation_dir, "messages.pot") bundled_dir = os.path.join(source_folder, package, "translations") cmdclass.update( get_babel_commandclasses( pot_file=pot_file, output_dir=translation_dir, bundled_dir=bundled_dir, pack_name_prefix="{name}-i18n-".format(**locals()), pack_path_prefix="_plugins/{identifier}/".format(**locals()), ) ) from setuptools import find_packages packages = set( [package] + list( filter( lambda x: x.startswith("{package}.".format(package=package)), find_packages(where=source_folder, exclude=ignored_packages), ) ) + additional_packages ) print("Found packages: {packages!r}".format(**locals())) return { "name": name, "version": version, "description": description, "author": author, "author_email": mail, "url": url, "license": license, # adding new commands "cmdclass": cmdclass, # we only have our plugin package to install "packages": packages, # we might have additional data files in sub folders that need to be installed too "package_data": { package: package_data_dirs( os.path.join(source_folder, package), ["static", "templates", "translations"] + additional_data, ) }, "include_package_data": True, # If you have any package data that needs to be accessible on the file system, such as templates or static assets # this plugin is not zip_safe. "zip_safe": False, "install_requires": requires, "extras_require": extra_requires, "dependency_links": dependency_links, # Hook the plugin into the "octoprint.plugin" entry point, mapping the plugin_identifier to the plugin_package. # That way OctoPrint will be able to find the plugin and load it. "entry_points": { "octoprint.plugin": ["{identifier} = {package}".format(**locals())] }, }
22,250
Python
.py
565
30.115044
121
0.598951
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,814
__init__.py
OctoPrint_OctoPrint/src/octoprint_client/__init__.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import json import time import requests import websocket def build_base_url( https=False, httpuser=None, httppass=None, host=None, port=None, prefix=None ): protocol = "https" if https else "http" httpauth = f"{httpuser}:{httppass}@" if httpuser and httppass else "" host = host if host else "127.0.0.1" port = f":{port}" if port else ":5000" prefix = prefix if prefix else "" return f"{protocol}://{httpauth}{host}{port}{prefix}" class SocketTimeout(BaseException): pass class SocketClient: def __init__(self, url, use_ssl=False, daemon=True, **kwargs): self._url = url self._use_ssl = use_ssl self._daemon = daemon self._ws_kwargs = kwargs self._seen_open = False self._seen_close = False self._waiting_for_reconnect = False self._ws = None self._thread = None # hello world def _prepare(self): """Prepares socket and thread for a new connection.""" # close the socket if it's currently open if self._ws is not None: try: self._ws.close() except Exception: # we can't handle that in any meaningful way right now pass # prepare a bunch of callback methods import functools callbacks = {} for callback in ("on_open", "on_message", "on_error", "on_close"): # now, normally we could just use functools.partial for something like # this, but websocket does a type check against a python function type # which the use of partial makes fail, so we have to use a lambda # wrapper here, and since we need to pick the current value of # callback from the current scope we need a factory method for that... def factory(cb): return lambda *fargs, **fkwargs: functools.partial(self._on_callback, cb)( *fargs, **fkwargs ) callbacks[callback] = factory(callback) # initialize socket instance with url and callbacks kwargs = dict(self._ws_kwargs) kwargs.update(callbacks) self._ws = websocket.WebSocketApp(self._url, **kwargs) # initialize thread import threading self._thread = threading.Thread(target=self._on_thread_run) self._thread.daemon = self._daemon def _on_thread_run(self): """Has the socket run forever (aka until closed...).""" self._ws.run_forever() def _on_callback(self, cb, *args, **kwargs): """ Callback for socket events. Will call any callback method defined on ``self`` that matches ``cb`` prefixed with an ``_ws_``, then will call any callback method provided in the socket keyword arguments (``self._ws_kwargs``) that matches ``cb``. Calling args and kwargs will be the ones passed to ``_on_callback``. Arguments: cb (str): the callback type """ internal = "_ws_" + cb if hasattr(self, internal): cb_func = getattr(self, internal) if callable(cb_func): cb_func(*args, **kwargs) cb_func = self._ws_kwargs.get(cb, None) if callable(cb_func): cb_func(*args, **kwargs) def _ws_on_open(self, ws): """ Callback for socket on_open event. Used only to track active reconnection attempts. """ if not self._waiting_for_reconnect: return if ws != self._ws: return self._seen_open = True def _ws_on_close(self, ws): """ Callback for socket on_close event. Used only to track active reconnection attempts. """ if not self._waiting_for_reconnect: return if ws != self._ws: return self._seen_close = True def connect(self): """Connects the socket.""" self._prepare() self._thread.start() def wait(self, timeout=None): """Waits for the closing of the socket or the timeout.""" start = None def test_condition(): if timeout and start and start + timeout > time.time(): raise SocketTimeout() start = time.time() while self._thread.is_alive(): test_condition() self._thread.join(timeout=1.0) @property def is_connected(self): """Whether the web socket is connected or not.""" return self._thread and self._ws and self._thread.is_alive() def disconnect(self): """Disconnect the web socket.""" if self._ws: self._ws.close() def reconnect(self, timeout=None, disconnect=True): """ Tries to reconnect to the web socket. If timeout is set will try to reconnect over the specified timeout in seconds and return False if the connection could not be re-established. If no timeout is provided, the method will block until the connection could be re-established. If disconnect is set to ``True`` will disconnect the socket explicitly first if it is currently connected. Arguments: timeout (number): timeout in seconds to wait for the reconnect to happen. disconnect (bool): Whether to disconnect explicitly from the socket if a connection is currently established (True, default) or not (False). Returns: bool - True if the reconnect was successful, False otherwise. """ self._seen_close = False self._seen_open = False self._waiting_for_reconnect = True if not self.is_connected: # not connected, so we are already closed self._seen_close = True elif disconnect: # connected and disconnect is True, so we disconnect self.disconnect() start = None if timeout: timeout_condition = ( lambda: start is not None and time.time() > start + timeout ) else: timeout_condition = lambda: False start = time.time() while not timeout_condition(): if self._seen_close and self._seen_open: # we saw a connection close and open, so a reconnect, success! return True else: # try to connect self.connect() # sleep a bit time.sleep(1.0) # if we land here the timeout condition became True without us seeing # a reconnect, that's a failure return False class Client: def __init__(self, baseurl, apikey): self.baseurl = baseurl self.apikey = apikey def prepare_request(self, method=None, path=None, params=None): url = None if self.baseurl: while path.startswith("/"): path = path[1:] url = self.baseurl + "/" + path return requests.Request( method=method, url=url, params=params, headers={"X-Api-Key": self.apikey} ).prepare() def request( self, method, path, data=None, files=None, encoding=None, params=None, timeout=None, ): if timeout is None: timeout = 30 s = requests.Session() request = self.prepare_request(method, path, params=params) if data or files: if encoding == "json": request.prepare_body(None, None, json=data) else: request.prepare_body(data, files=files) response = s.send(request, timeout=timeout) return response def get(self, path, params=None, timeout=None): return self.request("GET", path, params=params, timeout=timeout) def post(self, path, data, encoding=None, params=None, timeout=None): return self.request( "POST", path, data=data, encoding=encoding, params=params, timeout=timeout ) def post_json(self, path, data, params=None, timeout=None): return self.post(path, data, encoding="json", params=params, timeout=timeout) def post_command(self, path, command, additional=None, timeout=None): data = {"command": command} if additional: data.update(additional) return self.post_json(path, data, params=data, timeout=timeout) def upload( self, path, file_path, additional=None, file_name=None, content_type=None, params=None, timeout=None, ): import os if not os.path.isfile(file_path): raise ValueError(f"{file_path} cannot be uploaded since it is not a file") if file_name is None: file_name = os.path.basename(file_path) with open(file_path, "rb") as fp: if content_type: files = {"file": (file_name, fp, content_type)} else: files = {"file": (file_name, fp)} response = self.request( "POST", path, data=additional, files=files, params=params, timeout=timeout ) return response def delete(self, path, params=None, timeout=None): return self.request("DELETE", path, params=params, timeout=timeout) def patch(self, path, data, encoding=None, params=None, timeout=None): return self.request( "PATCH", path, data=data, encoding=encoding, params=params, timeout=timeout ) def put(self, path, data, encoding=None, params=None, timeout=None): return self.request( "PUT", path, data=data, encoding=encoding, params=params, timeout=timeout ) def create_socket(self, **kwargs): import random import uuid # creates websocket URL for SockJS according to # - http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-37 # - http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-50 url = "ws://{}/sockjs/{:0>3d}/{}/websocket".format( self.baseurl[ self.baseurl.find("//") + 2 : ], # host + port + prefix, but no protocol random.randrange(0, stop=999), # server_id uuid.uuid4(), # session_id ) use_ssl = self.baseurl.startswith("https:") on_open_cb = kwargs.get("on_open", None) on_heartbeat_cb = kwargs.get("on_heartbeat", None) on_message_cb = kwargs.get("on_message", None) on_close_cb = kwargs.get("on_close", None) on_error_cb = kwargs.get("on_error", None) on_sent_cb = kwargs.get("on_sent", None) daemon = kwargs.get("daemon", True) def send(ws, data): payload = '["' + json.dumps(data).replace('"', '\\"') + '"]' ws.send(payload) if callable(on_sent_cb): on_sent_cb(ws, data) def authenticate(ws): # perform passive login to retrieve username and session key for API key response = self.post("/api/login", {"passive": True}) response.raise_for_status() data = response.json() # prepare auth payload auth_message = {"auth": "{name}:{session}".format(**data)} # send it send(ws, auth_message) def on_message(ws, message): message_type = message[0] if message_type == "h": # "heartbeat" message if callable(on_heartbeat_cb): on_heartbeat_cb(ws) return elif message_type == "o": # "open" message return elif message_type == "c": # "close" message return if not callable(on_message_cb): return message_body = message[1:] if not message_body: return data = json.loads(message_body) if message_type == "m": data = [ data, ] for d in data: for internal_type, internal_message in d.items(): on_message_cb(ws, internal_type, internal_message) if internal_type == "connected": # we just got connected to the server, authenticate authenticate(ws) def on_open(ws): if callable(on_open_cb): on_open_cb(ws) def on_close(ws): if callable(on_close_cb): on_close_cb(ws) def on_error(ws, error): if callable(on_error_cb): on_error_cb(ws, error) class CustomSocketClient(SocketClient): def auth(self, username, key): self.send({"auth": f"{username}:{key}"}) def throttle(self, factor): self.send({"throttle": factor}) def send(self, data): send(self._ws, data) socket = CustomSocketClient( url, use_ssl=use_ssl, daemon=daemon, on_open=on_open, on_message=on_message, on_close=on_close, on_error=on_error, ) socket.connect() return socket
13,686
Python
.py
340
29.402941
103
0.56978
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,815
users.py
OctoPrint_OctoPrint/src/octoprint/users.py
__author__ = "Marc Hannappel <salandora@gmail.com>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" # Wrapper to the new access.users location import warnings from octoprint.access.users import * # noqa: F401, F403 ## possibly used by other modules from octoprint.access.users import User, deprecated warnings.warn( "octoprint.users is deprecated, use octoprint.access.users instead", DeprecationWarning, stacklevel=2, ) AccessUser = User class User(AccessUser): @deprecated( "octoprint.users.User is deprecated, please use octoprint.access.users.User instead" ) def __init__(self, username, passwordHash, active, roles, apikey=None, settings=None): from octoprint.server import groupManager if "admin" in roles: groups = [groupManager.admin_group] elif "user" in roles: groups = [groupManager.user_group] else: groups = [groupManager.guest_group] AccessUser( username=username, passwordHash=passwordHash, active=active, permissions=None, groups=groups, apikey=apikey, settings=settings, )
1,344
Python
.py
34
32.382353
103
0.678709
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,816
webcams.py
OctoPrint_OctoPrint/src/octoprint/webcams.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import octoprint.plugin from octoprint.plugin import plugin_manager from octoprint.schema.webcam import Webcam def get_webcams(plugin_manager=None): webcams = dict() def success_callback(name, plugin, result): nonlocal webcams logger = logging.getLogger(__name__) if result is None: return if not isinstance(result, (list, tuple)): logger.error( f"Received object from `get_webcam_configurations` of plugin {name} that is not a list of Webcam instances", extra={"plugin": name}, ) return for webcam in result: if not isinstance(webcam, Webcam): logger.warning( f"Received object in list from `get_webcam_configurations` of plugin {name} that is not an instance of Webcam, skipping", extra={"plugin": name}, ) continue if webcam.name in webcams: logger.warning( f"Webcam name {webcam.name} provided by plugin {name} is already in use", extra={"plugin": name}, ) continue webcams[webcam.name] = ProvidedWebcam( config=webcam, providerIdentifier=name, ) def error_callback(name, _, exc): logging.getLogger(__name__).info(exc) octoprint.plugin.call_plugin( octoprint.plugin.WebcamProviderPlugin, "get_webcam_configurations", sorting_context="WebcamProviderPlugin.get_webcam_configurations", callback=success_callback, error_callback=error_callback, manager=plugin_manager, ) return webcams def get_default_webcam(settings=None, plugin_manager=None): def fallbackFilter(webcam: Webcam): return webcam.config.compat return __get_webcam_by_setting("defaultWebcam", fallbackFilter) def get_snapshot_webcam(settings=None, plugin_manager=None): def fallbackFilter(webcam: Webcam): return webcam.config.canSnapshot return __get_webcam_by_setting("snapshotWebcam", fallbackFilter) def __get_webcam_by_setting(setting, fallbackFilter, settings=None, plugin_manager=None): webcams = get_webcams(plugin_manager=plugin_manager) if not webcams: return None if settings is None: from octoprint.settings import settings as s settings = s() name = settings.get(["webcam", setting]) webcam = webcams.get(name) if webcam: return webcam return next(filter(fallbackFilter, iter(webcams.values())), None) def get_webcams_as_dicts(plugin_manager=None): def to_dict(webcam): webcam_dict = webcam.config.dict() webcam_dict["provider"] = webcam.providerIdentifier return webcam_dict return list(map(to_dict, get_webcams(plugin_manager=plugin_manager).values())) class WebcamNotAbleToTakeSnapshotException(Exception): """Raised a webcam that is not able to take a snapshot is used to take a snapshot""" def __init__(self, webcam_name): self.webcam_name = webcam_name self.message = f"Webcam {webcam_name} can't take snapshots" super().__init__(self.message) class ProvidedWebcam: config: Webcam """the ``WebcamConfiguration`` configuration""" providerIdentifier: str """identifier of the plugin providing this Webcam""" providerPlugin: str """plugin instance of the plugin providing this Webcam""" def __init__(self, config, providerIdentifier): self.config = config self.providerIdentifier = providerIdentifier providerPluginInfo = plugin_manager().get_plugin_info(providerIdentifier) if providerPluginInfo is None: raise Exception(f"Can't find plugin {providerIdentifier}") if not providerPluginInfo.implementation: raise Exception( f"Plugin {providerIdentifier} does not have an implementation" ) self.providerPlugin = providerPluginInfo.implementation if self.config is None: raise Exception("Can't create ProvidedWebcam with None config") if self.providerIdentifier is None: raise Exception("Can't create ProvidedWebcam with None providerIdentifier")
4,553
Python
.py
101
35.960396
141
0.665911
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,817
_version.py
OctoPrint_OctoPrint/src/octoprint/_version.py
""" This file is responsible for calculating the version of OctoPrint. It's based heavily on versioneer and miniver. The version is calculated as follows: If a file named `_static_version.py` exists in the package root, it is imported and the version is read from there. This is the case for source distributions created by `setup.py sdist` as well as binary distributions built by `setup.py bdist` and `setup.py bdist_wheel`. If no such file exists, the version is calculated from git and the provided set of branch version rules. If the current branch matches one of the rules, the version is calculated as `<tag>.dev<distance>+g<short>` where `<tag>` is the virtual tag associated with the current branch, `<distance>` is the distance of the current HEAD from the reference commit of the branch and `<short>` is the short SHA1 of the current HEAD. If the current branch does not match any of the rules, the version is the closest tag reachable from the current HEAD. If the current HEAD is dirty, the version as calculated from a matching branch rule is appended with `.dirty`. Versions from a closest tag instead get `.post<distance>.dev0` appended. If no tag can be determined but a commit hash, the version is `0+unknown.g<short>`. If no commit hash can be determined either, the version is `0+unknown`. """ import errno import os import re import subprocess import sys # Adjust this on every release (candidate) ---------------------------------------------- BRANCH_VERSIONS = """ # Configuration for the branch versions, manually mapping tags based on branches # # Format is # # <branch-regex> <tag> <reference commit> # # The data is processed from top to bottom, the first matching line wins. # maintenance is currently the branch for preparation of maintenance release 1.10.0 # so are any fix/... and improve/... branches maintenance 1.10.0 cd955e9a46782119b36cc22b8dea5652ebbf9774 fix/.* 1.10.0 cd955e9a46782119b36cc22b8dea5652ebbf9774 improve/.* 1.10.0 cd955e9a46782119b36cc22b8dea5652ebbf9774 # staging/bugfix is the branch for preparation of the 1.10.x bugfix releases # so are any bug/... branches staging/bugfix 1.10.2 e18547582a7dcd381b600eb32822799c8bb238f9 bug/.* 1.10.2 e18547582a7dcd381b600eb32822799c8bb238f9 # staging/maintenance is currently the branch for preparation of 1.10.0rc5 # so is regressionfix/... staging/maintenance 1.10.0rc5 https://data.octoprint.org/#achievements regressionfix/.* 1.10.0rc5 https://data.octoprint.org/#achievements # staging/devel is currently inactive (but has the 1.4.1rc4 namespace) staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f # devel and dev/* are development branches and thus get resolved to 2.0.0.dev for now devel 2.0.0 2da7aa358d950b4567aaab8f18d6b5779193e077 dev/* 2.0.0 2da7aa358d950b4567aaab8f18d6b5779193e077 feature/* 2.0.0 2da7aa358d950b4567aaab8f18d6b5779193e077 """ # --------------------------------------------------------------------------------------- package_root = os.path.dirname(os.path.realpath(__file__)) package_name = os.path.basename(package_root) STATIC_FILE = "_static_version.py" STATIC_FILE_TEMPLATE = """ # This file has been generated by _version.py. version = "{version}" branch = "{branch}" revision = "{revision}" """.strip() FALLBACK = "0+unknown" FALLBACK_WITH_SHA = "0+unknown.g{short}" FALLBACK_DICT = { "version": FALLBACK, "branch": None, "revision": None, } PEP440_REGEX = re.compile( r""" ^\s* v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version \s*$ """, re.VERBOSE | re.IGNORECASE, ) # Taken from the sources of packaging.version, https://github.com/pypa/packaging/blob/21.3/packaging/version.py#L225-L254 _verbose = False def _git(*args, **kwargs): git = ["git"] if sys.platform == "win32": git = ["git.cmd", "git.exe"] cwd = kwargs.pop("cwd", None) if cwd is None: cwd = os.path.dirname(__file__) hide_stderr = kwargs.pop("hide_stderr", False) verbose = kwargs.pop("verbose", False) p = None for c in git: try: dispcmd = str([c] + list(args)) if verbose: print("trying %s" % dispcmd) p = subprocess.Popen( [c] + list(args), cwd=cwd, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), ) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None else: if verbose: print(f"unable to find command, tried {git}") return None stdout = p.communicate()[0].strip().decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) return None return stdout def _get_long(): return _git("rev-parse", "HEAD") def _get_short(): return _git("rev-parse", "--short", "HEAD") def _get_tag(): return _git("describe", "--tags", "--abbrev=0", "--always") def _get_branch(): return _git("rev-parse", "--abbrev-ref", "HEAD") def _get_dirty(): describe = _git("describe", "--tags", "--dirty", "--always") return describe is None or describe.endswith("-dirty") def _get_distance(ref): distance = _git("rev-list", f"{ref}..HEAD", "--count") if distance is None: return None try: return int(distance) except Exception: return None def _parse_branch_versions(): # parses rules for branches with virtual tags as defined in BRANCH_VERSIONS if not BRANCH_VERSIONS: return [] import re branch_versions = [] for line in BRANCH_VERSIONS.splitlines(): if "#" in line: line = line[: line.index("#")] line = line.strip() if not line: continue try: split_line = list(map(lambda x: x.strip(), line.split())) if not len(split_line): continue if len(split_line) != 3: continue matcher = re.compile(split_line[0]) branch_versions.append([matcher, split_line[1], split_line[2]]) except Exception: break return branch_versions def _validate_version(version): # validates a version string against PEP440 return PEP440_REGEX.search(version) is not None def _get_data_from_git(): # retrieves version info from git checkout, taking virtual tags into account branch = _get_branch() if _verbose: print(f"Branch: {branch}") is_dirty = _get_dirty() if _verbose: print(f"Dirty: {is_dirty}") # noqa: E241 sha = _get_long() if _verbose: print(f"SHA: {sha}") # noqa: E241 short = _get_short() if _verbose: print(f"Short: {short}") # noqa: E241 tag = _get_tag() distance = _get_distance(tag) template = "{tag}" dirty = "+g{short}.dirty" if branch is not None: lookup = _parse_branch_versions() for matcher, virtual_tag, ref_commit in lookup: if not matcher.match(branch): continue tag = virtual_tag distance = _get_distance(ref_commit) template = "{tag}.dev{distance}+g{short}" dirty = ".dirty" break if is_dirty: template += dirty vars = { "tag": tag, "distance": distance, "full": sha, "short": short, } if any([vars[x] is None and "{" + x + "}" in template for x in vars]): if short is None: template = FALLBACK else: template = FALLBACK_WITH_SHA if is_dirty: template += ".dirty" version = template.format(**vars) if not _validate_version(version): return None return { "version": version, "branch": branch, "revision": sha, } def _get_data_from_static_file(): # retrieves version info from _static_version.py data = {} with open(os.path.join(package_root, STATIC_FILE)) as f: exec(f.read(), {}, data) if data["version"] == "__use_git__": return None if not _validate_version(data["version"]): return None return data def _get_data_from_keywords(): # retrieves version info from expanded git keywords git_refnames = "$Format:%d$" git_full = "$Format:%H$" if git_refnames.startswith("$Format") or git_full.startswith("$Format"): # keywords not expanded, method not applicable return None refs = { r.strip()[8:] if r.strip().startswith("HEAD -> ") else r.strip() for r in git_refnames.strip().strip("()").split(",") } tags = {r[5:] for r in refs if r.startswith("tag: ")} if not tags: tags = {r for r in refs if re.search(r"\d", r)} tag = sorted(tags)[0] if tags else None branches = [ r for r in refs if not r.startswith("tag: ") and r != "HEAD" and not r.startswith("refs/") ] branch = branches[0] if branches else None if tag is None: template = FALLBACK_WITH_SHA else: template = "{tag}" version = template.format(short=git_full[:8], tag=tag) if not _validate_version(version): return None return { "version": version, "branch": branch, "revision": git_full, } def _write_static_file(path, data=None): # writes version data to _static_version.py if data is None: data = get_data() try: os.remove(path) except OSError: pass with open(path, "w") as f: f.write(STATIC_FILE_TEMPLATE.format(**data)) def get_data(): # returns version data for method in ( _get_data_from_static_file, _get_data_from_keywords, _get_data_from_git, ): data = method() if data is not None: return data return FALLBACK_DICT get_versions = get_data # compatibility layer for OctoPi's welcome banner def get_cmdclass(pkg_source_path): from setuptools import Command from setuptools.command.build_py import build_py as build_py_orig from setuptools.command.sdist import sdist as sdist_orig class _build_py(build_py_orig): def run(self): super().run() src_marker = "src" + os.path.sep if pkg_source_path.startswith(src_marker): path = pkg_source_path[len(src_marker) :] else: path = pkg_source_path _write_static_file(os.path.join(self.build_lib, path, STATIC_FILE)) class _sdist(sdist_orig): def make_release_tree(self, base_dir, files): super().make_release_tree(base_dir, files) _write_static_file(os.path.join(base_dir, pkg_source_path, STATIC_FILE)) class version(Command): description = "prints the version" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): print(get_data()["version"]) return dict(sdist=_sdist, build_py=_build_py, version=version) if __name__ == "__main__": _verbose = True print(get_data()["version"])
12,255
Python
.py
340
29.152941
121
0.598275
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,818
environment.py
OctoPrint_OctoPrint/src/octoprint/environment.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import copy import logging import os import sys import threading import psutil from octoprint.plugin import EnvironmentDetectionPlugin from octoprint.util import yaml from octoprint.util.platform import get_os from octoprint.util.version import get_python_version_string class EnvironmentDetector: def __init__(self, plugin_manager): self._plugin_manager = plugin_manager self._cache = None self._cache_lock = threading.RLock() self._logger = logging.getLogger(__name__) try: self._environment_plugins = self._plugin_manager.get_implementations( EnvironmentDetectionPlugin ) except Exception: # just in case, see #3100... self._logger.exception( "There was an error fetching EnvironmentDetectionPlugins from the plugin manager" ) self._environment_plugins = [] @property def environment(self): with self._cache_lock: if self._cache is None: self.run_detection() return copy.deepcopy(self._cache) def run_detection(self, notify_plugins=True): try: environment = {} environment["os"] = self._detect_os() environment["python"] = self._detect_python() environment["hardware"] = self._detect_hardware() plugin_result = self._detect_from_plugins() if plugin_result: environment["plugins"] = plugin_result with self._cache_lock: self._cache = environment if notify_plugins: self.notify_plugins() return environment except Exception: self._logger.exception("Unexpected error while detecting environment") with self._cache_lock: self._cache = {} return self._cache def _detect_os(self): return { "id": get_os(), "platform": sys.platform, "bits": 64 if sys.maxsize > 2**32 else 32, } def _detect_python(self): result = {"version": "unknown", "pip": "unknown"} # determine python version try: result["version"] = get_python_version_string() except Exception: self._logger.exception("Error detecting python version") # determine if we are running from a virtual environment try: if hasattr(sys, "real_prefix") or ( hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix) ): result["virtualenv"] = sys.prefix except Exception: self._logger.exception( "Error detecting whether we are running in a virtual environment" ) # try to find pip version try: import pkg_resources result["pip"] = pkg_resources.get_distribution("pip").version except Exception: self._logger.exception("Error detecting pip version") return result def _detect_hardware(self): result = {"cores": "unknown", "freq": "unknown", "ram": "unknown"} try: cores = psutil.cpu_count() cpu_freq = psutil.cpu_freq() ram = psutil.virtual_memory() if cores: result["cores"] = cores if cpu_freq and hasattr(cpu_freq, "max"): result["freq"] = cpu_freq.max if ram and hasattr(ram, "total"): result["ram"] = ram.total except Exception: self._logger.exception("Error while detecting hardware environment") return result def _detect_from_plugins(self): result = {} for implementation in self._environment_plugins: try: additional = implementation.get_additional_environment() if ( additional is not None and isinstance(additional, dict) and len(additional) ): result[implementation._identifier] = additional except Exception: self._logger.exception( "Error while fetching additional " "environment data from plugin {}".format(implementation._identifier), extra={"plugin": implementation._identifier}, ) return result def log_detected_environment(self, only_to_handler=None): def _log(message, level=logging.INFO): if only_to_handler is not None: import octoprint.logging octoprint.logging.log_to_handler( self._logger, only_to_handler, level, message, [] ) else: self._logger.log(level, message) try: _log(self._format()) except Exception: self._logger.exception("Error logging detected environment") def _format(self): with self._cache_lock: if self._cache is None: self.run_detection() environment = copy.deepcopy(self._cache) dumped_environment = yaml.dump(environment, pretty=True).strip() environment_lines = "\n".join( map(lambda x: f"| {x}", dumped_environment.split("\n")) ) return "Detected environment is Python {} under {} ({}). Details:\n{}".format( environment["python"]["version"], environment["os"]["id"].title(), environment["os"]["platform"], environment_lines, ) def notify_plugins(self): with self._cache_lock: if self._cache is None: self.run_detection(notify_plugins=False) environment = copy.deepcopy(self._cache) for implementation in self._environment_plugins: try: implementation.on_environment_detected(environment) except Exception: self._logger.exception( "Error while sending environment " "detection result to plugin {}".format(implementation._identifier) )
6,483
Python
.py
158
29.132911
103
0.572564
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,819
timelapse.py
OctoPrint_OctoPrint/src/octoprint/timelapse.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" import collections import datetime import fnmatch import glob import logging import os import queue import re import shutil import sys import threading import time import sarge import octoprint.plugin import octoprint.util as util from octoprint.events import Events, eventManager from octoprint.plugin import plugin_manager from octoprint.settings import settings from octoprint.util import get_fully_qualified_classname as fqcn from octoprint.util import sv from octoprint.util.commandline import CommandlineCaller from octoprint.webcams import WebcamNotAbleToTakeSnapshotException, get_snapshot_webcam # currently configured timelapse current = None # currently active render job, if any current_render_job = None # filename formats _capture_format = "{prefix}-{number}.jpg" _capture_glob = "{prefix}-*.jpg" _output_format = "{prefix}{postfix}.{extension}" # thumbnails _thumbnail_extension = ".thumb.jpg" _thumbnail_format = "{}.thumb.jpg" # ffmpeg progress regexes _ffmpeg_duration_regex = re.compile(r"Duration: (\d{2}):(\d{2}):(\d{2})\.\d{2}") _ffmpeg_current_regex = re.compile(r"time=(\d{2}):(\d{2}):(\d{2})\.\d{2}") # old capture format, needed to delete old left-overs from # versions <1.2.9 _old_capture_format_re = re.compile(r"^tmp_\d{5}.jpg$") # valid timelapses _valid_timelapse_types = ["off", "timed", "zchange"] # callbacks for timelapse config updates _update_callbacks = [] # lock for timelapse cleanup, must be re-entrant _cleanup_lock = threading.RLock() # lock for timelapse job _job_lock = threading.RLock() # cached valid timelapse extensions _extensions = None def create_thumbnail_path(movie_path): return _thumbnail_format.format(movie_path) def valid_timelapse(path): global _extensions if _extensions is None: # create list of extensions extensions = ["mpg", "mpeg", "mp4", "m4v", "mkv"] hooks = plugin_manager().get_hooks("octoprint.timelapse.extensions") for name, hook in hooks.items(): try: result = hook() if result is None or not isinstance(result, list): continue extensions += result except Exception: logging.getLogger(__name__).exception( "Exception while retrieving additional timelapse " "extensions from hook {name}".format(name=name), extra={"plugin": name}, ) _extensions = list(set(extensions)) return util.is_allowed_file(path, _extensions) def valid_timelapse_thumbnail(path): global _thumbnail_extensions # Thumbnail path is valid if it ends with thumbnail extension and path without extension is valid timelpase if path.endswith(_thumbnail_extension): return valid_timelapse(path[: -len(_thumbnail_extension)]) else: return False def _extract_prefix(filename): """ >>> _extract_prefix("some_long_filename_without_hyphen.jpg") >>> _extract_prefix("-first_char_is_hyphen.jpg") >>> _extract_prefix("some_long_filename_with-stuff.jpg") 'some_long_filename_with' """ pos = filename.rfind("-") if not pos or pos < 0: return None return filename[:pos] def last_modified_finished(): return os.stat(settings().getBaseFolder("timelapse", check_writable=False)).st_mtime def last_modified_unrendered(): return os.stat( settings().getBaseFolder("timelapse_tmp", check_writable=False) ).st_mtime def get_finished_timelapses(): files = [] basedir = settings().getBaseFolder("timelapse", check_writable=False) for entry in os.scandir(basedir): if util.is_hidden_path(entry.path) or not valid_timelapse(entry.path): continue thumb = create_thumbnail_path(entry.path) if os.path.isfile(thumb) is True: thumb = os.path.basename(thumb) else: thumb = None files.append( { "name": entry.name, "size": util.get_formatted_size(entry.stat().st_size), "bytes": entry.stat().st_size, "thumbnail": thumb, "timestamp": entry.stat().st_mtime, "date": util.get_formatted_datetime( datetime.datetime.fromtimestamp(entry.stat().st_mtime) ), } ) return files def get_unrendered_timelapses(): global _job_lock global current delete_old_unrendered_timelapses() basedir = settings().getBaseFolder("timelapse_tmp", check_writable=False) jobs = collections.defaultdict( lambda: {"count": 0, "size": None, "bytes": 0, "date": None, "timestamp": None} ) for entry in os.scandir(basedir): if not fnmatch.fnmatch(entry.name, "*.jpg"): continue prefix = _extract_prefix(entry.name) if prefix is None: continue jobs[prefix]["count"] += 1 jobs[prefix]["bytes"] += entry.stat().st_size if ( jobs[prefix]["timestamp"] is None or entry.stat().st_mtime < jobs[prefix]["timestamp"] ): jobs[prefix]["timestamp"] = entry.stat().st_mtime with _job_lock: global current_render_job def finalize_fields(prefix, job): currently_recording = current is not None and current.prefix == prefix currently_rendering = ( current_render_job is not None and current_render_job["prefix"] == prefix ) job["size"] = util.get_formatted_size(job["bytes"]) job["date"] = util.get_formatted_datetime( datetime.datetime.fromtimestamp(job["timestamp"]) ) job["recording"] = currently_recording job["rendering"] = currently_rendering job["processing"] = currently_recording or currently_rendering del job["timestamp"] return job return sorted( ( util.dict_merge({"name": key}, finalize_fields(key, value)) for key, value in jobs.items() ), key=lambda x: sv(x["name"]), ) def delete_unrendered_timelapse(name): global _cleanup_lock pattern = f"{glob.escape(name)}*.jpg" basedir = settings().getBaseFolder("timelapse_tmp") with _cleanup_lock: for entry in os.scandir(basedir): try: if fnmatch.fnmatch(entry.name, pattern): os.remove(entry.path) except Exception: if logging.getLogger(__name__).isEnabledFor(logging.DEBUG): logging.getLogger(__name__).exception( f"Error while processing file {entry.name} during cleanup" ) def render_unrendered_timelapse(name, gcode=None, postfix=None, fps=None): capture_dir = settings().getBaseFolder("timelapse_tmp") output_dir = settings().getBaseFolder("timelapse") watermark = settings().getBoolean(["webcam", "watermark"]) if fps is None: fps = settings().getInt(["webcam", "timelapse", "fps"]) threads = settings().get(["webcam", "ffmpegThreads"]) videocodec = settings().get(["webcam", "ffmpegVideoCodec"]) webcam = get_snapshot_webcam() if webcam is None: logging.getLogger(__name__).error("No webcam configured, can't render timelapse") else: job = TimelapseRenderJob( capture_dir, output_dir, name, postfix=postfix, fps=fps, threads=threads, videocodec=videocodec, watermark=watermark, flipH=webcam.config.flipH, flipV=webcam.config.flipV, rotate=webcam.config.rotate90, on_start=_create_render_start_handler(name, gcode=gcode), on_success=_create_render_success_handler(name, gcode=gcode), on_fail=_create_render_fail_handler(name, gcode=gcode), on_always=_create_render_always_handler(name, gcode=gcode), ) job.process() def delete_old_unrendered_timelapses(): global _cleanup_lock basedir = settings().getBaseFolder("timelapse_tmp") clean_after_days = settings().getInt(["webcam", "cleanTmpAfterDays"]) cutoff = time.time() - clean_after_days * 24 * 60 * 60 prefixes_to_clean = [] with _cleanup_lock: for entry in os.scandir(basedir): try: prefix = _extract_prefix(entry.name) if prefix is None: # might be an old tmp_00000.jpg kinda frame. we can't # render those easily anymore, so delete that stuff if _old_capture_format_re.match(entry.name): os.remove(entry.path) continue if prefix in prefixes_to_clean: continue # delete if both creation and modification time are older than the cutoff if max(entry.stat().st_ctime, entry.stat().st_mtime) < cutoff: prefixes_to_clean.append(prefix) except Exception: if logging.getLogger(__name__).isEnabledFor(logging.DEBUG): logging.getLogger(__name__).exception( f"Error while processing file {entry.name} during cleanup" ) for prefix in prefixes_to_clean: delete_unrendered_timelapse(prefix) logging.getLogger(__name__).info(f"Deleted old unrendered timelapse {prefix}") def _create_render_start_handler(name, gcode=None): def f(movie): global _job_lock with _job_lock: global current_render_job payload = { "gcode": gcode if gcode is not None else "unknown", "movie": movie, "movie_basename": os.path.basename(movie), "movie_prefix": name, } current_render_job = {"prefix": name} current_render_job.update(payload) eventManager().fire(Events.MOVIE_RENDERING, payload) return f def _create_render_success_handler(name, gcode=None): def f(movie): delete_unrendered_timelapse(name) payload = { "gcode": gcode if gcode is not None else "unknown", "movie": movie, "movie_basename": os.path.basename(movie), "movie_prefix": name, } eventManager().fire(Events.MOVIE_DONE, payload) return f def _create_render_fail_handler(name, gcode=None): def f( movie, returncode=255, stdout="Unknown error", stderr="Unknown error", reason="unknown", ): payload = { "gcode": gcode if gcode is not None else "unknown", "movie": movie, "movie_basename": os.path.basename(movie), "movie_prefix": name, "returncode": returncode, "out": stdout, "error": stderr, "reason": reason, } eventManager().fire(Events.MOVIE_FAILED, payload) return f def _create_render_always_handler(name, gcode=None): def f(movie): global current_render_job global _job_lock with _job_lock: current_render_job = None return f def register_callback(callback): if callback not in _update_callbacks: _update_callbacks.append(callback) def unregister_callback(callback): try: _update_callbacks.remove(callback) except ValueError: # not registered pass def notify_callbacks(timelapse): if timelapse is None: config = None else: config = timelapse.config_data() for callback in _update_callbacks: notify_callback(callback, config) def notify_callback(callback, config=None, timelapse=None): if config is None and timelapse is not None: config = timelapse.config_data() try: callback.sendTimelapseConfig(config) except Exception: logging.getLogger(__name__).exception( "Exception while pushing timelapse configuration", extra={"callback": fqcn(callback)}, ) def configure_timelapse(config=None, persist=False): global current if config is None: config = settings().get(["webcam", "timelapse"], merged=True) if current is not None: current.unload() snapshot_webcam = get_snapshot_webcam() can_snapshot = ( snapshot_webcam.config.canSnapshot if snapshot_webcam is not None else False ) ffmpeg_path = settings().get(["webcam", "ffmpeg"]) timelapse_enabled = settings().getBoolean(["webcam", "timelapseEnabled"]) timelapse_precondition = ( can_snapshot is True and ffmpeg_path is not None and ffmpeg_path.strip() != "" ) type = config["type"] if not timelapse_precondition and timelapse_precondition: logging.getLogger(__name__).warning( "Essential timelapse settings unconfigured (snapshot URL or FFMPEG path) " "but timelapse enabled." ) if ( not timelapse_enabled or not timelapse_precondition or type is None or "off" == type ): current = None else: postRoll = 0 if "postRoll" in config and config["postRoll"] >= 0: postRoll = config["postRoll"] fps = 25 if "fps" in config and config["fps"] > 0: fps = config["fps"] if "zchange" == type: retractionZHop = 0 if ( "options" in config and "retractionZHop" in config["options"] and config["options"]["retractionZHop"] >= 0 ): retractionZHop = config["options"]["retractionZHop"] minDelay = 5 if ( "options" in config and "minDelay" in config["options"] and config["options"]["minDelay"] > 0 ): minDelay = config["options"]["minDelay"] current = ZTimelapse( post_roll=postRoll, retraction_zhop=retractionZHop, min_delay=minDelay, fps=fps, ) elif "timed" == type: interval = 10 if ( "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0 ): interval = config["options"]["interval"] current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps) notify_callbacks(current) if persist: settings().set(["webcam", "timelapse"], config) settings().save() class Timelapse: QUEUE_ENTRY_TYPE_CAPTURE = "capture" QUEUE_ENTRY_TYPE_CALLBACK = "callback" def __init__(self, post_roll=0, fps=25): self._logger = logging.getLogger(__name__) self._image_number = None self._in_timelapse = False self._gcode_file = None self._file_prefix = None self._capture_errors = 0 self._capture_success = 0 self._post_roll = post_roll self._on_post_roll_done = None self._webcam = get_snapshot_webcam() if self._webcam is None: raise Exception("Invalid webcam configuration, missing defaultWebcam") elif self._webcam.config.canSnapshot is False: raise WebcamNotAbleToTakeSnapshotException(self._webcam.webcam.name) self._capture_dir = settings().getBaseFolder("timelapse_tmp") self._movie_dir = settings().getBaseFolder("timelapse") 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 self._capture_queue_thread = threading.Thread(target=self._capture_queue_worker) self._capture_queue_thread.daemon = True self._capture_queue_thread.start() # subscribe events eventManager().subscribe(Events.PRINT_STARTED, self.on_print_started) eventManager().subscribe(Events.PRINT_FAILED, self.on_print_done) eventManager().subscribe(Events.PRINT_DONE, self.on_print_done) eventManager().subscribe(Events.PRINT_RESUMED, self.on_print_resumed) for event, callback in self.event_subscriptions(): eventManager().subscribe(event, callback) @property def prefix(self): return self._file_prefix @property def post_roll(self): return self._post_roll @property def fps(self): return self._fps def unload(self): if self._in_timelapse: self.stop_timelapse(do_create_movie=False) # unsubscribe events eventManager().unsubscribe(Events.PRINT_STARTED, self.on_print_started) eventManager().unsubscribe(Events.PRINT_FAILED, self.on_print_done) eventManager().unsubscribe(Events.PRINT_DONE, self.on_print_done) eventManager().unsubscribe(Events.PRINT_RESUMED, self.on_print_resumed) for event, callback in self.event_subscriptions(): eventManager().unsubscribe(event, callback) def on_print_started(self, event, payload): """ Override this to perform additional actions upon start of a print job. """ self.start_timelapse(payload["name"]) def on_print_done(self, event, payload): """ Override this to perform additional actions upon the stop of a print job. """ self.stop_timelapse(success=(event == Events.PRINT_DONE)) def on_print_resumed(self, event, payload): """ Override this to perform additional actions upon the pausing of a print job. """ if not self._in_timelapse: self.start_timelapse(payload["name"]) def event_subscriptions(self): """ Override this method to subscribe to additional events by returning an array of (event, callback) tuples. Events that are already subscribed: * PrintStarted - self.onPrintStarted * PrintResumed - self.onPrintResumed * PrintFailed - self.onPrintDone * PrintDone - self.onPrintDone """ return [] def config_data(self): """ Override this method to return the current timelapse configuration data. The data should have the following form: type: "<type of timelapse>", options: { <additional options> } """ return None def start_timelapse(self, gcode_file): self._logger.debug(f"Starting timelapse for {gcode_file}") self._image_number = 0 self._capture_errors = 0 self._capture_success = 0 self._in_timelapse = True self._gcode_file = os.path.basename(gcode_file) self._file_prefix = "{}_{}".format( os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S"), ) def stop_timelapse(self, do_create_movie=True, success=True): self._logger.debug("Stopping timelapse") self._in_timelapse = False def reset_image_number(): self._image_number = None def create_movie(): render_unrendered_timelapse( self._file_prefix, gcode=self._gcode_file, postfix=None if success else "-fail", fps=self._fps, ) def reset_and_create(): reset_image_number() create_movie() def wait_for_captures(callback): self._capture_queue.put( {"type": self.__class__.QUEUE_ENTRY_TYPE_CALLBACK, "callback": callback} ) def create_wait_for_captures(callback): def f(): wait_for_captures(callback) return f # wait for everything so far in the queue to be processed, then see if we should process from there def continue_rendering(): if self._capture_success == 0: # no images - either nothing was attempted to be captured or all attempts ran into an error if self._capture_errors > 0: # this is the latter case _create_render_fail_handler( self._file_prefix, gcode=self._gcode_file )("n/a", returncode=0, stdout="", stderr="", reason="no_frames") # in any case, don't continue return # check if we have post roll configured if self._post_roll > 0: # capture post roll, wait for THAT to finish, THEN render eventManager().fire( Events.POSTROLL_START, { "postroll_duration": self.calculate_post_roll(), "postroll_length": self.post_roll, "postroll_fps": self.fps, }, ) if do_create_movie: self._on_post_roll_done = create_wait_for_captures(reset_and_create) else: self._on_post_roll_done = reset_image_number self.process_post_roll() else: # no post roll? perfect, render if do_create_movie: wait_for_captures(reset_and_create) else: reset_image_number() self._logger.debug("Waiting to process capture queue") wait_for_captures(continue_rendering) def calculate_post_roll(self): return None def process_post_roll(self): self.post_roll_finished() def post_roll_finished(self): if self.post_roll: eventManager().fire(Events.POSTROLL_END) if self._on_post_roll_done is not None: self._on_post_roll_done() def capture_image(self): if self._capture_dir is None: self._logger.warning("Cannot capture image, capture directory is unset") return with self._capture_mutex: if self._image_number is None: self._logger.warning("Cannot capture image, image number is unset") return filename = os.path.join( self._capture_dir, _capture_format.format( prefix=self._file_prefix, number=self._image_number ), ) self._image_number += 1 self._logger.debug(f"Capturing image to {filename}") entry = { "type": self.__class__.QUEUE_ENTRY_TYPE_CAPTURE, "filename": filename, "onerror": self._on_capture_error, } self._capture_queue.put(entry) return filename def _on_capture_error(self): with self._capture_mutex: if self._image_number is not None and self._image_number > 0: self._image_number -= 1 def _capture_queue_worker(self): while self._capture_queue_active: try: entry = self._capture_queue.get(block=True) if ( entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CAPTURE and "filename" in entry ): filename = entry["filename"] onerror = entry.pop("onerror", None) self._perform_capture(filename, onerror=onerror) elif ( entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CALLBACK and "callback" in entry ): args = entry.pop("args", []) kwargs = entry.pop("kwargs", {}) entry["callback"](*args, **kwargs) except Exception: self._logger.exception( "Caught unhandled exception in timelapse queue worker" ) def _perform_capture(self, filename, onerror=None): # pre-capture hook for name, hook in self._pre_capture_hooks.items(): try: hook(filename) except Exception: self._logger.exception(f"Error while processing hook {name}.") eventManager().fire(Events.CAPTURE_START, {"file": filename}) try: self._logger.debug( f"Going to capture {filename} from {self._webcam.config.name} provided by {self._webcam.providerIdentifier}" ) snapshot = self._webcam.providerPlugin.take_webcam_snapshot(self._webcam) with open(filename, "wb") as f: for chunk in snapshot: if chunk: f.write(chunk) f.flush() self._logger.debug( f"Image {filename} captured from {self._webcam.config.name} provided by {self._webcam.providerIdentifier}" ) except Exception as e: self._logger.exception( f"Could not capture image {filename} from {self._webcam.config.name} provided by {self._webcam.providerIdentifier}" ) self._capture_errors += 1 err = e else: self._capture_success += 1 err = None # post-capture hook for name, hook in self._post_capture_hooks.items(): try: hook(filename, err is None) except Exception: self._logger.exception(f"Error while processing hook {name}.") # handle events and onerror call if err is None: eventManager().fire(Events.CAPTURE_DONE, {"file": filename}) return True else: if callable(onerror): onerror() eventManager().fire( Events.CAPTURE_FAILED, { "file": filename, "error": str(err), "webcamDisplay": self._webcam.config.displayName, "snapshotDisplay": self._webcam.config.snapshotDisplay, "webcamProvider": self._webcam.providerIdentifier, }, ) return False def _copying_postroll(self): with self._capture_mutex: filename = os.path.join( self._capture_dir, _capture_format.format( prefix=self._file_prefix, number=self._image_number ), ) self._image_number += 1 if self._perform_capture(filename): for _ in range(self._post_roll * self._fps): newFile = os.path.join( self._capture_dir, _capture_format.format( prefix=self._file_prefix, number=self._image_number ), ) self._image_number += 1 shutil.copyfile(filename, newFile) def clean_capture_dir(self): if not os.path.isdir(self._capture_dir): self._logger.warning("Cannot clean capture directory, it is unset") return delete_unrendered_timelapse(self._file_prefix) class ZTimelapse(Timelapse): def __init__(self, retraction_zhop=0, min_delay=5.0, post_roll=0, fps=25): Timelapse.__init__(self, post_roll=post_roll, fps=fps) if min_delay < 0: min_delay = 0 self._retraction_zhop = retraction_zhop self._min_delay = min_delay self._last_snapshot = None self._logger.debug("ZTimelapse initialized") @property def retraction_zhop(self): return self._retraction_zhop @property def min_delay(self): return self._min_delay def event_subscriptions(self): return [(Events.Z_CHANGE, self._on_z_change)] def config_data(self): return {"type": "zchange", "options": {"retractionZHop": self._retraction_zhop}} def process_post_roll(self): # we always copy the final image for the whole post roll # for z based timelapses self._copying_postroll() Timelapse.process_post_roll(self) def _on_z_change(self, event, payload): # check if height difference equals z-hop, if so don't take a picture if ( self._retraction_zhop != 0 and payload["old"] is not None and payload["new"] is not None ): diff = round(abs(payload["new"] - payload["old"]), 3) zhop = round(self._retraction_zhop, 3) if diff == zhop: return # check if last picture has been less than min_delay ago, if so don't take a picture (anti vase mode...) now = time.monotonic() if ( self._min_delay and self._last_snapshot and self._last_snapshot + self._min_delay > now ): self._logger.debug("Rate limited z-change, not taking a snapshot") return self.capture_image() self._last_snapshot = now class TimedTimelapse(Timelapse): def __init__(self, interval=1, post_roll=0, fps=25): Timelapse.__init__(self, post_roll=post_roll, fps=fps) self._interval = interval if self._interval < 1: self._interval = 1 # force minimum interval of 1s self._timer = None self._logger.debug("TimedTimelapse initialized") @property def interval(self): return self._interval def config_data(self): return {"type": "timed", "options": {"interval": self._interval}} def on_print_started(self, event, payload): Timelapse.on_print_started(self, event, payload) if self._timer is not None: return self._logger.debug("Starting timer for interval based timelapse") from octoprint.util import RepeatedTimer self._timer = RepeatedTimer( self._interval, self._timer_task, run_first=True, condition=self._timer_active, on_finish=self._on_timer_finished, ) self._timer.start() def process_post_roll(self): # we only use the final image as post roll self._copying_postroll() self.post_roll_finished() def _timer_active(self): return self._in_timelapse def _timer_task(self): self.capture_image() def _on_timer_finished(self): # timer is done, delete it self._timer = None class TimelapseRenderJob: render_job_lock = threading.RLock() def __init__( self, capture_dir, output_dir, prefix, postfix=None, capture_glob=_capture_glob, capture_format=_capture_format, output_format=_output_format, flipH=False, flipV=False, rotate=False, watermark=False, fps=25, threads=1, videocodec="mpeg2video", on_start=None, on_success=None, on_fail=None, on_always=None, ): self._capture_dir = capture_dir self._output_dir = output_dir self._prefix = prefix self._postfix = postfix self._capture_glob = capture_glob self._capture_format = capture_format self._output_format = output_format self._fps = fps self._threads = threads self._videocodec = videocodec self._on_start = on_start self._on_success = on_success self._on_fail = on_fail self._on_always = on_always self._hflip = flipH self._vflip = flipV self._rotate = rotate self._watermark = watermark self._thread = None self._logger = logging.getLogger(__name__) self._parsed_duration = 0 def process(self): """Processes the job.""" self._thread = threading.Thread( target=self._render, name="TimelapseRenderJob_{prefix}_{postfix}".format( prefix=self._prefix, postfix=self._postfix ), ) self._thread.daemon = True self._thread.start() def _render(self): """Rendering runnable.""" ffmpeg = settings().get(["webcam", "ffmpeg"]) commandline = settings().get(["webcam", "ffmpegCommandline"]) bitrate = settings().get(["webcam", "bitrate"]) if ffmpeg is None or bitrate is None: self._logger.warning( "Cannot create movie, path to ffmpeg or desired bitrate is unset" ) return if self._videocodec == "mpeg2video": extension = "mpg" else: extension = "mp4" # input pattern for ffmpeg input = os.path.join( self._capture_dir, self._capture_format.format( prefix=self._prefix.replace( "%", "%%" ), # ffmpeg, and ONLY that, needs % replaced postfix=self._postfix if self._postfix is not None else "", number="%d", ), ) # pattern for checking if snapshots were made at all snapshot = os.path.join( self._capture_dir, self._capture_format.format( prefix=self._prefix, postfix=self._postfix if self._postfix is not None else "", number="{number}", ), ) # output file name output_name = self._output_format.format( prefix=self._prefix, postfix=self._postfix if self._postfix is not None else "", extension=extension, ) temporary = os.path.join(self._output_dir, f".{output_name}") output = os.path.join(self._output_dir, output_name) for i in range(4): if os.path.exists(snapshot.format(number=i)): break else: self._logger.warning("Cannot create a movie, no frames captured") self._notify_callback( "fail", output, returncode=0, stdout="", stderr="", reason="no_frames" ) return watermark = None if self._watermark: watermark = os.path.join( os.path.dirname(__file__), "static", "img", "watermark.png" ) if sys.platform == "win32": # Because ffmpeg hiccups on windows' drive letters and backslashes we have to give the watermark # path a special treatment. Yeah, I couldn't believe it either... watermark = watermark.replace("\\", "/").replace(":", "\\\\:") # prepare ffmpeg command command_str = self._create_ffmpeg_command_string( commandline, ffmpeg, self._fps, bitrate, self._threads, input, temporary, self._videocodec, hflip=self._hflip, vflip=self._vflip, rotate=self._rotate, watermark=watermark, ) self._logger.debug(f"Executing command: {command_str}") with self.render_job_lock: try: self._notify_callback("start", output) self._logger.debug("Parsing ffmpeg output") c = CommandlineCaller() c.on_log_stderr = self._process_ffmpeg_output returncode, stdout_text, stderr_text = c.call( command_str, delimiter=b"\r", buffer_size=512 ) self._logger.debug("Done with parsing") if returncode == 0: shutil.move(temporary, output) self._try_generate_thumbnail( ffmpeg=ffmpeg, movie_path=output, ) self._notify_callback("success", output) else: self._logger.warning( "Could not render movie, got return code %r: %s" % (returncode, stderr_text) ) self._notify_callback( "fail", output, returncode=returncode, stdout=stdout_text, stderr=stderr_text, reason="returncode", ) except Exception: self._logger.exception("Could not render movie due to unknown error") self._notify_callback("fail", output, reason="unknown") finally: try: if os.path.exists(temporary): os.remove(temporary) except Exception: self._logger.warning( f"Could not delete temporary timelapse {temporary}" ) self._notify_callback("always", output) def _process_ffmpeg_output(self, *lines): for line in lines: # We should be getting the time more often, so try it first current_time = _ffmpeg_current_regex.search(line) if current_time is not None and self._parsed_duration != 0: current_s = self._convert_time(*current_time.groups()) progress = current_s / self._parsed_duration * 100 # Update progress bar for callback in _update_callbacks: try: callback.sendRenderProgress(progress) except Exception: self._logger.exception("Exception while pushing render progress") else: duration = _ffmpeg_duration_regex.search(line) if duration is not None: self._parsed_duration = self._convert_time(*duration.groups()) @classmethod def _try_generate_thumbnail(cls, ffmpeg, movie_path): logger = logging.getLogger(__name__) try: thumb_path = create_thumbnail_path(movie_path) commandline = settings().get(["webcam", "ffmpegThumbnailCommandline"]) thumb_command_str = cls._create_ffmpeg_command_string( commandline=commandline, ffmpeg=ffmpeg, input=movie_path, output=thumb_path, fps=None, videocodec=None, threads=None, bitrate=None, ) c = CommandlineCaller() returncode, stdout_text, stderr_text = c.call( thumb_command_str, delimiter=b"\r", buffer_size=512 ) if returncode != 0: logger.warning( "Failed to generate optional thumbnail %r: %s" % (returncode, stderr_text) ) return True except Exception as ex: logger.warning( "Failed to generate thumbnail from {} to {} ({})".format( movie_path, thumb_path, ex ) ) return False @staticmethod def _convert_time(hours, minutes, seconds): return (int(hours) * 60 + int(minutes)) * 60 + int(seconds) @classmethod def _create_ffmpeg_command_string( cls, commandline, ffmpeg, fps, bitrate, threads, input, output, videocodec, hflip=False, vflip=False, rotate=False, watermark=None, pixfmt="yuv420p", ): """ Create ffmpeg command string based on input parameters. Arguments: commandline (str): Command line template to use ffmpeg (str): Path to ffmpeg fps (int): Frames per second for output bitrate (str): Bitrate of output threads (int): Number of threads to use for rendering videocodec (str): Videocodec to be used for encoding input (str): Absolute path to input files including file mask output (str): Absolute path to output file hflip (bool): Perform horizontal flip on input material. vflip (bool): Perform vertical flip on input material. rotate (bool): Perform 90° CCW rotation on input material. watermark (str): Path to watermark to apply to lower left corner. pixfmt (str): Pixel format to use for output. Default of yuv420p should usually fit the bill. Returns: (str): Prepared command string to render `input` to `output` using ffmpeg. """ ### See unit tests in test/timelapse/test_timelapse_renderjob.py logger = logging.getLogger(__name__) ### Not all players can handle non-mpeg2 in VOB format if not videocodec: videocodec = "libx264" if videocodec == "mpeg2video": containerformat = "vob" else: containerformat = "mp4" filter_string = cls._create_filter_string( hflip=hflip, vflip=vflip, rotate=rotate, watermark=watermark ) placeholders = { "ffmpeg": ffmpeg, "fps": str(fps if fps else "25"), "input": input, "output": output, "videocodec": videocodec, "threads": str(threads if threads else "1"), "bitrate": str(bitrate if bitrate else "10000k"), "containerformat": containerformat, "filters": ("-vf " + sarge.shell_quote(filter_string)) if filter_string else "", } logger.debug(f"Rendering movie to {output}") return commandline.format(**placeholders) @classmethod def _create_filter_string( cls, hflip=False, vflip=False, rotate=False, watermark=None, pixfmt="yuv420p" ): """ Creates an ffmpeg filter string based on input parameters. Arguments: hflip (bool): Perform horizontal flip on input material. vflip (bool): Perform vertical flip on input material. rotate (bool): Perform 90° CCW rotation on input material. watermark (str): Path to watermark to apply to lower left corner. pixfmt (str): Pixel format to use, defaults to "yuv420p" which should usually fit the bill Returns: (str or None): filter string or None if no filters are required """ ### See unit tests in test/timelapse/test_timelapse_renderjob.py # apply pixel format filters = [f"format={pixfmt}"] # flip video if configured if hflip: filters.append("hflip") if vflip: filters.append("vflip") if rotate: filters.append("transpose=2") # add watermark if configured watermark_filter = None if watermark is not None: watermark_filter = "movie={} [wm]; [{{input_name}}][wm] overlay=10:main_h-overlay_h-10".format( watermark ) filter_string = None if len(filters) > 0: if watermark_filter is not None: filter_string = "[in] {} [postprocessed]; {} [out]".format( ",".join(filters), watermark_filter.format(input_name="postprocessed") ) else: filter_string = "[in] {} [out]".format(",".join(filters)) elif watermark_filter is not None: filter_string = watermark_filter.format(input_name="in") + " [out]" return filter_string def _notify_callback(self, callback, *args, **kwargs): """Notifies registered callbacks of type `callback`.""" name = f"_on_{callback}" method = getattr(self, name, None) if method is not None and callable(method): method(*args, **kwargs)
44,603
Python
.py
1,105
29.086878
131
0.573413
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,820
daemon.py
OctoPrint_OctoPrint/src/octoprint/daemon.py
""" Generic linux daemon base class Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35 """ import os import signal import sys import time class Daemon: """ A generic daemon class. Usage: subclass the daemon class and override the run() method. If you want to log the output to someplace different that stdout and stderr, also override the echo() and error() methods. """ def __init__(self, pidfile): self.pidfile = pidfile def _daemonize(self): """Daemonize class. UNIX double fork mechanism.""" self._double_fork() self._redirect_io() # write pidfile pid = str(os.getpid()) self.set_pid(pid) def _double_fork(self): try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError as err: self.error(f"First fork failed: {str(err)}") sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0o002) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError as err: self.error(f"Second fork failed: {str(err)}") sys.exit(1) def _redirect_io(self): # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() si = open(os.devnull, encoding="utf-8") so = open(os.devnull, "a+", encoding="utf-8") se = open(os.devnull, "a+", encoding="utf-8") os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) def terminated(self): self.remove_pidfile() def start(self): """Start the daemon.""" # Check for a pidfile to see if the daemon already runs pid = self.get_pid() if pid: self.error( "pidfile {} already exist. Is the daemon already running?".format( self.pidfile ) ) sys.exit(1) self.echo("Starting daemon...") # Start the daemon self._daemonize() self.run() def stop(self, check_running=True): """Stop the daemon.""" pid = self.get_pid() if not pid: if not check_running: return self.error( "pidfile {} does not exist. Is the daemon really running?".format( self.pidfile ) ) sys.exit(1) self.echo("Stopping daemon...") # Try killing the daemon process try: while 1: os.kill(pid, signal.SIGTERM) time.sleep(0.1) except OSError as err: e = str(err.args) if e.find("No such process") > 0: self.remove_pidfile() else: self.error(e) sys.exit(1) def restart(self): """Restart the daemon.""" self.stop(check_running=False) self.start() def status(self): """Prints the daemon status.""" if self.is_running(): self.echo("Daemon is running") else: self.echo("Daemon is not running") def is_running(self): """Check if a process is running under the specified pid.""" pid = self.get_pid() if pid is None: return False try: os.kill(pid, 0) except OSError: try: self.remove_pidfile() except Exception: self.error("Daemon found not running, but could not remove stale pidfile") return False else: return True def get_pid(self): """Get the pid from the pidfile.""" try: with open(self.pidfile, encoding="utf-8") as pf: pid = int(pf.read().strip()) except (OSError, ValueError): pid = None return pid def set_pid(self, pid): """Write the pid to the pidfile.""" with open(self.pidfile, "w+", encoding="utf-8") as f: f.write(str(pid) + "\n") def remove_pidfile(self): """Removes the pidfile.""" if os.path.isfile(self.pidfile): os.remove(self.pidfile) def run(self): """You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart().""" raise NotImplementedError() @classmethod def echo(cls, line): print(line) @classmethod def error(cls, line): print(line, file=sys.stderr)
4,891
Python
.py
150
22.6
95
0.537824
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,821
__init__.py
OctoPrint_OctoPrint/src/octoprint/__init__.py
#!/usr/bin/env python import logging as log import os import sys from ._version import get_data as get_version_data # ~~ version version_data = get_version_data() __version__ = version_data["version"] __branch__ = version_data["branch"] __display_version__ = __version__ __revision__ = version_data["revision"] del version_data del get_version_data # figure out current umask - sadly only doable by setting a new one and resetting it, no query method UMASK = os.umask(0) os.umask(UMASK) urllib3_ssl = True """Whether requests/urllib3 and urllib3 (if installed) should be able to establish a sound SSL environment or not.""" version_info = sys.version_info if version_info.major == 3 and version_info.minor >= 8 and sys.platform == "win32": # Python 3.8 makes proactor event loop the default on Windows, Tornado doesn't like that # # see https://github.com/tornadoweb/tornado/issues/2608 import asyncio asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) del version_info # ~~ custom exceptions class FatalStartupError(Exception): def __init__(self, message, cause=None): self.cause = cause Exception.__init__(self, message) def __str__(self): result = Exception.__str__(self) if self.cause: return f"{result}: {str(self.cause)}" else: return result # ~~ init methods to bring up platform def init_platform( basedir, configfile, overlays=None, use_logging_file=True, logging_file=None, logging_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None, disable_color=True, safe_mode=False, ignore_blacklist=False, after_preinit_logging=None, after_settings_init=None, after_logging=None, after_safe_mode=None, after_settings_valid=None, after_event_manager=None, after_connectivity_checker=None, after_plugin_manager=None, after_environment_detector=None, ): kwargs = {} logger, recorder = preinit_logging( debug, verbosity, uncaught_logger, uncaught_handler ) kwargs["logger"] = logger kwargs["recorder"] = recorder if callable(after_preinit_logging): after_preinit_logging(**kwargs) try: settings = init_settings(basedir, configfile, overlays=overlays) except Exception as ex: raise FatalStartupError("Could not initialize settings manager", cause=ex) kwargs["settings"] = settings if callable(after_settings_init): after_settings_init(**kwargs) try: logger = init_logging( settings, use_logging_file=use_logging_file, logging_file=logging_file, default_config=logging_config, debug=debug, verbosity=verbosity, uncaught_logger=uncaught_logger, uncaught_handler=uncaught_handler, disable_color=disable_color, ) except Exception as ex: raise FatalStartupError("Could not initialize logging", cause=ex) kwargs["logger"] = logger if callable(after_logging): after_logging(**kwargs) settings_start_once_in_safemode = ( "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None ) settings_incomplete_startup_safemode = ( "incomplete_startup" if os.path.exists(os.path.join(settings._basedir, ".incomplete_startup")) and not settings.getBoolean(["server", "ignoreIncompleteStartup"]) else None ) safe_mode = ( safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode ) kwargs["safe_mode"] = safe_mode if callable(after_safe_mode): after_safe_mode(**kwargs) # now before we continue, let's make sure *all* our folders are sane try: settings.sanity_check_folders() except Exception as ex: raise FatalStartupError("Configured folders didn't pass sanity check", cause=ex) if callable(after_settings_valid): after_settings_valid(**kwargs) try: event_manager = init_event_manager(settings) except Exception as ex: raise FatalStartupError("Could not initialize event manager", cause=ex) kwargs["event_manager"] = event_manager if callable(after_event_manager): after_event_manager(**kwargs) try: connectivity_checker = init_connectivity_checker(settings, event_manager) except Exception as ex: raise FatalStartupError("Could not initialize connectivity checker", cause=ex) kwargs["connectivity_checker"] = connectivity_checker if callable(after_connectivity_checker): after_connectivity_checker(**kwargs) try: plugin_manager = init_pluginsystem( settings, safe_mode=safe_mode, ignore_blacklist=ignore_blacklist, connectivity_checker=connectivity_checker, ) except Exception as ex: raise FatalStartupError("Could not initialize plugin manager", cause=ex) kwargs["plugin_manager"] = plugin_manager if callable(after_plugin_manager): after_plugin_manager(**kwargs) try: environment_detector = init_environment_detector(plugin_manager) except Exception as ex: raise FatalStartupError("Could not initialize environment detector", cause=ex) kwargs["environment_detector"] = environment_detector if callable(after_environment_detector): after_environment_detector(**kwargs) return ( settings, logger, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector, ) def init_settings(basedir, configfile, overlays=None): """Inits the settings instance based on basedir and configfile to use.""" from octoprint.settings import InvalidSettings, settings try: return settings( init=True, basedir=basedir, configfile=configfile, overlays=overlays ) except InvalidSettings as e: raise FatalStartupError(str(e)) def preinit_logging( debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None ): config = { "version": 1, "formatters": { "simple": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"} }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "simple", "stream": "ext://sys.stdout", } }, "loggers": { "octoprint": {"level": "DEBUG" if debug else "INFO"}, "octoprint.util": {"level": "INFO"}, }, "root": {"level": "WARN", "handlers": ["console"]}, } logger = set_logging_config( config, debug, verbosity, uncaught_logger, uncaught_handler ) from octoprint.logging.handlers import RecordingLogHandler recorder = RecordingLogHandler(level=log.DEBUG) log.getLogger().addHandler(recorder) return logger, recorder def init_logging( settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None, disable_color=True, ): """Sets up logging.""" import os from octoprint.util import dict_merge # default logging configuration if default_config is None: simple_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" date_format = "%Y-%m-%d %H:%M:%S" default_config = { "version": 1, "formatters": { "simple": {"format": simple_format}, "colored": { "()": "colorlog.ColoredFormatter", "format": "%(log_color)s" + simple_format + "%(reset)s", "reset": True, "log_colors": { "DEBUG": "cyan", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "bold_red", }, }, "serial": {"format": "%(asctime)s - %(message)s"}, "tornado": { "()": "tornado.log.LogFormatter", "color": False, "format": simple_format, "datefmt": date_format, }, "auth": {"format": "%(asctime)s - %(message)s"}, "timings": {"format": "%(asctime)s - %(message)s"}, "timingscsv": {"format": "%(asctime)s;%(func)s;%(timing)f"}, }, "handlers": { "console": { "class": "octoprint.logging.handlers.OctoPrintStreamHandler", "level": "DEBUG", "formatter": "simple" if disable_color else "colored", "stream": "ext://sys.stdout", }, "file": { "class": "octoprint.logging.handlers.OctoPrintLogHandler", "level": "DEBUG", "formatter": "simple", "when": "D", "backupCount": 6, "filename": os.path.join( settings.getBaseFolder("logs"), "octoprint.log" ), }, "serialFile": { "class": "octoprint.logging.handlers.SerialLogHandler", "level": "DEBUG", "formatter": "serial", "backupCount": 3, "filename": os.path.join( settings.getBaseFolder("logs"), "serial.log" ), "delay": True, }, "tornadoFile": { "class": "octoprint.logging.handlers.TornadoLogHandler", "level": "DEBUG", "formatter": "tornado", "when": "D", "backupCount": 1, "filename": os.path.join( settings.getBaseFolder("logs"), "tornado.log" ), }, "authFile": { "class": "octoprint.logging.handlers.AuthLogHandler", "level": "DEBUG", "formatter": "auth", "when": "D", "backupCount": 1, "filename": os.path.join(settings.getBaseFolder("logs"), "auth.log"), }, "pluginTimingsFile": { "class": "octoprint.logging.handlers.PluginTimingsLogHandler", "level": "DEBUG", "formatter": "timings", "backupCount": 3, "filename": os.path.join( settings.getBaseFolder("logs"), "plugintimings.log" ), "delay": True, }, "pluginTimingsCsvFile": { "class": "octoprint.logging.handlers.PluginTimingsLogHandler", "level": "DEBUG", "formatter": "timingscsv", "backupCount": 3, "filename": os.path.join( settings.getBaseFolder("logs"), "plugintimings.csv" ), "delay": True, }, }, "loggers": { "SERIAL": { "level": "INFO", "handlers": ["serialFile"], "propagate": False, }, "AUTH": { "level": "INFO", "handlers": ["authFile"], "propagate": False, }, "PLUGIN_TIMINGS": { "level": "INFO", "handlers": ["pluginTimingsFile", "pluginTimingsCsvFile"], "propagate": False, }, "PLUGIN_TIMINGS.octoprint.plugin": {"level": "INFO"}, "tornado.access": { "level": "INFO", "handlers": ["tornadoFile"], "propagate": False, }, "octoprint": {"level": "INFO"}, "octoprint.util": {"level": "INFO"}, "octoprint.plugins": {"level": "INFO"}, }, "root": {"level": "WARN", "handlers": ["console", "file"]}, } if debug or verbosity > 0: default_config["loggers"]["octoprint"]["level"] = "DEBUG" default_config["root"]["level"] = "INFO" if verbosity > 1: default_config["loggers"]["octoprint.plugins"]["level"] = "DEBUG" if verbosity > 2: default_config["root"]["level"] = "DEBUG" config = default_config if use_logging_file: # further logging configuration from file... if logging_file is None: logging_file = os.path.join(settings.getBaseFolder("base"), "logging.yaml") config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): from octoprint.util import yaml config_from_file = yaml.load_from_file(path=logging_file) # we merge that with the default config if config_from_file is not None and isinstance(config_from_file, dict): config = dict_merge(default_config, config_from_file) # configure logging globally return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) def octoprint_plugin_inject_factory(settings, components): import octoprint.plugin def f(name, implementation): """Factory for injections for all OctoPrintPlugins""" if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin): return None components_copy = dict(components) if "printer" in components: import functools import wrapt def tagwrap(f): @functools.wraps(f) def wrapper(*args, **kwargs): tags = kwargs.get("tags", set()) | { "source:plugin", f"plugin:{name}", } kwargs["tags"] = tags return f(*args, **kwargs) wrapper.__tagwrapped__ = True return wrapper class TaggedFuncsPrinter(wrapt.ObjectProxy): def __getattribute__(self, attr): __wrapped__ = super().__getattribute__("__wrapped__") if attr == "__wrapped__": return __wrapped__ item = getattr(__wrapped__, attr) if ( callable(item) and ( "tags" in item.__code__.co_varnames or "kwargs" in item.__code__.co_varnames ) and not getattr(item, "__tagwrapped__", False) ): return tagwrap(item) else: return item components_copy["printer"] = TaggedFuncsPrinter(components["printer"]) props = {} props.update(components_copy) props.update({"data_folder": os.path.join(settings.getBaseFolder("data"), name)}) return props return f def settings_plugin_inject_factory(settings): import octoprint.plugin def f(name, implementation): """Factory for additional injections/initializations depending on plugin type""" if not isinstance(implementation, octoprint.plugin.SettingsPlugin): return default_settings_overlay = {"plugins": {}} default_settings_overlay["plugins"][name] = implementation.get_settings_defaults() settings.add_overlay(default_settings_overlay, at_end=True) plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin( name, implementation ) if plugin_settings is None: return return {"settings": plugin_settings} return f def init_settings_plugin_config_migration_and_cleanup(plugin_manager): import logging import octoprint.plugin def settings_plugin_config_migration_and_cleanup(identifier, implementation): """Take care of migrating and cleaning up any old settings""" if not isinstance(implementation, octoprint.plugin.SettingsPlugin): return settings_version = implementation.get_settings_version() settings_migrator = implementation.on_settings_migrate if settings_version is not None and settings_migrator is not None: stored_version = implementation._settings.get_int( [octoprint.plugin.SettingsPlugin.config_version_key] ) if stored_version is None or stored_version < settings_version: settings_migrator(settings_version, stored_version) implementation._settings.set_int( [octoprint.plugin.SettingsPlugin.config_version_key], settings_version, force=True, ) implementation.on_settings_cleanup() implementation._settings.save() implementation.on_settings_initialized() settingsPlugins = plugin_manager.get_implementations(octoprint.plugin.SettingsPlugin) for implementation in settingsPlugins: try: settings_plugin_config_migration_and_cleanup( implementation._identifier, implementation ) except Exception: logging.getLogger(__name__).exception( "Error while trying to migrate settings for " "plugin %s, ignoring it", implementation._identifier, extra={"plugin": implementation._identifier}, ) plugin_manager.implementation_post_inits = [ settings_plugin_config_migration_and_cleanup ] def init_webcam_compat_overlay(settings, plugin_manager): import logging import octoprint.webcams def set_overlay(): default_webcam = octoprint.webcams.get_default_webcam( settings=settings, plugin_manager=plugin_manager ) if default_webcam is None: settings.remove_overlay("webcam_compat") return if not default_webcam.config or not default_webcam.config.compat: settings.remove_overlay("webcam_compat") return logging.getLogger(__name__).info( f"Installing webcam compat overlay for configured default webcam {default_webcam}" ) overlay = {"webcam": default_webcam.config.compat.dict(by_alias=True)} settings.add_overlay( overlay, key="webcam_compat", at_end=True, deprecated="Please use the webcam system introduced with 1.9.0, this compatibility layer will be removed in a future release.", replace=True, ) def callback(path, current_value, new_value): set_overlay() set_overlay() settings.add_path_update_callback(["webcam", "defaultWebcam"], callback) def init_custom_events(plugin_manager): import logging import octoprint.events logger = logging.getLogger(__name__) custom_events_hooks = plugin_manager.get_hooks( "octoprint.events.register_custom_events" ) for name, hook in custom_events_hooks.items(): try: result = hook() if isinstance(result, (list, tuple)): for event in result: constant, value = octoprint.events.Events.register_event( event, prefix=f"plugin_{name}_" ) logger.debug( 'Registered event %s of plugin %s as Events. %s = "%s"', event, name, constant, value, ) except Exception: logger.exception( "Error while retrieving custom event list from plugin %s", name, extra={"plugin": name}, ) def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler): # configure logging globally import logging.config as logconfig from octoprint.logging.filters import TornadoAccessFilter logconfig.dictConfig(config) # make sure we log any warnings log.captureWarnings(True) import warnings categories = (DeprecationWarning, PendingDeprecationWarning) if verbosity > 2: warnings.simplefilter("always") elif debug or verbosity > 0: for category in categories: warnings.simplefilter("always", category=category) # make sure we also log any uncaught exceptions if uncaught_logger is None: logger = log.getLogger(__name__) else: logger = log.getLogger(uncaught_logger) if uncaught_handler is None: def exception_logger(exc_type, exc_value, exc_tb): logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) uncaught_handler = exception_logger sys.excepthook = uncaught_handler tornado_logger = log.getLogger("tornado.access") tornado_logger.addFilter(TornadoAccessFilter()) return logger def init_pluginsystem( settings, safe_mode=False, ignore_blacklist=True, connectivity_checker=None ): """Initializes the plugin manager based on the settings.""" import os # we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins import octoprint.plugins # noqa: F401 logger = log.getLogger(__name__ + ".startup") plugin_folders = [ ( os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins") ), "octoprint.plugins", True, ), settings.getBaseFolder("plugins"), ] plugin_entry_points = ["octoprint.plugin"] plugin_disabled_list = settings.get(["plugins", "_disabled"]) plugin_sorting_order = settings.get(["plugins", "_sortingOrder"], merged=True) plugin_blacklist = [] if not ignore_blacklist and settings.getBoolean( ["server", "pluginBlacklist", "enabled"] ): plugin_blacklist = get_plugin_blacklist( settings, connectivity_checker=connectivity_checker ) plugin_validators = [] if safe_mode: def safe_mode_validator(phase, plugin_info): if phase in ("before_import", "before_load", "before_enable"): plugin_info.safe_mode_victim = not plugin_info.bundled if not plugin_info.bundled: return False return True plugin_validators.append(safe_mode_validator) compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"]) from octoprint.plugin import plugin_manager pm = plugin_manager( init=True, plugin_folders=plugin_folders, plugin_entry_points=plugin_entry_points, plugin_disabled_list=plugin_disabled_list, plugin_sorting_order=plugin_sorting_order, plugin_blacklist=plugin_blacklist, plugin_validators=plugin_validators, compatibility_ignored_list=compatibility_ignored_list, ) settings_overlays = {} disabled_from_overlays = {} def handle_plugin_loaded(name, plugin): if plugin.instance and hasattr(plugin.instance, "__plugin_settings_overlay__"): plugin.needs_restart = True # plugin has a settings overlay, inject it overlay_definition = plugin.instance.__plugin_settings_overlay__ if isinstance(overlay_definition, (tuple, list)): overlay_definition, order = overlay_definition else: order = None overlay = settings.load_overlay(overlay_definition) if "plugins" in overlay and "_disabled" in overlay["plugins"]: disabled_plugins = overlay["plugins"]["_disabled"] del overlay["plugins"]["_disabled"] disabled_from_overlays[name] = (disabled_plugins, order) settings_overlays[name] = overlay logger.debug("Found settings overlay on plugin %s", name) def handle_plugins_loaded( startup=False, initialize_implementations=True, force_reload=None ): if not startup: return from octoprint.util import sv sorted_disabled_from_overlays = sorted( ((key, value[0], value[1]) for key, value in disabled_from_overlays.items()), key=lambda x: (x[2] is None, sv(x[2]), sv(x[0])), ) disabled_list = pm.plugin_disabled_list already_processed = [] for name, addons, _ in sorted_disabled_from_overlays: if name not in disabled_list and not name.endswith("disabled"): for addon in addons: if addon in disabled_list: continue if addon in already_processed: logger.info( "Plugin %s wants to disable plugin %s, but that was already processed", name, addon, ) if addon not in already_processed and addon not in disabled_list: disabled_list.append(addon) logger.info( "Disabling plugin %s as defined by plugin %s", addon, name ) already_processed.append(name) def handle_plugin_enabled(name, plugin): if name in settings_overlays: settings.add_overlay(settings_overlays[name]) logger.info("Added settings overlay from plugin %s", name) pm.on_plugin_loaded = handle_plugin_loaded pm.on_plugins_loaded = handle_plugins_loaded pm.on_plugin_enabled = handle_plugin_enabled pm.reload_plugins(startup=True, initialize_implementations=False) return pm def get_plugin_blacklist(settings, connectivity_checker=None): import os import time import requests from octoprint.util.version import is_octoprint_compatible, is_python_compatible logger = log.getLogger(__name__ + ".startup") if connectivity_checker is not None and not connectivity_checker.online: logger.info("We don't appear to be online, not fetching plugin blacklist") return [] def format_blacklist(entries): format_entry = ( lambda x: f"{x[0]} ({x[1]})" if isinstance(x, (list, tuple)) and len(x) == 2 else f"{x} (any)" ) return ", ".join(map(format_entry, entries)) def process_blacklist(entries): result = [] if not isinstance(entries, list): return result for entry in entries: if "plugin" not in entry: continue if "octoversions" in entry and not is_octoprint_compatible( *entry["octoversions"] ): continue if "pythonversions" in entry and not is_python_compatible( *entry["pythonversions"] ): continue if "pluginversions" in entry: logger.debug( "Blacklisted plugin: %s, versions: %s", entry["plugin"], ", ".join(entry["pluginversions"]), ) for version in entry["pluginversions"]: result.append((entry["plugin"], version)) elif "versions" in entry: logger.debug( "Blacklisted plugin: %s, versions: %s", entry["plugin"], ", ".join(entry["versions"]), ) for version in entry["versions"]: result.append((entry["plugin"], f"=={version}")) else: logger.debug("Blacklisted plugin: %s", entry["plugin"]) result.append(entry["plugin"]) return result def fetch_blacklist_from_cache(path, ttl): if not os.path.isfile(path): return None if os.stat(path).st_mtime + ttl < time.time(): return None from octoprint.util import yaml result = yaml.load_from_file(path=path) if isinstance(result, list): return result def fetch_blacklist_from_url(url, timeout=3.05, cache=None): result = [] try: r = requests.get(url, timeout=timeout) result = process_blacklist(r.json()) if cache is not None: try: from octoprint.util import yaml yaml.save_to_file(result, path=cache) except Exception as e: logger.info( "Fetched plugin blacklist but couldn't write it to its cache file: %s", e, ) except Exception as e: logger.info( "Unable to fetch plugin blacklist from %s, proceeding without it: %s", url, e, ) return result try: # first attempt to fetch from cache cache_path = os.path.join(settings.getBaseFolder("data"), "plugin_blacklist.yaml") ttl = settings.getInt(["server", "pluginBlacklist", "ttl"]) blacklist = fetch_blacklist_from_cache(cache_path, ttl) if blacklist is None: # no result from the cache, let's fetch it fresh url = settings.get(["server", "pluginBlacklist", "url"]) timeout = settings.getFloat(["server", "pluginBlacklist", "timeout"]) blacklist = fetch_blacklist_from_url(url, timeout=timeout, cache=cache_path) if blacklist is None: # still now result, so no blacklist blacklist = [] if blacklist: logger.info( "Blacklist processing done, adding %s blacklisted plugin versions: %s", len(blacklist), format_blacklist(blacklist), ) else: logger.info("Blacklist processing done") return blacklist except Exception: logger.exception( "Something went wrong while processing the plugin blacklist. Proceeding without it." ) def init_event_manager(settings): from octoprint.events import eventManager return eventManager() def init_connectivity_checker(settings, event_manager): from octoprint.events import Events from octoprint.util import ConnectivityChecker # start regular check if we are connected to the internet connectivityEnabled = settings.getBoolean(["server", "onlineCheck", "enabled"]) connectivityInterval = settings.getInt(["server", "onlineCheck", "interval"]) connectivityHost = settings.get(["server", "onlineCheck", "host"]) connectivityPort = settings.getInt(["server", "onlineCheck", "port"]) connectivityName = settings.get(["server", "onlineCheck", "name"]) def on_connectivity_change( old_value, new_value, connection_working=None, resolution_working=None ): event_manager.fire( Events.CONNECTIVITY_CHANGED, payload={ "old": old_value, "new": new_value, "connection": connection_working, "resolution": resolution_working, }, ) connectivityChecker = ConnectivityChecker( connectivityInterval, connectivityHost, port=connectivityPort, name=connectivityName, enabled=connectivityEnabled, on_change=on_connectivity_change, ) connectivityChecker.check_immediately() connectivityChecker.log_full_report() return connectivityChecker def init_environment_detector(plugin_manager): from octoprint.environment import EnvironmentDetector return EnvironmentDetector(plugin_manager) # ~~ server main method def main(): import sys # os args are gained differently on win32 try: from click.utils import get_os_args args = get_os_args() except ImportError: # for whatever reason we are running an older Click version? args = sys.argv[1:] if len(args) >= len(sys.argv): # Now some ugly preprocessing of our arguments starts. We have a somewhat difficult situation on our hands # here if we are running under Windows and want to be able to handle utf-8 command line parameters (think # plugin parameters such as names or something, e.g. for the "dev plugin:new" command) while at the same # time also supporting sys.argv rewriting for debuggers etc (e.g. PyCharm). # # So what we try to do here is solve this... Generally speaking, sys.argv and whatever Windows returns # for its CommandLineToArgvW win32 function should have the same length. If it doesn't however and # sys.argv is shorter than the win32 specific command line arguments, obviously stuff was cut off from # sys.argv which also needs to be cut off of the win32 command line arguments. # # So this is what we do here. # -1 because first entry is the script that was called sys_args_length = len(sys.argv) - 1 # cut off stuff from the beginning args = args[-1 * sys_args_length :] if sys_args_length else [] from octoprint.cli import octo octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT") if __name__ == "__main__": main()
34,228
Python
.py
819
30.379731
139
0.584176
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,822
events.py
OctoPrint_OctoPrint/src/octoprint/events.py
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import collections import datetime import logging import queue import re import subprocess import threading import octoprint.plugin from octoprint.settings import settings # singleton _instance = None def all_events(): return [ getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and name not in ("register_event",) ] class Events: # server STARTUP = "Startup" SHUTDOWN = "Shutdown" CONNECTIVITY_CHANGED = "ConnectivityChanged" # connect/disconnect to printer CONNECTING = "Connecting" CONNECTED = "Connected" DISCONNECTING = "Disconnecting" DISCONNECTED = "Disconnected" CONNECTIONS_AUTOREFRESHED = "ConnectionsAutorefreshed" # State changes PRINTER_STATE_CHANGED = "PrinterStateChanged" PRINTER_RESET = "PrinterReset" # connect/disconnect by client CLIENT_OPENED = "ClientOpened" CLIENT_CLOSED = "ClientClosed" CLIENT_AUTHED = "ClientAuthed" CLIENT_DEAUTHED = "ClientDeauthed" # user login/logout USER_LOGGED_IN = "UserLoggedIn" USER_LOGGED_OUT = "UserLoggedOut" # File management UPLOAD = "Upload" FILE_SELECTED = "FileSelected" FILE_DESELECTED = "FileDeselected" UPDATED_FILES = "UpdatedFiles" METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted" METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished" METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated" FILE_ADDED = "FileAdded" FILE_REMOVED = "FileRemoved" FILE_MOVED = "FileMoved" FOLDER_ADDED = "FolderAdded" FOLDER_REMOVED = "FolderRemoved" FOLDER_MOVED = "FolderMoved" # SD Upload TRANSFER_STARTED = "TransferStarted" TRANSFER_DONE = "TransferDone" TRANSFER_FAILED = "TransferFailed" # print job PRINT_STARTED = "PrintStarted" PRINT_DONE = "PrintDone" PRINT_FAILED = "PrintFailed" PRINT_CANCELLING = "PrintCancelling" PRINT_CANCELLED = "PrintCancelled" PRINT_PAUSED = "PrintPaused" PRINT_RESUMED = "PrintResumed" ERROR = "Error" CHART_MARKED = "ChartMarked" # print/gcode events POWER_ON = "PowerOn" POWER_OFF = "PowerOff" HOME = "Home" Z_CHANGE = "ZChange" WAITING = "Waiting" DWELL = "Dwelling" COOLING = "Cooling" ALERT = "Alert" CONVEYOR = "Conveyor" EJECT = "Eject" E_STOP = "EStop" POSITION_UPDATE = "PositionUpdate" FIRMWARE_DATA = "FirmwareData" TOOL_CHANGE = "ToolChange" REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived" COMMAND_SUPPRESSED = "CommandSuppressed" INVALID_TOOL_REPORTED = "InvalidToolReported" FILAMENT_CHANGE = "FilamentChange" # Timelapse CAPTURE_START = "CaptureStart" CAPTURE_DONE = "CaptureDone" CAPTURE_FAILED = "CaptureFailed" POSTROLL_START = "PostRollStart" POSTROLL_END = "PostRollEnd" MOVIE_RENDERING = "MovieRendering" MOVIE_DONE = "MovieDone" MOVIE_FAILED = "MovieFailed" # Slicing SLICING_STARTED = "SlicingStarted" SLICING_DONE = "SlicingDone" SLICING_FAILED = "SlicingFailed" SLICING_CANCELLED = "SlicingCancelled" SLICING_PROFILE_ADDED = "SlicingProfileAdded" SLICING_PROFILE_MODIFIED = "SlicingProfileModified" SLICING_PROFILE_DELETED = "SlicingProfileDeleted" # Printer Profiles PRINTER_PROFILE_ADDED = "PrinterProfileAdded" PRINTER_PROFILE_MODIFIED = "PrinterProfileModified" PRINTER_PROFILE_DELETED = "PrinterProfileDeleted" # Settings SETTINGS_UPDATED = "SettingsUpdated" @classmethod def register_event(cls, event, prefix=None): name = cls._to_identifier(event) if prefix: event = prefix + event name = cls._to_identifier(prefix) + name setattr(cls, name, event) return name, event # based on https://stackoverflow.com/a/1176023 _first_cap_re = re.compile("([^_])([A-Z][a-z]+)") _all_cap_re = re.compile("([a-z0-9])([A-Z])") @classmethod def _to_identifier(cls, name): s1 = cls._first_cap_re.sub(r"\1_\2", name) return cls._all_cap_re.sub(r"\1_\2", s1).upper() def eventManager(): global _instance if _instance is None: _instance = EventManager() return _instance class EventManager: """ Handles receiving events and dispatching them to subscribers """ def __init__(self): self._registeredListeners = collections.defaultdict(list) self._logger = logging.getLogger(__name__) self._logger_fire = logging.getLogger(f"{__name__}.fire") self._startup_signaled = False self._shutdown_signaled = False self._queue = queue.Queue() self._held_back = queue.Queue() self._worker = threading.Thread(target=self._work) self._worker.daemon = True self._worker.start() def _work(self): try: while not self._shutdown_signaled: event, payload = self._queue.get(True) if event == Events.SHUTDOWN: # we've got the shutdown event here, stop event loop processing after this has been processed self._logger.info( "Processing shutdown event, this will be our last event" ) self._shutdown_signaled = True eventListeners = self._registeredListeners[event] self._logger_fire.debug(f"Firing event: {event} (Payload: {payload!r})") for listener in eventListeners: self._logger.debug(f"Sending action to {listener!r}") try: listener(event, payload) except Exception: self._logger.exception( "Got an exception while sending event {} (Payload: {!r}) to {}".format( event, payload, listener ) ) octoprint.plugin.call_plugin( octoprint.plugin.types.EventHandlerPlugin, "on_event", args=(event, payload), ) self._logger.info("Event loop shut down") except Exception: self._logger.exception("Ooops, the event bus worker loop crashed") def fire(self, event, payload=None): """ Fire an event to anyone subscribed to it Any object can generate an event and any object can subscribe to the event's name as a string (arbitrary, but case sensitive) and any extra payload data that may pertain to the event. Callbacks must implement the signature "callback(event, payload)", with "event" being the event's name and payload being a payload object specific to the event. """ send_held_back = False if event == Events.STARTUP: self._logger.info("Processing startup event, this is our first event") self._startup_signaled = True send_held_back = True self._enqueue(event, payload) if send_held_back: self._logger.info( "Adding {} events to queue that " "were held back before startup event".format(self._held_back.qsize()) ) while True: try: self._queue.put(self._held_back.get(block=False)) except queue.Empty: break def _enqueue(self, event, payload): if self._startup_signaled: q = self._queue else: q = self._held_back q.put((event, payload)) def subscribe(self, event, callback): """ Subscribe a listener to an event -- pass in the event name (as a string) and the callback object """ if callback in self._registeredListeners[event]: # callback is already subscribed to the event return self._registeredListeners[event].append(callback) self._logger.debug(f"Subscribed listener {callback!r} for event {event}") def unsubscribe(self, event, callback): """ Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object """ try: self._registeredListeners[event].remove(callback) except ValueError: # not registered pass def join(self, timeout=None): self._worker.join(timeout) return self._worker.is_alive() class GenericEventListener: """ The GenericEventListener can be subclassed to easily create custom event listeners. """ def __init__(self): self._logger = logging.getLogger(__name__) def subscribe(self, events): """ Subscribes the eventCallback method for all events in the given list. """ for event in events: eventManager().subscribe(event, self.eventCallback) def unsubscribe(self, events): """ Unsubscribes the eventCallback method for all events in the given list """ for event in events: eventManager().unsubscribe(event, self.eventCallback) def eventCallback(self, event, payload): """ Actual event callback called with name of event and optional payload. Not implemented here, override in child classes. """ pass class DebugEventListener(GenericEventListener): def __init__(self): GenericEventListener.__init__(self) events = list(filter(lambda x: not x.startswith("__"), dir(Events))) self.subscribe(events) def eventCallback(self, event, payload): GenericEventListener.eventCallback(self, event, payload) self._logger.debug(f"Received event: {event} (Payload: {payload!r})") class CommandTrigger(GenericEventListener): def __init__(self, printer): GenericEventListener.__init__(self) self._printer = printer self._subscriptions = {} self._initSubscriptions() def _initSubscriptions(self): """ Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their respective commands. """ if not settings().get(["events"]): return if not settings().getBoolean(["events", "enabled"]): return eventsToSubscribe = [] subscriptions = settings().get(["events", "subscriptions"]) for subscription in subscriptions: if not isinstance(subscription, dict): self._logger.info( "Invalid subscription definition, not a dictionary: {!r}".format( subscription ) ) continue if ( "event" not in subscription or "command" not in subscription or "type" not in subscription or subscription["type"] not in ["system", "gcode"] ): self._logger.info( "Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format( subscription ) ) continue if "enabled" in subscription and not subscription["enabled"]: self._logger.info(f"Disabled command trigger: {subscription!r}") continue events = subscription["event"] command = subscription["command"] commandType = subscription["type"] debug = subscription["debug"] if "debug" in subscription else False # "event" in the configuration can be a string, or # a list of strings. If it's the former, convert it # into the latter. if not isinstance(events, (tuple, list, set)): events = [events] for event in events: if event not in self._subscriptions: self._subscriptions[event] = [] self._subscriptions[event].append((command, commandType, debug)) if event not in eventsToSubscribe: eventsToSubscribe.append(event) self.subscribe(eventsToSubscribe) def eventCallback(self, event, payload): """ Event callback, iterates over all subscribed commands for the given event, processes the command string and then executes the command via the abstract executeCommand method. """ GenericEventListener.eventCallback(self, event, payload) if event not in self._subscriptions: return for command, commandType, debug in self._subscriptions[event]: try: if isinstance(command, (tuple, list, set)): processedCommand = [] for c in command: processedCommand.append(self._processCommand(c, event, payload)) else: processedCommand = self._processCommand(command, event, payload) self.executeCommand(processedCommand, commandType, debug=debug) except KeyError: self._logger.warning( "There was an error processing one or more placeholders in the following command: %s" % command ) def executeCommand(self, command, commandType, debug=False): if commandType == "system": self._executeSystemCommand(command, debug=debug) elif commandType == "gcode": self._executeGcodeCommand(command, debug=debug) def _executeSystemCommand(self, command, debug=False): def commandExecutioner(cmd): if debug: self._logger.info(f"Executing system command: {cmd}") else: self._logger.info("Executing a system command") # we run this with shell=True since we have to trust whatever # our admin configured as command and since we want to allow # shell-alike handling here... subprocess.check_call(cmd, shell=True) def process(): try: if isinstance(command, (list, tuple, set)): for c in command: commandExecutioner(c) else: commandExecutioner(command) except subprocess.CalledProcessError as e: if debug: self._logger.warning( "Command failed with return code {}: {}".format( e.returncode, str(e) ) ) else: self._logger.warning( "Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format( e.returncode ) ) except Exception: self._logger.exception("Command failed") t = threading.Thread(target=process) t.daemon = True t.start() def _executeGcodeCommand(self, command, debug=False): commands = [command] if isinstance(command, (list, tuple, set)): commands = list(command) if debug: self._logger.info("Executing GCode commands: %r" % command) self._printer.commands(commands) def _processCommand(self, command, event, payload): """ Performs string substitutions in the command string based on a few current parameters. The following substitutions are currently supported: - {__currentZ} : current Z position of the print head, or -1 if not available - {__eventname} : the name of the event hook being triggered - {__filename} : name of currently selected file, or "NO FILE" if no file is selected - {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected - {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected - {__progress} : current print progress in percent, 0 if no print is in progress - {__data} : the string representation of the event's payload - {__json} : the json representation of the event's payload, "{}" if there is no payload, "" if there was an error on serialization - {__now} : ISO 8601 representation of the current date and time Additionally, the keys of the event's payload can also be used as placeholder. """ json_string = "{}" if payload: import json try: json_string = json.dumps(payload) except Exception: self._logger.exception("JSON: Cannot dump %r", payload) json_string = "" params = { "__currentZ": "-1", "__eventname": event, "__filename": "NO FILE", "__filepath": "NO PATH", "__progress": "0", "__data": str(payload), "__json": json_string, "__now": datetime.datetime.now().isoformat(), } currentData = self._printer.get_current_data() if "currentZ" in currentData and currentData["currentZ"] is not None: params["__currentZ"] = str(currentData["currentZ"]) if ( "job" in currentData and "file" in currentData["job"] and "name" in currentData["job"]["file"] and currentData["job"]["file"]["name"] is not None ): params["__filename"] = currentData["job"]["file"]["name"] params["__filepath"] = currentData["job"]["file"]["path"] params["__fileorigin"] = currentData["job"]["file"]["origin"] if ( "progress" in currentData and currentData["progress"] is not None and "completion" in currentData["progress"] and currentData["progress"]["completion"] is not None ): params["__progress"] = str(round(currentData["progress"]["completion"])) # now add the payload keys as well if isinstance(payload, dict): params.update(payload) return command.format(**params)
18,741
Python
.py
441
31.811791
141
0.599681
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,823
filters.py
OctoPrint_OctoPrint/src/octoprint/logging/filters.py
import logging import urllib.parse class TornadoAccessFilter(logging.Filter): def filter(self, record): try: status, request_line, rtt = record.args if status == 409: _, url, _ = request_line.split() u = urllib.parse.urlparse(url) if u.path in ("/api/printer",): record.levelno = logging.INFO record.levelname = logging.getLevelName(record.levelno) except Exception: logging.getLogger(__name__).exception( f"Error while filtering log record {record!r}" ) return logging.Filter.filter(self, record)
682
Python
.py
17
28.294118
75
0.570348
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,824
handlers.py
OctoPrint_OctoPrint/src/octoprint/logging/handlers.py
import concurrent.futures import logging.handlers import os import re import time class AsyncLogHandlerMixin(logging.Handler): def __init__(self, *args, **kwargs): self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) super().__init__(*args, **kwargs) def emit(self, record): if getattr(self._executor, "_shutdown", False): return try: self._executor.submit(self._emit, record) except Exception: self.handleError(record) def _emit(self, record): # noinspection PyUnresolvedReferences super().emit(record) def close(self): self._executor.shutdown(wait=True) super().close() class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler): def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") super().__init__(*args, **kwargs) # clean up old files on handler start if self.backupCount > 0: for s in self.getFilesToDelete(): os.remove(s) class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler): rollover_callbacks = [] def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") super().__init__(*args, **kwargs) @classmethod def registerRolloverCallback(cls, callback, *args, **kwargs): cls.rollover_callbacks.append((callback, args, kwargs)) def doRollover(self): super().doRollover() for rcb in self.rollover_callbacks: callback, args, kwargs = rcb callback(*args, **kwargs) class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler): pass class TriggeredRolloverLogHandler( AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler ): do_rollover = False suffix_template = "%Y-%m-%d_%H-%M-%S" file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$") @classmethod def arm_rollover(cls): cls.do_rollover = True def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") super().__init__(*args, **kwargs) self.cleanupFiles() def shouldRollover(self, record): return self.do_rollover def getFilesToDelete(self): """ Determine the files to delete when rolling over. """ dirName, baseName = os.path.split(self.baseFilename) fileNames = os.listdir(dirName) result = [] prefix = baseName + "." plen = len(prefix) for fileName in fileNames: if fileName[:plen] == prefix: suffix = fileName[plen:] if type(self).file_pattern.match(suffix): result.append(os.path.join(dirName, fileName)) result.sort() if len(result) < self.backupCount: result = [] else: result = result[: len(result) - self.backupCount] return result def cleanupFiles(self): if self.backupCount > 0: for path in self.getFilesToDelete(): os.remove(path) def doRollover(self): self.do_rollover = False if self.stream: self.stream.close() self.stream = None if os.path.exists(self.baseFilename): # figure out creation date/time to use for file suffix t = time.localtime(os.stat(self.baseFilename).st_mtime) dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t) if os.path.exists(dfn): os.remove(dfn) os.rename(self.baseFilename, dfn) self.cleanupFiles() if not self.delay: self.stream = self._open() class SerialLogHandler(TriggeredRolloverLogHandler): pass class PluginTimingsLogHandler(TriggeredRolloverLogHandler): pass class TornadoLogHandler(CleaningTimedRotatingFileHandler): pass class AuthLogHandler(CleaningTimedRotatingFileHandler): pass class RecordingLogHandler(logging.Handler): def __init__(self, target=None, *args, **kwargs): super().__init__(*args, **kwargs) self._buffer = [] self._target = target def emit(self, record): self._buffer.append(record) def setTarget(self, target): self._target = target def flush(self): if not self._target: return self.acquire() try: for record in self._buffer: self._target.handle(record) self._buffer = [] finally: self.release() def close(self): self.flush() self.acquire() try: self._buffer = [] finally: self.release() def __len__(self): return len(self._buffer) # noinspection PyAbstractClass class CombinedLogHandler(logging.Handler): def __init__(self, *handlers): logging.Handler.__init__(self) self._handlers = handlers def setHandlers(self, *handlers): self._handlers = handlers def handle(self, record): self.acquire() try: if self._handlers: for handler in self._handlers: handler.handle(record) finally: self.release()
5,394
Python
.py
150
27.3
88
0.61232
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,825
__init__.py
OctoPrint_OctoPrint/src/octoprint/logging/__init__.py
from octoprint.logging import filters # noqa: F401 from octoprint.logging import handlers # noqa: F401 def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args): """ Logs to the provided handler only. Arguments: logger: logger to log to handler: handler to restrict logging to level: level to log at msg: message to log exc_info: optional exception info extra: optional extra data *args: log args """ import sys try: from logging import _srcfile except ImportError: _srcfile = None # this is just the same as logging.Logger._log if _srcfile: # IronPython doesn't track Python frames, so findCaller raises an # exception on some versions of IronPython. We trap it here so that # IronPython can use logging. try: fn, lno, func = logger.findCaller() except ValueError: fn, lno, func = "(unknown file)", 0, "(unknown function)" else: fn, lno, func = "(unknown file)", 0, "(unknown function)" if exc_info: if not isinstance(exc_info, tuple): exc_info = sys.exc_info() record = logger.makeRecord( logger.name, level, fn, lno, msg, args, exc_info, func, extra ) # and this is a mixture of logging.Logger.handle and logging.Logger.callHandlers if (not logger.disabled) and logger.filter(record): if record.levelno >= handler.level: handler.handle(record) def get_handler(name, logger=None): """ Retrieves the handler named ``name``. If optional ``logger`` is provided, search will be limited to that logger, otherwise the root logger will be searched. Arguments: name: the name of the handler to look for logger: (optional) the logger to search in, root logger if not provided Returns: the handler if it could be found, None otherwise """ import logging if logger is None: logger = logging.getLogger() for handler in logger.handlers: if handler.get_name() == name: return handler return None def get_divider_line(c, message=None, length=78, indent=3): """ Generate a divider line for logging, optionally with included message. Examples: >>> get_divider_line("-") '------------------------------------------------------------------------------' >>> get_divider_line("=", length=10) '==========' >>> get_divider_line("-", message="Hi", length=10) '--- Hi ---' >>> get_divider_line("-", message="A slightly longer text") '--- A slightly longer text ---------------------------------------------------' >>> get_divider_line("-", message="A slightly longer text", indent=5) '----- A slightly longer text -------------------------------------------------' >>> get_divider_line("-", message="Hello World!", length=10) '--- Hello World!' >>> get_divider_line(None) Traceback (most recent call last): ... AssertionError: c is not text >>> get_divider_line("´`") Traceback (most recent call last): ... AssertionError: c is not a single character >>> get_divider_line("-", message=3) Traceback (most recent call last): ... AssertionError: message is not text >>> get_divider_line("-", length="hello") Traceback (most recent call last): ... AssertionError: length is not an int >>> get_divider_line("-", indent="hi") Traceback (most recent call last): ... AssertionError: indent is not an int Arguments: c: character to use for the line message: message to print in the line length: length of the line indent: indentation of message in line Returns: formatted divider line """ assert isinstance(c, str), "c is not text" assert len(c) == 1, "c is not a single character" assert isinstance(length, int), "length is not an int" assert isinstance(indent, int), "indent is not an int" if message is None: return c * length assert isinstance(message, str), "message is not text" space = length - 2 * (indent + 1) if space >= len(message): return c * indent + " " + message + " " + c * (length - indent - 2 - len(message)) else: return c * indent + " " + message def prefix_multilines(text: str, prefix: str = ": ") -> str: from octoprint.util import to_unicode lines = text.splitlines() if not lines: return "" if len(lines) == 1: return to_unicode(lines[0]) return ( to_unicode(lines[0]) + "\n" + "\n".join(map(lambda line: prefix + to_unicode(line), lines[1:])) )
4,961
Python
.py
127
31.023622
90
0.576218
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,826
__init__.py
OctoPrint_OctoPrint/src/octoprint/systemcommands/__init__.py
""" This module represents OctoPrint's system and server commands. """ __author__ = "Johan Verrept <johan@verrept.eu>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging from octoprint.settings import settings from octoprint.util.commandline import CommandlineCaller, CommandlineError # singleton _instance = None def system_command_manager(): global _instance if _instance is None: _instance = SystemCommandManager() return _instance class SystemCommandManager: SERVER_RESTART_COMMAND = "serverRestartCommand" SYSTEM_RESTART_COMMAND = "systemRestartCommand" SYSTEM_SHUTDOWN_COMMAND = "systemShutdownCommand" def __init__(self): self._logger = logging.getLogger(__name__) self._caller = CommandlineCaller() def execute(self, command): if not command: return False try: # we run this with shell=True since we have to trust whatever # our admin configured as command and since we want to allow # shell-alike handling here... p = self._caller.non_blocking_call(command, shell=True) if p is None: raise CommandlineError(None, "", "") if p.returncode is not None: stdout = p.stdout.text if p is not None and p.stdout is not None else "" stderr = p.stderr.text if p is not None and p.stderr is not None else "" raise CommandlineError(p.returncode, stdout, stderr) except CommandlineError: raise except Exception: self._logger.exception(f"Error while executing command: {command}") raise CommandlineError(None, "", "") return True def get_command(self, cmd): return settings().get(["server", "commands", cmd]) def has_command(self, cmd): return self.get_command(cmd) is not None def get_server_restart_command(self): return self.get_command(self.SERVER_RESTART_COMMAND) def get_system_restart_command(self): return self.get_command(self.SYSTEM_RESTART_COMMAND) def get_system_shutdown_command(self): return self.get_command(self.SYSTEM_SHUTDOWN_COMMAND) def has_server_restart_command(self): return self.get_server_restart_command() is not None def has_system_restart_command(self): return self.get_system_restart_command() is not None def has_system_shutdown_command(self): return self.get_system_shutdown_command() is not None def perform_server_restart(self): return self.execute(self.get_server_restart_command()) def perform_system_restart(self): return self.execute(self.get_system_restart_command()) def perform_system_shutdown(self): return self.execute(self.get_system_shutdown_command())
2,984
Python
.py
65
38.184615
103
0.683483
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,827
__init__.py
OctoPrint_OctoPrint/src/octoprint/schema/__init__.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from pydantic import BaseModel as PydanticBaseModel class BaseModel(PydanticBaseModel): class Config: use_enum_values = True
332
Python
.py
6
51.833333
103
0.767802
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,828
access_control.py
OctoPrint_OctoPrint/src/octoprint/schema/config/access_control.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import List, Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class AccessControlConfig(BaseModel): salt: Optional[str] = None """Secret salt used for password hashing. **DO NOT TOUCH!** If changed you will no longer be able to log in with your existing accounts. Default unset, generated on first run.""" userManager: str = "octoprint.access.users.FilebasedUserManager" """The user manager implementation to use for accessing user information. Currently only a filebased user manager is implemented which stores configured accounts in a YAML file (Default: `users.yaml` in the default configuration folder).""" groupManager: str = "octoprint.access.groups.FilebasedGroupManager" """The group manager implementation to use for accessing group information. Currently only a filebased user manager is implemented which stores configured groups in a YAML file (Default: `groups.yaml` in the default configuration folder).""" permissionManager: str = "octoprint.access.permissions.PermissionManager" """The permission manager implementation to use.""" userfile: Optional[str] = None """The YAML user file to use. If left out defaults to `users.yaml` in the default configuration folder.""" groupfile: Optional[str] = None """The YAML group file to use. If left out defaults to `groups.yaml` in the default configuration folder.""" autologinLocal: bool = False """If set to true, will automatically log on clients originating from any of the networks defined in `localNetworks` as the user defined in `autologinAs`.""" localNetworks: List[str] = ["127.0.0.0/8", "::1/128"] """A list of networks or IPs for which an automatic logon as the user defined in `autologinAs` will take place. If available OctoPrint will evaluate the `X-Forwarded-For` HTTP header for determining the client's IP address. Defaults to anything originating from localhost.""" autologinAs: Optional[str] = None """The name of the user to automatically log on clients originating from `localNetworks` as. Must be the name of one of your configured users.""" autologinHeadsupAcknowledged: bool = False """Whether the user has acknowledged the heads-up about the importance of a correct reverse proxy configuration in the presence of autologin.""" trustBasicAuthentication: bool = False """Whether to trust Basic Authentication headers. If you have setup Basic Authentication in front of OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will be logged into OctoPrint as the user during Basic Authentication. **ONLY ENABLE THIS** if your OctoPrint instance is only accessible through a connection locked down through Basic Authentication!""" checkBasicAuthenticationPassword: bool = True """Whether to also check the password provided through Basic Authentication, if the Basic Authentication header is to be trusted. Disabling this will only match the user name in the Basic Authentication header and login the user without further checks, thus disable with caution.""" trustRemoteUser: bool = False """Whether to trust remote user headers. If you have setup authentication in front of OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will be logged into OctoPrint as the user provided in the header. **ONLY ENABLE THIS** if your OctoPrint instance is only accessible through a connection locked down through an authenticating reverse proxy!""" remoteUserHeader: str = "REMOTE_USER" """Header used by the reverse proxy to convey the authenticated user.""" addRemoteUsers: bool = False """If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.""" defaultReauthenticationTimeout: int = 5 """Default timeout after which to require reauthentication by a user for dangerous changes, in minutes. Defaults to 5 minutes. Set to 0 to disable reauthentication requirements (SECURITY IMPACT!)."""
4,333
Python
.py
39
106.333333
407
0.774035
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,829
controls.py
OctoPrint_OctoPrint/src/octoprint/schema/config/controls.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum from typing import List, Optional, Union from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs class LayoutEnum(str, Enum): horizontal = "horizontal" vertical = "vertical" class ControlSliderInputConfig(BaseModel): min: int = 0 """Minimum value of the slider.""" max: int = 255 """Maximum value of the slider.""" step: int = 1 """Step size per slider tick.""" class ControlInputConfig(BaseModel): name: str """Name to display for the input field.""" parameter: str """Internal parameter name for the input field, used as a placeholder in `command`/`commands`.""" default: Union[str, int, float, bool] """Default value for the input field.""" slider: Optional[ControlSliderInputConfig] = None """If this attribute is included, instead of an input field a slider control will be rendered.""" @with_attrs_docs class ContainerConfig(BaseModel): children: "List[Union[ContainerConfig, ControlConfig]]" = [] """A list of children controls or containers contained within this container.""" name: Optional[str] = None """A name to display above the container, basically a section header.""" layout: LayoutEnum = LayoutEnum.vertical """The layout to use for laying out the contained children, either from top to bottom (`vertical`) or from left to right (`horizontal`).""" @with_attrs_docs class ControlConfig(BaseModel): name: str """The name of the control, will be displayed either on the button if it's a control sending a command or as a label for controls which only display output.""" command: Optional[str] = None """A single GCODE command to send to the printer. Will be rendered as a button which sends the command to the printer upon click. The button text will be the value of the `name` attribute. Mutually exclusive with `commands` and `script`. The rendered button be disabled if the printer is currently offline or printing or alternatively if the requirements defined via the `enabled` attribute are not met.""" commands: Optional[List[str]] = None """A list of GCODE commands to send to the printer. Will be rendered as a button which sends the commands to the printer upon click. The button text will be the value of the `name` attribute. Mutually exclusive with `command` and `script`. The rendered button will be disabled if the printer is currently offline or printing or alternatively if the requirements defined via the `enabled` attribute are not met.""" script: Optional[str] = None """The name of a full blown [GCODE script]() to send to the printer. Will be rendered as a button which sends the script to the printer upon click. The button text will be the value of the `name` attribute. Mutually exclusive with `command` and `commands`. The rendered button will be disabled if the printer is currently offline or printing or alternatively if the requirements defined via the `enabled` attribute are not met. Values of input parameters will be available in the template context under the `parameter` variable (e.g. an input parameter `speed` will be available in the script template as `parameter.speed`). On top of that all other variables defined in the [GCODE template context]() will be available.""" javascript: Optional[str] = None """A JavaScript snippet to be executed when the button rendered for `command` or `commands` is clicked. This allows to override the direct sending of the command or commands to the printer with more sophisticated behaviour. The JavaScript snippet is `eval`'d and processed in a context where the control it is part of is provided as local variable `data` and the `ControlViewModel` is available as `self`.""" additionalClasses: Optional[str] = None """Additional classes to apply to the button of a `command`, `commands`, `script` or `javascript` control, other than the default `btn`. Can be used to visually style the button, e.g. set to `btn-danger` to turn the button red.""" enabled: Optional[str] = None """A JavaScript snippet returning either `true` or `false` determining whether the control should be enabled or not. This allows to override the default logic for the enable state of the control (disabled if printer is offline). The JavaScript snippet is `eval`'d and processed in a context where the control it is part of is provided as local variable `data` and the `ControlViewModel` is available as `self`.""" input: Optional[List[ControlInputConfig]] = [] """A list of definitions of input parameters for a `command` or `commands`, to be rendered as additional input fields. `command`/`commands` may contain placeholders to be replaced by the values obtained from the user for the defined input fields.""" regex: Optional[str] = None """A [regular expression <re-syntax>](https://docs.python.org/3/library/re.html#regular-expression-syntax) to match against lines received from the printer to retrieve information from it (e.g. specific output). Together with `template` this allows rendition of received data from the printer within the UI.""" template: Optional[str] = None r"""A template to use for rendering the match of `regex`. May contain placeholders in [Python Format String Syntax](https://docs.python.org/3/library/string.html#formatstrings) for either named groups within the regex (e.g. `Temperature: {temperature}` for a regex `T:\s*(?P<temperature>\d+(\.\d*)`) or positional groups within the regex (e.g. `Position: X={0}, Y={1}, Z={2}, E={3}` for a regex `X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)`).""" confirm: Optional[str] = None """A text to display to the user to confirm his button press. Can be used with sensitive custom controls like changing EEPROM values in order to prevent accidental clicks. The text will be displayed in a confirmation dialog."""
6,121
Python
.py
57
102.789474
727
0.746313
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,830
feature.py
OctoPrint_OctoPrint/src/octoprint/schema/config/feature.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import List from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class FeatureConfig(BaseModel): temperatureGraph: bool = True """Whether to enable the temperature graph in the UI or not.""" sdSupport: bool = True """Specifies whether support for SD printing and file management should be enabled.""" keyboardControl: bool = True """Whether to enable the keyboard control feature in the control tab.""" pollWatched: bool = False """Whether to actively poll the watched folder (true) or to rely on the OS's file system notifications instead (false).""" modelSizeDetection: bool = True """Whether to enable model size detection and warning (true) or not (false).""" rememberFileFolder: bool = False """Whether to remember the selected folder on the file manager.""" printStartConfirmation: bool = False """Whether to show a confirmation on print start (true) or not (false)""" printCancelConfirmation: bool = True """Whether to show a confirmation on print cancelling (true) or not (false)""" uploadOverwriteConfirmation: bool = True autoUppercaseBlacklist: List[str] = ["M117", "M118"] """Commands that should never be auto-uppercased when sent to the printer through the Terminal tab.""" g90InfluencesExtruder: bool = False """Whether `G90`/`G91` also influence absolute/relative mode of extruders.""" enforceReallyUniversalFilenames: bool = False """Replace all special characters and spaces with text equivalent to make them universally compatible. Most OS filesystems work fine with unicode characters, but just in case you can revert to the older behaviour by setting this to true.""" enableDragDropUpload: bool = True """Enable drag and drop upload overlay"""
2,049
Python
.py
32
59.40625
244
0.747126
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,831
temperature.py
OctoPrint_OctoPrint/src/octoprint/schema/config/temperature.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import List from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class TemperatureProfile(BaseModel): name: str """Name of the profile.""" extruder: int """Hotend temperature to set with the profile.""" bed: int """Bed temperature to set with the profile.""" @with_attrs_docs class TemperatureConfig(BaseModel): profiles: List[TemperatureProfile] = [ TemperatureProfile(name="ABS", extruder=210, bed=100), TemperatureProfile(name="PLA", extruder=180, bed=60), ] """Temperature profiles to offer in the UI for quick pre-heating.""" cutoff: int = 30 """Cut off time for the temperature data, in minutes.""" sendAutomatically: bool = False """Whether to send new temperature settings made in the UI automatically.""" sendAutomaticallyAfter: int = 1 """After what time to send the new temperature settings automatically, in seconds."""
1,187
Python
.py
26
41.307692
103
0.728696
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,832
devel.py
OctoPrint_OctoPrint/src/octoprint/schema/config/devel.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs class StylesheetEnum(str, Enum): css = "css" less = "less" @with_attrs_docs class DevelWebassetsConfig(BaseModel): bundle: bool = True """If set to true, OctoPrint will merge all JS, all CSS and all Less files into one file per type to reduce request count. Setting it to false will load all assets individually. Note: if this is set to false, no minification will take place regardless of the `minify` setting.""" clean_on_startup: bool = True """Whether to delete generated web assets on server startup (forcing a regeneration).""" minify: bool = True """If set to true, OctoPrint will the core and library javascript assets. Note: if `bundle` is set to false, no minification will take place either.""" minify_plugins: bool = False """If set to true, OctoPrint will also minify the third party plugin javascript assets. Note: if `bundle` or `minify` are set to false, no minification of the plugin assets will take place either.""" class DevelCacheConfig(BaseModel): enabled: bool = True """Whether to enable caching. Defaults to true. Setting it to false will cause the UI to always be fully rerendered on request to `/` on the server.""" preemptive: bool = True """Whether to enable the preemptive cache.""" @with_attrs_docs class DevelConfig(BaseModel): stylesheet: StylesheetEnum = StylesheetEnum.css """Settings for stylesheet preference. OctoPrint will prefer to use the stylesheet type specified here. Usually (on a production install) that will be the compiled css (default). Developers may specify less here too.""" cache: DevelCacheConfig = DevelCacheConfig() """Settings for OctoPrint's internal caching.""" webassets: DevelWebassetsConfig = DevelWebassetsConfig() """Settings for OctoPrint's web asset merging and minifying.""" useFrozenDictForPrinterState: bool = True showLoadingAnimation: bool = True """Enable or disable the loading animation.""" sockJsConnectTimeout: float = 30 pluginTimings: bool = False enableRateLimiter: bool = True """Enable or disable the rate limiter. Careful, disabling this reduces security.""" enableCsrfProtection: bool = True """Enable or disable the CSRF protection. Careful, disabling this reduces security."""
2,614
Python
.py
40
60.925
283
0.750881
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,833
slicing.py
OctoPrint_OctoPrint/src/octoprint/schema/config/slicing.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import Dict, Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class SlicingConfig(BaseModel): enabled: bool = True """Whether to enable slicing support or not.""" defaultSlicer: Optional[str] = None """Default slicer to use.""" defaultProfiles: Dict[str, str] = {} """Default slicing profiles per slicer, maps slicer identifier to profile identifier."""
665
Python
.py
13
47.846154
103
0.752322
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,834
plugins.py
OctoPrint_OctoPrint/src/octoprint/schema/config/plugins.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import Dict, List from pydantic import Field from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class PluginsConfig(BaseModel): disabled: List[str] = Field([], alias="_disabled") """Identifiers of installed but disabled plugins.""" forced_compatible: List[str] = Field([], alias="_forcedCompatible") """Identifiers of plugins for which python compatibility information will be ignored and the plugin considered compatible in any case. Only for development, do **NOT** use in production.""" sorting_order: Dict[str, Dict[str, int]] = Field({}, alias="_sortingOrder") """Custom sorting of hooks and implementations provided by plugins. Two-tiered dictionary structure, plugin identifier mapping to a dictionary of order overrides mapped by sorting context/hook name."""
1,069
Python
.py
14
73.142857
205
0.766221
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,835
gcode_analysis.py
OctoPrint_OctoPrint/src/octoprint/schema/config/gcode_analysis.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs class RunAtEnum(str, Enum): never = "never" idle = "idle" always = "always" @with_attrs_docs class GcodeAnalysisConfig(BaseModel): maxExtruders: int = 10 """Maximum number of extruders to support/to sanity check for.""" throttle_normalprio: float = 0.01 """Pause between each processed GCODE line batch in normal priority mode, seconds.""" throttle_highprio: float = 0.0 """Pause between each processed GCODE line batch in high priority mode (e.g. on fresh uploads), seconds.""" throttle_lines: int = 100 """GCODE line batch size.""" runAt: RunAtEnum = RunAtEnum.idle """Whether to run the analysis only when idle (not printing), regardless of printing state or never.""" bedZ: float = 0.0 """Z position considered the location of the bed."""
1,128
Python
.py
23
44.956522
111
0.726691
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,836
serial.py
OctoPrint_OctoPrint/src/octoprint/schema/config/serial.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum from typing import List, Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs class AlwaysDetectNeverEnum(str, Enum): always = "always" detect = "detect" never = "never" class InfoWarnNeverEnum(str, Enum): info = "info" warn = "warn" never = "never" @with_attrs_docs class SerialTimeoutConfig(BaseModel): detectionFirst: float = 10.0 detectionConsecutive: float = 2.0 connection: float = 10.0 """Timeout for waiting to establish a connection with the selected port, in seconds""" communication: float = 30.0 """Timeout during serial communication, in seconds""" communicationBusy: float = 3.0 """Timeout during serial communication when busy protocol support is detected, in seconds""" temperature: float = 5.0 """Timeout after which to query temperature when no target is set""" temperatureTargetSet: float = 2.0 """Timeout after which to query temperature when a target is set""" temperatureAutoreport: float = 2.0 sdStatus: float = 1.0 """Timeout after which to query the SD status while SD printing""" sdStatusAutoreport: float = 1.0 posAutoreport: float = 5.0 resendOk: float = 0.5 baudrateDetectionPause: float = 1.0 positionLogWait: float = 10.0 @with_attrs_docs class SerialMaxTimeouts(BaseModel): idle: int = 2 """Max. timeouts when the printer is idle""" printing: int = 5 """Max. timeouts when the printer is printing""" long: int = 5 """Max. timeouts when a long running command is active""" @with_attrs_docs class SerialCapabilities(BaseModel): autoreport_temp: bool = True """Whether to enable temperature autoreport in the firmware if its support is detected""" autoreport_sdstatus: bool = True """Whether to enable SD printing autoreport in the firmware if its support is detected""" autoreport_pos: bool = True """Whether to enable position autoreport in the firmware if its support is detected""" busy_protocol: bool = True """Whether to shorten the communication timeout if the firmware seems to support the busy protocol""" emergency_parser: bool = True """Whether to send emergency commands out of band if the firmware seems to support the emergency parser""" extended_m20: bool = True """Whether to request extended M20 (file list) output from the firmware if its support is detected""" lfn_write: bool = True """Whether to enable long filename support for SD card writes if the firmware reports support for it""" @with_attrs_docs class SerialConfig(BaseModel): port: Optional[str] = None """The default port to use to connect to the printer. If unset or set to `AUTO`, the port will be auto-detected.""" baudrate: Optional[int] = None """The default baudrate to use to connect to the printer. If unset or set to 0, the baudrate will be auto-detected.""" exclusive: bool = True """Whether to request the serial port exclusively or not""" lowLatency: bool = False """Whether to request low latency mode on the serial port or not""" autoconnect: bool = False """Whether to try to automatically connect to the printer on startup or not""" autorefresh: bool = True """Whether to automatically refresh the port list while no connection is established""" autorefreshInterval: int = 1 """Interval in seconds at which to refresh the port list while no connection is established""" log: bool = False """Whether to log whole communication to serial.log (warning: might decrease performance)""" timeout: SerialTimeoutConfig = SerialTimeoutConfig() """Timeouts used for the serial connection to the printer, you might want to adjust these if you are experiencing connection problems""" maxCommunicationTimeouts: SerialMaxTimeouts = SerialMaxTimeouts() maxWritePasses: int = 5 """Maximum number of write attempts to serial during which nothing can be written before the communication with the printer is considered dead and OctoPrint will disconnect with an error""" additionalPorts: List[str] = [] """Use this to define additional patterns to consider for serial port listing. Must be a valid ["glob" pattern](http://docs.python.org/3/library/glob.html)""" additionalBaudrates: List[int] = [] """Use this to define additional baud rates to offer for connecting to serial ports. Must be a valid integer""" blacklistedPorts: List[str] = [] blacklistedBaudrates: List[int] = [] longRunningCommands: List[str] = [ "G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600", ] """Commands which are known to take a long time to be acknowledged by the firmware, e.g. homing, dwelling, auto leveling etc.""" blockedCommands: List[str] = ["M0", "M1"] """Commands which should not be sent to the printer, e.g. because they are known to block serial communication until physical interaction with the printer as is the case on most firmwares with the default M0 and M1.""" ignoredCommands: List[str] = [] """Commands which should not be sent to the printer and just silently ignored. An example of when you may wish to use this could be useful if you wish to manually change a filament on M600, by using that as a Pausing command.""" pausingCommands: List[str] = ["M0", "M1", "M25"] """Commands which should cause OctoPrint to pause any ongoing prints.""" emergencyCommands: List[str] = ["M112", "M108", "M410"] checksumRequiringCommands: List[str] = ["M110"] """Commands which need to always be send with a checksum.""" helloCommand: str = "M110 N0" """Command to send in order to initiate a handshake with the printer.""" disconnectOnErrors: bool = True """Whether to disconnect from the printer on errors or not.""" ignoreErrorsFromFirmware: bool = False """Whether to completely ignore errors from the firmware or not.""" terminalLogSize: int = 20 lastLineBufferSize: int = 50 logResends: bool = True """Whether to log resends to octoprint.log or not. Invaluable debug tool without performance impact, leave on if possible please.""" supportResendsWithoutOk: AlwaysDetectNeverEnum = "detect" """Whether to support resends without follow-up ok or not.""" logPositionOnPause: bool = True logPositionOnCancel: bool = False abortHeatupOnCancel: bool = True waitForStartOnConnect: bool = False """Whether OctoPrint should wait for the `start` response from the printer before trying to send commands during connect.""" waitToLoadSdFileList: bool = True """Specifies whether OctoPrint should wait to load the SD card file list until the first firmware capability report is processed.""" alwaysSendChecksum: bool = False """Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for successful communication with Repetier firmware.""" neverSendChecksum: bool = False sendChecksumWithUnknownCommands: bool = False r"""Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not* detected as valid GCODE (as in, they do not match the regular expression `^\s*([GM]\d+|T)`).""" unknownCommandsNeedAck: bool = False r"""Specifies whether OctoPrint should also use up acknowledgments (`ok`) for commands that are *not* detected as valid GCODE (as in, they do not match the regular expression `^\s*([GM]\d+|T)`).""" sdRelativePath: bool = False """Specifies whether firmware expects relative paths for selecting SD files.""" sdAlwaysAvailable: bool = False """Whether to always assume that an SD card is present in the printer. Needed by some firmwares which don't report the SD card status properly.""" sdLowerCase: bool = False sdCancelCommand: str = "M25" maxNotSdPrinting: int = 2 swallowOkAfterResend: bool = True repetierTargetTemp: bool = False """Whether the printer sends repetier style target temperatures in the format `TargetExtr0:<temperature>` instead of attaching that information to the regular `M105` responses.""" externalHeatupDetection: bool = True """Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to communication, so disable for printers running Repetier firmware.""" supportWait: bool = True ignoreIdenticalResends: bool = False """Whether to ignore identical resends from the printer (true, repetier) or not (false).""" identicalResendsCountdown: int = 7 """If `ignoreIdenticalResends` is true, how many consecutive identical resends to ignore.""" supportFAsCommand: bool = False """Whether to support `F` on its own as a valid GCODE command (true) or not (false).""" firmwareDetection: bool = True """Whether to attempt to auto detect the firmware of the printer and adjust settings accordingly (true) or not and rely on manual configuration (false).""" blockWhileDwelling: bool = False """Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier) or not (false).""" useParityWorkaround: AlwaysDetectNeverEnum = "detect" maxConsecutiveResends: int = 10 sendM112OnError: bool = True disableSdPrintingDetection: bool = False ackMax: int = 1 sanityCheckTools: bool = True notifySuppressedCommands: InfoWarnNeverEnum = "warn" capabilities: SerialCapabilities = SerialCapabilities() resendRatioThreshold: int = 10 """Percentage of resend requests among all sent lines that should be considered critical.""" resendRatioStart: int = 100 ignoreEmptyPorts: bool = False encoding: str = "ascii" """Encoding to use when talking to a machine. `ascii` limits access to characters 0-127, `latin_1` enables access to the "extended" ascii characters 0-255. Other values can be used, see [Python's standard encodings](https://docs.python.org/3/library/codecs.html#standard-encodings).""" enableShutdownActionCommand: bool = False """Whether to enable support for the shutdown action command, allowing the printer to shut down OctoPrint and the system it's running on.""" # command specific flags triggerOkForM29: bool = True """Whether to automatically trigger an ok for `M29` (a lot of versions of this command are buggy and the response skips on the ok)."""
10,859
Python
.py
177
56.084746
289
0.731868
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,837
folder.py
OctoPrint_OctoPrint/src/octoprint/schema/config/folder.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class FolderConfig(BaseModel): uploads: Optional[str] = None """Absolute path where to store gcode uploads. Defaults to the `uploads` folder in OctoPrint's base folder.""" timelapse: Optional[str] = None """Absolute path where to store finished timelase recordings. Defaults to the `timelapse` folder in OctoPrint's base folder.""" timelapse_tmp: Optional[str] = None """Absolute path where to store temporary timelapse snapshots. Defaults to the `timelapse/tmp` folder in OctoPrint's base folder.""" logs: Optional[str] = None """Absolute path where to store logs. Defaults to the `logs` folder in OctoPrint's base folder.""" virtualSd: Optional[str] = None """Absolute path where to store the virtual printer's SD card files. Defaults to the `virtualSd` folder in OctoPrint's base folder.""" watched: Optional[str] = None """Absolute path to the watched folder. Defaults to the `watched` folder in OctoPrint's base folder.""" plugins: Optional[str] = None """Absolute path where to locate and install single file plugins. Defaults to the `plugins` folder in OctoPrint's base folder.""" slicingProfiles: Optional[str] = None """Absolute path where to store slicing profiles. Defaults to the `slicingProfiles` folder in OctoPrint's base folder.""" printerProfiles: Optional[str] = None """Absolute path where to store printer profiles. Defaults to the `printerProfiles` folder in OctoPrint's base folder.""" scripts: Optional[str] = None """Absolute path where to store (GCODE) scripts. Defaults to the `scripts` folder in OctoPrint's base folder.""" translations: Optional[str] = None """Absolute path where to store additional translations. Defaults to the `translations` folder in OctoPrint's base folder.""" generated: Optional[str] = None """Absolute path where to store generated files. Defaults to the `generated` folder in OctoPrint's base folder.""" data: Optional[str] = None """Absolute path where to store additional data. Defaults to the `data` folder in OctoPrint's base folder."""
2,453
Python
.py
33
69.69697
138
0.744176
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,838
printer_profiles.py
OctoPrint_OctoPrint/src/octoprint/schema/config/printer_profiles.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class PrinterProfilesConfig(BaseModel): default: Optional[str] = None """Name of the printer profile to default to."""
468
Python
.py
9
49.666667
103
0.782418
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,839
estimation.py
OctoPrint_OctoPrint/src/octoprint/schema/config/estimation.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class PrintTimeEstimationConfig(BaseModel): statsWeighingUntil: float = 0.5 """Until which percentage to do a weighted mixture of statistical duration (analysis or past prints) with the result from the calculated estimate if that's already available. Utilized to compensate for the fact that the earlier in a print job, the least accuracy even a stable calculated estimate provides.""" validityRange: float = 0.15 """Range the assumed percentage (based on current estimated statistical, calculated or mixed total vs elapsed print time so far) needs to be around the actual percentage for the result to be used.""" forceDumbFromPercent: float = 0.3 """If no estimate could be calculated until this percentage and no statistical data is available, use dumb linear estimate. Value between 0 and 1.0.""" forceDumbAfterMin: float = 30.0 """If no estimate could be calculated until this many minutes into the print and no statistical data is available, use dumb linear estimate.""" stableThreshold: int = 60 """Average fluctuation between individual calculated estimates to consider in stable range. Seconds of difference.""" @with_attrs_docs class EstimationConfig(BaseModel): printTime: PrintTimeEstimationConfig = PrintTimeEstimationConfig() """Parameters for the print time estimation during an ongoing print job."""
1,681
Python
.py
20
80.2
313
0.782688
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,840
api.py
OctoPrint_OctoPrint/src/octoprint/schema/config/api.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import Dict, Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class ApiConfig(BaseModel): key: Optional[str] = None """Global API key, deprecated, use User API keys instead. Unset by default, will be generated on first run.""" apps: Dict[str, str] = {} allowCrossOrigin: bool = False """Whether to allow cross origin access to the API or not."""
653
Python
.py
12
51.25
114
0.748031
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,841
terminalfilters.py
OctoPrint_OctoPrint/src/octoprint/schema/config/terminalfilters.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class TerminalFilterEntry(BaseModel): name: str """The name of the filter.""" regex: str """The regular expression to match. Use [JavaScript regular expressions](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions).""" DEFAULT_TERMINAL_FILTERS = [ TerminalFilterEntry( name="Suppress temperature messages", regex=r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+([PBN]\d+\s+)*)?([BCLPR]|T\d*):-?\d+)", ), TerminalFilterEntry( name="Suppress SD status messages", regex=r"(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)", ), TerminalFilterEntry( name="Suppress position messages", regex=r"(Send:\s+(N\d+\s+)?M114)|(Recv:\s+(ok\s+)?X:[+-]?([0-9]*[.])?[0-9]+\s+Y:[+-]?([0-9]*[.])?[0-9]+\s+Z:[+-]?([0-9]*[.])?[0-9]+\s+E\d*:[+-]?([0-9]*[.])?[0-9]+).*", ), TerminalFilterEntry(name="Suppress wait responses", regex=r"Recv: wait"), TerminalFilterEntry( name="Suppress processing responses", regex=r"Recv: (echo:\s*)?busy:\s*processing", ), ]
1,406
Python
.py
29
43.275862
175
0.637491
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,842
appearance.py
OctoPrint_OctoPrint/src/octoprint/schema/config/appearance.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum from typing import List from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs class ColorEnum(str, Enum): red = "red" orange = "orange" yellow = "yellow" green = "green" blue = "blue" violet = "violet" default = "default" @with_attrs_docs class ComponentOrderConfig(BaseModel): navbar: List[str] = [ "settings", "systemmenu", "plugin_announcements", "plugin_logging_seriallog", "plugin_logging_plugintimingslog", "plugin_pi_support", "login", ] """Order of navbar items.""" sidebar: List[str] = [ "plugin_firmware_check_warning", "plugin_firmware_check_info", "connection", "state", "files", ] """Order of sidebar items.""" tab: List[str] = [ "temperature", "control", "plugin_gcodeviewer", "terminal", "timelapse", ] """Order of tabs.""" settings: List[str] = [ "section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts", "section_features", "features", "webcam", "accesscontrol", "plugin_gcodeviewer", "api", "plugin_appkeys", "section_octoprint", "server", "folders", "appearance", "plugin_logging", "plugin_pluginmanager", "plugin_softwareupdate", "plugin_announcements", "plugin_eventmanager", "plugin_backup", "plugin_tracking", "plugin_errortracking", "plugin_pi_support", ] """Order of settings.""" usersettings: List[str] = ["access", "interface"] """Order of user settings.""" wizard: List[str] = [ "plugin_softwareupdate_update", "plugin_backup", "plugin_corewizard_acl", "plugin_corewizard_onlinecheck", ] """Order of wizards.""" about: List[str] = [ "about", "plugin_pi_support", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager", "plugin_achievements", "plugin_achievements_2", "systeminfo", ] """Order of about dialog items.""" generic: List[str] = [] """Order of generic items.""" @with_attrs_docs class ComponentDisabledConfig(BaseModel): navbar: List[str] = [] """Disabled navbar items.""" sidebar: List[str] = [] """Disabled sidebar items.""" tab: List[str] = [] """Disabled tabs.""" settings: List[str] = [] """Disabled settings.""" usersettings: List[str] = [] """Disabled user settings.""" wizard: List[str] = [] """Disabled wizards.""" about: List[str] = [] """Disabled about dialog items.""" generic: List[str] = [] """Disabled generic items.""" @with_attrs_docs class ComponentConfig(BaseModel): order: ComponentOrderConfig = ComponentOrderConfig() """Defines the order of the components within their respective containers.""" disabled: ComponentDisabledConfig = ComponentDisabledConfig() """Disabled components per container. If a component is included here it will not be included in OctoPrint's UI at all. Note that this might mean that critical functionality will not be available if no replacement is registered.""" @with_attrs_docs class AppearanceConfig(BaseModel): name: str = "" """Use this to give your OctoPrint instance a name. It will be displayed in the title bar (as "<Name> [OctoPrint]") and in the navigation bar (as "OctoPrint: <>")""" color: ColorEnum = ColorEnum.default """Use this to color the navigation bar.""" colorTransparent: bool = False """Makes the color of the navigation bar "transparent". In case your printer uses acrylic for its frame 😉.""" colorIcon: bool = True defaultLanguage: str = "_default" """Default language of OctoPrint. If left unset OctoPrint will try to match up available languages with the user's browser settings.""" showFahrenheitAlso: bool = False fuzzyTimes: bool = True closeModalsWithClick: bool = True showInternalFilename: bool = True """Show the internal filename in the files sidebar, if necessary.""" components: ComponentConfig = ComponentConfig() """Configures the order and availability of the UI components."""
4,693
Python
.py
138
27.550725
235
0.633672
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,843
webcam.py
OctoPrint_OctoPrint/src/octoprint/schema/config/webcam.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum from typing import Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs class TimelapseTypeEnum(str, Enum): off = "off" zchange = "zchange" timed = "timed" @with_attrs_docs class TimelapseOptions(BaseModel): interval: Optional[int] = None """`timed` timelapses only: The interval which to leave between images in seconds.""" capturePostRoll: Optional[bool] = None """`timed` timelapses only: Whether to capture the snapshots for the post roll (true) or just copy the last captured snapshot from the print over and over again (false).""" retractionZHop: Optional[float] = None """`zchange` timelapses only: z-hop height during retractions to ignore for capturing snapshots.""" @with_attrs_docs class TimelapseConfig(BaseModel): type: TimelapseTypeEnum = TimelapseTypeEnum.off """The timelapse type.""" fps: int = 25 """The framerate at which to render the movie.""" postRoll: int = 0 """The number of seconds in the rendered video to add after a finished print. The exact way how the additional images will be recorded depends on timelapse type. `zchange` timelapses will take one final picture and add it `fps * postRoll` times. `timed` timelapses continue to record just like at the beginning, so the recording will continue another `fps * postRoll * interval` seconds. This behaviour can be overridden by setting the `capturePostRoll` option to `false`, in which case the post roll will be created identically to `zchange` mode.""" options: TimelapseOptions = TimelapseOptions() """Additional options depending on the timelapse type.""" @with_attrs_docs class WebcamConfig(BaseModel): webcamEnabled: bool = True """Use this option to enable display of a webcam stream in the UI, e.g. via MJPG-Streamer. Webcam support will be disabled if not set.""" timelapseEnabled: bool = True """Use this option to enable timelapse support via snapshot, e.g. via MJPG-Streamer. Timelapse support will be disabled if not set.""" ffmpeg: Optional[str] = None """Path to ffmpeg binary to use for creating timelapse recordings. Timelapse support will be disabled if not set.""" ffmpegThreads: int = 1 """Number of how many threads to instruct ffmpeg to use for encoding.""" ffmpegVideoCodec: str = "libx264" """Videocodec to be used for encoding.""" bitrate: str = "10000k" """The bitrate to use for rendering the timelapse video. This gets directly passed to ffmpeg.""" watermark: bool = True """Whether to include a "created with OctoPrint" watermark in the generated timelapse recordings.""" ffmpegCommandline: str = '{ffmpeg} -framerate {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"' ffmpegThumbnailCommandline: str = ( '{ffmpeg} -sseof -1 -i "{input}" -update 1 -q:v 0.7 "{output}"' ) timelapse: TimelapseConfig = TimelapseConfig() """The default timelapse settings.""" cleanTmpAfterDays: int = 7 """After how many days unrendered timelapses will be deleted.""" defaultWebcam: str = "classic" """The name of the default webcam""" snapshotWebcam: str = "classic" """The name of the default webcam to use for snapshots"""
3,556
Python
.py
56
58.875
554
0.73078
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,844
__init__.py
OctoPrint_OctoPrint/src/octoprint/schema/config/__init__.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import List, Union from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs from .access_control import AccessControlConfig from .api import ApiConfig from .appearance import AppearanceConfig from .controls import ContainerConfig, ControlConfig from .devel import DevelConfig from .estimation import EstimationConfig from .events import EventsConfig from .feature import FeatureConfig from .folder import FolderConfig from .gcode_analysis import GcodeAnalysisConfig from .plugins import PluginsConfig from .printer_parameters import PrinterParametersConfig from .printer_profiles import PrinterProfilesConfig from .scripts import ScriptsConfig from .serial import SerialConfig from .server import ServerConfig from .slicing import SlicingConfig from .system import SystemConfig from .temperature import TemperatureConfig from .terminalfilters import DEFAULT_TERMINAL_FILTERS, TerminalFilterEntry from .webcam import WebcamConfig @with_attrs_docs class Config(BaseModel): accessControl: AccessControlConfig = AccessControlConfig() api: ApiConfig = ApiConfig() appearance: AppearanceConfig = AppearanceConfig() controls: List[Union[ControlConfig, ContainerConfig]] = [] devel: DevelConfig = DevelConfig() estimation: EstimationConfig = EstimationConfig() events: EventsConfig = EventsConfig() feature: FeatureConfig = FeatureConfig() folder: FolderConfig = FolderConfig() gcodeAnalysis: GcodeAnalysisConfig = GcodeAnalysisConfig() plugins: PluginsConfig = PluginsConfig() printerParameters: PrinterParametersConfig = PrinterParametersConfig() printerProfiles: PrinterProfilesConfig = PrinterProfilesConfig() scripts: ScriptsConfig = ScriptsConfig() serial: SerialConfig = SerialConfig() server: ServerConfig = ServerConfig() slicing: SlicingConfig = SlicingConfig() system: SystemConfig = SystemConfig() temperature: TemperatureConfig = TemperatureConfig() terminalFilters: List[TerminalFilterEntry] = DEFAULT_TERMINAL_FILTERS webcam: WebcamConfig = WebcamConfig()
2,299
Python
.py
49
44.102041
103
0.819599
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,845
events.py
OctoPrint_OctoPrint/src/octoprint/schema/config/events.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum from typing import List, Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs class SubscriptionTypeEnum(str, Enum): system = "system" gcode = "gcode" @with_attrs_docs class EventSubscription(BaseModel): event: str """The event to subscribe to.""" name: Optional[str] = None """The event name to show on the UI""" command: str """The command to execute when the event is triggered, either a GCODE or a system command.""" type: SubscriptionTypeEnum """The type of the command.""" enabled: bool = True """Whether the event subscription should be enabled.""" debug: bool = False """If set to `true`, OctoPrint will log the command after performing all placeholder replacements.""" @with_attrs_docs class EventsConfig(BaseModel): enabled: bool = True """Whether event subscriptions should be enabled or not.""" subscriptions: List[EventSubscription] = [] """A list of event subscriptions."""
1,244
Python
.py
29
38.931034
105
0.72856
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,846
system.py
OctoPrint_OctoPrint/src/octoprint/schema/config/system.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import List, Optional from pydantic import Field from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class ActionConfig(BaseModel): action: str """The identifier used internally to identify the action. Set to `divider` to generate a divider in the menu.""" name: Optional[str] = None """The name of the action that will be shown on the menu. Must be set if the action is not a divider.""" command: Optional[str] = None """The command to execute when the action is selected. Must be set if the action is not a divider.""" async_: bool = Field(False, alias="async") """Whether to run the command asynchronously.""" confirm: Optional[str] = None """An optional confirmation message to show before executing the command.""" @with_attrs_docs class SystemConfig(BaseModel): actions: List[ActionConfig] = [] """A list of system actions to show in the UI."""
1,179
Python
.py
22
49.909091
116
0.737347
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,847
server.py
OctoPrint_OctoPrint/src/octoprint/schema/config/server.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum from typing import Dict, List, Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs CONST_15MIN = 15 * 60 CONST_1GB = 1024 * 1024 * 1024 CONST_500MB = 500 * 1024 * 1024 CONST_200MB = 200 * 1024 * 1024 CONST_100KB = 100 * 1024 @with_attrs_docs class ReverseProxyConfig(BaseModel): prefixHeader: Optional[str] = None """The request header from which to determine the URL prefix under which OctoPrint is served by the reverse proxy.""" schemeHeader: Optional[str] = None """The request header from which to determine the scheme (http or https) under which a specific request to OctoPrint was made to the reverse proxy.""" hostHeader: Optional[str] = None """The request header from which to determine the host under which OctoPrint is served by the reverse proxy.""" serverHeader: Optional[str] = None portHeader: Optional[str] = None prefixFallback: Optional[str] = None """Use this option to define an optional URL prefix (with a leading /, so absolute to your server's root) under which to run OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse proxy under a different root endpoint than `/` and can't configure said reverse proxy to send a prefix HTTP header (X-Script-Name by default, see above) with forwarded requests.""" schemeFallback: Optional[str] = None """Use this option to define an optional forced scheme (http or https) under which to run OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse proxy that also does HTTPS determination but can't configure said reverse proxy to send a scheme HTTP header (X-Scheme by default, see above) with forwarded requests.""" hostFallback: Optional[str] = None """Use this option to define an optional forced host under which to run OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse proxy with a different hostname than OctoPrint itself but can't configure said reverse proxy to send a host HTTP header (X-Forwarded-Host by default, see above) with forwarded requests.""" serverFallback: Optional[str] = None portFallback: Optional[str] = None trustedDownstream: List[str] = ["127.0.0.1", "::1"] """List of trusted downstream servers for which to ignore the IP address when trying to determine the connecting client's IP address. A reverse proxy on the same machine as OctoPrint (e.g. as found on OctoPi) will be handled correctly by default, further proxies in front of that you'll have to add yourself.""" @with_attrs_docs class UploadsConfig(BaseModel): maxSize: int = CONST_1GB """Maximum size of uploaded files in bytes, defaults to 1GB.""" nameSuffix: str = "name" """Suffix used for storing the filename in the file upload headers when streaming uploads.""" pathSuffix: str = "path" """Suffix used for storing the path to the temporary file in the file upload headers when streaming uploads.""" @with_attrs_docs class CommandsConfig(BaseModel): systemShutdownCommand: Optional[str] = None """Command to shut down the system OctoPrint is running on.""" systemRestartCommand: Optional[str] = None """Command to restart the system OctoPrint is running on.""" serverRestartCommand: Optional[str] = None """Command to restart OctoPrint.""" localPipCommand: Optional[str] = None """pip command associated with OctoPrint, used for installing plugins and updates, if unset (default) the command will be autodetected based on the current python executable - unless you have a really special setup this is the right way to do it and there should be no need to ever touch this setting.""" @with_attrs_docs class OnlineCheckConfig(BaseModel): enabled: Optional[bool] = None """Whether the online check is enabled. Ships unset, the user will be asked to make a decision as part of the setup wizard.""" interval: int = CONST_15MIN """Interval in which to check for online connectivity (in seconds), defaults to 15 minutes.""" host: str = "1.1.1.1" """DNS host against which to check, defaults to Cloudflare's DNS.""" port: int = 53 """DNS port against which to check, defaults to the standard DNS port.""" name: str = "octoprint.org" """Host name for which to check name resolution, defaults to OctoPrint's main domain.""" @with_attrs_docs class PluginBlacklistConfig(BaseModel): enabled: Optional[bool] = None """Whether use of the blacklist is enabled. If unset, the user will be asked to make a decision as part of the setup wizard.""" url: str = "https://plugins.octoprint.org/blacklist.json" """The URL from which to fetch the blacklist.""" ttl: int = CONST_15MIN """Time to live of the cached blacklist, in seconds (default: 15 minutes).""" timeout: float = 3.05 """Timeout for fetching the blacklist, in seconds (default: 3.05 seconds).""" @with_attrs_docs class DiskspaceConfig(BaseModel): warning: int = CONST_500MB """Threshold (bytes) after which to consider disk space becoming sparse, defaults to 500MB.""" critical: int = CONST_200MB """Threshold (bytes) after which to consider disk space becoming critical, defaults to 200MB.""" @with_attrs_docs class PreemptiveCacheConfig(BaseModel): exceptions: List[str] = [] """Which server paths to exclude from the preemptive cache, e.g. `/some/path`.""" until: int = 7 """How many days to leave unused entries in the preemptive cache config.""" @with_attrs_docs class IpCheckConfig(BaseModel): enabled: bool = True """Whether to enable the check.""" trustedSubnets: List[str] = [] """Additional non-local subnets to consider trusted, in CIDR notation, e.g. `192.168.1.0/24`.""" class SameSiteEnum(str, Enum): strict = "Strict" lax = "Lax" none = "None" @with_attrs_docs class CookiesConfig(BaseModel): secure: bool = False """Whether to set the `Secure` flag to true on cookies. Only set to true if you are running OctoPrint behind a reverse proxy taking care of SSL termination.""" samesite: Optional[SameSiteEnum] = SameSiteEnum.lax """`SameSite` setting to use on the cookies. Possible values are `None`, `Lax` and `Strict`. Defaults to `Lax`. Be advised that if forced unset, this has security implications as many browsers now default to `Lax` unless you configure cookies to be set with `Secure` flag set, explicitly set `SameSite` setting here and also serve OctoPrint over https. The `Lax` setting is known to cause with embedding OctoPrint in frames. See also ["Feature: Cookies default to SameSite=Lax"](https://www.chromestatus.com/feature/5088147346030592), ["Feature: Reject insecure SameSite=None cookies"](https://www.chromestatus.com/feature/5633521622188032) and [issue #3482](https://github.com/OctoPrint/OctoPrint/issues/3482).""" @with_attrs_docs class ServerConfig(BaseModel): host: Optional[str] = None """Use this option to define the host to which to bind the server. If unset, OctoPrint will attempt to bind on all available interfaces, IPv4 and v6 unless either is disabled.""" port: int = 5000 """Use this option to define the port to which to bind the server.""" firstRun: bool = True """If this option is true, OctoPrint will show the First Run wizard and set the setting to false after that completes.""" startOnceInSafeMode: bool = False """If this option is true, OctoPrint will enable safe mode on the next server start and reset the setting to false""" ignoreIncompleteStartup: bool = False """Set this to true to make OctoPrint ignore incomplete startups. Helpful for development.""" seenWizards: Dict[str, str] = {} secretKey: Optional[str] = None """Secret key for encrypting cookies and such, randomly generated on first run.""" heartbeat: int = CONST_15MIN reverseProxy: ReverseProxyConfig = ReverseProxyConfig() """Settings if OctoPrint is running behind a reverse proxy (haproxy, nginx, apache, ...) that doesn't correctly set the [required headers](https://community.octoprint.org/t/reverse-proxy-configuration-examples/1107). These are necessary in order to make OctoPrint generate correct external URLs so that AJAX requests and download URLs work, and so that client IPs are read correctly.""" uploads: UploadsConfig = UploadsConfig() """Settings for file uploads to OctoPrint, such as maximum allowed file size and header suffixes to use for streaming uploads. OctoPrint does some nifty things internally in order to allow streaming of large file uploads to the application rather than just storing them in memory. For that it needs to do some rewriting of the incoming upload HTTP requests, storing the uploaded file to a temporary location on disk and then sending an internal request to the application containing the original filename and the location of the temporary file.""" maxSize: int = CONST_100KB """Maximum size of requests other than file uploads in bytes, defaults to 100KB.""" commands: CommandsConfig = CommandsConfig() """Commands to restart/shutdown octoprint or the system it's running on.""" onlineCheck: OnlineCheckConfig = OnlineCheckConfig() """Configuration of the regular online connectivity check.""" pluginBlacklist: PluginBlacklistConfig = PluginBlacklistConfig() """Configuration of the plugin blacklist.""" diskspace: DiskspaceConfig = DiskspaceConfig() """Settings of when to display what disk space warning.""" preemptiveCache: PreemptiveCacheConfig = PreemptiveCacheConfig() """Configuration of the preemptive cache.""" ipCheck: IpCheckConfig = IpCheckConfig() """Configuration of the client IP check to warn about connections from external networks.""" allowFraming: bool = False """Whether to allow OctoPrint to be embedded in a frame or not. Note that depending on your setup you might have to set SameSite to None, Secure to true and serve OctoPrint through a reverse proxy that enables https for cookies and thus logging in to work.""" cookies: CookiesConfig = CookiesConfig() """Settings for further configuration of the cookies that OctoPrint sets (login, remember me, ...).""" allowedLoginRedirectPaths: List[str] = [] """List of paths that are allowed to be used as redirect targets for the login page, in addition to the default ones (`/`, `/recovery/` and `/plugin/appkeys/auth/`)"""
10,741
Python
.py
139
72.690647
718
0.747626
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,848
printer_parameters.py
OctoPrint_OctoPrint/src/octoprint/schema/config/printer_parameters.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import List from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class PrinterParametersConfig(BaseModel): pauseTriggers: List[str] = []
413
Python
.py
8
49.625
103
0.793017
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,849
scripts.py
OctoPrint_OctoPrint/src/octoprint/schema/config/scripts.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from typing import Dict, Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs @with_attrs_docs class GcodeScriptsConfig(BaseModel): afterPrinterConnected: Optional[str] = None beforePrinterDisconnected: Optional[str] = None beforePrintStarted: Optional[str] = None afterPrintCancelled: Optional[ str ] = "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0" afterPrintDone: Optional[str] = None beforePrintPaused: Optional[str] = None afterPrintResumed: Optional[str] = None beforeToolChange: Optional[str] = None afterToolChange: Optional[str] = None snippets: Dict[str, str] = { "disable_hotends": "{% if printer_profile.extruder.sharedNozzle %}M104 T0 S0\n{% else %}{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}{% endif %}", "disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}", } @with_attrs_docs class ScriptsConfig(BaseModel): gcode: GcodeScriptsConfig = GcodeScriptsConfig()
1,353
Python
.py
25
49.84
197
0.726929
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,850
__init__.py
OctoPrint_OctoPrint/src/octoprint/schema/webcam/__init__.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from enum import Enum from typing import List, Optional from octoprint.schema import BaseModel from octoprint.vendor.with_attrs_docs import with_attrs_docs class RatioEnum(str, Enum): sixteen_nine = "16:9" four_three = "4:3" @with_attrs_docs class WebcamCompatibility(BaseModel): streamTimeout: int = 5 """The timeout of the stream in seconds""" streamRatio: RatioEnum = RatioEnum.sixteen_nine """The stream's native aspect ratio""" streamWebrtcIceServers: List[str] = ["stun:stun.l.google.com:19302"] """The WebRTC STUN and TURN servers""" cacheBuster: bool = False """Whether the URL should be randomized to bust caches""" stream: str """The URL to get an MJPEG stream from""" snapshot: str = None """The URL to get the snapshot from""" snapshotTimeout: int = 5 """The timeout when retrieving snapshots""" snapshotSslValidation: bool = True """Whether to validate SSL certificates when retrieving a snapshot""" @with_attrs_docs class Webcam(BaseModel): name: str """Identifier of this webcam""" displayName: str """Displayable name for this webcam""" canSnapshot: bool = False """Whether this webcam can take a snapshot.""" snapshotDisplay: str = None """Human readable information about how a snapshot is captured or a HTTP URL from which the snapshot is loaded (optional, only for user reference)""" flipH: bool = False """Whether to flip the webcam horizontally.""" flipV: bool = False """Whether to flip the webcam vertically.""" rotate90: bool = False """Whether to rotate the webcam 90° counter clockwise.""" extras: dict = {} """Unstructured data describing this webcam""" compat: Optional[WebcamCompatibility] = None """A compatibility configuration to allow older clients to make use of this webcam"""
2,073
Python
.py
47
39.553191
153
0.716925
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,851
profile.py
OctoPrint_OctoPrint/src/octoprint/printer/profile.py
""" This module contains printer profile related code. A printer profile is a ``dict`` of the following structure: .. list-table:: :widths: 15 5 30 :header-rows: 1 * - Name - Type - Description * - ``id`` - ``string`` - Internal id of the printer profile * - ``name`` - ``string`` - Human readable name of the printer profile * - ``model`` - ``string`` - Printer model * - ``color`` - ``string`` - Color to associate with the printer profile * - ``volume`` - ``dict`` - Information about the print volume * - ``volume.width`` - ``float`` - Width of the print volume (X axis) * - ``volume.depth`` - ``float`` - Depth of the print volume (Y axis) * - ``volume.height`` - ``float`` - Height of the print volume (Z axis) * - ``volume.formFactor`` - ``string`` - Form factor of the print bed, either ``rectangular`` or ``circular`` * - ``volume.origin`` - ``string`` - Location of gcode origin in the print volume, either ``lowerleft`` or ``center`` * - ``volume.custom_box`` - ``dict`` or ``False`` - Custom boundary box overriding the default bounding box based on the provided width, depth, height and origin. If ``False``, the default boundary box will be used. * - ``volume.custom_box.x_min`` - ``float`` - Minimum valid X coordinate * - ``volume.custom_box.y_min`` - ``float`` - Minimum valid Y coordinate * - ``volume.custom_box.z_min`` - ``float`` - Minimum valid Z coordinate * - ``volume.custom_box.x_max`` - ``float`` - Maximum valid X coordinate * - ``volume.custom_box.y_max`` - ``float`` - Maximum valid Y coordinate * - ``volume.custom_box.z_max`` - ``float`` - Maximum valid Z coordinate * - ``heatedBed`` - ``bool`` - Whether the printer has a heated bed (``True``) or not (``False``) * - ``heatedChamber`` - ``bool`` - Whether the printer has a heated chamber (``True``) or not (``False``) * - ``extruder`` - ``dict`` - Information about the printer's extruders * - ``extruder.count`` - ``int`` - How many extruders the printer has (default 1) * - ``extruder.offsets`` - ``list`` of ``tuple`` - Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0) * - ``extruder.nozzleDiameter`` - ``float`` - Diameter of the printer nozzle(s) * - ``extruder.sharedNozzle`` - ``boolean`` - Whether there's only one nozzle shared among all extruders (true) or one nozzle per extruder (false). * - ``extruder.defaultExtrusionLength`` - ``int`` - Default extrusion length used in Control tab on initial page load in mm. * - ``axes`` - ``dict`` - Information about the printer axes * - ``axes.x`` - ``dict`` - Information about the printer's X axis * - ``axes.x.speed`` - ``float`` - Speed of the X axis in mm/min * - ``axes.x.inverted`` - ``bool`` - Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True) * - ``axes.y`` - ``dict`` - Information about the printer's Y axis * - ``axes.y.speed`` - ``float`` - Speed of the Y axis in mm/min * - ``axes.y.inverted`` - ``bool`` - Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True) * - ``axes.z`` - ``dict`` - Information about the printer's Z axis * - ``axes.z.speed`` - ``float`` - Speed of the Z axis in mm/min * - ``axes.z.inverted`` - ``bool`` - Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True) * - ``axes.e`` - ``dict`` - Information about the printer's E axis * - ``axes.e.speed`` - ``float`` - Speed of the E axis in mm/min * - ``axes.e.inverted`` - ``bool`` - Whether a positive value change extrudes (False, default) or retracts (True) filament .. autoclass:: PrinterProfileManager :members: .. autoclass:: BedFormFactor :members: .. autoclass:: BedOrigin :members: .. autoclass:: SaveError .. autoclass:: CouldNotOverwriteError .. autoclass:: InvalidProfileError """ __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import copy import logging import os from octoprint.settings import settings from octoprint.util import ( dict_contains_keys, dict_merge, dict_sanitize, is_hidden_path, yaml, ) class SaveError(Exception): """Saving a profile failed""" pass class CouldNotOverwriteError(SaveError): """Overwriting of a profile not allowed""" pass class InvalidProfileError(Exception): """Profile invalid""" pass class BedFormFactor: """Valid values for bed form factor""" RECTANGULAR = "rectangular" """Rectangular bed""" CIRCULAR = "circular" """Circular bed""" @classmethod def values(cls): return [ getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values") ] BedTypes = BedFormFactor """Deprecated name of :class:`BedFormFactors`""" class BedOrigin: """Valid values for bed origin""" LOWERLEFT = "lowerleft" """Origin at lower left corner of the bed when looking from the top""" CENTER = "center" """Origin at the center of the bed when looking from top""" @classmethod def values(cls): return [ getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values") ] class PrinterProfileManager: """ Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove, load and save printer profiles. """ default = { "id": "_default", "name": "Default", "model": "Generic RepRap Printer", "color": "default", "volume": { "width": 200, "depth": 200, "height": 200, "formFactor": BedFormFactor.RECTANGULAR, "origin": BedOrigin.LOWERLEFT, "custom_box": False, }, "heatedBed": True, "heatedChamber": False, "extruder": { "count": 1, "offsets": [(0, 0)], "nozzleDiameter": 0.4, "sharedNozzle": False, "defaultExtrusionLength": 5, }, "axes": { "x": {"speed": 6000, "inverted": False}, "y": {"speed": 6000, "inverted": False}, "z": {"speed": 200, "inverted": False}, "e": {"speed": 300, "inverted": False}, }, } def __init__(self): self._current = None self._logger = logging.getLogger(__name__) fresh = settings().checkBaseFolder("printerProfiles") self._folder = settings().getBaseFolder("printerProfiles") self._migrate_old_default_profile() self._verify_default_available(fresh=fresh) def _migrate_old_default_profile(self): default_overrides = settings().get(["printerProfiles", "defaultProfile"]) if not default_overrides: return if self.exists("_default"): return if not isinstance(default_overrides, dict): self._logger.warning( "Existing default profile from settings is not a valid profile, refusing to migrate: {!r}".format( default_overrides ) ) return default_overrides["id"] = "_default" self.save(default_overrides) settings().set(["printerProfiles", "defaultProfile"], None) settings().save() self._logger.info( "Migrated default printer profile from settings to _default.profile: {!r}".format( default_overrides ) ) def _verify_default_available(self, fresh=False): default_id = settings().get(["printerProfiles", "default"]) if default_id is None: default_id = "_default" if not self.exists(default_id): if not self.exists("_default"): if not fresh: if default_id == "_default": self._logger.error( "Profile _default does not exist, creating _default again and setting it as default" ) else: self._logger.error( "Selected default profile {} and _default do not exist, creating _default again and setting it as default".format( default_id ) ) self.save(self.__class__.default, allow_overwrite=True, make_default=True) else: self._logger.error( "Selected default profile {} does not exists, resetting to _default".format( default_id ) ) settings().set(["printerProfiles", "default"], "_default") settings().save() default_id = "_default" profile = self.get(default_id) if profile is None: self._logger.error( "Selected default profile {} is invalid, resetting to default values".format( default_id ) ) profile = copy.deepcopy(self.__class__.default) profile["id"] = default_id self.save(self.__class__.default, allow_overwrite=True, make_default=True) def select(self, identifier): if identifier is None or not self.exists(identifier): self._current = self.get_default() return False else: self._current = self.get(identifier) if self._current is None: self._logger.error( "Profile {} is invalid, cannot select, falling back to default".format( identifier ) ) self._current = self.get_default() return False else: return True def deselect(self): self._current = None def get_all(self): return self._load_all() def get(self, identifier): try: if self.exists(identifier): return self._load_from_path(self._get_profile_path(identifier)) else: return None except InvalidProfileError: return None def remove(self, identifier, trigger_event=False): if self._current is not None and self._current["id"] == identifier: return False elif settings().get(["printerProfiles", "default"]) == identifier: return False removed = self._remove_from_path(self._get_profile_path(identifier)) if removed and trigger_event: from octoprint.events import Events, eventManager payload = {"identifier": identifier} eventManager().fire(Events.PRINTER_PROFILE_DELETED, payload=payload) return removed def save( self, profile, allow_overwrite=False, make_default=False, trigger_event=False ): if "id" in profile: identifier = profile["id"] elif "name" in profile: identifier = profile["name"] else: raise InvalidProfileError("profile must contain either id or name") identifier = self._sanitize(identifier) profile["id"] = identifier self._migrate_profile(profile) profile = dict_sanitize(profile, self.__class__.default) profile = dict_merge(self.__class__.default, profile) path = self._get_profile_path(identifier) is_overwrite = os.path.exists(path) self._save_to_path(path, profile, allow_overwrite=allow_overwrite) if make_default: settings().set(["printerProfiles", "default"], identifier) settings().save() if self._current is not None and self._current["id"] == identifier: self.select(identifier) from octoprint.events import Events, eventManager if trigger_event: payload = {"identifier": identifier} event = ( Events.PRINTER_PROFILE_MODIFIED if is_overwrite else Events.PRINTER_PROFILE_ADDED ) eventManager().fire(event, payload=payload) return self.get(identifier) def is_default_unmodified(self): default = settings().get(["printerProfiles", "default"]) return default is None or default == "_default" or not self.exists("_default") @property def profile_count(self): return len(self._load_all_identifiers()) @property def last_modified(self): dates = [os.stat(self._folder).st_mtime] dates += [ entry.stat().st_mtime for entry in os.scandir(self._folder) if entry.name.endswith(".profile") ] return max(dates) def get_default(self): default = settings().get(["printerProfiles", "default"]) if default is not None and self.exists(default): profile = self.get(default) if profile is not None: return profile else: self._logger.warning( "Default profile {} is invalid, falling back to built-in defaults".format( default ) ) return copy.deepcopy(self.__class__.default) def set_default(self, identifier): all_identifiers = self._load_all_identifiers() if identifier is not None and identifier not in all_identifiers: return settings().set(["printerProfiles", "default"], identifier) settings().save() def get_current_or_default(self): if self._current is not None: return self._current else: return self.get_default() def get_current(self): return self._current def exists(self, identifier): if identifier is None: return False else: path = self._get_profile_path(identifier) return os.path.exists(path) and os.path.isfile(path) def _load_all(self): all_identifiers = self._load_all_identifiers() results = {} for identifier, path in all_identifiers.items(): try: profile = self._load_from_path(path) except InvalidProfileError: self._logger.warning(f"Profile {identifier} is invalid, skipping") continue if profile is None: continue results[identifier] = dict_merge(self.__class__.default, profile) return results def _load_all_identifiers(self): results = {} for entry in os.scandir(self._folder): if is_hidden_path(entry.name) or not entry.name.endswith(".profile"): continue if not entry.is_file(): continue identifier = entry.name[: -len(".profile")] results[identifier] = entry.path return results def _load_from_path(self, path): if not os.path.exists(path) or not os.path.isfile(path): return None profile = yaml.load_from_file(path=path) if profile is None or not isinstance(profile, dict): raise InvalidProfileError("Profile is None or not a dictionary") if self._migrate_profile(profile): try: self._save_to_path(path, profile, allow_overwrite=True) except Exception: self._logger.exception( "Tried to save profile to {path} after migrating it while loading, ran into exception".format( path=path ) ) profile = self._ensure_valid_profile(profile) if not profile: self._logger.warning("Invalid profile: %s" % path) raise InvalidProfileError() return profile def _save_to_path(self, path, profile, allow_overwrite=False): validated_profile = self._ensure_valid_profile(profile) if not validated_profile: raise InvalidProfileError() if os.path.exists(path) and not allow_overwrite: raise SaveError( "Profile %s already exists and not allowed to overwrite" % profile["id"] ) from octoprint.util import atomic_write try: with atomic_write(path, mode="wt", max_permissions=0o666) as f: yaml.save_to_file(profile, file=f, pretty=True) except Exception as e: self._logger.exception( "Error while trying to save profile %s" % profile["id"] ) raise SaveError("Cannot save profile {}: {}".format(profile["id"], str(e))) def _remove_from_path(self, path): try: os.remove(path) return True except Exception: return False def _get_profile_path(self, identifier): return os.path.join(self._folder, "%s.profile" % identifier) def _sanitize(self, name): if name is None: return None if "/" in name or "\\" in name: raise ValueError("name must not contain / or \\") import string valid_chars = "-_.() {ascii}{digits}".format( ascii=string.ascii_letters, digits=string.digits ) sanitized_name = "".join(c for c in name if c in valid_chars) sanitized_name = sanitized_name.replace(" ", "_") return sanitized_name def _migrate_profile(self, profile): # make sure profile format is up to date modified = False if ( "volume" in profile and "formFactor" in profile["volume"] and "origin" not in profile["volume"] ): profile["volume"]["origin"] = ( BedOrigin.CENTER if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR else BedOrigin.LOWERLEFT ) modified = True if "volume" in profile and "custom_box" not in profile["volume"]: profile["volume"]["custom_box"] = False modified = True if "extruder" in profile and "sharedNozzle" not in profile["extruder"]: profile["extruder"]["sharedNozzle"] = False modified = True if ( "extruder" in profile and "sharedNozzle" in profile["extruder"] and profile["extruder"]["sharedNozzle"] ): profile["extruder"]["offsets"] = [(0.0, 0.0)] modified = True if "extruder" in profile and "defaultExtrusionLength" not in profile["extruder"]: profile["extruder"]["defaultExtrusionLength"] = self.default["extruder"][ "defaultExtrusionLength" ] modified = True if "heatedChamber" not in profile: profile["heatedChamber"] = False modified = True return modified def _ensure_valid_profile(self, profile): # ensure all keys are present if not dict_contains_keys(self.default, profile): self._logger.warning( "Profile invalid, missing keys. Expected: {expected!r}. Actual: {actual!r}".format( expected=list(self.default.keys()), actual=list(profile.keys()) ) ) return False # conversion helper def convert_value(profile, path, converter): value = profile for part in path[:-1]: if not isinstance(value, dict) or part not in value: raise RuntimeError("%s is not contained in profile" % ".".join(path)) value = value[part] if not isinstance(value, dict) or path[-1] not in value: raise RuntimeError("%s is not contained in profile" % ".".join(path)) value[path[-1]] = converter(value[path[-1]]) def validate_value(profile, path, validator): value = profile for part in path[:-1]: if not isinstance(value, dict) or part not in value: raise RuntimeError("%s is not contained in profile" % ".".join(path)) value = value[part] if not isinstance(value, dict) or path[-1] not in value: raise RuntimeError("%s is not contained in profile" % ".".join(path)) return validator(value[path[-1]]) # convert ints for path in ( ("extruder", "count"), ("axes", "x", "speed"), ("axes", "y", "speed"), ("axes", "z", "speed"), ("axes", "e", "speed"), ): try: convert_value(profile, path, int) except Exception as e: self._logger.warning( "Profile has invalid value for path {path!r}: {msg}".format( path=".".join(path), msg=str(e) ) ) return False # convert floats for path in ( ("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter"), ): try: convert_value(profile, path, float) except Exception as e: self._logger.warning( "Profile has invalid value for path {path!r}: {msg}".format( path=".".join(path), msg=str(e) ) ) return False # convert booleans for path in ( ("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted"), ("extruder", "sharedNozzle"), ): try: convert_value(profile, path, bool) except Exception as e: self._logger.warning( "Profile has invalid value for path {path!r}: {msg}".format( path=".".join(path), msg=str(e) ) ) return False # validate volume size range for path in ( ("volume", "width"), ("volume", "depth"), ("volume", "height"), ): if not validate_value(profile, path, lambda x: x > 0 and x < 10000): return False # validate extruder count range if not validate_value( profile, ("extruder", "count"), lambda x: x > 0 and x < 100 ): return False # validate form factor if profile["volume"]["formFactor"] not in BedFormFactor.values(): self._logger.warning( "Profile has invalid value volume.formFactor: {formFactor}".format( formFactor=profile["volume"]["formFactor"] ) ) return False # validate origin type if profile["volume"]["origin"] not in BedOrigin.values(): self._logger.warning( "Profile has invalid value in volume.origin: {origin}".format( origin=profile["volume"]["origin"] ) ) return False # ensure origin and form factor combination is legal if ( profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR and not profile["volume"]["origin"] == BedOrigin.CENTER ): profile["volume"]["origin"] = BedOrigin.CENTER # force width and depth of volume to be identical for circular beds, with width being the reference if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR: profile["volume"]["depth"] = profile["volume"]["width"] # if we have a custom bounding box, validate it if profile["volume"]["custom_box"] and isinstance( profile["volume"]["custom_box"], dict ): if not len(profile["volume"]["custom_box"]): profile["volume"]["custom_box"] = False else: default_box = self._default_box_for_volume(profile["volume"]) for prop, limiter in ( ("x_min", min), ("y_min", min), ("z_min", min), ("x_max", max), ("y_max", max), ("z_max", max), ): if ( prop not in profile["volume"]["custom_box"] or profile["volume"]["custom_box"][prop] is None ): profile["volume"]["custom_box"][prop] = default_box[prop] else: value = profile["volume"]["custom_box"][prop] try: value = limiter(float(value), default_box[prop]) profile["volume"]["custom_box"][prop] = value except Exception: self._logger.warning( "Profile has invalid value in volume.custom_box.{}: {!r}".format( prop, value ) ) return False # make sure we actually do have a custom box and not just the same values as the # default box for prop in profile["volume"]["custom_box"]: if profile["volume"]["custom_box"][prop] != default_box[prop]: break else: # exactly the same as the default box, remove custom box profile["volume"]["custom_box"] = False # validate offsets offsets = [] for offset in profile["extruder"]["offsets"]: if not len(offset) == 2: self._logger.warning( "Profile has an invalid extruder.offsets entry: {entry!r}".format( entry=offset ) ) return False x_offset, y_offset = offset try: offsets.append((float(x_offset), float(y_offset))) except Exception: self._logger.warning( "Profile has an extruder.offsets entry with non-float values: {entry!r}".format( entry=offset ) ) return False profile["extruder"]["offsets"] = offsets return profile @staticmethod def _default_box_for_volume(volume): if volume["origin"] == BedOrigin.CENTER: half_width = volume["width"] / 2 half_depth = volume["depth"] / 2 return { "x_min": -half_width, "x_max": half_width, "y_min": -half_depth, "y_max": half_depth, "z_min": 0.0, "z_max": volume["height"], } else: return { "x_min": 0.0, "x_max": volume["width"], "y_min": 0.0, "y_max": volume["depth"], "z_min": 0.0, "z_max": volume["height"], }
28,175
Python
.py
719
27.821975
142
0.54097
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,852
estimation.py
OctoPrint_OctoPrint/src/octoprint/printer/estimation.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.settings import settings class PrintTimeEstimator: """ Estimator implementation. Subclass this and register via the octoprint.printer.estimation.factory hook to provide your own implementation. """ def __init__(self, job_type): self.stats_weighing_until = settings().getFloat( ["estimation", "printTime", "statsWeighingUntil"] ) self.validity_range = settings().getFloat( ["estimation", "printTime", "validityRange"] ) self.force_dumb_from_percent = settings().getFloat( ["estimation", "printTime", "forceDumbFromPercent"] ) self.force_dumb_after_min = settings().getFloat( ["estimation", "printTime", "forceDumbAfterMin"] ) threshold = None rolling_window = None countdown = None if job_type == "local" or job_type == "sdcard": # we are happy if the average of the estimates stays within 60s of the prior one threshold = settings().getFloat( ["estimation", "printTime", "stableThreshold"] ) if job_type == "sdcard": # we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived # by that divided by the sd status polling interval interval = settings().getFloat(["serial", "timeout", "sdStatus"]) if interval <= 0: interval = 1.0 rolling_window = int(15 // interval) if rolling_window < 1: rolling_window = 1 # we are happy when one rolling window has been stable countdown = rolling_window self._data = TimeEstimationHelper( rolling_window=rolling_window, countdown=countdown, threshold=threshold ) def estimate( self, progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType, ): """ Tries to estimate the print time left for the print job This is somewhat horrible since accurate print time estimation is pretty much impossible to achieve, considering that we basically have only two data points (current progress in file and time needed for that so far - former prints or a file analysis might not have happened or simply be completely impossible e.g. if the file is stored on the printer's SD card) and hence can only do a linear estimation of a completely non-linear process. That's a recipe for inaccurate predictions right there. Yay. Anyhow, here's how this implementation works. This method gets the current progress in the printed file (percentage based on bytes read vs total bytes), the print time that elapsed, the same print time with the heat up times subtracted (if possible) and if available also some statistical total print time (former prints or a result from the GCODE analysis). 1. First get an "intelligent" estimate based on the :class:`~octoprint.printer.estimation.TimeEstimationHelper`. That thing tries to detect if the estimation based on our progress and time needed for that becomes stable over time through a rolling window and only returns a result once that appears to be the case. 2. If we have any statistical data (former prints or a result from the GCODE analysis) but no intelligent estimate yet, we'll use that for the next step. Otherwise, up to a certain percentage in the print we do a percentage based weighing of the statistical data and the intelligent estimate - the closer to the beginning of the print, the more precedence for the statistical data, the closer to the cut off point, the more precedence for the intelligent estimate. This is our preliminary total print time. 3. If the total print time is set, we do a sanity check for it. Based on the total print time estimate and the time we already spent printing, we calculate at what percentage we SHOULD be and compare that to the percentage at which we actually ARE. If it's too far off, our total can't be trusted and we fall back on the dumb estimate. Same if the time we spent printing is already higher than our total estimate. 4. If we do NOT have a total print time estimate yet but we've been printing for longer than a configured amount of minutes or are further in the file than a configured percentage, we also use the dumb estimate for now. Yes, all this still produces horribly inaccurate results. But we have to do this live during the print and hence can't produce to much computational overhead, we do not have any insight into the firmware implementation with regards to planner setup and acceleration settings, we might not even have access to the printed file's contents and such we need to find something that works "mostly" all of the time without costing too many resources. Feel free to propose a better solution within the above limitations (and I mean that, this solution here makes me unhappy). Args: progress (float or None): Current percentage in the printed file printTime (float or None): Print time elapsed so far cleanedPrintTime (float or None): Print time elapsed minus the time needed for getting up to temperature (if detectable). statisticalTotalPrintTime (float or None): Total print time of past prints against same printer profile, or estimated total print time from GCODE analysis. statisticalTotalPrintTimeType (str or None): Type of statistical print time, either "average" (total time of former prints) or "analysis" Returns: (2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation """ if ( progress is None or progress == 0 or printTime is None or cleanedPrintTime is None ): return None, None dumbTotalPrintTime = printTime / progress estimatedTotalPrintTime = self.estimate_total(progress, cleanedPrintTime) totalPrintTime = estimatedTotalPrintTime printTimeLeftOrigin = "estimate" if statisticalTotalPrintTime is not None: if estimatedTotalPrintTime is None: # no estimate yet, we'll use the statistical total totalPrintTime = statisticalTotalPrintTime printTimeLeftOrigin = statisticalTotalPrintTimeType else: if progress < self.stats_weighing_until: # still inside weighing range, use part stats, part current estimate sub_progress = progress * (1 / self.stats_weighing_until) if sub_progress > 1.0: sub_progress = 1.0 printTimeLeftOrigin = "mixed-" + statisticalTotalPrintTimeType else: # use only the current estimate sub_progress = 1.0 printTimeLeftOrigin = "estimate" # combine totalPrintTime = ( -sub_progress * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime ) printTimeLeft = None if totalPrintTime is not None: # sanity check current total print time estimate assumed_progress = cleanedPrintTime / totalPrintTime min_progress = progress - self.validity_range max_progress = progress + self.validity_range if ( min_progress <= assumed_progress <= max_progress and totalPrintTime > cleanedPrintTime ): # appears sane, we'll use it printTimeLeft = totalPrintTime - cleanedPrintTime else: # too far from the actual progress or negative, # we use the dumb print time instead printTimeLeft = dumbTotalPrintTime - cleanedPrintTime printTimeLeftOrigin = "linear" else: printTimeLeftOrigin = "linear" if ( progress > self.force_dumb_from_percent or cleanedPrintTime >= self.force_dumb_after_min * 60 ): # more than x% or y min printed and still no real estimate, ok, we'll use the dumb variant :/ printTimeLeft = dumbTotalPrintTime - cleanedPrintTime if printTimeLeft is not None and printTimeLeft < 0: # shouldn't actually happen, but let's make sure printTimeLeft = None return printTimeLeft, printTimeLeftOrigin def estimate_total(self, progress, printTime): if not progress or not printTime or not self._data: return None else: return self._data.update(printTime / progress) class TimeEstimationHelper: STABLE_THRESHOLD = 0.1 STABLE_COUNTDOWN = 250 STABLE_ROLLING_WINDOW = 250 def __init__(self, rolling_window=None, countdown=None, threshold=None): if rolling_window is None: rolling_window = self.__class__.STABLE_ROLLING_WINDOW if countdown is None: countdown = self.__class__.STABLE_COUNTDOWN if threshold is None: threshold = self.__class__.STABLE_THRESHOLD self._rolling_window = rolling_window self._countdown = countdown self._threshold = threshold import collections self._distances = collections.deque([], self._rolling_window) self._totals = collections.deque([], self._rolling_window) self._sum_total = 0 self._count = 0 self._stable_counter = -1 def is_stable(self): return self._stable_counter >= self._countdown def update(self, new_estimate): old_average_total = self.average_total self._sum_total += new_estimate self._totals.append(new_estimate) self._count += 1 if old_average_total: self._distances.append(abs(self.average_total - old_average_total)) if -self._threshold < self.average_distance < self._threshold: self._stable_counter += 1 else: self._stable_counter = -1 if self.is_stable(): return self.average_total_rolling else: return None @property def average_total(self): if not self._count: return 0 else: return self._sum_total / self._count @property def average_total_rolling(self): if not self._count or self._count < self._rolling_window or not len(self._totals): return -1 else: return sum(self._totals) / len(self._totals) @property def average_distance(self): if ( not self._count or self._count < self._rolling_window + 1 or not len(self._distances) ): return -1 else: return sum(self._distances) / len(self._distances)
11,738
Python
.py
225
40.444444
124
0.635008
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,853
__init__.py
OctoPrint_OctoPrint/src/octoprint/printer/__init__.py
""" This module defines the interface for communicating with a connected printer. The communication is in fact divided in two components, the :class:`PrinterInterface` and a deeper lying communication layer. However, plugins should only ever need to use the :class:`PrinterInterface` as the abstracted version of the actual printer communication. .. autofunction:: get_connection_options .. autoclass:: PrinterInterface :members: .. autoclass:: PrinterCallback :members: """ __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import re from octoprint.filemanager import FileDestinations from octoprint.settings import settings from octoprint.util import deprecated, natural_key @deprecated( message="get_connection_options has been replaced by PrinterInterface.get_connection_options", includedoc="Replaced by :func:`PrinterInterface.get_connection_options`", since="1.3.0", ) def get_connection_options(): return PrinterInterface.get_connection_options() class PrinterInterface: """ The :class:`PrinterInterface` represents the developer interface to the :class:`~octoprint.printer.standard.Printer` instance. """ valid_axes = ("x", "y", "z", "e") """Valid axes identifiers.""" valid_tool_regex = re.compile(r"^(tool\d+)$") """Regex for valid tool identifiers.""" valid_heater_regex = re.compile(r"^(tool\d+|bed|chamber)$") """Regex for valid heater identifiers.""" @classmethod def get_connection_options(cls, *args, **kwargs): """ Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer. Returned ``dict`` has the following structure:: ports: <list of available serial ports> baudrates: <list of available baudrates> portPreference: <configured default serial port> baudratePreference: <configured default baudrate> autoconnect: <whether autoconnect upon server startup is enabled or not> Returns: (dict): A dictionary holding the connection options in the structure specified above """ import octoprint.util.comm as comm return { "ports": sorted(comm.serialList(), key=natural_key), "baudrates": sorted(comm.baudrateList(), reverse=True), "portPreference": settings().get(["serial", "port"]), "baudratePreference": settings().getInt(["serial", "baudrate"]), "autoconnect": settings().getBoolean(["serial", "autoconnect"]), } def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs): """ Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a connection is already established, that connection will be closed prior to connecting anew with the provided parameters. Arguments: port (str): Name of the serial port to connect to. If not provided, an auto detection will be attempted. baudrate (int): Baudrate to connect with. If not provided, an auto detection will be attempted. profile (str): Name of the printer profile to use for this connection. If not provided, the default will be retrieved from the :class:`PrinterProfileManager`. """ pass def disconnect(self, *args, **kwargs): """ Disconnects from the printer. Does nothing if no connection is currently established. """ raise NotImplementedError() def get_transport(self, *args, **kwargs): """ Returns the communication layer's transport object, if a connection is currently established. Note that this doesn't have to necessarily be a :class:`serial.Serial` instance, it might also be something different, so take care to do instance checks before attempting to access any properties or methods. Returns: object: The communication layer's transport object """ raise NotImplementedError() def job_on_hold(self, blocking=True, *args, **kwargs): """ Contextmanager that allows executing code while printing while making sure that no commands from the file being printed are continued to be sent to the printer. Note that this will only work for local files, NOT SD files. Example: .. code-block:: python with printer.job_on_hold(): park_printhead() take_snapshot() send_printhead_back() It should be used sparingly and only for very specific situations (such as parking the print head somewhere, taking a snapshot from the webcam, then continuing). If you abuse this, you WILL cause print quality issues! A lock is in place that ensures that the context can only actually be held by one thread at a time. If you don't want to block on acquire, be sure to set ``blocking`` to ``False`` and catch the ``RuntimeException`` thrown if the lock can't be acquired. Args: blocking (bool): Whether to block while attempting to acquire the lock (default) or not """ raise NotImplementedError() def set_job_on_hold(self, value, blocking=True, *args, **kwargs): """ Setter for finer control over putting jobs on hold. Set to ``True`` to ensure that no commands from the file being printed are continued to be sent to the printer. Set to ``False`` to resume. Note that this will only work for local files, NOT SD files. Make absolutely sure that if you set this flag, you will always also unset it again. If you don't, the job will be stuck forever. Example: .. code-block:: python if printer.set_job_on_hold(True): try: park_printhead() take_snapshot() send_printhead_back() finally: printer.set_job_on_hold(False) Just like :func:`~octoprint.printer.PrinterInterface.job_on_hold` this should be used sparingly and only for very specific situations. If you abuse this, you WILL cause print quality issues! Args: value (bool): The value to set blocking (bool): Whether to block while attempting to set the value (default) or not Returns: (bool) Whether the value could be set successfully (True) or a timeout was encountered (False) """ raise NotImplementedError() def fake_ack(self, *args, **kwargs): """ Fakes an acknowledgment for the communication layer. If the communication between OctoPrint and the printer gets stuck due to lost "ok" responses from the server due to communication issues, this can be used to get things going again. """ raise NotImplementedError() def commands(self, commands, tags=None, force=False, *args, **kwargs): """ Sends the provided ``commands`` to the printer. Arguments: commands (str, list): The commands to send. Might be a single command provided just as a string or a list of multiple commands to send in order. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle force (bool): Whether to force sending of the command right away or allow queuing while printing """ raise NotImplementedError() def script(self, name, context=None, tags=None, *args, **kwargs): """ Sends the GCODE script ``name`` to the printer. The script will be run through the template engine, the rendering context can be extended by providing a ``context`` with additional template variables to use. If the script is unknown, an :class:`UnknownScriptException` will be raised. Arguments: name (str): The name of the GCODE script to render. context (dict): An optional context of additional template variables to provide to the renderer. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle Raises: UnknownScriptException: There is no GCODE script with name ``name`` """ raise NotImplementedError() def jog(self, axes, relative=True, speed=None, tags=None, *args, **kwargs): """ Jogs the specified printer ``axis`` by the specified ``amount`` in mm. Arguments: axes (dict): Axes and distances to jog, keys are axes ("x", "y", "z"), values are distances in mm relative (bool): Whether to interpret the distance values as relative (true, default) or absolute (false) coordinates speed (int, bool or None): Speed at which to jog (F parameter). If set to ``False`` no speed will be set specifically. If set to ``None`` (or left out) the minimum of all involved axes speeds from the printer profile will be used. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def home(self, axes, tags=None, *args, **kwargs): """ Homes the specified printer ``axes``. Arguments: axes (str, list): The axis or axes to home, each of which must converted to lower case must match one of "x", "y", "z" and "e" tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def extrude(self, amount, speed=None, tags=None, *args, **kwargs): """ Extrude ``amount`` millimeters of material from the tool. Arguments: amount (int, float): The amount of material to extrude in mm speed (int, None): Speed at which to extrude (F parameter). If set to ``None`` (or left out) the maximum speed of E axis from the printer profile will be used. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def change_tool(self, tool, tags=None, *args, **kwargs): """ Switch the currently active ``tool`` (for which extrude commands will apply). Arguments: tool (str): The tool to switch to, matching the regex "tool[0-9]+" (e.g. "tool0", "tool1", ...) tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def set_temperature(self, heater, value, tags=None, *args, **kwargs): """ Sets the target temperature on the specified ``heater`` to the given ``value`` in celsius. Arguments: heater (str): The heater for which to set the target temperature. Either "bed" for setting the bed temperature, "chamber" for setting the temperature of the heated enclosure or something matching the regular expression "tool[0-9]+" (e.g. "tool0", "tool1", ...) for the hotends of the printer. However, addressing components that are disabled or unconfigured in the printer profile will result in a "Suppressed command" error popup message. value (int, float): The temperature in celsius to set the target temperature to. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle. """ raise NotImplementedError() def set_temperature_offset(self, offsets=None, tags=None, *args, **kwargs): """ Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing. Arguments: offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater`` parameter to :func:`set_temperature`, so "bed" for the offset for the bed target temperature and "tool[0-9]+" for the offsets to the hotend target temperatures. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def feed_rate(self, factor, tags=None, *args, **kwargs): """ Sets the ``factor`` for the printer's feed rate. Arguments: factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an int between 0 and 100 or a float between 0 and 1. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def flow_rate(self, factor, tags=None, *args, **kwargs): """ Sets the ``factor`` for the printer's flow rate. Arguments: factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an int between 0 and 100 or a float between 0 and 1. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def can_modify_file(self, path, sd, *args, **kwargs): """ Determines whether the ``path`` (on the printer's SD if ``sd`` is True) may be modified (updated or deleted) or not. A file that is currently being printed is not allowed to be modified. Any other file or the current file when it is not being printed is fine though. :since: 1.3.2 .. warning:: This was introduced in 1.3.2 to work around an issue when updating a file that is already selected. I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide to depend on this particular method in this interface, be advised that it might vanish in future versions! Arguments: path (str): path in storage of the file to check sd (bool): True if to check against SD storage, False otherwise Returns: (bool) True if the file may be modified, False otherwise """ return not ( self.is_current_file(path, sd) and (self.is_printing() or self.is_paused()) ) def is_current_file(self, path, sd, *args, **kwargs): """ Returns whether the provided ``path`` (on the printer's SD if ``sd`` is True) is the currently selected file for printing. :since: 1.3.2 .. warning:: This was introduced in 1.3.2 to work around an issue when updating a file that is already selected. I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide to depend on this particular method in this interface, be advised that it might vanish in future versions! Arguments: path (str): path in storage of the file to check sd (bool): True if to check against SD storage, False otherwise Returns: (bool) True if the file is currently selected, False otherwise """ current_job = self.get_current_job() if current_job is not None and "file" in current_job: current_job_file = current_job["file"] if "path" in current_job_file and "origin" in current_job_file: current_file_path = current_job_file["path"] current_file_origin = current_job_file["origin"] return path == current_file_path and sd == ( current_file_origin == FileDestinations.SDCARD ) return False def select_file( self, path, sd, printAfterSelect=False, pos=None, tags=None, *args, **kwargs ): """ Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not. Optionally can also directly start the print after selecting the file. Arguments: path (str): The path to select for printing. Either an absolute path or relative path to a local file in the uploads folder or a filename on the printer's SD card. sd (boolean): Indicates whether the file is on the printer's SD card or not. printAfterSelect (boolean): Indicates whether a print should be started after the file is selected. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle Raises: InvalidFileType: if the file is not a machinecode file and hence cannot be printed InvalidFileLocation: if an absolute path was provided and not contained within local storage or doesn't exist """ raise NotImplementedError() def unselect_file(self, *args, **kwargs): """ Unselects and currently selected file. """ raise NotImplementedError() def start_print(self, tags=None, *args, **kwargs): """ Starts printing the currently selected file. If no file is currently selected, does nothing. Arguments: tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def pause_print(self, tags=None, *args, **kwargs): """ Pauses the current print job if it is currently running, does nothing otherwise. Arguments: tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def resume_print(self, tags=None, *args, **kwargs): """ Resumes the current print job if it is currently paused, does nothing otherwise. Arguments: tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def toggle_pause_print(self, tags=None, *args, **kwargs): """ Pauses the current print job if it is currently running or resumes it if it is currently paused. Arguments: tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ if self.is_printing(): self.pause_print(tags=tags, *args, **kwargs) elif self.is_paused(): self.resume_print(tags=tags, *args, **kwargs) def cancel_print(self, tags=None, *args, **kwargs): """ Cancels the current print job. Arguments: tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle """ raise NotImplementedError() def log_lines(self, *lines): """ Logs the provided lines to the printer log and serial.log Args: *lines: the lines to log """ pass def get_state_string(self, *args, **kwargs): """ Returns: (str) A human readable string corresponding to the current communication state. """ raise NotImplementedError() def get_state_id(self, *args, **kwargs): """ Identifier of the current communication state. Possible values are: * OPEN_SERIAL * DETECT_SERIAL * DETECT_BAUDRATE * CONNECTING * OPERATIONAL * PRINTING * PAUSED * CLOSED * ERROR * CLOSED_WITH_ERROR * TRANSFERING_FILE * OFFLINE * UNKNOWN * NONE Returns: (str) A unique identifier corresponding to the current communication state. """ def get_current_data(self, *args, **kwargs): """ Returns: (dict) The current state data. """ raise NotImplementedError() def get_current_job(self, *args, **kwargs): """ Returns: (dict) The data of the current job. """ raise NotImplementedError() def get_current_temperatures(self, *args, **kwargs): """ Returns: (dict) The current temperatures. """ raise NotImplementedError() def get_temperature_history(self, *args, **kwargs): """ Returns: (list) The temperature history. """ raise NotImplementedError() def get_current_connection(self, *args, **kwargs): """ Returns: (tuple) The current connection information as a 4-tuple ``(connection_string, port, baudrate, printer_profile)``. If the printer is currently not connected, the tuple will be ``("Closed", None, None, None)``. """ raise NotImplementedError() def is_closed_or_error(self, *args, **kwargs): """ Returns: (boolean) Whether the printer is currently disconnected and/or in an error state. """ raise NotImplementedError() def is_operational(self, *args, **kwargs): """ Returns: (boolean) Whether the printer is currently connected and available. """ raise NotImplementedError() def is_printing(self, *args, **kwargs): """ Returns: (boolean) Whether the printer is currently printing. """ raise NotImplementedError() def is_cancelling(self, *args, **kwargs): """ Returns: (boolean) Whether the printer is currently cancelling a print. """ raise NotImplementedError() def is_pausing(self, *args, **kwargs): """ Returns: (boolean) Whether the printer is currently pausing a print. """ raise NotImplementedError() def is_paused(self, *args, **kwargs): """ Returns: (boolean) Whether the printer is currently paused. """ raise NotImplementedError() def is_error(self, *args, **kwargs): """ Returns: (boolean) Whether the printer is currently in an error state. """ raise NotImplementedError() def is_ready(self, *args, **kwargs): """ Returns: (boolean) Whether the printer is currently operational and ready for new print jobs (not printing). """ raise NotImplementedError() def register_callback(self, callback, *args, **kwargs): """ Registers a :class:`PrinterCallback` with the instance. Arguments: callback (PrinterCallback): The callback object to register. """ raise NotImplementedError() def unregister_callback(self, callback, *args, **kwargs): """ Unregisters a :class:`PrinterCallback` from the instance. Arguments: callback (PrinterCallback): The callback object to unregister. """ raise NotImplementedError() def send_initial_callback(self, callback): """ Sends the initial printer update to :class:`PrinterCallback`. Arguments: callback (PrinterCallback): The callback object to send initial data to. """ raise NotImplementedError() @property def firmware_info(self): raise NotImplementedError() @property def error_info(self): raise NotImplementedError() class PrinterCallback: def on_printer_add_log(self, data): """ Called when the :class:`PrinterInterface` receives a new communication log entry from the communication layer. Arguments: data (str): The received log line. """ pass def on_printer_add_message(self, data): """ Called when the :class:`PrinterInterface` receives a new message from the communication layer. Arguments: data (str): The received message. """ pass def on_printer_add_temperature(self, data): """ Called when the :class:`PrinterInterface` receives a new temperature data set from the communication layer. ``data`` is a ``dict`` of the following structure:: tool0: actual: <temperature of the first hotend, in degC> target: <target temperature of the first hotend, in degC> ... bed: actual: <temperature of the bed, in degC> target: <target temperature of the bed, in degC> chamber: actual: <temperature of the chamber, in degC> target: <target temperature of the chamber, in degC> Arguments: data (dict): A dict of all current temperatures in the format as specified above """ pass def on_printer_received_registered_message(self, name, output): """ Called when the :class:`PrinterInterface` received a registered message, e.g. from a feedback command. Arguments: name (str): Name of the registered message (e.g. the feedback command) output (str): Output for the registered message """ pass def on_printer_send_initial_data(self, data): """ Called when registering as a callback with the :class:`PrinterInterface` to receive the initial data (state, log and temperature history etc) from the printer. ``data`` is a ``dict`` of the following structure:: temps: - time: <timestamp of the temperature data point> tool0: actual: <temperature of the first hotend, in degC> target: <target temperature of the first hotend, in degC> ... bed: actual: <temperature of the bed, in degC> target: <target temperature of the bed, in degC> - ... logs: <list of current communication log lines> messages: <list of current messages from the firmware> Arguments: data (dict): The initial data in the format as specified above. """ pass def on_printer_send_current_data(self, data): """ Called when the internal state of the :class:`PrinterInterface` changes, due to changes in the printer state, temperatures, log lines, job progress etc. Updates via this method are guaranteed to be throttled to a maximum of 2 calls per second. ``data`` is a ``dict`` of the following structure:: state: text: <current state string> flags: operational: <whether the printer is currently connected and responding> printing: <whether the printer is currently printing> closedOrError: <whether the printer is currently disconnected and/or in an error state> error: <whether the printer is currently in an error state> paused: <whether the printer is currently paused> ready: <whether the printer is operational and ready for jobs> sdReady: <whether an SD card is present> job: file: name: <name of the file>, size: <size of the file in bytes>, origin: <origin of the file, "local" or "sdcard">, date: <last modification date of the file> estimatedPrintTime: <estimated print time of the file in seconds> lastPrintTime: <last print time of the file in seconds> filament: length: <estimated length of filament needed for this file, in mm> volume: <estimated volume of filament needed for this file, in ccm> progress: completion: <progress of the print job in percent (0-100)> filepos: <current position in the file in bytes> printTime: <current time elapsed for printing, in seconds> printTimeLeft: <estimated time left to finish printing, in seconds> currentZ: <current position of the z axis, in mm> offsets: <current configured temperature offsets, keys are "bed" or "tool[0-9]+", values the offset in degC> Arguments: data (dict): The current data in the format as specified above. """ pass class UnknownScript(Exception): def __init__(self, name, *args, **kwargs): self.name = name class InvalidFileLocation(Exception): pass class InvalidFileType(Exception): pass
29,243
Python
.py
596
38.723154
125
0.628
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,854
standard.py
OctoPrint_OctoPrint/src/octoprint/printer/standard.py
""" This module holds the standard implementation of the :class:`PrinterInterface` and it helpers. """ __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import copy import logging import os import threading import time from typing import List from frozendict import frozendict import octoprint.util.json from octoprint import util as util from octoprint.events import Events, eventManager from octoprint.filemanager import FileDestinations, NoSuchStorage, valid_file_type from octoprint.plugin import ProgressPlugin, plugin_manager from octoprint.printer import ( InvalidFileLocation, InvalidFileType, PrinterCallback, PrinterInterface, UnknownScript, ) from octoprint.printer.estimation import PrintTimeEstimator from octoprint.schema import BaseModel from octoprint.settings import settings from octoprint.util import InvariantContainer from octoprint.util import comm as comm from octoprint.util import get_fully_qualified_classname as fqcn from octoprint.util import to_unicode class ErrorInformation(BaseModel): error: str reason: str consequence: str = None faq: str = None logs: List[str] = None class Printer(PrinterInterface, comm.MachineComPrintCallback): """ Default implementation of the :class:`PrinterInterface`. Manages the communication layer object and registers itself with it as a callback to react to changes on the communication layer. """ def __init__(self, fileManager, analysisQueue, printerProfileManager): from collections import deque self._logger = logging.getLogger(__name__) self._logger_job = logging.getLogger(f"{__name__}.job") self._dict = ( frozendict if settings().getBoolean(["devel", "useFrozenDictForPrinterState"]) else dict ) self._analysisQueue = analysisQueue self._fileManager = fileManager self._printerProfileManager = printerProfileManager self._temps = DataHistory( cutoff=settings().getInt(["temperature", "cutoff"]) * 60 ) self._markings = DataHistory( cutoff=settings().getInt(["temperature", "cutoff"]) * 60 ) self._messages = deque([], 300) self._log = deque([], 300) self._state = None self._currentZ = None self._printAfterSelect = False self._posAfterSelect = None self._firmware_info = None self._error_info = None # sd handling self._sdPrinting = False self._sdStreaming = False self._streamingFinishedCallback = None self._streamingFailedCallback = None # job handling & estimation self._selectedFileMutex = threading.RLock() self._selectedFile = None self._estimator_factory = PrintTimeEstimator self._estimator = None analysis_queue_hooks = plugin_manager().get_hooks( "octoprint.printer.estimation.factory" ) for name, hook in analysis_queue_hooks.items(): try: estimator = hook() if estimator is not None: self._logger.info(f"Using print time estimator provided by {name}") self._estimator_factory = estimator except Exception: self._logger.exception( f"Error while processing analysis queues from {name}", extra={"plugin": name}, ) # hook card upload self.sd_card_upload_hooks = plugin_manager().get_hooks( "octoprint.printer.sdcardupload" ) # comm self._comm = None # callbacks self._callbacks = [] # progress plugins self._lastProgressReport = None self._progressPlugins = plugin_manager().get_implementations(ProgressPlugin) self._additional_data_hooks = plugin_manager().get_hooks( "octoprint.printer.additional_state_data" ) self._blacklisted_data_hooks = [] self._stateMonitor = StateMonitor( interval=0.5, on_update=self._sendCurrentDataCallbacks, on_add_temperature=self._sendAddTemperatureCallbacks, on_add_log=self._sendAddLogCallbacks, on_add_message=self._sendAddMessageCallbacks, on_get_progress=self._updateProgressDataCallback, on_get_resends=self._updateResendDataCallback, ) self._stateMonitor.reset( state=self._dict( text=self.get_state_string(), flags=self._getStateFlags(), error=self.get_error(), ), job_data=self._dict( file=self._dict(name=None, path=None, size=None, origin=None, date=None), estimatedPrintTime=None, lastPrintTime=None, filament=self._dict(length=None, volume=None), user=None, ), progress=self._dict( completion=None, filepos=None, printTime=None, printTimeLeft=None, printTimeLeftOrigin=None, ), current_z=None, offsets=self._dict(), resends=self._dict(count=0, ratio=0), ) eventManager().subscribe( Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished ) eventManager().subscribe( Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated ) eventManager().subscribe(Events.CONNECTED, self._on_event_Connected) eventManager().subscribe(Events.DISCONNECTED, self._on_event_Disconnected) eventManager().subscribe(Events.CHART_MARKED, self._on_event_ChartMarked) self._handle_connect_hooks = plugin_manager().get_hooks( "octoprint.printer.handle_connect" ) def _create_estimator(self, job_type=None): if job_type is None: with self._selectedFileMutex: if self._selectedFile is None: return if self._selectedFile["sd"]: job_type = "sdcard" else: job_type = "local" self._estimator = self._estimator_factory(job_type) @property def firmware_info(self): return frozendict(self._firmware_info) if self._firmware_info else None @property def error_info(self): return self._error_info.dict() if self._error_info else None # ~~ handling of PrinterCallbacks def register_callback(self, callback, *args, **kwargs): if not isinstance(callback, PrinterCallback): self._logger.warning( "Registering an object as printer callback which doesn't implement the PrinterCallback interface" ) self._callbacks.append(callback) def unregister_callback(self, callback, *args, **kwargs): try: self._callbacks.remove(callback) except ValueError: # not registered pass def send_initial_callback(self, callback): if callback in self._callbacks: self._sendInitialStateUpdate(callback) def _sendAddTemperatureCallbacks(self, data): for callback in self._callbacks: try: callback.on_printer_add_temperature(data) except Exception: self._logger.exception( "Exception while adding temperature data point to callback {}".format( callback ), extra={"callback": fqcn(callback)}, ) def _sendAddLogCallbacks(self, data): for callback in self._callbacks: try: callback.on_printer_add_log(data) except Exception: self._logger.exception( "Exception while adding communication log entry to callback {}".format( callback ), extra={"callback": fqcn(callback)}, ) def _sendAddMessageCallbacks(self, data): for callback in self._callbacks: try: callback.on_printer_add_message(data) except Exception: self._logger.exception( "Exception while adding printer message to callback {}".format( callback ), extra={"callback": fqcn(callback)}, ) def _sendCurrentDataCallbacks(self, data): plugin_data = self._get_additional_plugin_data(initial=False) for callback in self._callbacks: try: data_copy = copy.deepcopy(data) if plugin_data: data_copy.update(plugins=copy.deepcopy(plugin_data)) callback.on_printer_send_current_data(data_copy) except Exception: self._logger.exception( "Exception while pushing current data to callback {}".format( callback ), extra={"callback": fqcn(callback)}, ) def _get_additional_plugin_data(self, initial=False): plugin_data = {} for name, hook in self._additional_data_hooks.items(): if name in self._blacklisted_data_hooks: continue try: additional = hook(initial=initial) if additional and isinstance(additional, dict): octoprint.util.json.dumps({name: additional}) plugin_data[name] = additional except ValueError: self._logger.exception( f"Invalid additional data from plugin {name}", extra={"plugin": name}, ) except Exception: self._logger.exception( "Error while retrieving additional data from plugin {}, blacklisting it for further loops".format( name ), extra={"plugin": name}, ) self._blacklisted_data_hooks.append(name) return plugin_data # ~~ callback from metadata analysis event def _on_event_MetadataAnalysisFinished(self, event, data): with self._selectedFileMutex: if self._selectedFile: self._setJobData( self._selectedFile["filename"], self._selectedFile["filesize"], self._selectedFile["sd"], self._selectedFile["user"], ) def _on_event_MetadataStatisticsUpdated(self, event, data): with self._selectedFileMutex: if self._selectedFile: self._setJobData( self._selectedFile["filename"], self._selectedFile["filesize"], self._selectedFile["sd"], self._selectedFile["user"], ) # ~~ connection events def _on_event_Connected(self, event, data): self._markings.append( {"type": "connected", "label": "Connected", "time": time.time()} ) def _on_event_Disconnected(self, event, data): self._markings.append( {"type": "disconnected", "label": "Disconnected", "time": time.time()} ) # ~~ chart marking insertions def _on_event_ChartMarked(self, event, data): self._markings.append( { "type": data.get("type", "unknown"), "label": data.get("label"), "time": data.get("time", time.time()), } ) # ~~ progress plugin reporting def _reportPrintProgressToPlugins(self, progress): with self._selectedFileMutex: if ( progress is None or not self._selectedFile or "sd" not in self._selectedFile or "filename" not in self._selectedFile ): return storage = "sdcard" if self._selectedFile["sd"] else "local" filename = self._selectedFile["filename"] def call_plugins(storage, filename, progress): for plugin in self._progressPlugins: try: plugin.on_print_progress(storage, filename, progress) except Exception: self._logger.exception( "Exception while sending print progress to plugin %s" % plugin._identifier, extra={"plugin": plugin._identifier}, ) thread = threading.Thread(target=call_plugins, args=(storage, filename, progress)) thread.daemon = False thread.start() # ~~ PrinterInterface implementation def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs): """ Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection will be attempted. """ if self._comm is not None: return for name, hook in self._handle_connect_hooks.items(): try: if hook( self, *args, port=port, baudrate=baudrate, profile=profile, **kwargs ): self._logger.info(f"Connect signalled as handled by plugin {name}") return except Exception: self._logger.exception( f"Exception while handling connect in plugin {name}", extra={"plugin": name}, ) self._error_info = None eventManager().fire(Events.CONNECTING) self._printerProfileManager.select(profile) from octoprint.logging.handlers import SerialLogHandler SerialLogHandler.arm_rollover() if not logging.getLogger("SERIAL").isEnabledFor(logging.DEBUG): # if serial.log is not enabled, log a line to explain that to reduce "serial.log is empty" in tickets... logging.getLogger("SERIAL").info( "serial.log is currently not enabled, you can enable it via Settings > Serial Connection > Log communication to serial.log" ) self._firmware_info = None self._comm = comm.MachineCom( port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager, ) self._comm.start() def disconnect(self, *args, **kwargs): """ Closes the connection to the printer. """ eventManager().fire(Events.DISCONNECTING) if self._comm is not None: self._comm.close() else: eventManager().fire(Events.DISCONNECTED) self._firmware_info = None def get_transport(self, *args, **kwargs): if self._comm is None: return None return self._comm.getTransport() getTransport = util.deprecated( "getTransport has been renamed to get_transport", since="1.2.0-dev-590", includedoc="Replaced by :func:`get_transport`", ) def job_on_hold(self, blocking=True, *args, **kwargs): if self._comm is None: raise RuntimeError("No connection to the printer") return self._comm.job_put_on_hold(blocking=blocking) def set_job_on_hold(self, value, blocking=True, *args, **kwargs): if self._comm is None: raise RuntimeError("No connection to the printer") return self._comm.set_job_on_hold(value, blocking=blocking) def fake_ack(self, *args, **kwargs): if self._comm is None: return self._comm.fakeOk() def commands(self, commands, tags=None, force=False, *args, **kwargs): """ Sends one or more gcode commands to the printer. """ if self._comm is None: return if not isinstance(commands, (list, tuple)): commands = [commands] if tags is None: tags = set() tags |= {"trigger:printer.commands"} for command in commands: self._comm.sendCommand(command, tags=tags, force=force) def script( self, name, context=None, must_be_set=True, part_of_job=False, *args, **kwargs ): if self._comm is None: return if name is None or not name: raise ValueError("name must be set") # .capitalize() will lowercase all letters but the first # this code preserves existing CamelCase event_name = name[0].upper() + name[1:] event_start = f"GcodeScript{event_name}Running" payload = context.get("event", None) if isinstance(context, dict) else None eventManager().fire(event_start, payload) result = self._comm.sendGcodeScript( name, part_of_job=part_of_job, replacements=context, tags=kwargs.get("tags", set()) | {"trigger:printer.script"}, ) if not result and must_be_set: raise UnknownScript(name) event_end = f"GcodeScript{event_name}Finished" eventManager().fire(event_end, payload) def jog(self, axes, relative=True, speed=None, *args, **kwargs): if isinstance(axes, str): # legacy parameter format, there should be an amount as first anonymous positional arguments too axis = axes if not len(args) >= 1: raise ValueError("amount not set") amount = args[0] if not isinstance(amount, (int, float)): raise ValueError(f"amount must be a valid number: {amount}") axes = {} axes[axis] = amount if not axes: raise ValueError("At least one axis to jog must be provided") for axis in axes: if axis not in PrinterInterface.valid_axes: raise ValueError( "Invalid axis {}, valid axes are {}".format( axis, ", ".join(PrinterInterface.valid_axes) ) ) command = "G0 {}".format( " ".join([f"{axis.upper()}{amt}" for axis, amt in axes.items()]) ) if speed is None: printer_profile = self._printerProfileManager.get_current_or_default() speed = min(printer_profile["axes"][axis]["speed"] for axis in axes) if speed and not isinstance(speed, bool): command += f" F{speed}" if relative: commands = ["G91", command, "G90"] else: commands = ["G90", command] self.commands(commands, tags=kwargs.get("tags", set()) | {"trigger:printer.jog"}) def home(self, axes, *args, **kwargs): if not isinstance(axes, (list, tuple)): if isinstance(axes, str): axes = [axes] else: raise ValueError(f"axes is neither a list nor a string: {axes}") validated_axes = list( filter( lambda x: x in PrinterInterface.valid_axes, map(lambda x: x.lower(), axes) ) ) if len(axes) != len(validated_axes): raise ValueError(f"axes contains invalid axes: {axes}") self.commands( [ "G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90", ], tags=kwargs.get("tags", set) | {"trigger:printer.home"}, ) def extrude(self, amount, speed=None, *args, **kwargs): if not isinstance(amount, (int, float)): raise ValueError(f"amount must be a valid number: {amount}") printer_profile = self._printerProfileManager.get_current_or_default() # Use specified speed (if any) max_e_speed = printer_profile["axes"]["e"]["speed"] if speed is None: # No speed was specified so default to value configured in printer profile extrusion_speed = max_e_speed else: # Make sure that specified value is not greater than maximum as defined in printer profile extrusion_speed = min([speed, max_e_speed]) self.commands( ["G91", "M83", "G1 E%s F%d" % (amount, extrusion_speed), "M82", "G90"], tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"}, ) def change_tool(self, tool, *args, **kwargs): if not PrinterInterface.valid_tool_regex.match(tool): raise ValueError(f'tool must match "tool[0-9]+": {tool}') tool_num = int(tool[len("tool") :]) self.commands( "T%d" % tool_num, tags=kwargs.get("tags", set()) | {"trigger:printer.change_tool"}, ) def set_temperature(self, heater, value, *args, **kwargs): if not PrinterInterface.valid_heater_regex.match(heater): raise ValueError( 'heater must match "tool[0-9]+", "bed" or "chamber": {heater}'.format( heater=heater ) ) if not isinstance(value, (int, float)) or value < 0: raise ValueError(f"value must be a valid number >= 0: {value}") tags = kwargs.get("tags", set()) | {"trigger:printer.set_temperature"} if heater.startswith("tool"): printer_profile = self._printerProfileManager.get_current_or_default() extruder_count = printer_profile["extruder"]["count"] shared_nozzle = printer_profile["extruder"]["sharedNozzle"] if extruder_count > 1 and not shared_nozzle: toolNum = int(heater[len("tool") :]) self.commands(f"M104 T{toolNum} S{value}", tags=tags) else: self.commands(f"M104 S{value}", tags=tags) elif heater == "bed": self.commands(f"M140 S{value}", tags=tags) elif heater == "chamber": self.commands(f"M141 S{value}", tags=tags) def set_temperature_offset(self, offsets=None, *args, **kwargs): if offsets is None: offsets = {} if not isinstance(offsets, dict): raise ValueError("offsets must be a dict") validated_keys = list( filter(lambda x: PrinterInterface.valid_heater_regex.match(x), offsets.keys()) ) validated_values = list( filter(lambda x: isinstance(x, (int, float)), offsets.values()) ) if len(validated_keys) != len(offsets): raise ValueError(f"offsets contains invalid keys: {offsets}") if len(validated_values) != len(offsets): raise ValueError(f"offsets contains invalid values: {offsets}") if self._comm is None: return self._comm.setTemperatureOffset(offsets) self._setOffsets(self._comm.getOffsets()) def _convert_rate_value(self, factor, min_val=None, max_val=None): if not isinstance(factor, (int, float)): raise ValueError("factor is not a number") if isinstance(factor, float): factor = int(factor * 100) if min_val and factor < min_val: raise ValueError(f"factor must be a value >={min_val}") elif max_val and factor > max_val: raise ValueError(f"factor must be a value <={max_val}") return factor def feed_rate(self, factor, *args, **kwargs): factor = self._convert_rate_value(factor, min_val=1) self.commands( "M220 S%d" % factor, tags=kwargs.get("tags", set()) | {"trigger:printer.feed_rate"}, ) def flow_rate(self, factor, *args, **kwargs): factor = self._convert_rate_value(factor, min_val=1) self.commands( "M221 S%d" % factor, tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"}, ) def select_file( self, path, sd, printAfterSelect=False, user=None, pos=None, *args, **kwargs ): if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()): self._logger.info("Cannot load file: printer not connected or currently busy") return self._validateJob(path, sd) origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL if sd: path_on_disk = "/" + path path_in_storage = path else: path_on_disk = self._fileManager.path_on_disk(origin, path) path_in_storage = self._fileManager.path_in_storage(origin, path_on_disk) try: recovery_data = self._fileManager.get_recovery_data() if recovery_data: # clean up recovery data if we just selected a different file actual_origin = recovery_data.get("origin", None) actual_path = recovery_data.get("path", None) if ( actual_origin is None or actual_path is None or actual_origin != origin or actual_path != path_in_storage ): self._fileManager.delete_recovery_data() except Exception: # anything goes wrong with the recovery data, we ignore it self._logger.exception( "Something was wrong with processing the recovery data" ) self._printAfterSelect = printAfterSelect self._posAfterSelect = pos self._comm.selectFile( "/" + path if sd else path_on_disk, sd, user=user, tags=kwargs.get("tags", set()) | {"trigger:printer.select_file"}, ) self._updateProgressData() self._setCurrentZ(None) def unselect_file(self, *args, **kwargs): if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()): return self._comm.unselectFile() self._updateProgressData() self._setCurrentZ(None) def get_file_position(self): if self._comm is None: return None with self._selectedFileMutex: if self._selectedFile is None: return None return self._comm.getFilePosition() def get_markings(self): return self._markings def start_print(self, pos=None, user=None, *args, **kwargs): """ Starts the currently loaded print job. Only starts if the printer is connected and operational, not currently printing and a printjob is loaded """ if ( self._comm is None or not self._comm.isOperational() or self._comm.isPrinting() ): return with self._selectedFileMutex: if self._selectedFile is None: return self._fileManager.delete_recovery_data() self._lastProgressReport = None self._updateProgressData() self._setCurrentZ(None) self._comm.startPrint( pos=pos, user=user, tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"}, ) def pause_print(self, user=None, *args, **kwargs): """ Pause the current printjob. """ if self._comm is None: return if self._comm.isPaused(): return self._comm.setPause( True, user=user, tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"}, ) def resume_print(self, user=None, *args, **kwargs): """ Resume the current printjob. """ if self._comm is None: return if not self._comm.isPaused(): return self._comm.setPause( False, user=user, tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"}, ) def cancel_print(self, user=None, *args, **kwargs): """ Cancel the current printjob. """ if self._comm is None: return # tell comm layer to cancel - will also trigger our cancelled handler # for further processing self._comm.cancelPrint( user=user, tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"} ) def log_lines(self, *lines): serial_logger = logging.getLogger("SERIAL") self.on_comm_log("\n".join(lines)) for line in lines: serial_logger.debug(line) def get_state_string(self, state=None, *args, **kwargs): if self._comm is None: return "Offline" else: return self._comm.getStateString(state=state) def get_state_id(self, state=None, *args, **kwargs): if self._comm is None: return "OFFLINE" else: return self._comm.getStateId(state=state) def get_error(self): if self._comm is None: return "" else: return self._comm.getErrorString() def get_current_data(self, *args, **kwargs): return util.thaw_frozendict(self._stateMonitor.get_current_data()) def get_current_job(self, *args, **kwargs): currentData = self._stateMonitor.get_current_data() return util.thaw_frozendict(currentData["job"]) def get_current_temperatures(self, *args, **kwargs): if self._comm is not None: offsets = self._comm.getOffsets() else: offsets = {} last = self._temps.last if last is None: return {} return { key: { "actual": value["actual"], "target": value["target"], "offset": offsets[key] if offsets.get(key) is not None else 0, } for key, value in last.items() if key != "time" } def get_temperature_history(self, *args, **kwargs): return list(self._temps) def get_current_connection(self, *args, **kwargs): if self._comm is None: return "Closed", None, None, None port, baudrate = self._comm.getConnection() printer_profile = self._printerProfileManager.get_current_or_default() return self._comm.getStateString(), port, baudrate, printer_profile def is_closed_or_error(self, *args, **kwargs): return self._comm is None or self._comm.isClosedOrError() def is_operational(self, *args, **kwargs): return self._comm is not None and self._comm.isOperational() def is_printing(self, *args, **kwargs): return self._comm is not None and self._comm.isPrinting() def is_cancelling(self, *args, **kwargs): return self._comm is not None and self._comm.isCancelling() def is_pausing(self, *args, **kwargs): return self._comm is not None and self._comm.isPausing() def is_paused(self, *args, **kwargs): return self._comm is not None and self._comm.isPaused() def is_resuming(self, *args, **kwargs): return self._comm is not None and self._comm.isResuming() def is_finishing(self, *args, **kwargs): return self._comm is not None and self._comm.isFinishing() def is_error(self, *args, **kwargs): return self._comm is not None and self._comm.isError() def is_ready(self, *args, **kwargs): return ( self.is_operational() and not self._comm.isBusy() # isBusy is true when paused and not self._comm.isStreaming() ) def is_sd_ready(self, *args, **kwargs): if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None: return False else: return self._comm.isSdReady() # ~~ sd file handling def get_sd_files(self, *args, **kwargs): if not self.is_sd_ready(): return [] if kwargs.get("refresh"): self.refresh_sd_files(blocking=True) return list( map( lambda x: {"name": x[0][1:], "size": x[1], "display": x[2], "date": x[3]}, self._comm.getSdFiles(), ) ) def add_sd_file( self, filename, path, on_success=None, on_failure=None, *args, **kwargs ): if not self._comm or self._comm.isBusy() or not self._comm.isSdReady(): self._logger.error("No connection to printer or printer is busy") return self._streamingFinishedCallback = on_success self._streamingFailedCallback = on_failure def sd_upload_started(local_filename, remote_filename): eventManager().fire( Events.TRANSFER_STARTED, {"local": local_filename, "remote": remote_filename}, ) def sd_upload_succeeded(local_filename, remote_filename, elapsed): payload = { "local": local_filename, "remote": remote_filename, "time": elapsed, } eventManager().fire(Events.TRANSFER_DONE, payload) if callable(self._streamingFinishedCallback): self._streamingFinishedCallback( remote_filename, remote_filename, FileDestinations.SDCARD ) def sd_upload_failed(local_filename, remote_filename, elapsed): payload = { "local": local_filename, "remote": remote_filename, "time": elapsed, } eventManager().fire(Events.TRANSFER_FAILED, payload) if callable(self._streamingFailedCallback): self._streamingFailedCallback( remote_filename, remote_filename, FileDestinations.SDCARD ) for name, hook in self.sd_card_upload_hooks.items(): # first sd card upload plugin that feels responsible gets the job try: result = hook( self, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs, ) if result is not None: return result except Exception: self._logger.exception( "There was an error running the sd upload " "hook provided by plugin {}".format(name), extra={"plugin": name}, ) else: # no plugin feels responsible, use the default implementation return self._add_sd_file(filename, path, tags=kwargs.get("tags")) def _get_free_remote_name(self, filename): self.refresh_sd_files(blocking=True) existingSdFiles = list(map(lambda x: x[0], self._comm.getSdFiles())) if valid_file_type(filename, "gcode"): # figure out remote filename remote_name = util.get_dos_filename( filename, existing_filenames=existingSdFiles, extension="gco", whitelisted_extensions=["gco", "g"], ) else: # probably something else added through a plugin, use it's basename as-is remote_name = os.path.basename(filename) return remote_name def _add_sd_file(self, filename, path, tags=None): if tags is None: tags = set() self._create_estimator("stream") remote_name = self._comm.startFileTransfer( path, filename, special=not valid_file_type(filename, "gcode"), tags=tags | {"trigger:printer.add_sd_file"}, ) return remote_name def delete_sd_file(self, filename, *args, **kwargs): if not self._comm or not self._comm.isSdReady(): return self._comm.deleteSdFile( "/" + filename, tags=kwargs.get("tags", set()) | {"trigger:printer.delete_sd_file"}, ) def init_sd_card(self, *args, **kwargs): if not self._comm or self._comm.isSdReady(): return self._comm.initSdCard( tags=kwargs.get("tags", set()) | {"trigger:printer.init_sd_card"} ) def release_sd_card(self, *args, **kwargs): if not self._comm or not self._comm.isSdReady(): return self._comm.releaseSdCard( tags=kwargs.get("tags", set()) | {"trigger:printer.release_sd_card"} ) def refresh_sd_files(self, blocking=False, *args, **kwargs): """ Refreshes the list of file stored on the SD card attached to printer (if available and printer communication available). Optional blocking parameter allows making the method block (max 10s) until the file list has been received (and can be accessed via self._comm.getSdFiles()). Defaults to an asynchronous operation. """ if not self._comm or not self._comm.isSdReady(): return self._comm.refreshSdFiles( tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"}, blocking=blocking, timeout=kwargs.get("timeout", 10), ) # ~~ state monitoring def _setOffsets(self, offsets): self._stateMonitor.set_temp_offsets(offsets) def _setCurrentZ(self, currentZ): self._currentZ = currentZ self._stateMonitor.set_current_z(self._currentZ) def _setState(self, state, state_string=None, error_string=None): if state_string is None: state_string = self.get_state_string() if error_string is None: error_string = self.get_error() self._state = state self._stateMonitor.set_state( self._dict(text=state_string, flags=self._getStateFlags(), error=error_string) ) payload = { "state_id": self.get_state_id(self._state), "state_string": self.get_state_string(self._state), } eventManager().fire(Events.PRINTER_STATE_CHANGED, payload) def _addLog(self, log): self._log.append(log) self._stateMonitor.add_log(log) def _addMessage(self, message): self._messages.append(message) self._stateMonitor.add_message(message) def _updateProgressData( self, completion=None, filepos=None, printTime=None, printTimeLeft=None, printTimeLeftOrigin=None, ): self._stateMonitor.set_progress( self._dict( completion=int(completion * 100) if completion is not None else None, filepos=filepos, printTime=int(printTime) if printTime is not None else None, printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None, printTimeLeftOrigin=printTimeLeftOrigin, ) ) def _updateProgressDataCallback(self): if self._comm is None: progress = None filepos = None printTime = None cleanedPrintTime = None else: progress = self._comm.getPrintProgress() filepos = self._comm.getPrintFilepos() printTime = self._comm.getPrintTime() cleanedPrintTime = self._comm.getCleanedPrintTime() printTimeLeft = printTimeLeftOrigin = None estimator = self._estimator if progress is not None: progress_int = int(progress * 100) if self._lastProgressReport != progress_int: self._lastProgressReport = progress_int self._reportPrintProgressToPlugins(progress_int) if progress == 0: printTimeLeft = None printTimeLeftOrigin = None elif progress == 1: printTimeLeft = 0 printTimeLeftOrigin = None elif estimator is not None: statisticalTotalPrintTime = None statisticalTotalPrintTimeType = None with self._selectedFileMutex: if ( self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"] ): statisticalTotalPrintTime = self._selectedFile[ "estimatedPrintTime" ] statisticalTotalPrintTimeType = self._selectedFile.get( "estimatedPrintTimeType", None ) try: printTimeLeft, printTimeLeftOrigin = estimator.estimate( progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType, ) if printTimeLeft is not None: printTimeLeft = int(printTimeLeft) except Exception: self._logger.exception( f"Error while estimating print time via {estimator}" ) return self._dict( completion=progress * 100 if progress is not None else None, filepos=filepos, printTime=int(printTime) if printTime is not None else None, printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None, printTimeLeftOrigin=printTimeLeftOrigin, ) def _updateResendDataCallback(self): if not self._comm: return self._dict(count=0, transmitted=0, ratio=0) return self._dict( count=self._comm.received_resends, transmitted=self._comm.transmitted_lines, ratio=int(self._comm.resend_ratio * 100), ) def _addTemperatureData(self, tools=None, bed=None, chamber=None, custom=None): if tools is None: tools = {} if custom is None: custom = {} data = {"time": int(time.time())} for tool in tools.keys(): data["tool%d" % tool] = self._dict( actual=tools[tool][0], target=tools[tool][1] ) if bed is not None and isinstance(bed, tuple): data["bed"] = self._dict(actual=bed[0], target=bed[1]) if chamber is not None and isinstance(chamber, tuple): data["chamber"] = self._dict(actual=chamber[0], target=chamber[1]) for identifier, values in custom.items(): data[identifier] = self._dict(actual=values[0], target=values[1]) self._temps.append(data) self._stateMonitor.add_temperature(self._dict(**data)) def _validateJob(self, filename, sd): if not valid_file_type(filename, type="machinecode"): raise InvalidFileType(f"{filename} is not a machinecode file, cannot print") if sd: return path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename) if os.path.isabs(filename) and not filename == path_on_disk: raise InvalidFileLocation( "{} is not located within local storage, cannot select for printing".format( filename ) ) if not os.path.isfile(path_on_disk): raise InvalidFileLocation( "{} does not exist in local storage, cannot select for printing".format( filename ) ) def _setJobData(self, filename, filesize, sd, user=None, data=None): with self._selectedFileMutex: if filename is not None: if sd: name_in_storage = filename if name_in_storage.startswith("/"): name_in_storage = name_in_storage[1:] path_in_storage = name_in_storage path_on_disk = None else: path_in_storage = self._fileManager.path_in_storage( FileDestinations.LOCAL, filename ) path_on_disk = self._fileManager.path_on_disk( FileDestinations.LOCAL, filename ) _, name_in_storage = self._fileManager.split_path( FileDestinations.LOCAL, path_in_storage ) self._selectedFile = { "filename": path_in_storage, "filesize": filesize, "sd": sd, "estimatedPrintTime": None, "user": user, } else: self._selectedFile = None self._stateMonitor.set_job_data( self._dict( file=self._dict( name=None, path=None, display=None, origin=None, size=None, date=None, ), estimatedPrintTime=None, averagePrintTime=None, lastPrintTime=None, filament=None, user=None, ) ) return estimatedPrintTime = None lastPrintTime = None averagePrintTime = None date = None filament = None display_name = name_in_storage if path_on_disk: # Use an int for mtime because it could be float and the # javascript needs to exact match date = int(os.stat(path_on_disk).st_mtime) try: fileData = self._fileManager.get_metadata( FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk, ) except Exception: self._logger.exception("Error generating fileData") fileData = None if fileData is not None: if fileData.get("display"): display_name = fileData["display"] if isinstance(fileData.get("analysis"), dict): if estimatedPrintTime is None and fileData["analysis"].get( "estimatedPrintTime" ): estimatedPrintTime = fileData["analysis"][ "estimatedPrintTime" ] if fileData["analysis"].get("filament"): filament = fileData["analysis"]["filament"] if isinstance(fileData.get("statistics"), dict): printer_profile = ( self._printerProfileManager.get_current_or_default()["id"] ) if printer_profile in fileData["statistics"].get( "averagePrintTime", {} ): averagePrintTime = fileData["statistics"]["averagePrintTime"][ printer_profile ] if printer_profile in fileData["statistics"].get( "lastPrintTime", {} ): lastPrintTime = fileData["statistics"]["lastPrintTime"][ printer_profile ] if averagePrintTime is not None: self._selectedFile["estimatedPrintTime"] = averagePrintTime self._selectedFile["estimatedPrintTimeType"] = "average" elif estimatedPrintTime is not None: # TODO apply factor which first needs to be tracked! self._selectedFile["estimatedPrintTime"] = estimatedPrintTime self._selectedFile["estimatedPrintTimeType"] = "analysis" elif data: display_name = data.longname date = data.timestamp self._stateMonitor.set_job_data( self._dict( file=self._dict( name=name_in_storage, path=path_in_storage, display=display_name, origin=FileDestinations.SDCARD if sd else FileDestinations.LOCAL, size=filesize, date=date, ), estimatedPrintTime=estimatedPrintTime, averagePrintTime=averagePrintTime, lastPrintTime=lastPrintTime, filament=filament, user=user, ) ) def _updateJobUser(self, user): with self._selectedFileMutex: if ( self._selectedFile is not None and self._selectedFile.get("user", None) != user ): self._selectedFile["user"] = user job_data = self.get_current_job() self._stateMonitor.set_job_data( self._dict( file=job_data["file"], estimatedPrintTime=job_data["estimatedPrintTime"], averagePrintTime=job_data["averagePrintTime"], lastPrintTime=job_data["lastPrintTime"], filament=job_data["filament"], user=user, ) ) def _sendInitialStateUpdate(self, callback): try: data = self._stateMonitor.get_current_data() data.update( temps=list(self._temps), logs=list(self._log), messages=list(self._messages), markings=list(self._markings), ) plugin_data = self._get_additional_plugin_data(initial=False) if plugin_data: data.update(plugins=copy.deepcopy(plugin_data)) callback.on_printer_send_initial_data(data) except Exception: self._logger.exception( "Error while pushing initial state update to callback {}".format( callback ), extra={"callback": fqcn(callback)}, ) def _getStateFlags(self): return self._dict( operational=self.is_operational(), printing=self.is_printing(), cancelling=self.is_cancelling(), pausing=self.is_pausing(), resuming=self.is_resuming(), finishing=self.is_finishing(), closedOrError=self.is_closed_or_error(), error=self.is_error(), paused=self.is_paused(), ready=self.is_ready(), sdReady=self.is_sd_ready(), ) # ~~ comm.MachineComPrintCallback implementation def on_comm_log(self, message): """ Callback method for the comm object, called upon log output. """ self._addLog(to_unicode(message, "utf-8", errors="replace")) def on_comm_temperature_update(self, tools, bed, chamber, custom=None): if custom is None: custom = {} self._addTemperatureData( tools=copy.deepcopy(tools), bed=copy.deepcopy(bed), chamber=copy.deepcopy(chamber), custom=copy.deepcopy(custom), ) def on_comm_position_update(self, position, reason=None): payload = {"reason": reason} payload.update(position) eventManager().fire(Events.POSITION_UPDATE, payload) def on_comm_state_change(self, state): """ Callback method for the comm object, called if the connection state changes. """ oldState = self._state state_string = None error_string = None if self._comm is not None: state_string = self._comm.getStateString() error_string = self._comm.getErrorString() if oldState in (comm.MachineCom.STATE_PRINTING,): # if we were still printing and went into an error state, mark the print as failed if state in ( comm.MachineCom.STATE_CLOSED, comm.MachineCom.STATE_ERROR, comm.MachineCom.STATE_CLOSED_WITH_ERROR, ): with self._selectedFileMutex: if self._selectedFile is not None: payload = self._payload_for_print_job_event() if payload: payload["time"] = self._comm.getPrintTime() payload["reason"] = "error" payload["error"] = self._comm.getErrorString() payload["progress"] = self._comm.getPrintProgress() def finalize(): self._fileManager.log_print( payload["origin"], payload["path"], time.time(), payload["time"], False, self._printerProfileManager.get_current_or_default()[ "id" ], ) eventManager().fire(Events.PRINT_FAILED, payload) thread = threading.Thread(target=finalize) thread.daemon = True thread.start() try: self._analysisQueue.resume() # printing done, put those cpu cycles to good use except Exception: self._logger.exception("Error while resuming the analysis queue") elif state == comm.MachineCom.STATE_PRINTING: if settings().get(["gcodeAnalysis", "runAt"]) == "idle": try: self._analysisQueue.pause() # only analyse files while idle except Exception: self._logger.exception("Error while pausing the analysis queue") if ( state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR ): if self._comm is not None: self._comm = None with self._selectedFileMutex: if self._selectedFile is not None: eventManager().fire(Events.FILE_DESELECTED) self._setJobData(None, None, None) self._updateProgressData() self._setCurrentZ(None) self._setOffsets(None) self._addTemperatureData() self._printerProfileManager.deselect() eventManager().fire(Events.DISCONNECTED) self._setState(state, state_string=state_string, error_string=error_string) def on_comm_error(self, error, reason, consequence=None, faq=None, logs=None): # store error info self._error_info = ErrorInformation( error=error, reason=reason, consequence=consequence, faq=faq, logs=logs ) def on_comm_message(self, message): """ Callback method for the comm object, called upon message exchanges via serial. Stores the message in the message buffer, truncates buffer to the last 300 lines. """ self._addMessage(to_unicode(message, "utf-8", errors="replace")) def on_comm_progress(self): """ Callback method for the comm object, called upon any change in progress of the printjob. Triggers storage of new values for printTime, printTimeLeft and the current progress. """ self._stateMonitor.trigger_progress_update() def on_comm_z_change(self, newZ): """ Callback method for the comm object, called upon change of the z-layer. """ oldZ = self._currentZ if newZ != oldZ: # we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or # anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ}) self._setCurrentZ(newZ) def on_comm_sd_state_change(self, sdReady): self._stateMonitor.set_state( self._dict( text=self.get_state_string(), flags=self._getStateFlags(), error=self.get_error(), ) ) def on_comm_sd_files(self, files): eventManager().fire(Events.UPDATED_FILES, {"type": "printables"}) def on_comm_file_selected(self, full_path, size, sd, user=None, data=None): if full_path is not None: payload = self._payload_for_print_job_event( location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL, print_job_file=full_path, print_job_user=user, action_user=user, ) eventManager().fire(Events.FILE_SELECTED, payload) self._logger_job.info( "Print job selected - origin: {}, path: {}, owner: {}, user: {}".format( payload.get("origin"), payload.get("path"), payload.get("owner"), payload.get("user"), ) ) else: eventManager().fire(Events.FILE_DESELECTED) self._logger_job.info( "Print job deselected - user: {}".format(user if user else "n/a") ) self._setJobData(full_path, size, sd, user=user, data=data) self._stateMonitor.set_state( self._dict( text=self.get_state_string(), flags=self._getStateFlags(), error=self.get_error(), ) ) self._create_estimator() if self._printAfterSelect: self._printAfterSelect = False self.start_print(pos=self._posAfterSelect, user=user) def on_comm_print_job_started(self, suppress_script=False, user=None): # clear error info self._error_info = None self._updateJobUser( user ) # the final job owner should always be whoever _started_ the job self._stateMonitor.trigger_progress_update() payload = self._payload_for_print_job_event(print_job_user=user, action_user=user) if payload: eventManager().fire(Events.PRINT_STARTED, payload) eventManager().fire( Events.CHART_MARKED, {"type": "print", "label": "Start"}, ) self._logger_job.info( "Print job started - origin: {}, path: {}, owner: {}, user: {}".format( payload.get("origin"), payload.get("path"), payload.get("owner"), payload.get("user"), ) ) if not suppress_script: self.script( "beforePrintStarted", context={"event": payload}, part_of_job=True, must_be_set=False, ) def on_comm_print_job_done(self, suppress_script=False): self._fileManager.delete_recovery_data() payload = self._payload_for_print_job_event() if payload: payload["time"] = self._comm.getPrintTime() eventManager().fire( Events.CHART_MARKED, {"type": "done", "label": "Done"}, ) self._updateProgressData( completion=1.0, filepos=payload["size"], printTime=payload["time"], printTimeLeft=0, ) self._stateMonitor.set_state( self._dict( text=self.get_state_string(), flags=self._getStateFlags(), error=self.get_error(), ) ) eventManager().fire(Events.PRINT_DONE, payload) self._logger_job.info( "Print job done - origin: {}, path: {}, owner: {}".format( payload.get("origin"), payload.get("path"), payload.get("owner"), ) ) if not suppress_script: self.script( "afterPrintDone", context={"event": payload}, part_of_job=True, must_be_set=False, ) def log_print(): self._fileManager.log_print( payload["origin"], payload["path"], time.time(), payload["time"], True, self._printerProfileManager.get_current_or_default()["id"], ) thread = threading.Thread(target=log_print) thread.daemon = True thread.start() else: self._updateProgressData() self._stateMonitor.set_state( self._dict( text=self.get_state_string(), flags=self._getStateFlags(), error=self.get_error(), ) ) def on_comm_print_job_cancelling(self, firmware_error=None, user=None): payload = self._payload_for_print_job_event(action_user=user) if payload: if firmware_error: payload["firmwareError"] = firmware_error eventManager().fire(Events.PRINT_CANCELLING, payload) def on_comm_print_job_cancelled(self, suppress_script=False, user=None): self._setCurrentZ(None) self._updateProgressData() fileposition = self._comm.getFilePosition() if self._comm else None progress = self._comm.getPrintProgress() if self._comm else None payload = self._payload_for_print_job_event( position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None, fileposition=fileposition["pos"] if fileposition else None, progress=progress, action_user=user, ) if payload: payload["time"] = self._comm.getPrintTime() eventManager().fire(Events.PRINT_CANCELLED, payload) eventManager().fire( Events.CHART_MARKED, {"type": "cancel", "label": "Cancel"}, ) self._logger_job.info( "Print job cancelled - origin: {}, path: {}, owner: {}, user: {}, fileposition: {}, position: {}".format( payload.get("origin"), payload.get("path"), payload.get("owner"), payload.get("user"), payload.get("fileposition"), payload.get("position"), ) ) if not suppress_script: self.script( "afterPrintCancelled", context={"event": payload}, part_of_job=True, must_be_set=False, ) payload["reason"] = "cancelled" def finalize(): self._fileManager.log_print( payload["origin"], payload["path"], time.time(), payload["time"], False, self._printerProfileManager.get_current_or_default()["id"], ) eventManager().fire(Events.PRINT_FAILED, payload) thread = threading.Thread(target=finalize) thread.daemon = True thread.start() def on_comm_print_job_paused(self, suppress_script=False, user=None): fileposition = self._comm.getFilePosition() if self._comm else None progress = self._comm.getPrintProgress() if self._comm else None payload = self._payload_for_print_job_event( position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position and not suppress_script else None, fileposition=fileposition["pos"] if fileposition else None, progress=progress, action_user=user, ) if payload: eventManager().fire(Events.PRINT_PAUSED, payload) self._logger_job.info( "Print job paused - origin: {}, path: {}, owner: {}, user: {}, fileposition: {}, position: {}".format( payload.get("origin"), payload.get("path"), payload.get("owner"), payload.get("user"), payload.get("fileposition"), payload.get("position"), ) ) eventManager().fire( Events.CHART_MARKED, {"type": "pause", "label": "Pause"}, ) if not suppress_script: self.script( "afterPrintPaused", context={"event": payload}, part_of_job=True, must_be_set=False, ) def on_comm_print_job_resumed(self, suppress_script=False, user=None): payload = self._payload_for_print_job_event(action_user=user) if payload: eventManager().fire(Events.PRINT_RESUMED, payload) eventManager().fire( Events.CHART_MARKED, {"type": "resume", "label": "Resume"}, ) self._logger_job.info( "Print job resumed - origin: {}, path: {}, owner: {}, user: {}".format( payload.get("origin"), payload.get("path"), payload.get("owner"), payload.get("user"), ) ) if not suppress_script: self.script( "beforePrintResumed", context={"event": payload}, part_of_job=True, must_be_set=False, ) def on_comm_file_transfer_started( self, local_filename, remote_filename, filesize, user=None ): eventManager().fire( Events.TRANSFER_STARTED, {"local": local_filename, "remote": remote_filename} ) self._sdStreaming = True self._setJobData(remote_filename, filesize, True, user=user) self._updateProgressData(completion=0.0, filepos=0, printTime=0) self._stateMonitor.set_state( self._dict( text=self.get_state_string(), flags=self._getStateFlags(), error=self.get_error(), ) ) def on_comm_file_transfer_done( self, local_filename, remote_filename, elapsed, failed=False ): self._sdStreaming = False payload = {"local": local_filename, "remote": remote_filename, "time": elapsed} if failed: eventManager().fire(Events.TRANSFER_FAILED, payload) if callable(self._streamingFailedCallback): self._streamingFailedCallback( remote_filename, remote_filename, FileDestinations.SDCARD ) else: eventManager().fire(Events.TRANSFER_DONE, payload) if callable(self._streamingFinishedCallback): self._streamingFinishedCallback( remote_filename, remote_filename, FileDestinations.SDCARD ) self._setCurrentZ(None) self._setJobData(None, None, None) self._updateProgressData() self._stateMonitor.set_state( self._dict( text=self.get_state_string(), flags=self._getStateFlags(), error=self.get_error(), ) ) def on_comm_file_transfer_failed(self, local_filename, remote_filename, elapsed): self.on_comm_file_transfer_done( local_filename, remote_filename, elapsed, failed=True ) def on_comm_force_disconnect(self): self.disconnect() def on_comm_record_fileposition(self, origin, name, pos): try: self._fileManager.save_recovery_data(origin, name, pos) except NoSuchStorage: pass except Exception: self._logger.exception("Error while trying to persist print recovery data") def on_comm_firmware_info(self, firmware_name, firmware_data): self._firmware_info = {"name": firmware_name, "data": firmware_data} def _payload_for_print_job_event( self, location=None, print_job_file=None, print_job_size=None, print_job_user=None, position=None, fileposition=None, progress=None, action_user=None, ): if print_job_file is None: with self._selectedFileMutex: selected_file = self._selectedFile if not selected_file: return {} print_job_file = selected_file.get("filename", None) print_job_size = selected_file.get("filesize", None) print_job_user = selected_file.get("user", None) location = ( FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL ) if not print_job_file or not location: return {} if location == FileDestinations.SDCARD: full_path = print_job_file if full_path.startswith("/"): full_path = full_path[1:] name = path = full_path origin = FileDestinations.SDCARD else: full_path = self._fileManager.path_on_disk( FileDestinations.LOCAL, print_job_file ) path = self._fileManager.path_in_storage( FileDestinations.LOCAL, print_job_file ) _, name = self._fileManager.split_path(FileDestinations.LOCAL, path) origin = FileDestinations.LOCAL result = {"name": name, "path": path, "origin": origin, "size": print_job_size} if position is not None: result["position"] = position if fileposition is not None: result["fileposition"] = fileposition if progress is not None: result["progress"] = int(progress * 100) if print_job_user is not None: result["owner"] = print_job_user if action_user is not None: result["user"] = action_user return result class StateMonitor: def __init__( self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None, on_get_progress=None, on_get_resends=None, ): self._interval = interval self._update_callback = on_update self._on_add_temperature = on_add_temperature self._on_add_log = on_add_log self._on_add_message = on_add_message self._on_get_progress = on_get_progress self._on_get_resends = on_get_resends self._state = None self._job_data = None self._current_z = None self._offsets = {} self._progress = None self._resends = None self._progress_dirty = False self._resends_dirty = False self._change_event = threading.Event() self._state_lock = threading.Lock() self._progress_lock = threading.Lock() self._resends_lock = threading.Lock() self._last_update = time.monotonic() self._worker = threading.Thread(target=self._work) self._worker.daemon = True self._worker.start() def _get_current_progress(self): if callable(self._on_get_progress): return self._on_get_progress() return self._progress def _get_current_resends(self): if callable(self._on_get_resends): return self._on_get_resends() return self._resends def reset( self, state=None, job_data=None, progress=None, current_z=None, offsets=None, resends=None, ): self.set_state(state) self.set_job_data(job_data) self.set_progress(progress) self.set_current_z(current_z) self.set_temp_offsets(offsets) self.set_resends(resends) def add_temperature(self, temperature): self._on_add_temperature(temperature) self._change_event.set() def add_log(self, log): self._on_add_log(log) with self._resends_lock: self._resends_dirty = True self._change_event.set() def add_message(self, message): self._on_add_message(message) self._change_event.set() def set_current_z(self, current_z): self._current_z = current_z self._change_event.set() def set_state(self, state): with self._state_lock: self._state = state self._change_event.set() def set_job_data(self, job_data): self._job_data = job_data self._change_event.set() def trigger_progress_update(self): with self._progress_lock: self._progress_dirty = True self._change_event.set() def set_progress(self, progress): with self._progress_lock: self._progress_dirty = False self._progress = progress self._change_event.set() def set_resends(self, resend_ratio): with self._resends_lock: self._resends_dirty = False self._resends = resend_ratio self._change_event.set() def set_temp_offsets(self, offsets): if offsets is None: offsets = {} self._offsets = offsets self._change_event.set() def _work(self): try: while True: self._change_event.wait() now = time.monotonic() delta = now - self._last_update additional_wait_time = self._interval - delta if additional_wait_time > 0: time.sleep(additional_wait_time) with self._state_lock: data = self.get_current_data() self._update_callback(data) self._last_update = time.monotonic() self._change_event.clear() except Exception: logging.getLogger(__name__).exception( "Looks like something crashed inside the state update worker. " "Please report this on the OctoPrint issue tracker (make sure " "to include logs!)" ) def get_current_data(self): with self._progress_lock: if self._progress_dirty: self._progress = self._get_current_progress() self._progress_dirty = False with self._resends_lock: if self._resends_dirty: self._resends = self._get_current_resends() self._resends_dirty = False return { "state": self._state, "job": self._job_data, "currentZ": self._current_z, "progress": self._progress, "offsets": self._offsets, "resends": self._resends, } class DataHistory(InvariantContainer): def __init__(self, cutoff=30 * 60): def data_invariant(data): data.sort(key=lambda x: x["time"]) now = int(time.time()) return [item for item in data if item["time"] >= now - cutoff] InvariantContainer.__init__(self, guarantee_invariant=data_invariant) self._last = None @property def last(self): return self._last def append(self, item): try: return super().append(item) finally: self._last = self._data[-1] if len(self._data) else None
77,500
Python
.py
1,829
29.157463
139
0.548639
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,855
__init__.py
OctoPrint_OctoPrint/src/octoprint/settings/__init__.py
""" This module represents OctoPrint's settings management. Within this module the default settings for the core application are defined and the instance of the :class:`Settings` is held, which offers getter and setter methods for the raw configuration values as well as various convenience methods to access the paths to base folders of various types and the configuration file itself. .. autodata:: default_settings :annotation: = dict(...) .. autodata:: valid_boolean_trues .. autofunction:: settings .. autoclass:: Settings :members: :undoc-members: """ __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import fnmatch import logging import os import re import sys import threading import time from collections import ChainMap, defaultdict from collections.abc import KeysView from typing import Any, Dict, List from yaml import YAMLError from octoprint.schema.config import Config from octoprint.util import ( CaseInsensitiveSet, atomic_write, deprecated, dict_merge, fast_deepcopy, generate_api_key, is_hidden_path, time_this, yaml, ) _APPNAME = "OctoPrint" _instance = None def settings(init=False, basedir=None, configfile=None, overlays=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.settings.Settings` singleton. Arguments: init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not (False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError` will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to False. basedir (str): Path of the base directory for all of OctoPrint's settings, log files, uploads etc. If not set the default will be used: ``~/.octoprint`` on Linux, ``%APPDATA%/OctoPrint`` on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS. configfile (str): Path of the configuration file (``config.yaml``) to work on. If not set the default will be used: ``<basedir>/config.yaml`` for ``basedir`` as defined above. overlays (list): List of paths to config overlays to put between default settings and config.yaml Returns: Settings: The fully initialized :class:`Settings` instance. Raises: ValueError: ``init`` is True but settings are already initialized or vice versa. """ global _instance if _instance is not None: if init: raise ValueError("Settings Manager already initialized") else: if init: _instance = Settings( configfile=configfile, basedir=basedir, overlays=overlays ) else: raise ValueError("Settings not initialized yet") return _instance # TODO: This is a temporary solution to get the default settings from the pydantic model. _config = Config() default_settings = _config.dict(by_alias=True) """The default settings of the core application.""" valid_boolean_trues = CaseInsensitiveSet(True, "true", "yes", "y", "1", 1) """ Values that are considered to be equivalent to the boolean ``True`` value, used for type conversion in various places.""" class NoSuchSettingsPath(Exception): pass class InvalidSettings(Exception): pass class InvalidYaml(InvalidSettings): def __init__(self, file, line=None, column=None, details=None): self.file = file self.line = line self.column = column self.details = details def __str__(self): message = ( "Error parsing the configuration file {}, " "it is invalid YAML.".format(self.file) ) if self.line and self.column: message += " The parser reported an error on line {}, column {}.".format( self.line, self.column ) return message class DuplicateFolderPaths(InvalidSettings): def __init__(self, folders): self.folders = folders self.duplicates = {} for folder, path in folders.items(): duplicates = [] for other_folder, other_path in folders.items(): if other_folder == folder: continue if other_path == path: duplicates.append(other_folder) if len(duplicates): self.duplicates[folder] = duplicates def __str__(self): duplicates = [ "{} (duplicates: {})".format(folder, ", ".join(dupes)) for folder, dupes in self.duplicates.items() ] return "There are duplicate folder paths configured: {}".format( ", ".join(duplicates) ) _CHAINMAP_SEP = "\x1f" class HierarchicalChainMap: """ Stores a bunch of nested dictionaries in chain map, allowing queries of nested values work on lower directories. For example: Example: >>> example_dict = {"a": "a", "b": {"c": "c"}} >>> hcm = HierarchicalChainMap({"b": {"d": "d"}}, example_dict) >>> cm = ChainMap({"b": {"d": "d"}}, example_dict) >>> cm["b"]["d"] 'd' >>> cm["b"]["c"] Traceback (most recent call last): ... KeyError: 'c' >>> hcm.get_by_path(["b", "d"]) 'd' >>> hcm.get_by_path(["b", "c"]) 'c' Internally, the chainmap is flattened, without any contained dictionaries. Combined with a prefix cache, this allows for fast lookups of nested values. The chainmap is also unflattened when needed, for example when returning sub trees or the full dictionary. For flattening, the path to each value is joined with a special separator character that is unlikely to appear in a normal key, ``\x1f``. Unflattening is then done by splitting the keys on this character and recreating the nested structure. """ @staticmethod def _flatten(d: Dict[str, Any], parent_key: str = "") -> Dict[str, Any]: """ Recursively flattens a hierarchical dictionary. Args: d (dict): The hierarchical dictionary to flatten. parent_key (str): The parent key to use for the current level. Returns: dict: The flattened dictionary. """ if d is None: return {} items = [] for k, v in d.items(): new_key = parent_key + _CHAINMAP_SEP + str(k) if parent_key else str(k) if v and isinstance(v, dict): items.extend(HierarchicalChainMap._flatten(v, new_key).items()) else: items.append((new_key, v)) return dict(items) @staticmethod def _unflatten(d: Dict[str, Any], prefix: str = "") -> Dict[str, Any]: """ Unflattens a flattened dictionary. Args: d (dict): The flattened dictionary. prefix (str): The prefix to use for the top level keys. If provided, only keys starting with this prefix will be unflattened and part of the result. Returns: dict: The unflattened dictionary. """ if d is None: return {} result = {} for key, value in d.items(): if not key.startswith(prefix): continue subkeys = key[len(prefix) :].split(_CHAINMAP_SEP) current = result path = [] for subkey in subkeys[:-1]: # we only need that for logging in case of data weirdness below path.append(subkey) # make sure the subkey is in the current dict, and that it is a dict if subkey not in current: current[subkey] = {} elif not isinstance(current[subkey], dict): logging.getLogger(__name__).warning( f"There is a non-dict value on the path to {key} at {path!r}, ignoring." ) current[subkey] = {} # go down a level current = current[subkey] current[subkeys[-1]] = value return result @staticmethod def _path_to_key(path: List[str]) -> str: """Converts a path to a key.""" return _CHAINMAP_SEP.join(path) @staticmethod def from_layers(*layers: Dict[str, Any]) -> "HierarchicalChainMap": """Generates a new chain map from the provided layers.""" result = HierarchicalChainMap() result._chainmap.maps = layers return result def __init__(self, *maps: Dict[str, Any]): self._chainmap = ChainMap(*map(self._flatten, maps)) self._prefixed_keys = {} def _has_prefix(self, prefix: str, current: ChainMap = None) -> bool: """ Check if the given prefix is in the current map. This utilizes the cached prefix keys to avoid recomputing the list every time. """ if current is None: current = self._chainmap return any(map(lambda x: x in current, self._cached_prefixed_keys(prefix))) def _with_prefix(self, prefix: str, current: ChainMap = None) -> Dict[str, Any]: """ Get a dict with all keys that start with the given prefix. This utilizes the cached prefix keys to avoid recomputing the list every time. """ if current is None: current = self._chainmap return {k: current[k] for k in self._cached_prefixed_keys(prefix) if k in current} def _cached_prefixed_keys(self, prefix: str) -> List[str]: """ Get a list of keys that start with the given prefix. This is cached to avoid recomputing the list every time. """ if prefix not in self._prefixed_keys: keys = [k for k in self._chainmap.keys() if k.startswith(prefix)] if keys: self._prefixed_keys[prefix] = keys return self._prefixed_keys.get(prefix, []) def _invalidate_prefixed_keys(self, prefix: str) -> None: """ Invalidate the cache of prefixed keys for the given prefix. This is done the following way: - Iterate backwards through all prefixes of the given prefix and delete any cached keys for them. - Delete all keys that start with the given prefix. """ seps = [] for i, c in enumerate(prefix): if c == _CHAINMAP_SEP: seps.append(i) for sep in reversed(seps): try: del self._prefixed_keys[prefix[: sep + 1]] except KeyError: pass to_delete = [key for key in self._prefixed_keys.keys() if key.startswith(prefix)] for prefix in to_delete: del self._prefixed_keys[prefix] def deep_dict(self) -> Dict[str, Any]: """Returns an unflattened copy of the current chainmap.""" return self._unflatten(self._chainmap) def has_path( self, path: List[str], only_local: bool = False, only_defaults: bool = False ) -> bool: """ Checks if the given path exists in the current map. Args: only_local (bool): Only check the top most map. only_defaults (bool): Only check everything but the top most map. Returns: bool: True if the path exists, False otherwise. """ if only_defaults: current = self._chainmap.parents elif only_local: current = self._chainmap.maps[0] else: current = self._chainmap key = self._path_to_key(path) prefix = key + _CHAINMAP_SEP return key in current or self._has_prefix(prefix, current) @time_this( logtarget="octoprint.settings.timings.HierarchicalChainMap.get_by_path", message="{func}({func_args}) took {timing:.6f}ms", incl_func_args=True, ) def get_by_path( self, path: List[str], only_local: bool = False, only_defaults: bool = False, merged: bool = False, ) -> Any: """ Retrieves the value at the given path. If the path is not found, a KeyError is raised. Makes heavy use of the prefix cache to avoid recomputing the list of keys every time. Args: path (list): The path to the value to retrieve. only_local (bool): Only check the top most map. only_defaults (bool): Only check everything but the top most map. merged (bool): If true and the value is a dict, merge all values from all layers. Returns: The value at the given path. """ if only_defaults: current = self._chainmap.parents elif only_local: current = self._chainmap.maps[0] else: current = self._chainmap key = self._path_to_key(path) prefix = key + _CHAINMAP_SEP if key in current and not self._has_prefix(prefix, current): # found it, return return current[key] # if we arrived here we might be trying to grab a dict, look for children # TODO 2.0.0 remove this & make 'merged' the default if not merged and hasattr(current, "maps"): # we do something a bit odd here: if merged is not true, we don't include the # full contents of the key. Instead, we only include the contents of the key # on the first level where we find the value. for layer in current.maps: if self._has_prefix(prefix, layer): current = layer break result = self._unflatten(self._with_prefix(prefix, current), prefix=prefix) if not result: raise KeyError("Could not find entry for " + str(path)) return result def set_by_path(self, path: List[str], value: Any) -> None: """ Sets the value at the given path. Only the top most map is written to. Takes care of invalidating the prefix cache as needed. Args: path (list): The path to the value to set. value: The value to set. """ current = self._chainmap.maps[0] # config only key = self._path_to_key(path) prefix = key + _CHAINMAP_SEP # path might have had subkeys before, clean them up self._del_prefix(current, prefix) if isinstance(value, dict): current.update(self._flatten(value, key)) self._invalidate_prefixed_keys(prefix) else: # make sure to clear anything below the path (e.g. switching from dict # to something else, for whatever reason) self._clean_upward_path(current, path) # finally set the new value current[key] = value def del_by_path(self, path: List[str]) -> None: """ Deletes the value at the given path. Only the top most map is written to. Takes care of invalidating the prefix cache as needed. Args: path (list): The path to the value to delete. Raises: KeyError: If the path does not exist. """ if not path: raise ValueError("Invalid path") current = self._chainmap.maps[0] # config only key = self._path_to_key(path) prefix = key + _CHAINMAP_SEP deleted = False # delete any subkeys deleted = self._del_prefix(current, prefix) # delete the key itself if it's there try: del current[key] deleted = True except KeyError: pass if not deleted: raise KeyError("Could not find entry for " + str(path)) # clean anything that's now empty and above our path self._clean_upward_path(current, path) def _del_prefix(self, current: ChainMap, prefix: str) -> bool: """ Deletes all keys that start with the given prefix. Takes care of invalidating the prefix cache as needed. Args: current (ChainMap): The map to delete from. prefix (str): The prefix to delete. Returns: bool: True if any keys were deleted, False otherwise. """ to_delete = self._with_prefix(prefix, current).keys() for k in to_delete: del current[k] if len(to_delete) > 0: self._invalidate_prefixed_keys(prefix) return len(to_delete) > 0 def _clean_upward_path(self, current: ChainMap, path: List[str]) -> None: """ Cleans up the path upwards from the given path, getting rid of any empty dicts. Args: current (ChainMap): The map to clean up. path (list): The path to clean up from. """ working_path = path while len(working_path): working_path = working_path[:-1] if not working_path: break key = self._path_to_key(working_path) prefix = key + _CHAINMAP_SEP if self._has_prefix(prefix, current): # there's at least one subkey here, we're done break # delete the key itself if it's there try: del current[key] except KeyError: # key itself wasn't in there pass def with_config_defaults( self, config: Dict[str, Any] = None, defaults: Dict[str, Any] = None ) -> "HierarchicalChainMap": """ Builds a new map with the following layers: provided config + any intermediary parents + provided defaults + regular defaults. Args: config (dict): The config to use as the top layer. May be None in which case it will be set to the current config. May be unflattened. defaults (dict): The defaults to use above the bottom layer. May be None in which case it will be set to an empty layer. May be unflattened. Returns: HierarchicalChainMap: A new chain map with the provided layers. """ if config is None and defaults is None: return self if config is not None: config = self._flatten(config) else: config = self._chainmap.maps[0] if defaults is not None: defaults = [self._flatten(defaults)] else: defaults = [] layers = [config] + self._middle_layers() + defaults + [self._chainmap.maps[-1]] return self.with_layers(*layers) def with_layers(self, *layers: Dict[str, Any]) -> "HierarchicalChainMap": """ Builds a new map with the provided layers. Makes sure to copy the current prefix cache to the new map. Args: layers: The layers to use in the new map. May be unflattened. Returns: HierarchicalChainMap: A new chain map with the provided layers. """ chain = HierarchicalChainMap.from_layers(*layers) chain._prefixed_keys = ( self._prefixed_keys ) # be sure to copy the cache or it will lose sync return chain @property def top_map(self) -> Dict[str, Any]: """This is the layer that is written to, unflattened""" return self._unflatten(self._chainmap.maps[0]) @top_map.setter def top_map(self, value): self._chainmap.maps[0] = self._flatten(value) @property def bottom_map(self) -> Dict[str, Any]: """The very bottom layer is the default layer, unflattened""" return self._unflatten(self._chainmap.maps[-1]) def insert_map(self, pos: int, d: Dict[str, Any]) -> None: """ Inserts a new map at the given position into the chainmap. The map is flattened before being inserted. Takes care of invalidating the prefix cache as needed. Args: pos (int): The position to insert the map at. d (dict): The unflattened map to insert. May be unflattened. """ flattened = self._flatten(d) for k in flattened: self._invalidate_prefixed_keys(k + _CHAINMAP_SEP) self._chainmap.maps.insert(pos, flattened) def delete_map(self, pos: int) -> None: """ Deletes the map at the given position from the chainmap. Takes care of invalidating the prefix cache as needed. Args: pos (int): The position to delete the map from. """ flattened = self._chainmap.maps[pos] for k in flattened: self._invalidate_prefixed_keys(k + _CHAINMAP_SEP) del self._chainmap.maps[pos] @property def all_layers(self) -> List[Dict[str, Any]]: """A list of all layers in this map, flattened.""" return self._chainmap.maps def _middle_layers(self) -> List[dict]: """Returns all layers between the top and bottom layer, flattened.""" if len(self._chainmap.maps) > 2: return self._chainmap.maps[1:-1] else: return [] class Settings: """ The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings directory, loading the configuration from ``config.yaml``, persisting changes to disk etc and provides access methods for getting and setting specific values from the overall settings structure via paths. A general word on the concept of paths, since they play an important role in OctoPrint's settings management. A path is basically a list or tuple consisting of keys to follow down into the settings (which are basically like a ``dict``) in order to set or retrieve a specific value (or more than one). For example, for a settings structure like the following:: serial: port: "/dev/ttyACM0" baudrate: 250000 timeout: communication: 20.0 temperature: 5.0 sdStatus: 1.0 connection: 10.0 server: host: "0.0.0.0" port: 5000 the following paths could be used: ========================================== ============================================================================ Path Value ========================================== ============================================================================ ``["serial", "port"]`` :: "/dev/ttyACM0" ``["serial", "timeout"]`` :: communication: 20.0 temperature: 5.0 sdStatus: 1.0 connection: 10.0 ``["serial", "timeout", "temperature"]`` :: 5.0 ``["server", "port"]`` :: 5000 ========================================== ============================================================================ However, these would be invalid paths: ``["key"]``, ``["serial", "port", "value"]``, ``["server", "host", 3]``. """ OVERLAY_KEY = "__overlay__" def __init__(self, configfile=None, basedir=None, overlays=None): self._logger = logging.getLogger(__name__) self._basedir = None if overlays is None: overlays = [] assert isinstance(default_settings, dict) self._map = HierarchicalChainMap({}, default_settings) self.load_overlays(overlays) self._dirty = False self._dirty_time = 0 self._last_config_hash = None self._last_effective_hash = None self._mtime = None self._lock = threading.RLock() self._get_preprocessors = {"controls": self._process_custom_controls} self._set_preprocessors = {} self._path_update_callbacks = defaultdict(list) self._deprecated_paths = defaultdict(dict) self.flagged_basefolders = {} self._init_basedir(basedir) if configfile is not None: self._configfile = configfile else: self._configfile = os.path.join(self._basedir, "config.yaml") self.load(migrate=True) apikey = self.get(["api", "key"]) if not apikey or apikey == "n/a": self.generateApiKey() self._script_env = self._init_script_templating() self.sanity_check_folders( folders=[ "logs", ] ) self.warn_about_risky_settings() def _init_basedir(self, basedir): if basedir is not None: self._basedir = basedir else: self._basedir = _default_basedir(_APPNAME) if not os.path.isdir(self._basedir): try: os.makedirs(self._basedir) except Exception: self._logger.fatal( "Could not create basefolder at {}. This is a fatal error, OctoPrint " "can't run without a writable base folder.".format(self._basedir), exc_info=1, ) raise def sanity_check_folders(self, folders=None): if folders is None: folders = default_settings["folder"].keys() folder_map = {} for folder in folders: folder_map[folder] = self.getBaseFolder( folder, check_writable=True, deep_check_writable=True ) # validate uniqueness of folder paths if len(folder_map.values()) != len(set(folder_map.values())): raise DuplicateFolderPaths(folders) def warn_about_risky_settings(self): if not self.getBoolean(["devel", "enableRateLimiter"]): self._logger.warning( "Rate limiting is disabled, this is a security risk. Do not run this in production." ) if not self.getBoolean(["devel", "enableCsrfProtection"]): self._logger.warning( "CSRF Protection is disabled, this is a security risk. Do not run this in production." ) def _is_deprecated_path(self, path): if path and isinstance(path[-1], (list, tuple)): prefix = path[:-1] return any( map(lambda x: bool(self._deprecated_paths[tuple(prefix + [x])]), path[-1]) ) if ( tuple(path) not in self._deprecated_paths or not self._deprecated_paths[tuple(path)] ): return False try: return list(self._deprecated_paths[tuple(path)].values())[-1] except StopIteration: return False def _path_modified(self, path, current_value, new_value): callbacks = self._path_update_callbacks.get(tuple(path)) if callbacks: for callback in callbacks: try: if callable(callback): callback(path, current_value, new_value) except Exception: self._logger.exception( f"Error while executing callback {callback} for path {path}" ) def _get_default_folder(self, type): folder = default_settings["folder"][type] if folder is None: folder = os.path.join(self._basedir, type.replace("_", os.path.sep)) return folder def _init_script_templating(self): from jinja2 import BaseLoader, ChoiceLoader, TemplateNotFound from jinja2.ext import Extension from jinja2.nodes import Include from jinja2.sandbox import SandboxedEnvironment from octoprint.util.jinja import FilteredFileSystemLoader class SnippetExtension(Extension): tags = {"snippet"} fields = Include.fields def parse(self, parser): node = parser.parse_include() if not node.template.value.startswith("/"): node.template.value = "snippets/" + node.template.value return node class SettingsScriptLoader(BaseLoader): def __init__(self, s): self._settings = s def get_source(self, environment, template): parts = template.split("/") if not len(parts): raise TemplateNotFound(template) script = self._settings.get(["scripts"], merged=True) for part in parts: if isinstance(script, dict) and part in script: script = script[part] else: raise TemplateNotFound(template) source = script if source is None: raise TemplateNotFound(template) mtime = self._settings._mtime return source, None, lambda: mtime == self._settings.last_modified def list_templates(self): scripts = self._settings.get(["scripts"], merged=True) return self._get_templates(scripts) def _get_templates(self, scripts): templates = [] for key in scripts: if isinstance(scripts[key], dict): templates += list( map( lambda x: key + "/" + x, self._get_templates(scripts[key]) ) ) elif isinstance(scripts[key], str): templates.append(key) return templates class SelectLoader(BaseLoader): def __init__(self, default, mapping, sep=":"): self._default = default self._mapping = mapping self._sep = sep def get_source(self, environment, template): if self._sep in template: prefix, name = template.split(self._sep, 1) if prefix not in self._mapping: raise TemplateNotFound(template) return self._mapping[prefix].get_source(environment, name) return self._default.get_source(environment, template) def list_templates(self): return self._default.list_templates() class RelEnvironment(SandboxedEnvironment): def __init__(self, prefix_sep=":", *args, **kwargs): super().__init__(*args, **kwargs) self._prefix_sep = prefix_sep def join_path(self, template, parent): prefix, name = self._split_prefix(template) if name.startswith("/"): return self._join_prefix(prefix, name[1:]) else: _, parent_name = self._split_prefix(parent) parent_base = parent_name.split("/")[:-1] return self._join_prefix(prefix, "/".join(parent_base) + "/" + name) def _split_prefix(self, template): if self._prefix_sep in template: return template.split(self._prefix_sep, 1) else: return "", template def _join_prefix(self, prefix, template): if len(prefix): return prefix + self._prefix_sep + template else: return template path_filter = lambda path: not is_hidden_path(path) file_system_loader = FilteredFileSystemLoader( self.getBaseFolder("scripts"), path_filter=path_filter ) settings_loader = SettingsScriptLoader(self) choice_loader = ChoiceLoader([file_system_loader, settings_loader]) select_loader = SelectLoader( choice_loader, {"bundled": settings_loader, "file": file_system_loader} ) return RelEnvironment(loader=select_loader, extensions=[SnippetExtension]) def _get_script_template(self, script_type, name, source=False): from jinja2 import TemplateNotFound template_name = script_type + "/" + name try: if source: template_name, _, _ = self._script_env.loader.get_source( self._script_env, template_name ) return template_name else: return self._script_env.get_template(template_name) except TemplateNotFound: return None except Exception: self._logger.exception( f"Exception while trying to resolve template {template_name}" ) return None def _get_scripts(self, script_type): return self._script_env.list_templates( filter_func=lambda x: x.startswith(script_type + "/") ) def _process_custom_controls(self, controls): def process_control(c): # shallow copy result = dict(c) if "regex" in result and "template" in result: # if it's a template matcher, we need to add a key to associate with the matcher output import hashlib key_hash = hashlib.md5() key_hash.update(result["regex"].encode("utf-8")) result["key"] = key_hash.hexdigest() template_key_hash = hashlib.md5() template_key_hash.update(result["template"].encode("utf-8")) result["template_key"] = template_key_hash.hexdigest() elif "children" in result: # if it has children we need to process them recursively result["children"] = list( map( process_control, [child for child in result["children"] if child is not None], ) ) return result return list(map(process_control, controls)) def _forget_hashes(self): self._last_config_hash = None self._last_effective_hash = None def _mark_dirty(self): with self._lock: self._dirty = True self._dirty_time = time.time() self._forget_hashes() @property def effective(self): return self._map.deep_dict() @property def effective_yaml(self): return yaml.dump(self.effective) @property def effective_hash(self): if self._last_effective_hash is not None: return self._last_effective_hash import hashlib hash = hashlib.md5() hash.update(self.effective_yaml.encode("utf-8")) self._last_effective_hash = hash.hexdigest() return self._last_effective_hash @property def config_yaml(self): return yaml.dump(self.config) @property def config_hash(self): if self._last_config_hash: return self._last_config_hash import hashlib hash = hashlib.md5() hash.update(self.config_yaml.encode("utf-8")) self._last_config_hash = hash.hexdigest() return self._last_config_hash @property def config(self): """ A view of the local config as stored in config.yaml Does not support modifications, they will be thrown away silently. If you need to modify anything in the settings, utilize the provided set and remove methods. """ return self._map.top_map @property @deprecated( "Settings._config has been deprecated and is a read-only view. Please use Settings.config or the set & remove methods instead.", since="1.8.0", ) def _config(self): return self.config @_config.setter @deprecated( "Setting of Settings._config has been deprecated. Please use the set & remove methods instead and get in touch if you have a usecase they don't cover.", since="1.8.0", ) def _config(self, value): self._map.top_map = value @property def _overlay_layers(self): if len(self._map.all_layers) > 2: return self._map.all_layers[1:-1] else: return [] @property def _default_map(self): return self._map.bottom_map @property def last_modified(self): """ Returns: (int) The last modification time of the configuration file. """ stat = os.stat(self._configfile) return stat.st_mtime @property def last_modified_or_made_dirty(self): return max(self.last_modified, self._dirty_time) # ~~ load and save def load(self, migrate=False): config = None mtime = None if os.path.exists(self._configfile) and os.path.isfile(self._configfile): with open(self._configfile, encoding="utf-8", errors="replace") as f: try: config = yaml.load_from_file(file=f) mtime = self.last_modified except YAMLError as e: details = str(e) if hasattr(e, "problem_mark"): line = e.problem_mark.line column = e.problem_mark.column else: line = None column = None raise InvalidYaml( self._configfile, details=details, line=line, column=column, ) # changed from else to handle cases where the file exists, but is empty / 0 bytes if not config or not isinstance(config, dict): config = {} self._map.top_map = config self._mtime = mtime if migrate: self._migrate_config() self._forget_hashes() def load_overlays(self, overlays, migrate=True): for overlay in overlays: if not os.path.exists(overlay): continue def process(path): try: overlay_config = self.load_overlay(path, migrate=migrate) self.add_overlay(overlay_config) self._logger.info(f"Added config overlay from {path}") except Exception: self._logger.exception(f"Could not add config overlay from {path}") if os.path.isfile(overlay): process(overlay) elif os.path.isdir(overlay): for entry in os.scandir(overlay): name = entry.name path = entry.path if is_hidden_path(path) or not fnmatch.fnmatch(name, "*.yaml"): continue process(path) def load_overlay(self, overlay, migrate=True): config = None if callable(overlay): try: overlay = overlay(self) except Exception: self._logger.exception("Error loading overlay from callable") return if isinstance(overlay, str): if os.path.exists(overlay) and os.path.isfile(overlay): config = yaml.load_from_file(path=overlay) elif isinstance(overlay, dict): config = overlay else: raise ValueError( "Overlay must be either a path to a yaml file or a dictionary" ) if not isinstance(config, dict): raise ValueError( f"Configuration data must be a dict but is a {config.__class__}" ) if migrate: self._migrate_config(config) return config def add_overlay( self, overlay, at_end=False, key=None, deprecated=None, replace=False ): assert isinstance(overlay, dict) if key is None: overlay_yaml = yaml.dump(overlay) import hashlib hash = hashlib.md5() hash.update(overlay_yaml.encode("utf-8")) key = hash.hexdigest() if replace: self.remove_overlay(key) if deprecated is not None: self._logger.debug( f"Marking all (recursive) paths in this overlay as deprecated: {overlay}" ) for path in _paths([], overlay): self._deprecated_paths[tuple(path)][key] = deprecated overlay[self.OVERLAY_KEY] = key if at_end: self._map.insert_map(-1, overlay) else: self._map.insert_map(1, overlay) return key def remove_overlay(self, key): index = -1 for i, overlay in enumerate(self._overlay_layers): if key == overlay.get(self.OVERLAY_KEY): index = i overlay = self._map._unflatten(overlay) break if index > -1: self._map.delete_map(index + 1) self._logger.debug( f"Removing all deprecation marks for (recursive) paths in this overlay: {overlay}" ) for path in _paths([], overlay): try: del self._deprecated_paths[tuple(path)][key] except KeyError: # key not in dict pass return True return False def add_path_update_callback(self, path, callback): callbacks = self._path_update_callbacks[tuple(path)] if callback not in callbacks: callbacks.append(callback) def remove_path_update_callback(self, path, callback): try: self._path_update_callbacks[tuple(path)].remove(callback) except ValueError: # callback not in list pass def _migrate_config(self, config=None, persist=False): if config is None: config = self._map.top_map persist = True dirty = False migrators = ( self._migrate_event_config, self._migrate_reverse_proxy_config, self._migrate_printer_parameters, self._migrate_gcode_scripts, self._migrate_core_system_commands, self._migrate_serial_features, self._migrate_resend_without_ok, self._migrate_string_temperature_profile_values, self._migrate_blocked_commands, self._migrate_gcodeviewer_enabled, ) for migrate in migrators: dirty = migrate(config) or dirty if dirty and persist: self._map.top_map = ( config # we need to write it back here or the changes will be lost ) self.save(force=True) def _migrate_gcode_scripts(self, config): """ Migrates an old development version of gcode scripts to the new template based format. Added in 1.2.0 """ dirty = False if "scripts" in config: if "gcode" in config["scripts"]: if "templates" in config["scripts"]["gcode"]: del config["scripts"]["gcode"]["templates"] replacements = { "disable_steppers": "M84", "disable_hotends": "{% snippet 'disable_hotends' %}", "disable_bed": "M140 S0", "disable_fan": "M106 S0", } for name, script in config["scripts"]["gcode"].items(): self.saveScript("gcode", name, script.format(**replacements)) del config["scripts"] dirty = True return dirty def _migrate_printer_parameters(self, config): """ Migrates the old "printer > parameters" data structure to the new printer profile mechanism. Added in 1.2.0 """ default_profile = ( config["printerProfiles"]["defaultProfile"] if "printerProfiles" in config and "defaultProfile" in config["printerProfiles"] else {} ) dirty = False if "printerParameters" in config: printer_parameters = config["printerParameters"] if ( "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters ): dirty = True default_profile["axes"] = {"x": {}, "y": {}, "z": {}, "e": {}} if "movementSpeed" in printer_parameters: for axis in ("x", "y", "z", "e"): if axis in printer_parameters["movementSpeed"]: default_profile["axes"][axis]["speed"] = printer_parameters[ "movementSpeed" ][axis] del config["printerParameters"]["movementSpeed"] if "invertedAxes" in printer_parameters: for axis in ("x", "y", "z", "e"): if axis in printer_parameters["invertedAxes"]: default_profile["axes"][axis]["inverted"] = True del config["printerParameters"]["invertedAxes"] if ( "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters ): dirty = True if "extruder" not in default_profile: default_profile["extruder"] = {} if "numExtruders" in printer_parameters: default_profile["extruder"]["count"] = printer_parameters[ "numExtruders" ] del config["printerParameters"]["numExtruders"] if "extruderOffsets" in printer_parameters: extruder_offsets = [] for offset in printer_parameters["extruderOffsets"]: if "x" in offset and "y" in offset: extruder_offsets.append((offset["x"], offset["y"])) default_profile["extruder"]["offsets"] = extruder_offsets del config["printerParameters"]["extruderOffsets"] if "bedDimensions" in printer_parameters: dirty = True bed_dimensions = printer_parameters["bedDimensions"] if "volume" not in default_profile: default_profile["volume"] = {} if ( "circular" in bed_dimensions and "r" in bed_dimensions and bed_dimensions["circular"] ): default_profile["volume"]["formFactor"] = "circular" default_profile["volume"]["width"] = 2 * bed_dimensions["r"] default_profile["volume"]["depth"] = default_profile["volume"][ "width" ] elif "x" in bed_dimensions or "y" in bed_dimensions: default_profile["volume"]["formFactor"] = "rectangular" if "x" in bed_dimensions: default_profile["volume"]["width"] = bed_dimensions["x"] if "y" in bed_dimensions: default_profile["volume"]["depth"] = bed_dimensions["y"] del config["printerParameters"]["bedDimensions"] if dirty: if "printerProfiles" not in config: config["printerProfiles"] = {} config["printerProfiles"]["defaultProfile"] = default_profile return dirty def _migrate_reverse_proxy_config(self, config): """ Migrates the old "server > baseUrl" and "server > scheme" configuration entries to "server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback". Added in 1.2.0 """ if "server" in config and ( "baseUrl" in config["server"] or "scheme" in config["server"] ): prefix = "" if "baseUrl" in config["server"]: prefix = config["server"]["baseUrl"] del config["server"]["baseUrl"] scheme = "" if "scheme" in config["server"]: scheme = config["server"]["scheme"] del config["server"]["scheme"] if "reverseProxy" not in config["server"] or not isinstance( config["server"]["reverseProxy"], dict ): config["server"]["reverseProxy"] = {} if prefix: config["server"]["reverseProxy"]["prefixFallback"] = prefix if scheme: config["server"]["reverseProxy"]["schemeFallback"] = scheme self._logger.info("Migrated reverse proxy configuration to new structure") return True else: return False def _migrate_event_config(self, config): """ Migrates the old event configuration format of type "events > gcodeCommandTrigger" and "event > systemCommandTrigger" to the new events format. Added in 1.2.0 """ if "events" in config and ( "gcodeCommandTrigger" in config["events"] or "systemCommandTrigger" in config["events"] ): self._logger.info("Migrating config (event subscriptions)...") # migrate event hooks to new format placeholderRe = re.compile(r"%\((.*?)\)s") eventNameReplacements = { "ClientOpen": "ClientOpened", "TransferStart": "TransferStarted", } payloadDataReplacements = { "Upload": {"data": "{file}", "filename": "{file}"}, "Connected": {"data": "{port} at {baudrate} baud"}, "FileSelected": {"data": "{file}", "filename": "{file}"}, "TransferStarted": {"data": "{remote}", "filename": "{remote}"}, "TransferDone": {"data": "{remote}", "filename": "{remote}"}, "ZChange": {"data": "{new}"}, "CaptureStart": {"data": "{file}"}, "CaptureDone": {"data": "{file}"}, "MovieDone": {"data": "{movie}", "filename": "{gcode}"}, "Error": {"data": "{error}"}, "PrintStarted": {"data": "{file}", "filename": "{file}"}, "PrintDone": {"data": "{file}", "filename": "{file}"}, } def migrateEventHook(event, command): # migrate placeholders command = placeholderRe.sub("{__\\1}", command) # migrate event names if event in eventNameReplacements: event = eventNameReplacements["event"] # migrate payloads to more specific placeholders if event in payloadDataReplacements: for key in payloadDataReplacements[event]: command = command.replace( "{__%s}" % key, payloadDataReplacements[event][key] ) # return processed tuple return event, command disableSystemCommands = False if ( "systemCommandTrigger" in config["events"] and "enabled" in config["events"]["systemCommandTrigger"] ): disableSystemCommands = not config["events"]["systemCommandTrigger"][ "enabled" ] disableGcodeCommands = False if ( "gcodeCommandTrigger" in config["events"] and "enabled" in config["events"]["gcodeCommandTrigger"] ): disableGcodeCommands = not config["events"]["gcodeCommandTrigger"][ "enabled" ] disableAllCommands = disableSystemCommands and disableGcodeCommands newEvents = {"enabled": not disableAllCommands, "subscriptions": []} if ( "systemCommandTrigger" in config["events"] and "subscriptions" in config["events"]["systemCommandTrigger"] ): for trigger in config["events"]["systemCommandTrigger"]["subscriptions"]: if not ("event" in trigger and "command" in trigger): continue newTrigger = {"type": "system"} if disableSystemCommands and not disableAllCommands: newTrigger["enabled"] = False newTrigger["event"], newTrigger["command"] = migrateEventHook( trigger["event"], trigger["command"] ) newEvents["subscriptions"].append(newTrigger) if ( "gcodeCommandTrigger" in config["events"] and "subscriptions" in config["events"]["gcodeCommandTrigger"] ): for trigger in config["events"]["gcodeCommandTrigger"]["subscriptions"]: if not ("event" in trigger and "command" in trigger): continue newTrigger = {"type": "gcode"} if disableGcodeCommands and not disableAllCommands: newTrigger["enabled"] = False newTrigger["event"], newTrigger["command"] = migrateEventHook( trigger["event"], trigger["command"] ) newTrigger["command"] = newTrigger["command"].split(",") newEvents["subscriptions"].append(newTrigger) config["events"] = newEvents self._logger.info( "Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"]) ) return True else: return False def _migrate_core_system_commands(self, config): """ Migrates system commands for restart, reboot and shutdown as defined on OctoPi or according to the official setup guide to new core system commands to remove duplication. If server commands for action is not yet set, migrates command. Otherwise only deletes definition from custom system commands. Added in 1.3.0 """ changed = False migration_map = { "shutdown": "systemShutdownCommand", "reboot": "systemRestartCommand", "restart": "serverRestartCommand", } if ( "system" in config and "actions" in config["system"] and isinstance(config["system"]["actions"], (list, tuple)) ): actions = config["system"]["actions"] to_delete = [] for index, spec in enumerate(actions): action = spec.get("action") command = spec.get("command") if action is None or command is None: continue migrate_to = migration_map.get(action) if migrate_to is not None: if ( "server" not in config or "commands" not in config["server"] or migrate_to not in config["server"]["commands"] ): if "server" not in config: config["server"] = {} if "commands" not in config["server"]: config["server"]["commands"] = {} config["server"]["commands"][migrate_to] = command self._logger.info( "Migrated {} action to server.commands.{}".format( action, migrate_to ) ) to_delete.append(index) self._logger.info( "Deleting {} action from configured system commands, superseded by server.commands.{}".format( action, migrate_to ) ) for index in reversed(to_delete): actions.pop(index) changed = True if changed: # let's make a backup of our current config, in case someone wants to roll back to an # earlier version and needs to recover the former system commands for that backup_path = self.backup("system_command_migration") self._logger.info( "Made a copy of the current config at {} to allow recovery of manual system command configuration".format( backup_path ) ) return changed def _migrate_serial_features(self, config): """ Migrates feature flags identified as serial specific from the feature to the serial config tree and vice versa. If a flag already exists in the target tree, only deletes the copy in the source tree. Added in 1.3.7 """ changed = False FEATURE_TO_SERIAL = ( "waitForStartOnConnect", "alwaysSendChecksum", "neverSendChecksum", "sendChecksumWithUnknownCommands", "unknownCommandsNeedAck", "sdRelativePath", "sdAlwaysAvailable", "swallowOkAfterResend", "repetierTargetTemp", "externalHeatupDetection", "supportWait", "ignoreIdenticalResends", "identicalResendsCountdown", "supportFAsCommand", "firmwareDetection", "blockWhileDwelling", ) SERIAL_TO_FEATURE = ("autoUppercaseBlacklist",) def migrate_key(key, source, target): if source in config and key in config[source]: if config.get(target) is None: # make sure we have a serial tree config[target] = {} if key not in config[target]: # only copy over if it's not there yet config[target][key] = config[source][key] # delete feature flag del config[source][key] return True return False for key in FEATURE_TO_SERIAL: changed = migrate_key(key, "feature", "serial") or changed for key in SERIAL_TO_FEATURE: changed = migrate_key(key, "serial", "feature") or changed if changed: # let's make a backup of our current config, in case someone wants to roll back to an # earlier version and needs a backup of their flags backup_path = self.backup("serial_feature_migration") self._logger.info( "Made a copy of the current config at {} to allow recovery of serial feature flags".format( backup_path ) ) return changed def _migrate_resend_without_ok(self, config): """ Migrates supportResendsWithoutOk flag from boolean to ("always", "detect", "never") value range. True gets migrated to "always", False to "detect" (which is the new default). Added in 1.3.7 """ if ( "serial" in config and "supportResendsWithoutOk" in config["serial"] and config["serial"]["supportResendsWithoutOk"] not in ("always", "detect", "never") ): value = config["serial"]["supportResendsWithoutOk"] if value: config["serial"]["supportResendsWithoutOk"] = "always" else: config["serial"]["supportResendsWithoutOk"] = "detect" return True return False def _migrate_string_temperature_profile_values(self, config): """ Migrates/fixes temperature profile wrongly saved with strings instead of ints as temperature values. Added in 1.3.8 """ if "temperature" in config and "profiles" in config["temperature"]: profiles = config["temperature"]["profiles"] if any( map( lambda x: not isinstance(x.get("extruder", 0), int) or not isinstance(x.get("bed", 0), int), profiles, ) ): result = [] for profile in profiles: try: profile["extruder"] = int(profile["extruder"]) profile["bed"] = int(profile["bed"]) except ValueError: pass result.append(profile) config["temperature"]["profiles"] = result return True return False def _migrate_blocked_commands(self, config): if "serial" in config and "blockM0M1" in config["serial"]: blockM0M1 = config["serial"]["blockM0M1"] blockedCommands = config["serial"].get("blockedCommands", []) if blockM0M1: blockedCommands = set(blockedCommands) blockedCommands.add("M0") blockedCommands.add("M1") config["serial"]["blockedCommands"] = sorted(blockedCommands) else: config["serial"]["blockedCommands"] = sorted( v for v in blockedCommands if v not in ("M0", "M1") ) del config["serial"]["blockM0M1"] return True return False def _migrate_gcodeviewer_enabled(self, config): if ( "gcodeViewer" in config and "enabled" in config["gcodeViewer"] and not config["gcodeViewer"]["enabled"] ): if "plugins" not in config: config["plugins"] = {} if "_disabled" not in config["plugins"]: config["plugins"]["_disabled"] = [] config["plugins"]["_disabled"].append("gcodeviewer") del config["gcodeViewer"]["enabled"] return True return False def backup(self, suffix=None, path=None, ext=None, hidden=False): import shutil if path is None: path = os.path.dirname(self._configfile) basename = os.path.basename(self._configfile) name, default_ext = os.path.splitext(basename) if ext is None: ext = default_ext if suffix is None and ext == default_ext: raise ValueError("Need a suffix or a different extension") if suffix is None: suffix = "" backup = os.path.join( path, "{}{}.{}{}".format("." if hidden else "", name, suffix, ext) ) shutil.copy(self._configfile, backup) return backup def save(self, force=False, trigger_event=False): with self._lock: if not self._dirty and not force: return False try: with atomic_write( self._configfile, mode="wt", prefix="octoprint-config-", suffix=".yaml", permissions=0o600, max_permissions=0o666, ) as configFile: yaml.save_to_file(self._map.top_map, file=configFile) self._dirty = False except Exception: self._logger.exception("Error while saving config.yaml!") raise else: from octoprint.events import Events, eventManager self.load() if trigger_event: payload = { "config_hash": self.config_hash, "effective_hash": self.effective_hash, } eventManager().fire(Events.SETTINGS_UPDATED, payload=payload) return True ##~~ Internal getter def _get_by_path(self, path, config): current = config for key in path: if key not in current: raise NoSuchSettingsPath() current = current[key] return current def _get_value( self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True, do_copy=True, ): if not path: raise NoSuchSettingsPath() is_deprecated = self._is_deprecated_path(path) if is_deprecated: self._logger.warning( f"DeprecationWarning: Detected access to deprecated settings path {path}, returned value is derived from compatibility overlay. {is_deprecated if isinstance(is_deprecated, str) else ''}" ) config = {} chain = self._map.with_config_defaults(config=config, defaults=defaults) if preprocessors is None: preprocessors = self._get_preprocessors preprocessor = None try: preprocessor = self._get_by_path(path, preprocessors) except NoSuchSettingsPath: pass parent_path = path[:-1] last = path[-1] if not isinstance(last, (list, tuple)): keys = [last] else: keys = last if asdict: results = {} else: results = list() for key in keys: try: value = chain.get_by_path( parent_path + [key], only_local=not incl_defaults, merged=merged ) except KeyError: raise NoSuchSettingsPath() if isinstance(value, dict) and merged: try: default_value = chain.get_by_path( parent_path + [key], only_defaults=True, merged=True ) if default_value is not None: value = dict_merge(default_value, value) except KeyError: # no default value, so nothing to merge pass if callable(preprocessor): value = preprocessor(value) if do_copy: if isinstance(value, KeysView): value = list(value) value = fast_deepcopy(value) if asdict: results[key] = value else: results.append(value) if not isinstance(last, (list, tuple)): if asdict: return list(results.values()).pop() else: return results.pop() else: return results # ~~ has def has(self, path, **kwargs): try: self._get_value(path, **kwargs) except NoSuchSettingsPath: return False else: return True # ~~ getter def get(self, path, **kwargs): error_on_path = kwargs.pop("error_on_path", False) validator = kwargs.pop("validator", None) fallback = kwargs.pop("fallback", None) def process(): try: return self._get_value(path, **kwargs) except NoSuchSettingsPath: if error_on_path: raise return None result = process() if callable(validator) and not validator(result): result = fallback return result def getInt(self, path, **kwargs): minimum = kwargs.pop("min", None) maximum = kwargs.pop("max", None) value = self.get(path, **kwargs) if value is None: return None try: intValue = int(value) if minimum is not None and intValue < minimum: return minimum elif maximum is not None and intValue > maximum: return maximum else: return intValue except ValueError: self._logger.warning( "Could not convert %r to a valid integer when getting option %r" % (value, path) ) return None def getFloat(self, path, **kwargs): minimum = kwargs.pop("min", None) maximum = kwargs.pop("max", None) value = self.get(path, **kwargs) if value is None: return None try: floatValue = float(value) if minimum is not None and floatValue < minimum: return minimum elif maximum is not None and floatValue > maximum: return maximum else: return floatValue except ValueError: self._logger.warning( "Could not convert %r to a valid integer when getting option %r" % (value, path) ) return None def getBoolean(self, path, **kwargs): value = self.get(path, **kwargs) if value is None: return None if isinstance(value, bool): return value if isinstance(value, (int, float)): return value != 0 if isinstance(value, str): return value.lower() in valid_boolean_trues return value is not None def checkBaseFolder(self, type): if type != "base" and type not in default_settings["folder"]: return False if type == "base": return os.path.exists(self._basedir) folder = self.get(["folder", type]) default_folder = self._get_default_folder(type) if folder is None: folder = default_folder return os.path.exists(folder) def getBaseFolder( self, type, create=True, allow_fallback=True, check_writable=True, deep_check_writable=False, ): if type != "base" and type not in default_settings["folder"]: return None if type == "base": return self._basedir folder = self.get(["folder", type]) default_folder = self._get_default_folder(type) if folder is None: folder = default_folder try: _validate_folder( folder, create=create, check_writable=check_writable, deep_check_writable=deep_check_writable, ) except Exception as exc: if folder != default_folder and allow_fallback: self._logger.exception( "Invalid configured {} folder at {}, attempting to " "fall back on default folder at {}".format( type, folder, default_folder ) ) _validate_folder( default_folder, create=create, check_writable=check_writable, deep_check_writable=deep_check_writable, ) folder = default_folder self.flagged_basefolders[type] = str(exc) try: self.remove(["folder", type]) self.save() except KeyError: pass else: raise return folder def listScripts(self, script_type): return list( map( lambda x: x[len(script_type + "/") :], filter( lambda x: x.startswith(script_type + "/"), self._get_scripts(script_type), ), ) ) def loadScript(self, script_type, name, context=None, source=False): if context is None: context = {} context.update({"script": {"type": script_type, "name": name}}) template = self._get_script_template(script_type, name, source=source) if template is None: return None if source: script = template else: try: script = template.render(**context) except Exception: self._logger.exception( f"Exception while trying to render script {script_type}:{name}" ) return None return script # ~~ remove def remove(self, path, config=None, error_on_path=False, defaults=None): if not path: if error_on_path: raise NoSuchSettingsPath() return chain = self._map.with_config_defaults(config=config, defaults=defaults) try: with self._lock: chain.del_by_path(path) self._mark_dirty() except KeyError: if error_on_path: raise NoSuchSettingsPath() pass # ~~ setter def set( self, path, value, force=False, defaults=None, config=None, preprocessors=None, error_on_path=False, *args, **kwargs, ): if not path: if error_on_path: raise NoSuchSettingsPath() return is_deprecated = self._is_deprecated_path(path) if is_deprecated: self._logger.warning( f"[Deprecation] Prevented write of `{value}` to deprecated settings path {path}. {is_deprecated if isinstance(is_deprecated, str) else ''}" ) return if self._mtime is not None and self.last_modified != self._mtime: self.load() chain = self._map.with_config_defaults(config=config, defaults=defaults) if preprocessors is None: preprocessors = self._set_preprocessors preprocessor = None try: preprocessor = self._get_by_path(path, preprocessors) except NoSuchSettingsPath: pass if callable(preprocessor): value = preprocessor(value) try: current = chain.get_by_path(path) except KeyError: current = None try: default_value = chain.get_by_path(path, only_defaults=True) except KeyError: if error_on_path: raise NoSuchSettingsPath() default_value = None with self._lock: in_local = chain.has_path(path, only_local=True) in_defaults = chain.has_path(path, only_defaults=True) if not force and in_defaults and in_local and default_value == value: try: chain.del_by_path(path) self._mark_dirty() self._path_modified(path, current, value) except KeyError: if error_on_path: raise NoSuchSettingsPath() pass elif ( force or (not in_local and in_defaults and default_value != value) or (in_local and current != value) ): chain.set_by_path(path, value) self._mark_dirty() self._path_modified(path, current, value) # we've changed the interface to no longer mutate the passed in config, so we # must manually do that here if config is not None: config.clear() config.update(chain.top_map) def setInt(self, path, value, **kwargs): if value is None: self.set(path, None, **kwargs) return minimum = kwargs.pop("min", None) maximum = kwargs.pop("max", None) try: intValue = int(value) if minimum is not None and intValue < minimum: intValue = minimum if maximum is not None and intValue > maximum: intValue = maximum except ValueError: self._logger.warning( "Could not convert %r to a valid integer when setting option %r" % (value, path) ) return self.set(path, intValue, **kwargs) def setFloat(self, path, value, **kwargs): if value is None: self.set(path, None, **kwargs) return minimum = kwargs.pop("min", None) maximum = kwargs.pop("max", None) try: floatValue = float(value) if minimum is not None and floatValue < minimum: floatValue = minimum if maximum is not None and floatValue > maximum: floatValue = maximum except ValueError: self._logger.warning( "Could not convert %r to a valid integer when setting option %r" % (value, path) ) return self.set(path, floatValue, **kwargs) def setBoolean(self, path, value, **kwargs): if value is None or isinstance(value, bool): self.set(path, value, **kwargs) elif isinstance(value, str) and value.lower() in valid_boolean_trues: self.set(path, True, **kwargs) else: self.set(path, False, **kwargs) def setBaseFolder(self, type, path, force=False, validate=True): if type not in default_settings["folder"]: return None currentPath = self.getBaseFolder(type) defaultPath = self._get_default_folder(type) if path is None or path == defaultPath: self.remove(["folder", type]) elif (path != currentPath and path != defaultPath) or force: if validate: _validate_folder(path, check_writable=True, deep_check_writable=True) self.set(["folder", type], path, force=force) def saveScript(self, script_type, name, script): script_folder = self.getBaseFolder("scripts") filename = os.path.realpath(os.path.join(script_folder, script_type, name)) if not filename.startswith(os.path.realpath(script_folder)): # oops, jail break, that shouldn't happen raise ValueError( f"Invalid script path to save to: {filename} (from {script_type}:{name})" ) path, _ = os.path.split(filename) if not os.path.exists(path): os.makedirs(path) with atomic_write(filename, mode="wt", max_permissions=0o666) as f: f.write(script) def generateApiKey(self): apikey = generate_api_key() self.set(["api", "key"], apikey) self.save(force=True) return apikey def deleteApiKey(self): self.set(["api", "key"], None) self.save(force=True) def _default_basedir(applicationName): # taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python if sys.platform == "darwin": import appdirs return appdirs.user_data_dir(applicationName, "") elif sys.platform == "win32": return os.path.join(os.environ["APPDATA"], applicationName) else: return os.path.expanduser(os.path.join("~", "." + applicationName.lower())) def _validate_folder(folder, create=True, check_writable=True, deep_check_writable=False): logger = logging.getLogger(__name__) if not os.path.exists(folder): if os.path.islink(folder): # broken symlink, see #2644 raise OSError(f"Folder at {folder} appears to be a broken symlink") elif create: # non existing, but we are allowed to create it try: os.makedirs(folder) except Exception: logger.exception(f"Could not create {folder}") raise OSError( "Folder for type {} at {} does not exist and creation failed".format( type, folder ) ) else: # not extisting, not allowed to create it raise OSError(f"No such folder: {folder}") elif os.path.isfile(folder): # hardening against misconfiguration, see #1953 raise OSError(f"Expected a folder at {folder} but found a file instead") elif check_writable: # make sure we can also write into the folder error = "Folder at {} doesn't appear to be writable, please fix its permissions".format( folder ) if not os.access(folder, os.W_OK): raise OSError(error) elif deep_check_writable: # try to write a file to the folder - on network shares that might be the only reliable way # to determine whether things are *actually* writable testfile = os.path.join(folder, ".testballoon.txt") try: with open(testfile, "w", encoding="utf-8") as f: f.write("test") os.remove(testfile) except Exception: logger.exception(f"Could not write test file to {testfile}") raise OSError(error) def _paths(prefix, data): if isinstance(data, dict): for k, v in data.items(): yield from _paths(prefix + [k], v) else: yield prefix
82,100
Python
.py
1,933
29.801345
202
0.548669
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,856
__init__.py
OctoPrint_OctoPrint/src/octoprint/plugin/__init__.py
""" This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the registered plugin types. .. autofunction:: plugin_manager .. autofunction:: plugin_settings .. autofunction:: call_plugin .. autoclass:: PluginSettings :members: """ __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os from octoprint.plugin.core import Plugin, PluginInfo, PluginManager # noqa: F401 from octoprint.plugin.types import * # noqa: F401,F403 ## used by multiple other modules from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin from octoprint.settings import settings as s from octoprint.util import deprecated # singleton _instance = None def _validate_plugin(phase, plugin_info): return True def plugin_manager( init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None, plugin_sorting_order=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_considered_bundled=None, plugin_validators=None, compatibility_ignored_list=None, ): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. Arguments: init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not (False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError` will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to False. plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and ``src/plugins`` within OctoPrint's code base. plugin_bases (list): A list of recognized plugin base classes for which to look for provided implementations. If not provided this defaults to :class:`~octoprint.plugin.OctoPrintPlugin`. plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided this defaults to the entry point ``octoprint.plugin``. plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this defaults to all plugins for which ``enabled`` is set to ``False`` in the settings. plugin_sorting_order (dict): A dict containing a custom sorting orders for plugins. The keys are plugin identifiers, mapped to dictionaries containing the sorting contexts as key and the custom sorting value as value. plugin_blacklist (list): A list of plugin identifiers/identifier-requirement tuples that are currently blacklisted. plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order be enabled/disabled. Does not have to contain full hook identifiers, will be matched with startswith similar to logging handlers plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will not be enabled since they might depend on functionality that is no longer available. plugin_considered_bundled (list): A list of plugin identifiers that are considered bundled plugins even if installed separately. plugin_validators (list): A list of additional plugin validators through which to process each plugin. compatibility_ignored_list (list): A list of plugin keys for which it will be ignored if they are flagged as incompatible. This is for development purposes only and should not be used in production. Returns: PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin management tasks. Raises: ValueError: ``init`` was True although the plugin manager was already initialized, or it was False although the plugin manager was not yet initialized. """ global _instance if _instance is not None: if init: raise ValueError("Plugin Manager already initialized") else: if init: if plugin_bases is None: plugin_bases = [OctoPrintPlugin] if plugin_restart_needing_hooks is None: plugin_restart_needing_hooks = [ "octoprint.server.http.*", "octoprint.printer.factory", "octoprint.access.permissions", "octoprint.timelapse.extensions", ] if plugin_obsolete_hooks is None: plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] if plugin_considered_bundled is None: plugin_considered_bundled = ["firmware_check", "file_check", "pi_support"] if plugin_validators is None: plugin_validators = [_validate_plugin] else: plugin_validators.append(_validate_plugin) _instance = PluginManager( plugin_folders, plugin_bases, plugin_entry_points, logging_prefix="octoprint.plugins.", plugin_disabled_list=plugin_disabled_list, plugin_sorting_order=plugin_sorting_order, plugin_blacklist=plugin_blacklist, plugin_restart_needing_hooks=plugin_restart_needing_hooks, plugin_obsolete_hooks=plugin_obsolete_hooks, plugin_considered_bundled=plugin_considered_bundled, plugin_validators=plugin_validators, compatibility_ignored_list=compatibility_ignored_list, ) else: raise ValueError("Plugin Manager not initialized yet") return _instance def plugin_settings( plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None, settings=None, ): """ Factory method for creating a :class:`PluginSettings` instance. Arguments: plugin_key (string): The plugin identifier for which to create the settings instance. defaults (dict): The default settings for the plugin, if different from get_settings_defaults. get_preprocessors (dict): The getter preprocessors for the plugin. set_preprocessors (dict): The setter preprocessors for the plugin. settings (octoprint.settings.Settings): The settings instance to use. Returns: PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's settings """ if settings is None: settings = s() return PluginSettings( settings, plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, ) def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): """ Factory method for creating a :class:`PluginSettings` instance for a given :class:`SettingsPlugin` instance. Will return `None` if the provided `instance` is not a :class:`SettingsPlugin` instance. Arguments: plugin_key (string): The plugin identifier for which to create the settings instance. implementation (octoprint.plugin.SettingsPlugin): The :class:`SettingsPlugin` instance. settings (octoprint.settings.Settings): The settings instance to use. Defaults to the global OctoPrint settings. Returns: PluginSettings or None: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's settings, or `None` if the provided `instance` was not a class:`SettingsPlugin` """ if not isinstance(instance, SettingsPlugin): return None try: get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() except Exception: logging.getLogger(__name__).exception( f"Error while retrieving preprocessors for plugin {plugin_key}" ) return None return plugin_settings( plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings, ) def call_plugin( types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True, manager=None, ): """ Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success and/or failure of each call which can be used to return individual results to the calling code. Example: .. sourcecode:: python def my_success_callback(name, plugin, result): print("{name} was called successfully and returned {result!r}".format(**locals())) def my_error_callback(name, plugin, exc): print("{name} raised an exception: {exc!s}".format(**locals())) octoprint.plugin.call_plugin( [octoprint.plugin.StartupPlugin], "on_startup", args=(my_host, my_port), callback=my_success_callback, error_callback=my_error_callback ) Arguments: types (list): A list of plugin implementation types to match against. method (string): Name of the method to call on all matching implementations. args (tuple): A tuple containing the arguments to supply to the called ``method``. Optional. kwargs (dict): A dictionary containing the keyword arguments to supply to the called ``method``. Optional. callback (function): A callback to invoke after an implementation has been called successfully. Will be called with the three arguments ``name``, ``plugin`` and ``result``. ``name`` will be the plugin identifier, ``plugin`` the plugin implementation instance itself and ``result`` the result returned from the ``method`` invocation. error_callback (function): A callback to invoke after the call of an implementation resulted in an exception. Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception. initialized (boolean): Ignored. manager (PluginManager or None): The plugin manager to use. If not provided, the global plugin manager """ if not isinstance(types, (list, tuple)): types = [types] if args is None: args = [] if kwargs is None: kwargs = {} if manager is None: manager = plugin_manager() logger = logging.getLogger(__name__) plugins = manager.get_implementations(*types, sorting_context=sorting_context) for plugin in plugins: if not hasattr(plugin, "_identifier"): continue if hasattr(plugin, method): logger.debug(f"Calling {method} on {plugin._identifier}") try: result = getattr(plugin, method)(*args, **kwargs) if callback: callback(plugin._identifier, plugin, result) except Exception as exc: logger.exception( "Error while calling plugin %s" % plugin._identifier, extra={"plugin": plugin._identifier}, ) if error_callback: error_callback(plugin._identifier, plugin, exc) class PluginSettings: """ The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings. It provides some convenience methods for directly accessing plugin settings via the regular :class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations. All getter and setter methods will ensure that plugin settings are stored in their correct location within the settings structure by modifying the supplied paths accordingly. Arguments: settings (Settings): The :class:`~octoprint.settings.Settings` instance on which to operate. plugin_key (str): The plugin identifier of the plugin for which to create this instance. defaults (dict): The plugin's defaults settings, will be used to determine valid paths within the plugin's settings structure .. method:: get(path, merged=False, asdict=False) Retrieves a raw value from the settings for ``path``, optionally merging the raw value with the default settings if ``merged`` is set to True. :param path: The path for which to retrieve the value. :type path: list, tuple :param boolean merged: Whether to merge the returned result with the default settings (True) or not (False, default). :returns: The retrieved settings value. :rtype: object .. method:: get_int(path, min=None, max=None) Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if the value is greater than it. .. method:: get_float(path, min=None, max=None) Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if the value is greater than it. .. method:: get_boolean(path) Like :func:`get` but tries to convert the retrieved value to ``boolean``. .. method:: set(path, value, force=False) Sets the raw value on the settings for ``path``. :param path: The path for which to retrieve the value. :type path: list, tuple :param object value: The value to set. :param boolean force: If set to True, the modified configuration will even be written back to disk if the value didn't change. .. method:: set_int(path, value, force=False, min=None, max=None) Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it. If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than that, ``max`` if greater than that) will be set instead. .. method:: set_float(path, value, force=False, min=None, max=None) Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it. If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than that, ``max`` if greater than that) will be set instead. .. method:: set_boolean(path, value, force=False) Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it. .. method:: save(force=False, trigger_event=False) Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated`` :ref:`event <sec-events-available_events-settings>` to get triggered. :param force: Force saving to ``config.yaml`` even if there are no changes. :type force: boolean :param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event <sec-events-available_events-settings>` on save. :type trigger_event: boolean .. method:: add_overlay(overlay, at_end=False, key=None) Adds a new config overlay for the plugin's settings. Will return the overlay's key in the map. :param overlay: Overlay dict to add :type overlay: dict :param at_end: Whether to add overlay at end or start (default) of config hierarchy :type at_end: boolean :param key: Key to use to identify overlay. If not set one will be built based on the overlay's hash :type key: str :rtype: str .. method:: remove_overlay(key) Removes an overlay from the settings based on its key. Return ``True`` if the overlay could be found and was removed, ``False`` otherwise. :param key: The key of the overlay to remove :type key: str :rtype: boolean """ def __init__( self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None, ): self.settings = settings self.plugin_key = plugin_key if defaults is not None: self.defaults = {"plugins": {}} self.defaults["plugins"][plugin_key] = defaults self.defaults["plugins"][plugin_key]["_config_version"] = None else: self.defaults = None if get_preprocessors is None: get_preprocessors = {} self.get_preprocessors = {"plugins": {}} self.get_preprocessors["plugins"][plugin_key] = get_preprocessors if set_preprocessors is None: set_preprocessors = {} self.set_preprocessors = {"plugins": {}} self.set_preprocessors["plugins"][plugin_key] = set_preprocessors def prefix_path_in_args(args, index=0): result = [] if index == 0: result.append(self._prefix_path(args[0])) result.extend(args[1:]) else: args_before = args[: index - 1] args_after = args[index + 1 :] result.extend(args_before) result.append(self._prefix_path(args[index])) result.extend(args_after) return result def add_getter_kwargs(kwargs): if "defaults" not in kwargs and self.defaults is not None: kwargs.update(defaults=self.defaults) if "preprocessors" not in kwargs: kwargs.update(preprocessors=self.get_preprocessors) return kwargs def add_setter_kwargs(kwargs): if "defaults" not in kwargs and self.defaults is not None: kwargs.update(defaults=self.defaults) if "preprocessors" not in kwargs: kwargs.update(preprocessors=self.set_preprocessors) return kwargs def wrap_overlay(args): result = list(args) overlay = result[0] result[0] = {"plugins": {plugin_key: overlay}} return result self.access_methods = { "has": ("has", prefix_path_in_args, add_getter_kwargs), "get": ("get", prefix_path_in_args, add_getter_kwargs), "get_int": ("getInt", prefix_path_in_args, add_getter_kwargs), "get_float": ("getFloat", prefix_path_in_args, add_getter_kwargs), "get_boolean": ("getBoolean", prefix_path_in_args, add_getter_kwargs), "set": ("set", prefix_path_in_args, add_setter_kwargs), "set_int": ("setInt", prefix_path_in_args, add_setter_kwargs), "set_float": ("setFloat", prefix_path_in_args, add_setter_kwargs), "set_boolean": ("setBoolean", prefix_path_in_args, add_setter_kwargs), "remove": ("remove", prefix_path_in_args, lambda x: x), "add_overlay": ("add_overlay", wrap_overlay, lambda x: x), "remove_overlay": ("remove_overlay", lambda x: x, lambda x: x), } self.deprecated_access_methods = { "getInt": "get_int", "getFloat": "get_float", "getBoolean": "get_boolean", "setInt": "set_int", "setFloat": "set_float", "setBoolean": "set_boolean", } def _prefix_path(self, path=None): if path is None: path = list() return ["plugins", self.plugin_key] + path def global_has(self, path, **kwargs): return self.settings.has(path, **kwargs) def global_remove(self, path, **kwargs): return self.settings.remove(path, **kwargs) def global_get(self, path, **kwargs): """ Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this to access global settings outside of your plugin. Directly forwards to :func:`octoprint.settings.Settings.get`. """ return self.settings.get(path, **kwargs) def global_get_int(self, path, **kwargs): """ Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getInt`. """ return self.settings.getInt(path, **kwargs) def global_get_float(self, path, **kwargs): """ Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getFloat`. """ return self.settings.getFloat(path, **kwargs) def global_get_boolean(self, path, **kwargs): """ Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`. """ return self.settings.getBoolean(path, **kwargs) def global_set(self, path, value, **kwargs): """ Setter for modifying settings not managed by the plugin itself on the core settings structure. Use this to modify global settings outside of your plugin. Directly forwards to :func:`octoprint.settings.Settings.set`. """ self.settings.set(path, value, **kwargs) def global_set_int(self, path, value, **kwargs): """ Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setInt`. """ self.settings.setInt(path, value, **kwargs) def global_set_float(self, path, value, **kwargs): """ Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`. """ self.settings.setFloat(path, value, **kwargs) def global_set_boolean(self, path, value, **kwargs): """ Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setBoolean`. """ self.settings.setBoolean(path, value, **kwargs) def global_get_basefolder(self, folder_type, **kwargs): """ Retrieves a globally defined basefolder of the given ``folder_type``. Directly forwards to :func:`octoprint.settings.Settings.getBaseFolder`. """ return self.settings.getBaseFolder(folder_type, **kwargs) def get_plugin_logfile_path(self, postfix=None): """ Retrieves the path to a logfile specifically for the plugin. If ``postfix`` is not supplied, the logfile will be named ``plugin_<plugin identifier>.log`` and located within the configured ``logs`` folder. If a postfix is supplied, the name will be ``plugin_<plugin identifier>_<postfix>.log`` at the same location. Plugins may use this for specific logging tasks. For example, a :class:`~octoprint.plugin.SlicingPlugin` might want to create a log file for logging the output of the slicing engine itself if some debug flag is set. Arguments: postfix (str): Postfix of the logfile for which to create the path. If set, the file name of the log file will be ``plugin_<plugin identifier>_<postfix>.log``, if not it will be ``plugin_<plugin identifier>.log``. Returns: str: Absolute path to the log file, directly usable by the plugin. """ filename = "plugin_" + self.plugin_key if postfix is not None: filename += "_" + postfix filename += ".log" return os.path.join(self.settings.getBaseFolder("logs"), filename) @deprecated( "PluginSettings.get_plugin_data_folder has been replaced by OctoPrintPlugin.get_plugin_data_folder", includedoc="Replaced by :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`", since="1.2.0", ) def get_plugin_data_folder(self): path = os.path.join(self.settings.getBaseFolder("data"), self.plugin_key) if not os.path.isdir(path): os.makedirs(path) return path def get_all_data(self, **kwargs): merged = kwargs.get("merged", True) asdict = kwargs.get("asdict", True) defaults = kwargs.get("defaults", self.defaults) preprocessors = kwargs.get("preprocessors", self.get_preprocessors) kwargs.update( { "merged": merged, "asdict": asdict, "defaults": defaults, "preprocessors": preprocessors, } ) return self.settings.get(self._prefix_path(), **kwargs) def clean_all_data(self): self.settings.remove(self._prefix_path()) def __getattr__(self, item): all_access_methods = list(self.access_methods.keys()) + list( self.deprecated_access_methods.keys() ) if item in all_access_methods: decorator = None if item in self.deprecated_access_methods: new = self.deprecated_access_methods[item] decorator = deprecated( f"{item} has been renamed to {new}", stacklevel=2, ) item = new settings_name, args_mapper, kwargs_mapper = self.access_methods[item] if hasattr(self.settings, settings_name) and callable( getattr(self.settings, settings_name) ): orig_func = getattr(self.settings, settings_name) if decorator is not None: orig_func = decorator(orig_func) def _func(*args, **kwargs): return orig_func(*args_mapper(args), **kwargs_mapper(kwargs)) _func.__name__ = item _func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None return _func return getattr(self.settings, item)
26,939
Python
.py
517
42.466151
127
0.651435
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,857
core.py
OctoPrint_OctoPrint/src/octoprint/plugin/core.py
""" In this module resides the core data structures and logic of the plugin system. .. autoclass:: PluginManager :members: .. autoclass:: PluginInfo :members: .. autoclass:: Plugin :members: .. autoclass:: RestartNeedingPlugin :members: .. autoclass:: SortablePlugin :members: """ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import fnmatch import inspect import logging import os from collections import OrderedDict, defaultdict, namedtuple from os import scandir import pkg_resources import pkginfo import octoprint.vendor.imp as imp from octoprint.util import sv, time_this, to_unicode from octoprint.util.version import get_python_version_string, is_python_compatible # noinspection PyDeprecation def _find_module(name, path=None): if path is not None: spec = imp.find_module(name, [path]) else: spec = imp.find_module(name) return spec[1], spec # noinspection PyDeprecation def _load_module(name, spec): f, filename, details = spec return imp.load_module(name, f, filename, details) def parse_plugin_metadata(path): result = {} logger = logging.getLogger(__name__) if not path: return result if os.path.isdir(path): path = os.path.join(path, "__init__.py") if not os.path.isfile(path): return result if not path.endswith(".py"): # we only support parsing plain text source files return result logger.debug(f"Parsing plugin metadata from AST of {path}") try: import ast with open(path, "rb") as f: root = ast.parse(f.read(), filename=path) assignments = list( filter(lambda x: isinstance(x, ast.Assign) and x.targets, root.body) ) function_defs = list( filter(lambda x: isinstance(x, ast.FunctionDef) and x.name, root.body) ) all_relevant = assignments + function_defs def extract_target_ids(node): return list( map( lambda x: x.id, filter(lambda x: isinstance(x, ast.Name), node.targets), ) ) def extract_names(node): if isinstance(node, ast.Assign): return extract_target_ids(node) elif isinstance(node, ast.FunctionDef): return [ node.name, ] else: return [] for key in ( ControlProperties.attr_name, ControlProperties.attr_version, ControlProperties.attr_author, ControlProperties.attr_description, ControlProperties.attr_url, ControlProperties.attr_license, ControlProperties.attr_pythoncompat, ): for a in reversed(assignments): targets = extract_target_ids(a) if key in targets: if isinstance(a.value, ast.Constant): result[key] = a.value.value elif isinstance(a.value, ast.Str): result[key] = a.value.s elif ( isinstance(a.value, ast.Call) and hasattr(a.value, "func") and a.value.func.id == "gettext" and a.value.args and isinstance(a.value.args[0], ast.Str) ): result[key] = a.value.args[0].s break for key in (ControlProperties.attr_hidden,): for a in reversed(assignments): targets = extract_target_ids(a) if key in targets: if isinstance(a.value, ast.Name) and a.value.id in ( "True", "False", ): result[key] = bool(a.value.id) break for a in reversed(all_relevant): targets = extract_names(a) if any(map(lambda x: x in targets, ControlProperties.all())): result["has_control_properties"] = True break except SyntaxError: raise except Exception: logger.exception(f"Error while parsing AST from {path}") return result class ControlProperties: attr_name = "__plugin_name__" """ Module attribute from which to retrieve the plugin's human readable name. """ attr_description = "__plugin_description__" """ Module attribute from which to retrieve the plugin's description. """ attr_disabling_DISCOURAGED = "__plugin_disabling_discouraged__" """ Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """ attr_version = "__plugin_version__" """ Module attribute from which to retrieve the plugin's version. """ attr_author = "__plugin_author__" """ Module attribute from which to retrieve the plugin's author. """ attr_url = "__plugin_url__" """ Module attribute from which to retrieve the plugin's website URL. """ attr_license = "__plugin_license__" """ Module attribute from which to retrieve the plugin's license. """ attr_privacypolicy = "__plugin_privacypolicy__" """ Module attribute from which to retrieve the plugin's privacy policy URL, if any. """ attr_pythoncompat = "__plugin_pythoncompat__" """ Module attribute from which to retrieve the plugin's python compatibility string. If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to Python 2 but not Python 3. To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended. Bundled plugins will automatically be assumed to be compatible. """ attr_hidden = "__plugin_hidden__" """ Module attribute from which to determine if the plugin's hidden or not. Only evaluated for bundled plugins, in order to hide them from the Plugin Manager and similar places. """ attr_hooks = "__plugin_hooks__" """ Module attribute from which to retrieve the plugin's provided hooks. """ attr_implementation = "__plugin_implementation__" """ Module attribute from which to retrieve the plugin's provided mixin implementation. """ attr_helpers = "__plugin_helpers__" """ Module attribute from which to retrieve the plugin's provided helpers. """ attr_check = "__plugin_check__" """ Module attribute which to call to determine if the plugin can be loaded. """ attr_load = "__plugin_load__" """ Module attribute which to call when loading the plugin. """ attr_unload = "__plugin_unload__" """ Module attribute which to call when unloading the plugin. """ attr_enable = "__plugin_enable__" """ Module attribute which to call when enabling the plugin. """ attr_disable = "__plugin_disable__" """ Module attribute which to call when disabling the plugin. """ default_pythoncompat = ">=2.7,<3" @classmethod def all(cls): return [getattr(cls, key) for key in dir(cls) if key.startswith("attr_")] _EntryPointOrigin = namedtuple( "EntryPointOrigin", "type, entry_point, module_name, package_name, package_version" ) class EntryPointOrigin(_EntryPointOrigin): """ Origin of a plugin registered via an entry point. .. attribute:: type Always ``entry_point``. .. attribute:: entry_point Name of the entry point, usually ``octoprint.plugin``. .. attribute:: module_name Module registered to the entry point. .. attribute:: package_name Python package containing the entry point. .. attribute:: package_version Version of the python package containing the entry point. """ _FolderOrigin = namedtuple("FolderOrigin", "type, folder") class FolderOrigin(_FolderOrigin): """ Origin of a (single file) plugin loaded from a plugin folder. .. attribute:: type Always `folder`. .. attribute:: folder Folder path from which the plugin was loaded. """ _ModuleOrigin = namedtuple("ModuleOrigin", "type, module_name, folder") class ModuleOrigin(_ModuleOrigin): """ Origin of a (single file) plugin loaded from a plugin folder. .. attribute:: type Always `module`. .. attribute:: module_name Name of the module from which the plugin was loaded. .. attribute:: folder Folder path from which the plugin was loaded. """ class PluginInfo: """ The :class:`PluginInfo` class wraps all available information about a registered plugin. This includes its meta data (like name, description, version, etc) as well as the actual plugin extensions like implementations, hooks and helpers. It works on Python module objects and extracts the relevant data from those via accessing the :ref:`control properties <sec-plugins-controlproperties>`. Arguments: key (str): Identifier of the plugin location (str): Installation folder of the plugin instance (module): Plugin module instance - this may be ``None`` if the plugin has been blacklisted! name (str): Human readable name of the plugin version (str): Version of the plugin description (str): Description of the plugin author (str): Author of the plugin url (str): URL of the website of the plugin license (str): License of the plugin """ def __init__( self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None, parsed_metadata=None, ): self.key = key self.location = location self.instance = instance self.origin = None """ The origin from which this plugin was loaded, either a :class:`EntryPointOrigin`, :class:`FolderOrigin` or :class:`ModuleOrigin` instance. Set during loading, initially ``None``. """ self.enabled = True """Whether the plugin is enabled.""" self.blacklisted = False """Whether the plugin is blacklisted.""" self.forced_disabled = False """Whether the plugin has been force disabled by the system, e.g. due to safe mode blacklisting.""" self.incompatible = False """Whether this plugin has been detected as incompatible.""" self.bundled = False """Whether this plugin is bundled with OctoPrint.""" self.loaded = False """Whether this plugin has been loaded.""" self.managable = True """Whether this plugin can be managed by OctoPrint.""" self.needs_restart = False """Whether this plugin needs a restart of OctoPrint after enabling/disabling.""" self.invalid_syntax = False """Whether invalid syntax was encountered while trying to load this plugin.""" self._name = name self._version = version self._description = description self._author = author self._url = url self._license = license self._logger = logging.getLogger(__name__) self._cached_parsed_metadata = parsed_metadata if self._cached_parsed_metadata is None: self._cached_parsed_metadata = self._parse_metadata() def validate(self, phase, additional_validators=None): """ Validates the plugin for various validation phases. ``phase`` can be one of ``before_import``, ``before_load``, ``after_load``. Used by :class:`PluginManager`, should not be used elsewhere. """ result = True if phase == "before_import": result = ( self.looks_like_plugin and not self.forced_disabled and not self.blacklisted and not self.incompatible and not self.invalid_syntax and result ) elif phase == "before_load": pass elif phase == "after_load": pass if additional_validators is not None: for validator in additional_validators: result = validator(phase, self) and result return result def __str__(self): if self.version: return f"{self.name} ({self.version})" else: return to_unicode(self.name) def long_str( self, show_bundled=False, bundled_strs=(" [B]", ""), show_location=False, location_str=" - {location}", show_enabled=False, enabled_strs=("* ", " ", "X ", "C "), ): """ Long string representation of the plugin's information. Will return a string of the format ``<enabled><str(self)><bundled><location>``. ``enabled``, ``bundled`` and ``location`` will only be displayed if the corresponding flags are set to ``True``. The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows: ``enabled_str`` a 4-tuple, the first entry being the string to insert when the plugin is enabled, the second entry the string to insert when it is not, the third entry the string when it is blacklisted and the fourth when it is incompatible. ``bundled_str`` a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second entry the string to insert when it is not. ``location_str`` a format string (to be parsed with ``str.format``), the ``{location}`` placeholder will be replaced with the plugin's installation folder on disk. Arguments: show_enabled (boolean): whether to show the ``enabled`` part enabled_strs (tuple): the 2-tuple containing the two possible strings to use for displaying the enabled state show_bundled (boolean): whether to show the ``bundled`` part bundled_strs(tuple): the 2-tuple containing the two possible strings to use for displaying the bundled state show_location (boolean): whether to show the ``location`` part location_str (str): the format string to use for displaying the plugin's installation location Returns: str: The long string representation of the plugin as described above """ if show_enabled: if self.incompatible: ret = to_unicode(enabled_strs[3]) elif self.blacklisted: ret = to_unicode(enabled_strs[2]) elif not self.enabled: ret = to_unicode(enabled_strs[1]) else: ret = to_unicode(enabled_strs[0]) else: ret = "" ret += str(self) if show_bundled: ret += ( to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1]) ) if show_location and self.location: ret += to_unicode(location_str).format(location=self.location) return ret def get_hook(self, hook): """ Arguments: hook (str): Hook to return. Returns: callable or None: Handler for the requested ``hook`` or None if no handler is registered. """ if hook not in self.hooks: return None return self.hooks[hook] def get_implementation(self, *types): """ Arguments: types (list): List of :class:`Plugin` sub classes the implementation needs to implement. Returns: object: The plugin's implementation if it matches all of the requested ``types``, None otherwise. """ if self.implementation and all( map(lambda t: isinstance(self.implementation, t), types) ): return self.implementation else: return None @property def name(self): """ Human readable name of the plugin. Will be taken from name attribute of the plugin module if available, otherwise from the ``name`` supplied during construction with a fallback to ``key``. Returns: str: Name of the plugin, fallback is the plugin's identifier. """ return self._get_instance_attribute( ControlProperties.attr_name, defaults=(self._name, self.key), incl_metadata=True, ) @property def description(self): """ Description of the plugin. Will be taken from the description attribute of the plugin module as defined in :attr:`attr_description` if available, otherwise from the ``description`` supplied during construction. May be None. Returns: str or None: Description of the plugin. """ return self._get_instance_attribute( ControlProperties.attr_description, default=self._description, incl_metadata=True, ) @property def disabling_discouraged(self): """ Reason why disabling of this plugin is discouraged. Only evaluated for bundled plugins! Will be taken from the disabling_discouraged attribute of the plugin module as defined in :attr:`attr_disabling_discouraged` if available. False if unset or plugin not bundled. Returns: str or None: Reason why disabling this plugin is discouraged (only for bundled plugins) """ return ( self._get_instance_attribute( ControlProperties.attr_disabling_DISCOURAGED, default=False ) if self.bundled else False ) @property def version(self): """ Version of the plugin. Will be taken from the version attribute of the plugin module as defined in :attr:`attr_version` if available, otherwise from the ``version`` supplied during construction. May be None. Returns: str or None: Version of the plugin. """ return ( self._version if self._version is not None else self._get_instance_attribute( ControlProperties.attr_version, default=self._version, incl_metadata=True, ) ) @property def author(self): """ Author of the plugin. Will be taken from the author attribute of the plugin module as defined in :attr:`attr_author` if available, otherwise from the ``author`` supplied during construction. May be None. Returns: str or None: Author of the plugin. """ return self._get_instance_attribute( ControlProperties.attr_author, default=self._author, incl_metadata=True ) @property def url(self): """ Website URL for the plugin. Will be taken from the url attribute of the plugin module as defined in :attr:`attr_url` if available, otherwise from the ``url`` supplied during construction. May be None. Returns: str or None: Website URL for the plugin. """ return self._get_instance_attribute( ControlProperties.attr_url, default=self._url, incl_metadata=True ) @property def license(self): """ License of the plugin. Will be taken from the license attribute of the plugin module as defined in :attr:`attr_license` if available, otherwise from the ``license`` supplied during construction. May be None. Returns: str or None: License of the plugin. """ return self._get_instance_attribute( ControlProperties.attr_license, default=self._license, incl_metadata=True ) @property def privacypolicy(self): """ Privacy Policy URL of the plugin. Will be taken from the privacy policy attribute of the plugin module as defined in :attr:`attr_privacypolicy` if available. May be None. Returns: str or None: Privacy Policy URL of the plugin. """ return self._get_instance_attribute( ControlProperties.attr_privacypolicy, default=None, incl_metadata=True ) @property def pythoncompat(self): """ Python compatibility string of the plugin module as defined in :attr:`attr_pythoncompat` if available, otherwise defaults to ``>=2.7,<3``. Returns: str: Python compatibility string of the plugin """ return self._get_instance_attribute( ControlProperties.attr_pythoncompat, default=">=2.7,<3", incl_metadata=True ) @property def hidden(self): """ Hidden flag. Returns: bool: Whether the plugin should be flagged as hidden or not """ return self._get_instance_attribute( ControlProperties.attr_hidden, default=False, incl_metadata=True ) @property def hooks(self): """ Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defined in :attr:`attr_hooks` if available, otherwise an empty dictionary is returned. Returns: dict: Hooks provided by the plugin. """ return self._get_instance_attribute(ControlProperties.attr_hooks, default={}) @property def implementation(self): """ Implementation provided by the plugin. Will be taken from the implementation attribute of the plugin module as defined in :attr:`attr_implementation` if available, otherwise None is returned. Returns: object: Implementation provided by the plugin. """ return self._get_instance_attribute( ControlProperties.attr_implementation, default=None ) @property def helpers(self): """ Helpers provided by the plugin. Will be taken from the helpers attribute of the plugin module as defined in :attr:`attr_helpers` if available, otherwise an empty list is returned. Returns: dict: Helpers provided by the plugin. """ return self._get_instance_attribute(ControlProperties.attr_helpers, default={}) @property def check(self): """ Method for pre-load check of plugin. Will be taken from the check attribute of the plugin module as defined in :attr:`attr_check` if available, otherwise a lambda always returning True is returned. Returns: callable: Check method for the plugin module which should return True if the plugin can be loaded, False otherwise. """ return self._get_instance_attribute( ControlProperties.attr_check, default=lambda: True ) @property def load(self): """ Method for loading the plugin module. Will be taken from the load attribute of the plugin module as defined in :attr:`attr_load` if available, otherwise a no-operation lambda will be returned. Returns: callable: Load method for the plugin module. """ return self._get_instance_attribute( ControlProperties.attr_load, default=lambda: True ) @property def unload(self): """ Method for unloading the plugin module. Will be taken from the unload attribute of the plugin module as defined in :attr:`attr_unload` if available, otherwise a no-operation lambda will be returned. Returns: callable: Unload method for the plugin module. """ return self._get_instance_attribute( ControlProperties.attr_unload, default=lambda: True ) @property def enable(self): """ Method for enabling the plugin module. Will be taken from the enable attribute of the plugin module as defined in :attr:`attr_enable` if available, otherwise a no-operation lambda will be returned. Returns: callable: Enable method for the plugin module. """ return self._get_instance_attribute( ControlProperties.attr_enable, default=lambda: True ) @property def disable(self): """ Method for disabling the plugin module. Will be taken from the disable attribute of the plugin module as defined in :attr:`attr_disable` if available, otherwise a no-operation lambda will be returned. Returns: callable: Disable method for the plugin module. """ return self._get_instance_attribute( ControlProperties.attr_disable, default=lambda: True ) def _get_instance_attribute( self, attr, default=None, defaults=None, incl_metadata=False ): if self.instance is None or not hasattr(self.instance, attr): if incl_metadata and attr in self.parsed_metadata: return self.parsed_metadata[attr] elif defaults is not None: for value in defaults: if callable(value): value = value() if value is not None: return value return default return getattr(self.instance, attr) @property def parsed_metadata(self): """The plugin metadata parsed from the plugin's AST.""" return self._cached_parsed_metadata @property def control_properties(self): return ControlProperties.all() @property def looks_like_plugin(self): """ Returns whether the plugin actually looks like a plugin (has control properties) or not. """ return self.parsed_metadata.get("has_control_properties", False) def _parse_metadata(self): try: return parse_plugin_metadata(self.location) except SyntaxError: self._logger.exception(f"Invalid syntax in plugin file of plugin {self.key}") self.invalid_syntax = True return {} class PluginManager: """ The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the system. It is able to discover plugins both through possible file system locations as well as customizable entry points. """ plugin_timings_logtarget = "PLUGIN_TIMINGS" plugin_timings_message = "{func} - {timing:05.2f}ms" default_order = 1000 def __init__( self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None, plugin_sorting_order=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_considered_bundled=None, plugin_validators=None, compatibility_ignored_list=None, ): self.logger = logging.getLogger(__name__) if logging_prefix is None: logging_prefix = "" if plugin_folders is None: plugin_folders = [] if plugin_bases is None: plugin_bases = [] if plugin_entry_points is None: plugin_entry_points = [] if plugin_disabled_list is None: plugin_disabled_list = [] if plugin_sorting_order is None: plugin_sorting_order = {} if plugin_blacklist is None: plugin_blacklist = [] if compatibility_ignored_list is None: compatibility_ignored_list = [] if plugin_considered_bundled is None: plugin_considered_bundled = [] processed_blacklist = [] for entry in plugin_blacklist: if isinstance(entry, (tuple, list)): key, version = entry try: processed_blacklist.append( (key, pkg_resources.Requirement.parse(key + version)) ) except Exception: self.logger.warning( "Invalid version requirement {} for blacklist " "entry {}, ignoring".format(version, key) ) else: processed_blacklist.append(entry) self.plugin_folders = plugin_folders self.plugin_bases = plugin_bases self.plugin_entry_points = plugin_entry_points self.plugin_disabled_list = plugin_disabled_list self.plugin_sorting_order = plugin_sorting_order self.plugin_blacklist = processed_blacklist self.plugin_restart_needing_hooks = plugin_restart_needing_hooks self.plugin_obsolete_hooks = plugin_obsolete_hooks self.plugin_validators = plugin_validators self.logging_prefix = logging_prefix self.compatibility_ignored_list = compatibility_ignored_list self.plugin_considered_bundled = plugin_considered_bundled self.enabled_plugins = {} self.disabled_plugins = {} self.plugin_implementations = {} self.plugin_implementations_by_type = defaultdict(list) self._plugin_hooks = defaultdict(list) self.implementation_injects = {} self.implementation_inject_factories = [] self.implementation_pre_inits = [] self.implementation_post_inits = [] self.on_plugin_loaded = lambda *args, **kwargs: None self.on_plugin_unloaded = lambda *args, **kwargs: None self.on_plugin_enabled = lambda *args, **kwargs: None self.on_plugin_disabled = lambda *args, **kwargs: None self.on_plugin_implementations_initialized = lambda *args, **kwargs: None self.on_plugins_loaded = lambda *args, **kwargs: None self.on_plugins_enabled = lambda *args, **kwargs: None self.registered_clients = [] self.marked_plugins = defaultdict(list) self._python_install_dir = None self._python_virtual_env = False self._detect_python_environment() def _detect_python_environment(self): import sys import sysconfig self._python_install_dir = sysconfig.get_path("purelib") self._python_prefix = os.path.realpath(sys.prefix) self._python_virtual_env = hasattr(sys, "real_prefix") or ( hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix) ) @property def plugins(self): """ Returns: (list) list of enabled and disabled registered plugins """ plugins = dict(self.enabled_plugins) plugins.update(self.disabled_plugins) return plugins @property def plugin_hooks(self): """ Returns: (dict) dictionary of registered hooks and their handlers """ return { key: list(map(lambda v: (v[1], v[2]), value)) for key, value in self._plugin_hooks.items() } def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False): added, found = self._find_plugins( existing=existing, ignore_uninstalled=ignore_uninstalled ) if incl_all_found: return added, found else: return added def _find_plugins(self, existing=None, ignore_uninstalled=True): if existing is None: existing = dict(self.plugins) result_added = OrderedDict() result_found = [] if self.plugin_folders: try: added, found = self._find_plugins_from_folders( self.plugin_folders, existing, ignored_uninstalled=ignore_uninstalled, ) result_added.update(added) result_found += found except Exception: self.logger.exception("Error fetching plugins from folders") if self.plugin_entry_points: existing.update(result_added) try: added, found = self._find_plugins_from_entry_points( self.plugin_entry_points, existing, ignore_uninstalled=ignore_uninstalled, ) result_added.update(added) result_found += found except Exception: self.logger.exception("Error fetching plugins from entry points") return result_added, result_found def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True): added = OrderedDict() found = [] for folder in folders: try: flagged_readonly = False package = None if isinstance(folder, (list, tuple)): if len(folder) == 2: folder, flagged_readonly = folder elif len(folder) == 3: folder, package, flagged_readonly = folder else: continue actual_readonly = not os.access(folder, os.W_OK) if not os.path.exists(folder): self.logger.warning( "Plugin folder {folder} could not be found, skipping it".format( folder=folder ) ) continue for entry in scandir(folder): try: if entry.is_dir(): init_py = os.path.join(entry.path, "__init__.py") if not os.path.isfile(init_py): # neither does exist, we ignore this continue key = entry.name elif entry.is_file(): key, ext = os.path.splitext(entry.name) if ext not in (".py",) or key.startswith("__"): # not py, or starts with __ (like __init__), we ignore this continue else: # whatever this is, we ignore it continue found.append(key) if ( key in existing or key in added or ( ignored_uninstalled and key in self.marked_plugins["uninstalled"] ) ): # plugin is already defined, ignore it continue bundled = flagged_readonly module_name = None if package: module_name = f"{package}.{key}" plugin = self._import_plugin_from_module( key, module_name=module_name, folder=folder, bundled=bundled ) if plugin: if module_name: plugin.origin = ModuleOrigin( "module", module_name, folder ) else: plugin.origin = FolderOrigin("folder", folder) plugin.managable = ( not flagged_readonly and not actual_readonly ) plugin.enabled = False added[key] = plugin except Exception: self.logger.exception( "Error processing folder entry {!r} from folder {}".format( entry, folder ) ) except Exception: self.logger.exception(f"Error processing folder {folder}") return added, found def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True): added = OrderedDict() found = [] # let's make sure we have a current working set ... working_set = pkg_resources.WorkingSet() # ... including the user's site packages import site import sys if site.ENABLE_USER_SITE: if site.USER_SITE not in working_set.entries: working_set.add_entry(site.USER_SITE) if site.USER_SITE not in sys.path: site.addsitedir(site.USER_SITE) if not isinstance(groups, (list, tuple)): groups = [groups] def wrapped(gen): # to protect against some issues in installed packages that make iteration over entry points # fall on its face - e.g. https://groups.google.com/forum/#!msg/octoprint/DyXdqhR0U7c/kKMUsMmIBgAJ for entry in gen: try: yield entry except Exception: self.logger.exception( "Something went wrong while processing the entry points of a package in the " "Python environment - broken entry_points.txt in some package?" ) for group in groups: for entry_point in wrapped( working_set.iter_entry_points(group=group, name=None) ): try: key = entry_point.name module_name = entry_point.module_name version = entry_point.dist.version found.append(key) if ( key in existing or key in added or ( ignore_uninstalled and key in self.marked_plugins["uninstalled"] ) ): # plugin is already defined or marked as uninstalled, ignore it continue bundled = key in self.plugin_considered_bundled kwargs = { "module_name": module_name, "version": version, "bundled": bundled, } package_name = entry_point.dist.project_name try: entry_point_metadata = EntryPointMetadata(entry_point) except Exception: self.logger.exception( "Something went wrong while retrieving metadata for module {}".format( module_name ) ) else: kwargs.update( { "name": entry_point_metadata.name, "summary": entry_point_metadata.summary, "author": entry_point_metadata.author, "url": entry_point_metadata.home_page, "license": entry_point_metadata.license, } ) plugin = self._import_plugin_from_module(key, **kwargs) if plugin: plugin.origin = EntryPointOrigin( "entry_point", group, module_name, package_name, version ) plugin.enabled = False # plugin is manageable if its location is writable and OctoPrint # is either not running from a virtual env or the plugin is # installed in that virtual env - the virtual env's pip will not # allow us to uninstall stuff that is installed outside # of the virtual env, so this check is necessary plugin.managable = os.access(plugin.location, os.W_OK) and ( not self._python_virtual_env or is_sub_path_of(plugin.location, self._python_prefix) or is_editable_install( self._python_install_dir, package_name, module_name, plugin.location, ) ) added[key] = plugin except Exception: self.logger.exception( "Error processing entry point {!r} for group {}".format( entry_point, group ) ) return added, found def _import_plugin_from_module( self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, ): # TODO error handling try: if folder: location, spec = _find_module(key, path=folder) elif module_name: location, spec = _find_module(module_name) else: return None except Exception: self.logger.exception(f"Could not locate plugin {key}") return None # Create a simple dummy entry first ... plugin = PluginInfo( key, location, None, name=name, version=version, description=summary, author=author, url=url, license=license, ) plugin.bundled = bundled if self._is_plugin_disabled(key): self.logger.info(f"Plugin {plugin} is disabled.") plugin.forced_disabled = True if self._is_plugin_blacklisted(key) or ( plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version) ): self.logger.warning(f"Plugin {plugin} is blacklisted.") plugin.blacklisted = True python_version = get_python_version_string() if self._is_plugin_incompatible(key, plugin): if plugin.invalid_syntax: self.logger.warning( "Plugin {} can't be compiled under Python {} due to invalid syntax".format( plugin, python_version ) ) else: self.logger.warning( "Plugin {} is not compatible to Python {} (compatibility string: {}).".format( plugin, python_version, plugin.pythoncompat ) ) plugin.incompatible = True if not plugin.validate( "before_import", additional_validators=self.plugin_validators ): return plugin # ... then create and return the real one return self._import_plugin( key, spec, module_name=module_name, name=name, location=plugin.location, version=version, summary=summary, author=author, url=url, license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata, ) def _import_plugin( self, key, spec, module_name=None, name=None, location=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None, ): try: if module_name: module = _load_module(module_name, spec) else: module = _load_module(key, spec) plugin = PluginInfo( key, location, module, name=name, version=version, description=summary, author=author, url=url, license=license, parsed_metadata=parsed_metadata, ) plugin.bundled = bundled except Exception: self.logger.exception(f"Error loading plugin {key}") return None if plugin.check(): return plugin else: self.logger.info( "Plugin {plugin} did not pass check, not loading.".format( plugin=str(plugin) ) ) return None def _is_plugin_disabled(self, key): return key in self.plugin_disabled_list or key.endswith("disabled") def _is_plugin_blacklisted(self, key): return key in self.plugin_blacklist def _is_plugin_incompatible(self, key, plugin): return ( not plugin.bundled and not is_python_compatible(plugin.pythoncompat) and key not in self.compatibility_ignored_list ) def _is_plugin_version_blacklisted(self, key, version): def matches_plugin(entry): if isinstance(entry, (tuple, list)) and len(entry) == 2: entry_key, entry_version = entry return entry_key == key and version in entry_version return False return any(map(matches_plugin, self.plugin_blacklist)) def reload_plugins( self, startup=False, initialize_implementations=True, force_reload=None ): """ Reloads plugins, detecting newly added ones in the process. Args: startup (boolean): whether this is called during startup of the platform initialize_implementations (boolean): whether plugin implementations should be initialized force_reload (list): list of plugin identifiers which should be force reloaded """ self.logger.info( "Loading plugins from {folders} and installed plugin packages...".format( folders=", ".join( map( lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders, ) ) ) ) if force_reload is None: force_reload = [] added, found = self.find_plugins( existing={k: v for k, v in self.plugins.items() if k not in force_reload}, incl_all_found=True, ) # let's clean everything we DIDN'T find first removed = [ key for key in list(self.enabled_plugins.keys()) + list(self.disabled_plugins.keys()) if key not in found ] for key in removed: try: del self.enabled_plugins[key] except KeyError: pass try: del self.disabled_plugins[key] except KeyError: pass self.disabled_plugins.update(added) # 1st pass: loading the plugins for name, plugin in added.items(): try: if ( plugin.looks_like_plugin and not plugin.blacklisted and not plugin.forced_disabled and not plugin.incompatible ): self.load_plugin( name, plugin, startup=startup, initialize_implementation=initialize_implementations, ) except PluginNeedsRestart: pass except PluginLifecycleException as e: self.logger.info(str(e)) self.on_plugins_loaded( startup=startup, initialize_implementations=initialize_implementations, force_reload=force_reload, ) # 2nd pass: enabling those plugins that need enabling for name, plugin in added.items(): try: if ( plugin.loaded and plugin.looks_like_plugin and not plugin.forced_disabled and not plugin.incompatible ): if plugin.blacklisted: self.logger.warning( f"Plugin {plugin} is blacklisted. Not enabling it." ) continue self.enable_plugin( name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup, ) except PluginNeedsRestart: pass except PluginLifecycleException as e: self.logger.info(str(e)) self.on_plugins_enabled( startup=startup, initialize_implementations=initialize_implementations, force_reload=force_reload, ) if len(self.enabled_plugins) <= 0: self.logger.info("No plugins found") else: self.logger.info( "Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format( count=len(self.enabled_plugins) + len(self.disabled_plugins), implementations=len(self.plugin_implementations), hooks=sum(map(lambda x: len(x), self.plugin_hooks.values())), ) ) def mark_plugin(self, name, **flags): """ Mark plugin ``name`` with an arbitrary number of flags. Args: name (str): plugin identifier **flags (dict): dictionary of flag names and values """ if name not in self.plugins: self.logger.debug(f"Trying to mark an unknown plugin {name}") for key, value in flags.items(): if value is None: continue if value and name not in self.marked_plugins[key]: self.marked_plugins[key].append(name) elif not value and name in self.marked_plugins[key]: self.marked_plugins[key].remove(name) def is_plugin_marked(self, name, flag): """ Checks whether a plugin has been marked with a certain flag. Args: name (str): the plugin's identifier flag (str): the flag to check Returns: (boolean): True if the plugin has been flagged, False otherwise """ if name not in self.plugins: return False return name in self.marked_plugins[flag] def load_plugin( self, name, plugin=None, startup=False, initialize_implementation=True ): if name not in self.plugins: self.logger.warning(f"Trying to load an unknown plugin {name}") return if plugin is None: plugin = self.plugins[name] try: if not plugin.validate( "before_load", additional_validators=self.plugin_validators ): return plugin.load() plugin.validate("after_load", additional_validators=self.plugin_validators) self.on_plugin_loaded(name, plugin) plugin.loaded = True self.logger.debug(f"Loaded plugin {name}: {plugin}") except PluginLifecycleException as e: raise e except Exception: self.logger.exception("There was an error loading plugin %s" % name) def unload_plugin(self, name): if name not in self.plugins: self.logger.warning(f"Trying to unload unknown plugin {name}") return plugin = self.plugins[name] try: if plugin.enabled: self.disable_plugin(name, plugin=plugin) plugin.unload() self.on_plugin_unloaded(name, plugin) if name in self.enabled_plugins: del self.enabled_plugins[name] if name in self.disabled_plugins: del self.disabled_plugins[name] plugin.loaded = False self.logger.debug(f"Unloaded plugin {name}: {plugin}") except PluginLifecycleException as e: raise e except Exception: self.logger.exception(f"There was an error unloading plugin {name}") # make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins if name in self.enabled_plugins: del self.enabled_plugins[name] if name not in self.disabled_plugins: self.disabled_plugins[name] = plugin def enable_plugin( self, name, plugin=None, initialize_implementation=True, startup=False ): """Enables a plugin""" if name not in self.disabled_plugins: self.logger.warning( f"Tried to enable plugin {name}, however it is not disabled" ) return if plugin is None: plugin = self.disabled_plugins[name] if not startup and self.is_restart_needing_plugin(plugin): raise PluginNeedsRestart(name) if self.has_obsolete_hooks(plugin): raise PluginCantEnable( name, "Dependency on obsolete hooks detected, full functionality cannot be guaranteed", ) try: if not plugin.validate( "before_enable", additional_validators=self.plugin_validators ): return False plugin.enable() self._activate_plugin(name, plugin) except PluginLifecycleException as e: raise e except Exception: self.logger.exception(f"There was an error while enabling plugin {name}") return False else: if name in self.disabled_plugins: del self.disabled_plugins[name] self.enabled_plugins[name] = plugin plugin.enabled = True if plugin.implementation: if initialize_implementation: if not self.initialize_implementation_of_plugin(name, plugin): return False plugin.implementation.on_plugin_enabled() self.on_plugin_enabled(name, plugin) self.logger.debug(f"Enabled plugin {name}: {plugin}") return True def disable_plugin(self, name, plugin=None): """Disables a plugin""" if name not in self.enabled_plugins: self.logger.warning( f"Tried to disable plugin {name}, however it is not enabled" ) return if plugin is None: plugin = self.enabled_plugins[name] if self.is_restart_needing_plugin(plugin): raise PluginNeedsRestart(name) try: plugin.disable() self._deactivate_plugin(name, plugin) except PluginLifecycleException as e: raise e except Exception: self.logger.exception(f"There was an error while disabling plugin {name}") return False else: if name in self.enabled_plugins: del self.enabled_plugins[name] self.disabled_plugins[name] = plugin plugin.enabled = False if plugin.implementation: plugin.implementation.on_plugin_disabled() self.on_plugin_disabled(name, plugin) self.logger.debug(f"Disabled plugin {name}: {plugin}") return True def _activate_plugin(self, name, plugin): plugin.hotchangeable = self.is_restart_needing_plugin(plugin) # evaluate registered hooks for hook, definition in plugin.hooks.items(): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: self.logger.warning( "There is something wrong with the hook definition {} for plugin {}: {}".format( definition, name, str(e) ) ) continue if not order: order = self.default_order override = self.plugin_sorting_order.get(name, {}).get(hook, None) if override: order = override self._plugin_hooks[hook].append((order, name, callback)) self._sort_hooks(hook) # evaluate registered implementation if plugin.implementation: mixins = self.mixins_matching_bases( plugin.implementation.__class__, *self.plugin_bases ) for mixin in mixins: self.plugin_implementations_by_type[mixin].append( (name, plugin.implementation) ) if not getattr(plugin.implementation, "__timing_wrapped", False): for method in filter( lambda a: not a.startswith("_") and callable(getattr(mixin, a)), dir(mixin), ): # wrap method with time_this setattr( plugin.implementation, method, time_this( logtarget=self.plugin_timings_logtarget, expand_logtarget=True, message=self.plugin_timings_message, )(getattr(plugin.implementation, method)), ) self.plugin_implementations[name] = plugin.implementation plugin.implementation.__timing_wrapped = True def _deactivate_plugin(self, name, plugin): for hook, definition in plugin.hooks.items(): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: self.logger.warning( "There is something wrong with the hook definition {} for plugin {}: {}".format( definition, name, str(e) ) ) continue if not order: order = self.default_order try: self._plugin_hooks[hook].remove((order, name, callback)) self._sort_hooks(hook) except ValueError: # that's ok, the plugin was just not registered for the hook pass if plugin.implementation is not None: if name in self.plugin_implementations: del self.plugin_implementations[name] mixins = self.mixins_matching_bases( plugin.implementation.__class__, *self.plugin_bases ) for mixin in mixins: try: self.plugin_implementations_by_type[mixin].remove( (name, plugin.implementation) ) except ValueError: # that's ok, the plugin was just not registered for the type pass def is_restart_needing_plugin(self, plugin): """Checks whether the plugin needs a restart on changes""" return ( plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin) ) def has_restart_needing_implementation(self, plugin): """Checks whether the plugin's implementation needs a restart on changes""" return self.has_any_of_mixins(plugin, RestartNeedingPlugin) def has_restart_needing_hooks(self, plugin): """Checks whether the plugin has any hooks that need a restart on changes""" return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks) def has_obsolete_hooks(self, plugin): """Checks whether the plugin uses any obsolete hooks""" return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks) def is_restart_needing_hook(self, hook): """Checks whether a hook needs a restart on changes""" return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks) def is_obsolete_hook(self, hook): """Checks whether a hook is obsolete""" return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks) @staticmethod def has_any_of_hooks(plugin, *hooks): """ Tests if the ``plugin`` contains any of the provided ``hooks``. Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`. Args: plugin: plugin to test hooks for *hooks: hooks to test against Returns: (bool): True if any of the plugin's hooks match the provided hooks, False otherwise. """ if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): hooks = hooks[0] hooks = list(filter(lambda hook: hook is not None, hooks)) if not hooks: return False if not plugin or not plugin.hooks: return False plugin_hooks = plugin.hooks.keys() return any( map( lambda hook: PluginManager.hook_matches_hooks(hook, *hooks), plugin_hooks, ) ) @staticmethod def hook_matches_hooks(hook, *hooks): """ Tests if ``hook`` matches any of the provided ``hooks`` to test for. ``hook`` is expected to be an exact hook name. ``hooks`` is expected to be a list containing one or more hook names or patterns. That can be either an exact hook name or an :func:`fnmatch.fnmatch` pattern. Args: hook: the hook to test hooks: the hook name patterns to test against Returns: (bool): True if the ``hook`` matches any of the ``hooks``, False otherwise. """ if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): hooks = hooks[0] hooks = list(filter(lambda hook: hook is not None, hooks)) if not hooks: return False if not hook: return False return any(map(lambda h: fnmatch.fnmatch(hook, h), hooks)) @staticmethod def mixins_matching_bases(klass, *bases): result = set() for c in inspect.getmro(klass): if c == klass or c in bases: # ignore the exact class and our bases continue if issubclass(c, bases): result.add(c) return result @staticmethod def has_any_of_mixins(plugin, *mixins): """ Tests if the ``plugin`` has an implementation implementing any of the provided ``mixins``. Args: plugin: plugin for which to check the implementation *mixins: mixins to test against Returns: (bool): True if the plugin's implementation implements any of the provided mixins, False otherwise. """ if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): mixins = mixins[0] mixins = list(filter(lambda mixin: mixin is not None, mixins)) if not mixins: return False if not plugin or not plugin.implementation: return False return isinstance(plugin.implementation, tuple(mixins)) def initialize_implementations( self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None, ): for name, plugin in self.enabled_plugins.items(): self.initialize_implementation_of_plugin( name, plugin, additional_injects=additional_injects, additional_inject_factories=additional_inject_factories, additional_pre_inits=additional_pre_inits, additional_post_inits=additional_post_inits, ) self.logger.info( "Initialized {count} plugin implementation(s)".format( count=len(self.plugin_implementations) ) ) def initialize_implementation_of_plugin( self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None, ): if plugin.implementation is None: return return self.initialize_implementation( name, plugin, plugin.implementation, additional_injects=additional_injects, additional_inject_factories=additional_inject_factories, additional_pre_inits=additional_pre_inits, additional_post_inits=additional_post_inits, ) def initialize_implementation( self, name, plugin, implementation, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None, ): if additional_injects is None: additional_injects = {} if additional_inject_factories is None: additional_inject_factories = [] if additional_pre_inits is None: additional_pre_inits = [] if additional_post_inits is None: additional_post_inits = [] injects = self.implementation_injects injects.update(additional_injects) inject_factories = self.implementation_inject_factories inject_factories += additional_inject_factories pre_inits = self.implementation_pre_inits pre_inits += additional_pre_inits post_inits = self.implementation_post_inits post_inits += additional_post_inits try: kwargs = dict(injects) kwargs.update( { "identifier": name, "plugin_name": plugin.name, "plugin_version": plugin.version, "plugin_info": plugin, "basefolder": os.path.realpath(plugin.location), "logger": logging.getLogger(self.logging_prefix + name), } ) # inject the additional_injects for arg, value in kwargs.items(): setattr(implementation, "_" + arg, value) # inject any injects produced in the additional_inject_factories for factory in inject_factories: try: return_value = factory(name, implementation) except Exception: self.logger.exception( "Exception while executing injection factory %r" % factory ) else: if return_value is not None: if isinstance(return_value, dict): for arg, value in return_value.items(): setattr(implementation, "_" + arg, value) # execute any additional pre init methods for pre_init in pre_inits: pre_init(name, implementation) implementation.initialize() # execute any additional post init methods for post_init in post_inits: post_init(name, implementation) except Exception as e: self._deactivate_plugin(name, plugin) plugin.enabled = False if isinstance(e, PluginLifecycleException): raise e else: self.logger.exception( f"Exception while initializing plugin {name}, disabling it" ) return False else: self.on_plugin_implementations_initialized(name, plugin) self.logger.debug(f"Initialized plugin mixin implementation for plugin {name}") return True def log_all_plugins( self, show_bundled=True, bundled_str=(" (bundled)", ""), show_location=True, location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!", "#", "*"), only_to_handler=None, ): all_plugins = list(self.enabled_plugins.values()) + list( self.disabled_plugins.values() ) def _log(message, level=logging.INFO): if only_to_handler is not None: import octoprint.logging octoprint.logging.log_to_handler( self.logger, only_to_handler, level, message, [] ) else: self.logger.log(level, message) if len(all_plugins) <= 0: _log("No plugins available") else: formatted_plugins = "\n".join( map( lambda x: "| " + x.long_str( show_bundled=show_bundled, bundled_strs=bundled_str, show_location=show_location, location_str=location_str, show_enabled=show_enabled, enabled_strs=enabled_str, ), sorted(self.plugins.values(), key=lambda x: str(x).lower()), ) ) legend = "Prefix legend: {1} = disabled, {2} = blacklisted, {3} = incompatible".format( *enabled_str ) _log( "{count} plugin(s) registered with the system:\n{plugins}\n{legend}".format( count=len(all_plugins), plugins=formatted_plugins, legend=legend ) ) def get_plugin(self, identifier, require_enabled=True): """ Retrieves the module of the plugin identified by ``identifier``. If the plugin is not registered or disabled and ``required_enabled`` is True (the default) None will be returned. Arguments: identifier (str): The identifier of the plugin to retrieve. require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's disabled. Returns: module: The requested plugin module or None """ plugin_info = self.get_plugin_info(identifier, require_enabled=require_enabled) if plugin_info is not None: return plugin_info.instance return None def get_plugin_info(self, identifier, require_enabled=True): """ Retrieves the :class:`PluginInfo` instance identified by ``identifier``. If the plugin is not registered or disabled and ``required_enabled`` is True (the default) None will be returned. Arguments: identifier (str): The identifier of the plugin to retrieve. require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's disabled. Returns: ~.PluginInfo: The requested :class:`PluginInfo` or None """ if identifier in self.enabled_plugins: return self.enabled_plugins[identifier] elif not require_enabled and identifier in self.disabled_plugins: return self.disabled_plugins[identifier] return None def get_hooks(self, hook): """ Retrieves all registered handlers for the specified hook. Arguments: hook (str): The hook for which to retrieve the handlers. Returns: dict: A dict containing all registered handlers mapped by their plugin's identifier. """ if hook not in self.plugin_hooks: return {} result = OrderedDict() for h in self.plugin_hooks[hook]: result[h[0]] = time_this( logtarget=self.plugin_timings_logtarget, expand_logtarget=True, message=self.plugin_timings_message, )(h[1]) return result def get_implementations(self, *types, **kwargs): """ Get all mixin implementations that implement *all* of the provided ``types``. Arguments: types (one or more type): The types a mixin implementation needs to implement in order to be returned. Returns: list: A list of all found implementations """ sorting_context = kwargs.get("sorting_context", None) result = None for t in types: implementations = self.plugin_implementations_by_type[t] if result is None: result = set(implementations) else: result = result.intersection(implementations) if result is None: return [] def sort_func(impl): sorting_value = None if sorting_context is not None and isinstance(impl[1], SortablePlugin): try: sorting_value = impl[1].get_sorting_key(sorting_context) except Exception: self.logger.exception( "Error while trying to retrieve sorting order for plugin {}".format( impl[0] ) ) if sorting_value is not None: try: sorting_value = int(sorting_value) except ValueError: self.logger.warning( "The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format( impl[0], sorting_context ) ) sorting_value = self.default_order else: sorting_value = self.default_order override = self.plugin_sorting_order.get(impl[0], {}).get( sorting_context, None ) if override: sorting_value = override plugin_info = self.get_plugin_info(impl[0], require_enabled=False) return ( sv(sorting_value, default_value=self.default_order), not plugin_info.bundled if plugin_info else True, sv(impl[0]), ) return [impl[1] for impl in sorted(result, key=sort_func)] def get_filtered_implementations(self, f, *types, **kwargs): """ Get all mixin implementations that implement *all* of the provided ``types`` and match the provided filter `f`. Arguments: f (callable): A filter function returning True for implementations to return and False for those to exclude. types (one or more type): The types a mixin implementation needs to implement in order to be returned. Returns: list: A list of all found and matching implementations. """ assert callable(f) implementations = self.get_implementations( *types, sorting_context=kwargs.get("sorting_context", None) ) return list(filter(f, implementations)) def get_helpers(self, name, *helpers): """ Retrieves the named ``helpers`` for the plugin with identifier ``name``. If the plugin is not available, returns None. Otherwise returns a :class:`dict` with the requested plugin helper names mapped to the method - if a helper could not be resolved, it will be missing from the dict. Arguments: name (str): Identifier of the plugin for which to look up the ``helpers``. helpers (one or more str): Identifiers of the helpers of plugin ``name`` to return. Returns: dict: A dictionary of all resolved helpers, mapped by their identifiers, or None if the plugin was not registered with the system. """ if name not in self.enabled_plugins: return None plugin = self.enabled_plugins[name] all_helpers = plugin.helpers if len(helpers): return {k: v for (k, v) in all_helpers.items() if k in helpers} else: return all_helpers def register_message_receiver(self, client): """ Registers a ``client`` for receiving plugin messages. The ``client`` needs to be a callable accepting two input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself), and one optional keyword argument, ``permissions`` (an optional list of permissions to test against). """ if client is None: return self.registered_clients.append(client) def unregister_message_receiver(self, client): """ Unregisters a ``client`` for receiving plugin messages. """ try: self.registered_clients.remove(client) except ValueError: # not registered pass def send_plugin_message(self, plugin, data, permissions=None): """ Sends ``data`` in the name of ``plugin`` to all currently registered message receivers by invoking them with the three arguments. Arguments: plugin (str): The sending plugin's identifier. data (object): The message. permissions (list): A list of permissions to test against in the client. """ for client in self.registered_clients: try: client(plugin, data, permissions=permissions) except Exception: self.logger.exception("Exception while sending plugin data to client") def _sort_hooks(self, hook): self._plugin_hooks[hook] = sorted( self._plugin_hooks[hook], key=lambda x: (sv(x[0]), sv(x[1]), sv(x[2])), ) def _get_callback_and_order(self, hook): if callable(hook): return hook, None elif isinstance(hook, tuple) and len(hook) == 2: callback, order = hook # test that callback is a callable if not callable(callback): raise ValueError("Hook callback is not a callable") # test that number is an int try: int(order) except ValueError: raise ValueError("Hook order is not a number") return callback, order else: raise ValueError( "Invalid hook definition, neither a callable nor a 2-tuple (callback, order): {!r}".format( hook ) ) def is_sub_path_of(path, parent): """ Tests if `path` is a sub path (or identical) to `path`. >>> is_sub_path_of("/a/b/c", "/a/b") True >>> is_sub_path_of("/a/b/c", "/a/b2") False >>> is_sub_path_of("/a/b/c", "/b/c") False >>> is_sub_path_of("/foo/bar/../../a/b/c", "/a/b") True >>> is_sub_path_of("/a/b", "/a/b") True """ rel_path = os.path.relpath(os.path.realpath(path), os.path.realpath(parent)) return not (rel_path == os.pardir or rel_path.startswith(os.pardir + os.sep)) def is_editable_install(install_dir, package, module, location): package_link = os.path.join(install_dir, f"{package}.egg-link") if os.path.isfile(package_link): expected_target = os.path.normcase(os.path.realpath(location)) try: with open(package_link, encoding="utf-8") as f: contents = f.readlines() for line in contents: target = os.path.normcase( os.path.realpath(os.path.join(line.strip(), module)) ) if target == expected_target: return True except Exception: raise # TODO really ignore this? pass return False class EntryPointMetadata(pkginfo.Distribution): def __init__(self, entry_point): self.entry_point = entry_point self.extractMetadata() def read(self): import warnings metadata_files = ("METADATA", "PKG-INFO") # wheel # egg if self.entry_point and self.entry_point.dist: for metadata_file in metadata_files: try: return self.entry_point.dist.get_metadata(metadata_file) except OSError: # noqa: B014 # file not found, metadata file might be missing, ignore pass warnings.warn( "No package metadata found for package {}".format( self.entry_point.module_name ), stacklevel=2, ) class Plugin: """ The parent class of all plugin implementations. .. attribute:: _identifier The identifier of the plugin. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _plugin_name The name of the plugin. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _plugin_version The version of the plugin. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _basefolder The base folder of the plugin. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _logger The logger instance to use, with the logging name set to the :attr:`PluginManager.logging_prefix` of the :class:`PluginManager` concatenated with :attr:`_identifier`. Injected by the plugin core system upon initialization of the implementation. """ def __init__(self): self._identifier = None self._plugin_name = None self._plugin_version = None self._basefolder = None self._logger = None def initialize(self): """ Called by the plugin core after performing all injections. Override this to initialize your implementation. """ pass def on_plugin_enabled(self): """ Called by the plugin core when the plugin was enabled. Override this to react to the event. """ pass def on_plugin_disabled(self): """ Called by the plugin core when the plugin was disabled. Override this to react to the event. """ pass class RestartNeedingPlugin(Plugin): """ Mixin for plugin types that need a restart after enabling/disabling them. """ class SortablePlugin(Plugin): """ Mixin for plugin types that are sortable. """ def get_sorting_key(self, context=None): """ Returns the sorting key to use for the implementation in the specified ``context``. May return ``None`` if order is irrelevant. Implementations returning None will be ordered by plugin identifier after all implementations which did return a sorting key value that was not None sorted by that. Arguments: context (str): The sorting context for which to provide the sorting key value. Returns: int or None: An integer signifying the sorting key value of the plugin (sorting will be done ascending), or None if the implementation doesn't care about calling order. """ return None class PluginNeedsRestart(Exception): def __init__(self, name): Exception.__init__(self) self.name = name self.message = f"Plugin {name} cannot be enabled or disabled after system startup" class PluginLifecycleException(Exception): def __init__(self, name, reason, message): Exception.__init__(self) self.name = name self.reason = reason self.message = message.format(**locals()) def __str__(self): return self.message class PluginCantInitialize(PluginLifecycleException): def __init__(self, name, reason): PluginLifecycleException.__init__( self, name, reason, "Plugin {name} cannot be initialized: {reason}" ) class PluginCantEnable(PluginLifecycleException): def __init__(self, name, reason): PluginLifecycleException.__init__( self, name, reason, "Plugin {name} cannot be enabled: {reason}" ) class PluginCantDisable(PluginLifecycleException): def __init__(self, name, reason): PluginLifecycleException.__init__( self, name, reason, "Plugin {name} cannot be disabled: {reason}" )
85,899
Python
.py
2,030
29.760591
147
0.570857
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,858
types.py
OctoPrint_OctoPrint/src/octoprint/plugin/types.py
""" This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent class, :class:`OctoPrintPlugin`. Please note that the plugin implementation types are documented in the section :ref:`Available plugin mixins <sec-plugins-mixins>`. .. autoclass:: OctoPrintPlugin :show-inheritance: :members: .. autoclass:: ReloadNeedingPlugin :show-inheritance: :members: """ __author__ = "Gina Häußge <osd@foosel.net>" __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 .core import Plugin, RestartNeedingPlugin, SortablePlugin class OctoPrintPlugin(Plugin): """ The parent class of all OctoPrint plugin mixins. .. attribute:: _plugin_manager The :class:`~octoprint.plugin.core.PluginManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _printer_profile_manager The :class:`~octoprint.printer.profile.PrinterProfileManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _event_bus The :class:`~octoprint.events.EventManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _analysis_queue The :class:`~octoprint.filemanager.analysis.AnalysisQueue` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _slicing_manager The :class:`~octoprint.slicing.SlicingManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _file_manager The :class:`~octoprint.filemanager.FileManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _printer The :class:`~octoprint.printer.PrinterInterface` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _app_session_manager The :class:`~octoprint.access.users.SessionManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _plugin_lifecycle_manager The :class:`~octoprint.server.LifecycleManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _user_manager The :class:`~octoprint.access.users.UserManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _connectivity_checker The :class:`~octoprint.util.ConnectivityChecker` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _data_folder Path to the data folder for the plugin to use for any data it might have to persist. Should always be accessed through :meth:`get_plugin_data_folder` since that function will also ensure that the data folder actually exists and if not creating it before returning it. Injected by the plugin core system upon initialization of the implementation. """ # noinspection PyMissingConstructor def __init__(self): self._plugin_manager = None self._printer_profile_manager = None self._event_bus = None self._analysis_queue = None self._slicing_manager = None self._file_manager = None self._printer = None self._app_session_manager = None self._plugin_lifecycle_manager = None self._user_manager = None self._connectivity_checker = None self._data_folder = None def get_plugin_data_folder(self): """ Retrieves the path to a data folder specifically for the plugin, ensuring it exists and if not creating it before returning it. Plugins may use this folder for storing additional data they need for their operation. """ if self._data_folder is None: raise RuntimeError( "self._plugin_data_folder is None, has the plugin been initialized yet?" ) import os os.makedirs(self._data_folder, exist_ok=True) return self._data_folder def on_plugin_pending_uninstall(self): """ Called by the plugin manager when the plugin is pending uninstall. Override this to react to the event. NOT called during plugin uninstalls triggered outside of OctoPrint! """ pass class ReloadNeedingPlugin(Plugin): """ Mixin for plugin types that need a reload of the UI after enabling/disabling them. """ class EnvironmentDetectionPlugin(OctoPrintPlugin, RestartNeedingPlugin): """ .. versionadded:: 1.3.6 """ def get_additional_environment(self): pass def on_environment_detected(self, environment, *args, **kwargs): pass class StartupPlugin(OctoPrintPlugin, SortablePlugin): """ The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services on or just after the startup of the server. ``StartupPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin` and provides sorting contexts for :meth:`~octoprint.plugin.StartupPlugin.on_startup` as well as :meth:`~octoprint.plugin.StartupPlugin.on_after_startup`. """ def on_startup(self, host, port): """ Called just before the server is actually launched. Plugins get supplied with the ``host`` and ``port`` the server will listen on. Note that the ``host`` may be ``0.0.0.0`` if it will listen on all interfaces, so you can't just blindly use this for constructing publicly reachable URLs. Also note that when this method is called, the server is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be externally reachable, use :func:`on_after_startup` instead or additionally. .. warning:: Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. The relevant sorting context is ``StartupPlugin.on_startup``. :param string host: the host the server will listen on, may be ``0.0.0.0`` :param int port: the port the server will listen on """ pass def on_after_startup(self): """ Called just after launch of the server, so when the listen loop is actually running already. .. warning:: Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. The relevant sorting context is ``StartupPlugin.on_after_startup``. """ pass class ShutdownPlugin(OctoPrintPlugin, SortablePlugin): """ The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the :class:`StartupPlugin` mixin, to cleanly shut down additional services again that where started by the :class:`StartupPlugin` part of the plugin. ``ShutdownPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin` and provides a sorting context for :meth:`~octoprint.plugin.ShutdownPlugin.on_shutdown`. """ def on_shutdown(self): """ Called upon the imminent shutdown of OctoPrint. .. warning:: Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. The relevant sorting context is ``ShutdownPlugin.on_shutdown``. """ pass class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin): """ The ``AssetPlugin`` mixin allows plugins to define additional static assets such as JavaScript or CSS files to be automatically embedded into the pages delivered by the server to be used within the client sided part of the plugin. A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used by templates injected through a :class:`TemplatePlugin`. ``AssetPlugin`` is a :class:`~octoprint.plugins.core.RestartNeedingPlugin`. """ def get_asset_folder(self): """ Defines the folder where the plugin stores its static assets as defined in :func:`get_assets`. Override this if your plugin stores its assets at some other place than the ``static`` sub folder in the plugin base directory. :return string: the absolute path to the folder where the plugin stores its static assets """ import os return os.path.join(self._basefolder, "static") def get_assets(self): """ Defines the static assets the plugin offers. The following asset types are recognized and automatically imported at the appropriate places to be available: js JavaScript files, such as additional view models jsclient JavaScript files containing additional parts for the JS Client Library (since 1.3.10) css CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode. less LESS files with additional styles, will be embedded into delivered pages when running in LESS mode. The expected format to be returned is a dictionary mapping one or more of these keys to a list of files of that type, the files being represented as relative paths from the asset folder as defined via :func:`get_asset_folder`. Example: .. code-block:: python def get_assets(self): return dict( js=['js/my_file.js', 'js/my_other_file.js'], clientjs=['clientjs/my_file.js'], css=['css/my_styles.css'], less=['less/my_styles.less'] ) The assets will be made available by OctoPrint under the URL ``/plugin/<plugin identifier>/static/<path>``, with ``plugin identifier`` being the plugin's identifier and ``path`` being the path as defined in the asset dictionary. Assets of the types ``js``, ``css`` and ``less`` will be automatically bundled by OctoPrint using `Flask-Assets <http://flask-assets.readthedocs.org/en/latest/>`_. :return dict: a dictionary describing the static assets to publish for the plugin """ return {} class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin): """ Using the ``TemplatePlugin`` mixin plugins may inject their own components into the OctoPrint web interface. Currently OctoPrint supports the following types of injections out of the box: Navbar The right part of the navigation bar located at the top of the UI can be enriched with additional links. Note that with the current implementation, plugins will always be located *to the left* of the existing links. The included template must be called ``<plugin identifier>_navbar.jinja2`` (e.g. ``myplugin_navbar.jinja2``) unless overridden by the configuration supplied through :func:`get_template_configs`. The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The wrapper structure will have all additional classes and styles applied as specified via the configuration supplied through :func:`get_template_configs`. Sidebar The left side bar containing Connection, State and Files sections can be enriched with additional sections. Note that with the current implementations, plugins will always be located *beneath* the existing sections. The included template must be called ``<plugin identifier>_sidebar.jinja2`` (e.g. ``myplugin_sidebar.jinja2``) unless overridden by the configuration supplied through :func:`get_template_configs`. The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The wrapper divs for both the whole box as well as the content pane will have all additional classes and styles applied as specified via the configuration supplied through :func:`get_template_configs`. Tabs The available tabs of the main part of the interface may be extended with additional tabs originating from within plugins. Note that with the current implementation, plugins will always be located *to the right* of the existing tabs. The included template must be called ``<plugin identifier>_tab.jinja2`` (e.g. ``myplugin_tab.jinja2``) unless overridden by the configuration supplied through :func:`get_template_configs`. The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The wrapper div and the link in the navigation will have the additional classes and styles applied as specified via the configuration supplied through :func:`get_template_configs`. Settings Plugins may inject a dialog into the existing settings view. Note that with the current implementation, plugins will always be listed beneath the "Plugins" header in the settings link list, ordered alphabetically after their displayed name. The included template must be called ``<plugin identifier>_settings.jinja2`` (e.g. ``myplugin_settings.jinja2``) unless overridden by the configuration supplied through :func:`get_template_configs`. The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The wrapper div and the link in the navigation will have the additional classes and styles applied as defined via the configuration through :func:`get_template_configs`. Webcam Plugins can provide a custom webcam view for watching a camera stream, which will be embedded into the "Control" panel of OctoPrint's default UI. The included template must be called ``<plugin identifier>_webcam.jinja2`` (e.g. ``myplugin_webcam.jinja2``) unless overridden by the configuration supplied through :func:`get_template_configs`. The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The wrapper div will have the additional classes and styles applied as defined via the configuration through :func:`get_template_configs`. .. versionadded:: 1.9.0 Wizards Plugins may define wizard dialogs to display to the user if necessary (e.g. in case of missing information that needs to be queried from the user to make the plugin work). Note that with the current implementation, all wizard dialogs will be will always be sorted by their ``mandatory`` attribute (which defaults to ``False``) and then alphabetically by their ``name``. Hence, mandatory wizard steps will come first, sorted alphabetically, then the optional steps will follow, also alphabetically. A wizard dialog provided through a plugin will only be displayed if the plugin reports the wizard as being required through :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required`. Please also refer to the :class:`~octoprint.plugin.WizardPlugin` mixin for further details on this. The included template must be called ``<plugin identifier>_wizard.jinja2`` (e.g. ``myplugin_wizard.jinja2``) unless overridden by the configuration supplied through :func:`get_template_configs`. The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The wrapper div and the link in the wizard navigation will have the additional classes and styles applied as defined via the configuration supplied through :func:`get_template_configs`. .. note:: A note about ``mandatory`` wizard steps: In the current implementation, marking a wizard step as mandatory will *only* make it styled accordingly. It is the task of the :ref:`view model <sec-plugins-viewmodels>` to actually prevent the user from skipping the dialog by implementing the ``onWizardTabChange`` callback and returning ``false`` there if it is detected that the user hasn't yet filled in the wizard step. .. versionadded:: 1.3.0 About Plugins may define additional panels into OctoPrint's "About" dialog. Note that with the current implementation further about dialog panels will be sorted alphabetically by their name and sorted after the predefined ones. The included template must be called ``<plugin identifier>_about.jinja2`` (e.g. ``myplugin_about.jinja2``) unless overridden by the configuration supplied through :func:`get_template_configs`. The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The wrapped div and the link in the navigation will have the additional classes and styles applied as defined via the configuration supplied through :func:`get_template_configs`. .. versionadded:: 1.3.0 Generic Plugins may also inject arbitrary templates into the page of the web interface itself, e.g. in order to add overlays or dialogs to be called from within the plugin's JavaScript code. .. figure:: ../images/template-plugin-types-main.png :align: center :alt: Template injection types in the main part of the interface Template injection types in the main part of the interface .. figure:: ../images/template-plugin-types-settings.png :align: center :alt: Template injection types in the settings Template injection types in the settings You can find an example for a simple plugin which injects navbar, tab and settings content into the interface in the "helloworld" plugin in OctoPrint's :ref:`Plugin Tutorial <sec-plugins-gettingstarted>`. Plugins may replace existing components, see the ``replaces`` keyword in the template configurations returned by :meth:`.get_template_configs` below. Note that if a plugin replaces a core component, it is the plugin's responsibility to ensure that all core functionality is still maintained. Plugins can also add additional template types by implementing the :ref:`octoprint.ui.web.templatetypes <sec-plugins-hook-ui-web-templatetypes>` hook. ``TemplatePlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`. """ @property def template_folder_key(self): return f"plugin_{self._identifier}" def get_template_configs(self): """ Allows configuration of injected navbar, sidebar, tab and settings templates (and also additional templates of types specified by plugins through the :ref:`octoprint.ui.web.templatetypes <sec-plugins-hook-ui-web-templatetypes>` hook). Should be a list containing one configuration object per template to inject. Each configuration object is represented by a dictionary which may contain the following keys: .. list-table:: :widths: 5 95 * - type - The template type the configuration is targeting. Possible values here are ``navbar``, ``sidebar``, ``tab``, ``settings`` and ``generic``. Mandatory. * - name - The name of the component, if not set the name of the plugin will be used. The name will be visible at a location depending on the ``type``: * ``navbar``: unused * ``sidebar``: sidebar heading * ``tab``: tab heading * ``settings``: settings link * ``wizard``: wizard link * ``about``: about link * ``generic``: unused * - template - Name of the template to inject, default value depends on the ``type``: * ``navbar``: ``<plugin identifier>_navbar.jinja2`` * ``sidebar``: ``<plugin identifier>_sidebar.jinja2`` * ``tab``: ``<plugin identifier>_tab.jinja2`` * ``settings``: ``<plugin identifier>_settings.jinja2`` * ``wizard``: ``<plugin identifier>_wizard.jinja2`` * ``about``: ``<plugin identifier>_about.jinja2`` * ``generic``: ``<plugin identifier>.jinja2`` * - suffix - Suffix to attach to the component identifier and the div identifier of the injected template. Will be ``_<index>`` if not provided and not the first template of the type, with ``index`` counting from 1 and increasing for each template of the same type. Example: If your plugin with identifier ``myplugin`` defines two tab components like this: .. code-block:: python return [ dict(type="tab", template="myplugin_first_tab.jinja2"), dict(type="tab", template="myplugin_second_tab.jinja2") ] then the first tab will have the component identifier ``plugin_myplugin`` and the second one will have the component identifier ``plugin_myplugin_2`` (the generated divs will be ``tab_plugin_myplugin`` and ``tab_plugin_myplugin_2`` accordingly). Notice that the first tab is *not* called ``plugin_myplugin_1`` -- as stated above while the ``index`` used as default suffix starts counting at 1, it will not be applied for the first component of a given type. If on the other hand your plugin's definition looks like this: .. code-block:: python return [ dict(type="tab", template="myplugin_first_tab_jinja2", suffix="_1st"), dict(type="tab", template="myplugin_second_tab_jinja2", suffix="_2nd") ] then the generated component identifier will be ``plugin_myplugin_1st`` and ``plugin_myplugin_2nd`` (and the divs will be ``tab_plugin_myplugin_1st`` and ``tab_plugin_myplugin_2nd``). * - div - Id for the div containing the component. If not provided, defaults to ``<type>_plugin_<plugin identifier>`` plus the ``suffix`` if provided or required. * - replaces - Id of the component this one replaces, might be either one of the core components or a component provided by another plugin. A list of the core component identifiers can be found :ref:`in the configuration documentation <sec-configuration-config_yaml-appearance>`. The identifiers of other plugin components always follow the format described above. * - custom_bindings - A boolean value indicating whether the default view model should be bound to the component (``false``) or if a custom binding will be used by the plugin (``true``, default). * - data_bind - Additional knockout data bindings to apply to the component, can be used to add further behaviour to the container based on internal state if necessary. * - classes - Additional classes to apply to the component, as a list of individual classes (e.g. ``classes=["myclass", "myotherclass"]``) which will be joined into the correct format by the template engine. * - styles - Additional CSS styles to apply to the component, as a list of individual declarations (e.g. ``styles=["color: red", "display: block"]``) which will be joined into the correct format by the template engine. Further keys to be included in the dictionary depend on the type: ``sidebar`` type .. list-table:: :widths: 5 95 * - icon - Icon to use for the sidebar header, should be the full name of a Font Awesome icon including the ``fas``/``far``/``fab`` prefix, eg. ``fas fa-plus``. * - template_header - Additional template to include in the head section of the sidebar item. For an example of this, see the additional options included in the "Files" section. * - classes_wrapper - Like ``classes`` but only applied to the whole wrapper around the sidebar box. * - classes_content - Like ``classes`` but only applied to the content pane itself. * - styles_wrapper - Like ``styles`` but only applied to the whole wrapper around the sidebar box. * - styles_content - Like ``styles`` but only applied to the content pane itself ``tab`` type and ``settings`` type .. list-table:: :widths: 5 95 * - classes_content - Like ``classes`` but only applied to the content pane itself. * - styles_content - Like ``styles`` but only applied to the content pane itself. * - classes_link - Like ``classes`` but only applied to the link in the navigation. * - styles_link - Like ``styles`` but only applied to the link in the navigation. ``webcam`` type .. list-table:: :widths: 5 95 * - classes_content - Like ``classes`` but only applied to the content pane itself. * - styles_content - Like ``styles`` but only applied to the content pane itself. ``wizard`` type .. list-table:: :widths: 5 95 * - mandatory - Whether the wizard step is mandatory (True) or not (False). Optional, defaults to False. If set to True, OctoPrint will sort visually mark the step as mandatory in the UI (bold in the navigation and a little alert) and also sort it into the first half. .. note:: As already outlined above, each template type has a default template name (i.e. the default navbar template of a plugin is called ``<plugin identifier>_navbar.jinja2``), which may be overridden using the template configuration. If a plugin needs to include more than one template of a given type, it needs to provide an entry for each of those, since the implicit default template will only be included automatically if no other templates of that type are defined. Example: If you have a plugin that injects two tab components, one defined in the template file ``myplugin_tab.jinja2`` (the default template) and one in the template ``myplugin_othertab.jinja2``, you might be tempted to just return the following configuration since one your templates is named by the default template name: .. code-block:: python return [ dict(type="tab", template="myplugin_othertab.jinja2") ] This will only include the tab defined in ``myplugin_othertab.jinja2`` though, ``myplugin_tab.jinja2`` will not be included automatically since the presence of a definition for the ``tab`` type overrides the automatic injection of the default template. You'll have to include it explicitly: .. code-block:: python return [ dict(type="tab", template="myplugin_tab.jinja2"), dict(type="tab", template="myplugin_othertab.jinja2") ] :return list: a list containing the configuration options for the plugin's injected templates """ return [] def get_template_vars(self): """ Defines additional template variables to include into the template renderer. Variable names will be prefixed with ``plugin_<plugin identifier>_``. :return dict: a dictionary containing any additional template variables to include in the renderer """ return {} def get_template_folder(self): """ Defines the folder where the plugin stores its templates. Override this if your plugin stores its templates at some other place than the ``templates`` sub folder in the plugin base directory. :return string: the absolute path to the folder where the plugin stores its jinja2 templates """ import os return os.path.join(self._basefolder, "templates") class UiPlugin(OctoPrintPlugin, SortablePlugin): """ The ``UiPlugin`` mixin allows plugins to completely replace the UI served by OctoPrint when requesting the main page hosted at `/`. OctoPrint will query whether your mixin implementation will handle a provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask `Request <https://flask.palletsprojects.com/api/#flask.Request>`_ object as parameter. If you plugin returns `True` here, OctoPrint will next call :meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like - again - the Flask Request object and the render keyword arguments as used by the default OctoPrint web interface. For more information see below. There are two methods used in order to allow for caching of the actual response sent to the client. Whatever a plugin implementation returns from the call to its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method will be cached server side. The cache will be emptied in case of explicit no-cache headers sent by the client, or if the ``_refresh`` query parameter on the request exists and is set to ``true``. To prevent caching of the response altogether, a plugin may set no-cache headers on the returned response as well. ``UiPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin` with a sorting context for :meth:`~octoprint.plugin.UiPlugin.will_handle_ui`. The first plugin to return ``True`` for :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` will be the one whose ui will be used, no further calls to :meth:`~octoprint.plugin.UiPlugin.on_ui_render` will be performed. If implementations want to serve custom templates in the :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method it is recommended to also implement the :class:`~octoprint.plugin.TemplatePlugin` mixin. **Example** What follows is a very simple example that renders a different (non functional and only exemplary) UI if the requesting client has a UserAgent string hinting at it being a mobile device: .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/__init__.py :tab-width: 4 :caption: `dummy_mobile_ui/__init__.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui/__init__.py>`_ .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 :tab-width: 4 :caption: `dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2>`_ Try installing the above plugin ``dummy_mobile_ui`` (also available in the `plugin examples repository <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui>`_) into your OctoPrint instance. If you access it from a regular desktop browser, you should still see the default UI. However if you access it from a mobile device (make sure to not have that request the desktop version of pages!) you should see the very simple dummy page defined above. **Preemptive and Runtime Caching** OctoPrint will also cache your custom UI for you in its server side UI cache, making sure it only gets re-rendered if the request demands that (by having no-cache headers set) or if the cache gets invalidated otherwise. In order to be able to do that, the ``UiPlugin`` offers overriding some cache specific methods used for figuring out the source files whose modification time to use for cache invalidation as well as override possibilities for ETag and LastModified calculation. Additionally there are methods to allow persisting call parameters to allow for preemptively caching your UI during server startup (basically eager caching instead of lazily waiting for the first request). See below for details on this. .. versionadded:: 1.3.0 """ # noinspection PyMethodMayBeStatic,PyUnusedLocal def will_handle_ui(self, request): """ Called by OctoPrint to determine if the mixin implementation will be able to handle the ``request`` provided as a parameter. Return ``True`` here to signal that your implementation will handle the request and that the result of its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method is what should be served to the user. The execution order of calls to this method can be influenced via the sorting context ``UiPlugin.will_handle_ui``. Arguments: request (flask.Request): A Flask `Request <https://flask.palletsprojects.com/api/#flask.Request>`_ object. Returns: bool: ``True`` if the implementation will serve the request, ``False`` otherwise. """ return False # noinspection PyMethodMayBeStatic,PyUnusedLocal def on_ui_render(self, now, request, render_kwargs): """ Called by OctoPrint to retrieve the response to send to the client for the ``request`` to ``/``. Only called if :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` returned ``True``. ``render_kwargs`` will be a dictionary (whose contents are cached) which will contain the following key and value pairs (note that not all key value pairs contained in the dictionary are listed here, only those you should depend on as a plugin developer at the current time): .. list-table:: :widths: 5 95 * - debug - ``True`` if debug mode is enabled, ``False`` otherwise. * - firstRun - ``True`` if the server is being run for the first time (not configured yet), ``False`` otherwise. * - version - OctoPrint's version information. This is a ``dict`` with the following keys: .. list-table:: :widths: 5 95 * - number - The version number (e.g. ``x.y.z``) * - branch - The GIT branch from which the OctoPrint instance was built (e.g. ``master``) * - display - The full human readable version string, including the branch information (e.g. ``x.y.z (master branch)`` * - uiApiKey - The UI API key to use for unauthorized API requests. This is freshly generated on every server restart. * - templates - Template data to render in the UI. Will be a ``dict`` containing entries for all known template types. The sub structure for each key will be as follows: .. list-table:: :widths: 5 95 * - order - A list of template names in the order they should appear in the final rendered page * - entries - The template entry definitions to render. Depending on the template type those are either 2-tuples of a name and a ``dict`` or directly ``dicts`` with information regarding the template to render. For the possible contents of the data ``dicts`` see the :class:`~octoprint.plugin.TemplatePlugin` mixin. * - pluginNames - A list of names of :class:`~octoprint.plugin.TemplatePlugin` implementation that were enabled when creating the ``templates`` value. * - locales - The locales for which there are translations available. * - supportedExtensions - The file extensions supported for uploads. On top of that all additional template variables as provided by :meth:`~octoprint.plugin.TemplatePlugin.get_template_vars` will be contained in the dictionary as well. Arguments: now (datetime.datetime): The datetime instance representing "now" for this request, in case your plugin implementation needs this information. request (flask.Request): A Flask `Request <https://flask.palletsprojects.com/api/#flask.Request>`_ object. render_kwargs (dict): The (cached) render keyword arguments that would usually be provided to the core UI render function. Returns: flask.Response: Should return a Flask `Response <https://flask.palletsprojects.com/api/#flask.Response>`_ object that can be served to the requesting client directly. May be created with ``flask.make_response`` combined with something like ``flask.render_template``. """ return None # noinspection PyMethodMayBeStatic def get_ui_additional_key_data_for_cache(self): """ Allows to return additional data to use in the cache key. Returns: list, tuple: A list or tuple of strings to use in the cache key. Will be joined by OctoPrint using ``:`` as separator and appended to the existing ``ui:<identifier>:<base url>:<locale>`` cache key. Ignored if ``None`` is returned. .. versionadded:: 1.3.0 """ return None # noinspection PyMethodMayBeStatic def get_ui_additional_tracked_files(self): """ Allows to return additional files to track for validating existing caches. By default OctoPrint will track all declared templates, assets and translation files in the system. Additional files can be added by a plugin through this callback. Returns: list: A list of paths to additional files whose modification to track for (in)validating the cache. Ignored if ``None`` is returned. .. versionadded:: 1.3.0 """ return None # noinspection PyMethodMayBeStatic def get_ui_custom_tracked_files(self): """ Allows to define a complete separate set of files to track for (in)validating the cache. If this method returns something, the templates, assets and translation files won't be tracked, only the files specified in the returned list. Returns: list: A list of paths representing the only files whose modification to track for (in)validating the cache. Ignored if ``None`` is returned. .. versionadded:: 1.3.0 """ return None # noinspection PyMethodMayBeStatic def get_ui_custom_etag(self): """ Allows to use a custom way to calculate the ETag, instead of the default method (hashing OctoPrint's version, tracked file paths and ``LastModified`` value). Returns: str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). .. versionadded:: 1.3.0 """ return None # noinspection PyMethodMayBeStatic def get_ui_additional_etag(self, default_additional): """ Allows to provide a list of additional fields to use for ETag generation. By default the same list will be returned that is also used in the stock UI (and injected via the parameter ``default_additional``). Arguments: default_additional (list): The list of default fields added to the ETag of the default UI Returns: (list): A list of additional fields for the ETag generation, or None .. versionadded:: 1.3.0 """ return default_additional # noinspection PyMethodMayBeStatic def get_ui_custom_lastmodified(self): """ Allows to calculate the LastModified differently than using the most recent modification date of all tracked files. Returns: int: An alternatively calculated LastModified value. Ignored if ``None`` is returned (default). .. versionadded:: 1.3.0 """ return None # noinspection PyMethodMayBeStatic def get_ui_preemptive_caching_enabled(self): """ Allows to control whether the view provided by the plugin should be preemptively cached on server startup (default) or not. Have this return False if you do not want your plugin's UI to ever be preemptively cached. Returns: bool: Whether to enable preemptive caching (True, default) or not (False) """ return True # noinspection PyMethodMayBeStatic def get_ui_data_for_preemptive_caching(self): """ Allows defining additional data to be persisted in the preemptive cache configuration, on top of the request path, base URL and used locale. Returns: dict: Additional data to persist in the preemptive cache configuration. .. versionadded:: 1.3.0 """ return None # noinspection PyMethodMayBeStatic def get_ui_additional_request_data_for_preemptive_caching(self): """ Allows defining additional request data to persist in the preemptive cache configuration and to use for the fake request used for populating the preemptive cache. Keys and values are used as keyword arguments for creating the `Werkzeug EnvironBuilder <http://werkzeug.pocoo.org/docs/0.11/test/#werkzeug.test.EnvironBuilder>`_ used for creating the fake request. Returns: dict: Additional request data to persist in the preemptive cache configuration and to use for request environment construction. .. versionadded:: 1.3.0 """ return None # noinspection PyMethodMayBeStatic def get_ui_preemptive_caching_additional_unless(self): """ Allows defining additional reasons for temporarily not adding a preemptive cache record for your plugin's UI. OctoPrint will call this method when processing a UI request, to determine whether to record the access or not. If you return ``True`` here, no record will be created. Returns: bool: Whether to suppress a record (True) or not (False, default) .. versionadded:: 1.3.0 """ return False # noinspection PyMethodMayBeStatic def get_ui_custom_template_filter(self, default_template_filter): """ Allows to specify a custom template filter to use for filtering the template contained in the ``render_kwargs`` provided to the templating sub system. Only relevant for UiPlugins that actually utilize the stock templates of OctoPrint. By default simply returns the provided ``default_template_filter``. Arguments: default_template_filter (callable): The default template filter used by the default UI Returns: (callable) A filter function accepting the ``template_type`` and ``template_key`` of a template and returning ``True`` to keep it and ``False`` to filter it out. If ``None`` is returned, no filtering will take place. .. versionadded:: 1.3.0 """ return default_template_filter # noinspection PyMethodMayBeStatic def get_ui_permissions(self): """ Determines a list of permissions that need to be on the current user session. If these requirements are not met, OctoPrint will instead redirect to a login screen. Plugins may override this with their own set of permissions. Returning an empty list will instruct OctoPrint to never show a login dialog when this UiPlugin's view renders, in which case it will fall to your plugin to implement its own login logic. Returns: (list) A list of permissions which to check the current user session against. May be empty to indicate that no permission checks should be made by OctoPrint. .. versionadded: 1.5.0 """ from octoprint.access.permissions import Permissions return [Permissions.STATUS, Permissions.SETTINGS_READ] class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin): """ The ``WizardPlugin`` mixin allows plugins to report to OctoPrint whether the ``wizard`` templates they define via the :class:`~octoprint.plugin.TemplatePlugin` should be displayed to the user, what details to provide to their respective wizard frontend components and what to do when the wizard is finished by the user. OctoPrint will only display such wizard dialogs to the user which belong to plugins that * report ``True`` in their :func:`is_wizard_required` method and * have not yet been shown to the user in the version currently being reported by the :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version` method Example: If a plugin with the identifier ``myplugin`` has a specific setting ``some_key`` it needs to have filled by the user in order to be able to work at all, it would probably test for that setting's value in the :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required` method and return ``True`` if the value is unset: .. code-block:: python class MyPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.WizardPlugin): def get_default_settings(self): return dict(some_key=None) def is_wizard_required(self): return self._settings.get(["some_key"]) is None OctoPrint will then display the wizard dialog provided by the plugin through the :class:`TemplatePlugin` mixin. Once the user finishes the wizard on the frontend, OctoPrint will store that it already showed the wizard of ``myplugin`` in the version reported by :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version` - here ``None`` since that is the default value returned by that function and the plugin did not override it. If the plugin in a later version needs another setting from the user in order to function, it will also need to change the reported version in order to have OctoPrint reshow the dialog. E.g. .. code-block:: python class MyPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.WizardPlugin): def get_default_settings(self): return dict(some_key=None, some_other_key=None) def is_wizard_required(self): some_key_unset = self._settings.get(["some_key"]) is None some_other_key_unset = self._settings.get(["some_other_key"]) is None return some_key_unset or some_other_key_unset def get_wizard_version(self): return 1 ``WizardPlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`. """ # noinspection PyMethodMayBeStatic def is_wizard_required(self): """ Allows the plugin to report whether it needs to display a wizard to the user or not. Defaults to ``False``. OctoPrint will only include those wizards from plugins which are reporting their wizards as being required through this method returning ``True``. Still, if OctoPrint already displayed that wizard in the same version to the user once it won't be displayed again regardless whether this method returns ``True`` or not. """ return False # noinspection PyMethodMayBeStatic def get_wizard_version(self): """ The version of this plugin's wizard. OctoPrint will only display a wizard of the same plugin and wizard version once to the user. After they finish the wizard, OctoPrint will remember that it already showed this wizard in this particular version and not reshow it. If a plugin needs to show its wizard to the user again (e.g. because of changes in the required settings), increasing this value is the way to notify OctoPrint of these changes. Returns: int or None: an int signifying the current wizard version, should be incremented by plugins whenever there are changes to the plugin that might necessitate reshowing the wizard if it is required. ``None`` will also be accepted and lead to the wizard always be ignored unless it has never been finished so far """ return None # noinspection PyMethodMayBeStatic def get_wizard_details(self): """ Called by OctoPrint when the wizard wrapper dialog is shown. Allows the plugin to return data that will then be made available to the view models via the view model callback ``onWizardDetails``. Use this if your plugin's view model that handles your wizard dialog needs additional data to perform its task. Returns: dict: a dictionary containing additional data to provide to the frontend. Whatever the plugin returns here will be made available on the wizard API under the plugin's identifier """ return {} # noinspection PyMethodMayBeStatic,PyUnusedLocal def on_wizard_finish(self, handled): """ Called by OctoPrint whenever the user finishes a wizard session. The ``handled`` parameter will indicate whether that plugin's wizard was included in the wizard dialog presented to the user (so the plugin providing it was reporting that the wizard was required and the wizard plus version was not ignored/had already been seen). Use this to do any clean up tasks necessary after wizard completion. Arguments: handled (bool): True if the plugin's wizard was previously reported as required, not ignored and thus presented to the user, False otherwise """ pass # noinspection PyProtectedMember @classmethod def is_wizard_ignored(cls, seen_wizards, implementation): """ Determines whether the provided implementation is ignored based on the provided information about already seen wizards and their versions or not. A wizard is ignored if * the current and seen versions are identical * the current version is None and the seen version is not * the seen version is not None and the current version is less or equal than the seen one .. code-block:: none | current | | N | 1 | 2 | N = None ----+---+---+---+ X = ignored s N | X | | | e --+---+---+---+ e 1 | X | X | | n --+---+---+---+ 2 | X | X | X | ----+---+---+---+ Arguments: seen_wizards (dict): A dictionary with information about already seen wizards and their versions. Mappings from the identifiers of the plugin providing the wizard to the reported wizard version (int or None) that was already seen by the user. implementation (object): The plugin implementation to check. Returns: bool: False if the provided ``implementation`` is either not a :class:`WizardPlugin` or has not yet been seen (in this version), True otherwise """ if not isinstance(implementation, cls): return False name = implementation._identifier if name not in seen_wizards: return False seen = seen_wizards[name] wizard_version = implementation.get_wizard_version() current = None if wizard_version is not None: try: current = int(wizard_version) except ValueError as e: import logging logging.getLogger(__name__).log( "WizardPlugin {} returned invalid value {} for wizard version: {}".format( name, wizard_version, str(e) ) ) return ( (current == seen) or (current is None and seen is not None) or (seen is not None and current <= seen) ) class SimpleApiPlugin(OctoPrintPlugin): """ Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one resource accepting JSON commands POSTed to it. This is the easy alternative for plugin's which don't need the full power of a `Flask Blueprint <https://flask.palletsprojects.com/blueprints/>`_ that the :class:`BlueprintPlugin` mixin offers. Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend and/or want to react to simple commands which boil down to a type of command and a few flat parameters supplied with it. The simple API constructed by OctoPrint for you will be made available under ``/api/plugin/<plugin identifier>/``. OctoPrint will do some preliminary request validation for your defined commands, making sure the request body is in the correct format (content type must be JSON) and contains all obligatory parameters for your command. Let's take a look at a small example for such a simple API and how you would go about calling it. Take this example of a plugin registered under plugin identifier ``mysimpleapiplugin``: .. code-block:: python import octoprint.plugin import flask class MySimpleApiPlugin(octoprint.plugin.SimpleApiPlugin): def get_api_commands(self): return dict( command1=[], command2=["some_parameter"] ) def on_api_command(self, command, data): import flask if command == "command1": parameter = "unset" if "parameter" in data: parameter = "set" self._logger.info("command1 called, parameter is {parameter}".format(**locals())) elif command == "command2": self._logger.info("command2 called, some_parameter is {some_parameter}".format(**data)) def on_api_get(self, request): return flask.jsonify(foo="bar") __plugin_implementation__ = MySimpleApiPlugin() Our plugin defines two commands, ``command1`` with no mandatory parameters and ``command2`` with one mandatory parameter ``some_parameter``. ``command1`` can also accept an optional parameter ``parameter``, and will log whether that parameter was set or unset. ``command2`` will log the content of the mandatory ``some_parameter`` parameter. A valid POST request for ``command2`` sent to ``/api/plugin/mysimpleapiplugin`` would look like this: .. sourcecode:: http POST /api/plugin/mysimpleapiplugin HTTP/1.1 Host: example.com Content-Type: application/json X-Api-Key: abcdef... { "command": "command2", "some_parameter": "some_value", "some_optional_parameter": 2342 } which would produce a response like this: .. sourcecode:: http HTTP/1.1 204 No Content and print something like this line to ``octoprint.log``:: 2015-02-12 17:40:21,140 - octoprint.plugins.mysimpleapiplugin - INFO - command2 called, some_parameter is some_value A GET request on our plugin's simple API resource will only return a JSON document like this: .. sourcecode:: http HTTP/1.1 200 Ok Content-Type: application/json { "foo": "bar" } """ # noinspection PyMethodMayBeStatic def get_api_commands(self): """ Return a dictionary here with the keys representing the accepted commands and the values being lists of mandatory parameter names. """ return None # noinspection PyMethodMayBeStatic def is_api_adminonly(self): """ Return True if the API is only available to users having the admin role. """ return False # noinspection PyMethodMayBeStatic def on_api_command(self, command, data): """ Called by OctoPrint upon a POST request to ``/api/plugin/<plugin identifier>``. ``command`` will contain one of the commands as specified via :func:`get_api_commands`, ``data`` will contain the full request body parsed from JSON into a Python dictionary. Note that this will also contain the ``command`` attribute itself. For the example given above, for the ``command2`` request the ``data`` received by the plugin would be equal to ``dict(command="command2", some_parameter="some_value")``. If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` for you. You may also return regular responses as you would return from any Flask view here though, e.g. ``return flask.jsonify(result="some json result")`` or ``flask.abort(404)``. :param string command: the command with which the resource was called :param dict data: the full request body of the POST request parsed from JSON into a Python dictionary :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally a proper Flask response. """ return None # noinspection PyMethodMayBeStatic def on_api_get(self, request): """ Called by OctoPrint upon a GET request to ``/api/plugin/<plugin identifier>``. ``request`` will contain the received `Flask request object <https://flask.palletsprojects.com/api/#flask.Request>`_ which you may evaluate for additional arguments supplied with the request. If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` for you. You may also return regular responses as you would return from any Flask view here though, e.g. ``return flask.jsonify(result="some json result")`` or ``flask.abort(404)``. :param request: the Flask request object :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally a proper Flask response. """ return None class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): """ The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose, be it a more sophisticated API than what is possible via the :class:`SimpleApiPlugin` or a custom web frontend. The mechanism at work here is `Flask's <https://flask.palletsprojects.com/>`_ own `Blueprint mechanism <https://flask.palletsprojects.com/blueprints/>`_. The mixin automatically creates a blueprint for you that will be registered under ``/plugin/<plugin identifier>/``. All you need to do is decorate all of your view functions with the :func:`route` decorator, which behaves exactly the same like Flask's regular ``route`` decorators. Example: .. code-block:: python import octoprint.plugin import flask class MyBlueprintPlugin(octoprint.plugin.BlueprintPlugin): @octoprint.plugin.BlueprintPlugin.route("/echo", methods=["GET"]) def myEcho(self): if not "text" in flask.request.values: abort(400, description="Expected a text to echo back.") return flask.request.values["text"] __plugin_implementation__ = MyBlueprintPlugin() Your blueprint will be published by OctoPrint under the base URL ``/plugin/<plugin identifier>/``, so the above example of a plugin with the identifier "myblueprintplugin" would be reachable under ``/plugin/myblueprintplugin/echo``. Just like with regular blueprints you'll be able to create URLs via ``url_for``, just use the prefix ``plugin.<plugin identifier>.<method_name>``, e.g.: .. code-block:: python flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo" .. warning:: As of OctoPrint 1.8.3, endpoints provided through a ``BlueprintPlugin`` do **not** automatically fall under OctoPrint's :ref:`CSRF protection <sec-api-general-csrf>`, for reasons of backwards compatibility. There will be a short grace period before this changes. You can and should however already opt into CSRF protection for your endpoints by implementing ``is_blueprint_csrf_protected`` and returning ``True`` from it. You can exempt certain endpoints from CSRF protection by decorating them with ``@octoprint.plugin.BlueprintPlugin.csrf_exempt``. .. code-block:: python class MyPlugin(octoprint.plugin.BlueprintPlugin): @octoprint.plugin.BlueprintPlugin.route("/hello_world", methods=["GET"]) def hello_world(self): # This is a GET request and thus not subject to CSRF protection return "Hello world!" @octoprint.plugin.BlueprintPlugin.route("/hello_you", methods=["POST"]) def hello_you(self): # This is a POST request and thus subject to CSRF protection. It is not exempt. return "Hello you!" @octoprint.plugin.BlueprintPlugin.route("/hello_me", methods=["POST"]) @octoprint.plugin.BlueprintPlugin.csrf_exempt() def hello_me(self): # This is a POST request and thus subject to CSRF protection, but this one is exempt. return "Hello me!" def is_blueprint_csrf_protected(self): return True ``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`. .. versionchanged:: 1.8.3 """ @staticmethod def route(rule, **options): """ A decorator to mark view methods in your BlueprintPlugin subclass. Works just the same as Flask's own ``route`` decorator available on blueprints. See `the documentation for flask.Blueprint.route <https://flask.palletsprojects.com/api/#flask.Blueprint.route>`_ and `the documentation for flask.Flask.route <https://flask.palletsprojects.com/api/#flask.Flask.route>`_ for more information. """ from collections import defaultdict def decorator(f): # We attach the decorator parameters directly to the function object, because that's the only place # we can access right now. # This neat little trick was adapted from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/ if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None: f._blueprint_rules = defaultdict(list) f._blueprint_rules[f.__name__].append((rule, options)) return f return decorator @staticmethod def errorhandler(code_or_exception): """ A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's own ``errorhandler`` decorator available on blueprints. See `the documentation for flask.Blueprint.errorhandler <https://flask.palletsprojects.com/api/#flask.Blueprint.errorhandler>`_ and `the documentation for flask.Flask.errorhandler <https://flask.palletsprojects.com/api/#flask.Flask.errorhandler>`_ for more information. .. versionadded:: 1.3.0 """ from collections import defaultdict def decorator(f): if ( not hasattr(f, "_blueprint_error_handler") or f._blueprint_error_handler is None ): f._blueprint_error_handler = defaultdict(list) f._blueprint_error_handler[f.__name__].append(code_or_exception) return f return decorator @staticmethod def csrf_exempt(): """ A decorator to mark a view method in your BlueprintPlugin as exempt from :ref:`CSRF protection <sec-api-general-csrf>`. This makes sense if you offer an authenticated API for a certain workflow (see e.g. the bundled appkeys plugin) but in most cases should not be needed. .. versionadded:: 1.8.3 """ def decorator(f): if ( not hasattr(f, "_blueprint_csrf_exempt") or f._blueprint_csrf_exempt is None ): f._blueprint_csrf_exempt = set() f._blueprint_csrf_exempt.add(f.__name__) return f return decorator # noinspection PyProtectedMember def get_blueprint(self): """ Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself. This method will only be called once during server initialization. :return: the blueprint ready to be registered with Flask """ if hasattr(self, "_blueprint"): # if we already constructed the blueprint and hence have it cached, # return that instance - we don't want to instance it multiple times return self._blueprint import flask from octoprint.server.util.csrf import add_exempt_view kwargs = self.get_blueprint_kwargs() blueprint = flask.Blueprint(self._identifier, self._identifier, **kwargs) # we now iterate over all members of ourselves and look if we find an attribute # that has data originating from one of our decorators - we ignore anything # starting with a _ to only handle public stuff for member in [x for x in dir(self) if not x.startswith("_")]: f = getattr(self, member) if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules: # this attribute was annotated with our @route decorator for blueprint_rule in f._blueprint_rules[member]: rule, options = blueprint_rule endpoint = options.pop("endpoint", f.__name__) blueprint.add_url_rule(rule, endpoint, view_func=f, **options) if ( hasattr(f, "_blueprint_csrf_exempt") and member in f._blueprint_csrf_exempt ): add_exempt_view(f"plugin.{self._identifier}.{endpoint}") if ( hasattr(f, "_blueprint_error_handler") and member in f._blueprint_error_handler ): # this attribute was annotated with our @error_handler decorator for code_or_exception in f._blueprint_error_handler[member]: blueprint.errorhandler(code_or_exception)(f) # cache and return the blueprint object self._blueprint = blueprint return blueprint def get_blueprint_kwargs(self): """ Override this if you want your blueprint constructed with additional options such as ``static_folder``, ``template_folder``, etc. Defaults to the blueprint's ``static_folder`` and ``template_folder`` to be set to the plugin's basefolder plus ``/static`` or respectively ``/templates``, or -- if the plugin also implements :class:`AssetPlugin` and/or :class:`TemplatePlugin` -- the paths provided by ``get_asset_folder`` and ``get_template_folder`` respectively. """ import os if isinstance(self, AssetPlugin): static_folder = self.get_asset_folder() else: static_folder = os.path.join(self._basefolder, "static") if isinstance(self, TemplatePlugin): template_folder = self.get_template_folder() else: template_folder = os.path.join(self._basefolder, "templates") return {"static_folder": static_folder, "template_folder": template_folder} # noinspection PyMethodMayBeStatic def is_blueprint_protected(self): """ Whether a login session by a registered user is needed to access the blueprint's endpoints. Requiring a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files are always accessible. If you want your blueprint's endpoints to have specific permissions, return ``False`` for this and do your permissions checks explicitly. """ return True # noinspection PyMethodMayBeStatic def is_blueprint_csrf_protected(self): """ Whether a blueprint's endpoints are :ref:`CSRF protected <sec-api-general-csrf>`. For now, this defaults to ``False`` to leave it up to plugins to decide which endpoints *should* be protected. Long term, this will default to ``True`` and hence enforce protection unless a plugin opts out by returning False here. If you do not override this method in your mixin implementation, a warning will be logged to the console to alert you of the requirement to make a decision here and to not rely on the default implementation, due to the forthcoming change in implemented default behaviour. .. versionadded:: 1.8.3 """ self._logger.warning( "The Blueprint of this plugin is relying on the default implementation of " "is_blueprint_csrf_protected (newly added in OctoPrint 1.8.3), which in a future version will " "be switched from False to True for security reasons. Plugin authors should ensure they explicitly " "declare the CSRF protection status in their BlueprintPlugin mixin implementation. " "Recommendation is to enable CSRF protection and exempt views that must not use it with the " "octoprint.plugin.BlueprintPlugin.csrf_exempt decorator." ) return False # noinspection PyMethodMayBeStatic def get_blueprint_api_prefixes(self): """ Return all prefixes of your endpoint that are an API that should be containing JSON only. Anything that matches this will generate JSON error messages in case of flask.abort calls, instead of the default HTML ones. Defaults to all endpoints under the blueprint. Limit this further as needed. E.g., if you only want your endpoints /foo, /foo/1 and /bar to be declared as API, return ``["/foo", "/bar"]``. A match will be determined via startswith. """ return [""] class SettingsPlugin(OctoPrintPlugin): """ Including the ``SettingsPlugin`` mixin allows plugins to store and retrieve their own settings within OctoPrint's configuration. Plugins including the mixin will get injected an additional property ``self._settings`` which is an instance of :class:`PluginSettingsManager` already properly initialized for use by the plugin. In order for the manager to know about the available settings structure and default values upon initialization, implementing plugins will need to provide a dictionary with the plugin's default settings through overriding the method :func:`get_settings_defaults`. The defined structure will then be available to access through the settings manager available as ``self._settings``. .. note:: Use the settings only to store configuration data or information that is relevant to the UI. Anything in the settings is part of the hash that is used to determine whether a client's copy of the UI is still up to date or not. If you store unrelated and possibly often changing information in the settings, you will force the client to reload the UI without visible changes, which will lead to a bad user experience. You may store additional data in your plugin's data folder instead, which is not part of the hash and whose path can be retrieved through :func:`~ octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`, e.g.: .. code-block:: python data_folder = self.get_plugin_data_folder() with open(os.path.join(data_folder, "some_file.txt"), "w") as f: f.write("some data") If your plugin needs to react to the change of specific configuration values on the fly, e.g. to adjust the log level of a logger when the user changes a corresponding flag via the settings dialog, you can override the :func:`on_settings_save` method and wrap the call to the implementation from the parent class with retrieval of the old and the new value and react accordingly. Example: .. code-block:: python import octoprint.plugin class MySettingsPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin): def get_settings_defaults(self): return dict( some_setting="foo", some_value=23, sub=dict( some_flag=True ) ) def on_settings_save(self, data): old_flag = self._settings.get_boolean(["sub", "some_flag"]) octoprint.plugin.SettingsPlugin.on_settings_save(self, data) new_flag = self._settings.get_boolean(["sub", "some_flag"]) if old_flag != new_flag: self._logger.info("sub.some_flag changed from {old_flag} to {new_flag}".format(**locals())) def on_after_startup(self): some_setting = self._settings.get(["some_setting"]) some_value = self._settings.get_int(["some_value"]) some_flag = self._settings.get_boolean(["sub", "some_flag"]) self._logger.info("some_setting = {some_setting}, some_value = {some_value}, sub.some_flag = {some_flag}".format(**locals()) __plugin_implementation__ = MySettingsPlugin() Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the default implementations do not fit your requirements. .. warning:: Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users) should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will return its settings on the REST API even to anonymous clients, but will filter out fields it knows are restricted, therefore you **must** make sure that you specify sensitive information accordingly to limit access as required! """ config_version_key = "_config_version" """Key of the field in the settings that holds the configuration format version.""" # noinspection PyMissingConstructor def __init__(self): self._settings = None """ The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by the plugin core system upon initialization of the implementation. """ def on_settings_load(self): """ Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from all plugins. Override this if you want to inject additional settings properties that are not stored within OctoPrint's configuration. .. note:: The default implementation will return your plugin's settings as is, so just in the structure and in the types that are currently stored in OctoPrint's configuration. If you need more granular control here, e.g. over the used data types, you'll need to override this method and iterate yourself over all your settings, using the proper retriever methods on the settings manager to retrieve the data in the correct format. The default implementation will also replace any paths that have been restricted by your plugin through :func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with either the provided default value (if one was provided), an empty dictionary (as fallback for restricted dictionaries), an empty list (as fallback for restricted lists) or ``None`` values where necessary. Make sure to do your own restriction if you decide to fully overload this method. :return: the current settings of the plugin, as a dictionary """ import copy from flask_login import current_user from octoprint.access.permissions import OctoPrintPermission, Permissions data = copy.deepcopy(self._settings.get_all_data(merged=True)) if self.config_version_key in data: del data[self.config_version_key] restricted_paths = self.get_settings_restricted_paths() # noinspection PyShadowingNames def restrict_path_unless(data, path, condition): if not path: return if condition(): return node = data if len(path) > 1: for entry in path[:-1]: if entry not in node: return node = node[entry] key = path[-1] default_value_available = False default_value = None if isinstance(key, (list, tuple)): # key, default_value tuple key, default_value = key default_value_available = True if key in node: if default_value_available: if callable(default_value): default_value = default_value() node[key] = default_value else: if isinstance(node[key], dict): node[key] = {} elif isinstance(node[key], (list, tuple)): node[key] = [] else: node[key] = None conditions = { "user": lambda: current_user is not None and not current_user.is_anonymous, "admin": lambda: current_user is not None and current_user.has_permission(Permissions.SETTINGS), "never": lambda: False, } for level, paths in restricted_paths.items(): if isinstance(level, OctoPrintPermission): condition = lambda: ( current_user is not None and current_user.has_permission(level) ) else: condition = conditions.get(level, lambda: False) for path in paths: restrict_path_unless(data, path, condition) return data def on_settings_save(self, data): """ Saves the settings for the plugin, called by the Settings API view in order to persist all settings from all plugins. Override this if you need to directly react to settings changes or want to extract additional settings properties that are not stored within OctoPrint's configuration. .. note:: The default implementation will persist your plugin's settings as is, so just in the structure and in the types that were received by the Settings API view. Values identical to the default settings values will *not* be persisted. If you need more granular control here, e.g. over the used data types, you'll need to override this method and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data`` and using the proper setter methods on the settings manager to persist the data in the correct format. Arguments: data (dict): The settings dictionary to be saved for the plugin Returns: dict: The settings that differed from the defaults and were actually saved. """ import octoprint.util # get the current data current = self._settings.get_all_data() if current is None: current = {} # merge our new data on top of it new_current = octoprint.util.dict_merge(current, data) if self.config_version_key in new_current: del new_current[self.config_version_key] # determine diff dict that contains minimal set of changes against the # default settings - we only want to persist that, not everything diff = octoprint.util.dict_minimal_mergediff( self.get_settings_defaults(), new_current ) version = self.get_settings_version() to_persist = dict(diff) if version: to_persist[self.config_version_key] = version if to_persist: self._settings.set([], to_persist) else: self._settings.clean_all_data() return diff # noinspection PyMethodMayBeStatic def get_settings_defaults(self): """ Retrieves the plugin's default settings with which the plugin's settings manager will be initialized. Override this in your plugin's implementation and return a dictionary defining your settings data structure with included default values. """ return {} # noinspection PyMethodMayBeStatic def get_settings_restricted_paths(self): """ Retrieves the list of paths in the plugin's settings which be restricted on the REST API. Override this in your plugin's implementation to restrict whether a path should only be returned to users with certain permissions, or never on the REST API. Return a ``dict`` with one of the following keys, mapping to a list of paths (as tuples or lists of the path elements) for which to restrict access via the REST API accordingly. * An :py:class:`~octoprint.access.permissions.OctoPrintPermission` instance: Paths will only be available on the REST API for users with the permission * ``admin``: Paths will only be available on the REST API for users with admin rights (any user with the SETTINGS permission) * ``user``: Paths will only be available on the REST API when accessed as a logged in user * ``never``: Paths will never be returned on the API Example: .. code-block:: python def get_settings_defaults(self): return dict(some=dict(admin_only=dict(path="path", foo="foo"), user_only=dict(path="path", bar="bar")), another=dict(admin_only=dict(path="path"), field="field"), path=dict(to=dict(never=dict(return="return"))), the=dict(webcam=dict(data="webcam"))) def get_settings_restricted_paths(self): from octoprint.access.permissions import Permissions return {'admin':[["some", "admin_only", "path"], ["another", "admin_only", "path"],], 'user':[["some", "user_only", "path"],], 'never':[["path", "to", "never", "return"],], Permissions.WEBCAM:[["the", "webcam", "data"],]} # this will make the plugin return settings on the REST API like this for an anonymous user # # dict(some=dict(admin_only=dict(path=None, foo="foo"), # user_only=dict(path=None, bar="bar")), # another=dict(admin_only=dict(path=None), # field="field"), # path=dict(to=dict(never=dict(return=None))), # the=dict(webcam=dict(data=None))) # # like this for a logged in user without the webcam permission # # dict(some=dict(admin_only=dict(path=None, foo="foo"), # user_only=dict(path="path", bar="bar")), # another=dict(admin_only=dict(path=None), # field="field"), # path=dict(to=dict(never=dict(return=None))), # the=dict(webcam=dict(data=None))) # # like this for a logged in user with the webcam permission # # dict(some=dict(admin_only=dict(path=None, foo="foo"), # user_only=dict(path="path", bar="bar")), # another=dict(admin_only=dict(path=None), # field="field"), # path=dict(to=dict(never=dict(return=None))), # the=dict(webcam=dict(data="webcam"))) # # and like this for an admin user # # dict(some=dict(admin_only=dict(path="path", foo="foo"), # user_only=dict(path="path", bar="bar")), # another=dict(admin_only=dict(path="path"), # field="field"), # path=dict(to=dict(never=dict(return=None))), # the=dict(webcam=dict(data="webcam"))) .. versionadded:: 1.2.17 """ return {} # noinspection PyMethodMayBeStatic def get_settings_preprocessors(self): """ Retrieves the plugin's preprocessors to use for preprocessing returned or set values prior to returning/setting them. The preprocessors should be provided as a dictionary mapping the path of the values to preprocess (hierarchically) to a transform function which will get the value to transform as only input and should return the transformed value. Example: .. code-block:: python def get_settings_defaults(self): return dict(some_key="Some_Value", some_other_key="Some_Value") def get_settings_preprocessors(self): return dict(some_key=lambda x: x.upper()), # getter preprocessors dict(some_other_key=lambda x: x.lower()) # setter preprocessors def some_method(self): # getting the value for "some_key" should turn it to upper case assert self._settings.get(["some_key"]) == "SOME_VALUE" # the value for "some_other_key" should be left alone assert self._settings.get(["some_other_key"] = "Some_Value" # setting a value for "some_other_key" should cause the value to first be turned to lower case self._settings.set(["some_other_key"], "SOME_OTHER_VALUE") assert self._settings.get(["some_other_key"]) == "some_other_value" Returns: (dict, dict): A tuple consisting of two dictionaries, the first being the plugin's preprocessors for getters, the second the preprocessors for setters """ return {}, {} # noinspection PyMethodMayBeStatic def get_settings_version(self): """ Retrieves the settings format version of the plugin. Use this to have OctoPrint trigger your migration function if it detects an outdated settings version in config.yaml. Returns: int or None: an int signifying the current settings format, should be incremented by plugins whenever there are backwards incompatible changes. Returning None here disables the version tracking for the plugin's configuration. """ return None # noinspection PyMethodMayBeStatic def on_settings_migrate(self, target, current): """ Called by OctoPrint if it detects that the installed version of the plugin necessitates a higher settings version than the one currently stored in _config.yaml. Will also be called if the settings data stored in config.yaml doesn't have version information, in which case the ``current`` parameter will be None. Your plugin's implementation should take care of migrating any data by utilizing self._settings. OctoPrint will take care of saving any changes to disk by calling `self._settings.save()` after returning from this method. This method will be called before your plugin's :func:`on_settings_initialized` method, with all injections already having taken place. You can therefore depend on the configuration having been migrated by the time :func:`on_settings_initialized` is called. Arguments: target (int): The settings format version the plugin requires, this should always be the same value as returned by :func:`get_settings_version`. current (int or None): The settings format version as currently stored in config.yaml. May be None if no version information can be found. """ pass def on_settings_cleanup(self): """ Called after migration and initialization but before call to :func:`on_settings_initialized`. Plugins may overwrite this method to perform additional clean up tasks. The default implementation just minimizes the data persisted on disk to only contain the differences to the defaults (in case the current data was persisted with an older version of OctoPrint that still duplicated default data). .. versionadded:: 1.3.0 """ import octoprint.util from octoprint.settings import NoSuchSettingsPath try: # let's fetch the current persisted config (so only the data on disk, # without the defaults) config = self._settings.get_all_data( merged=False, incl_defaults=False, error_on_path=True ) except NoSuchSettingsPath: # no config persisted, nothing to do => get out of here return if config is None: # config is set to None, that doesn't make sense, kill it and leave self._settings.clean_all_data() return if self.config_version_key in config and config[self.config_version_key] is None: # delete None entries for config version - it's the default, no need del config[self.config_version_key] # calculate a minimal diff between the settings and the current config - # anything already in the settings will be removed from the persisted # config, no need to duplicate it defaults = self.get_settings_defaults() diff = octoprint.util.dict_minimal_mergediff(defaults, config) if not diff: # no diff to defaults, no need to have anything persisted self._settings.clean_all_data() else: # diff => persist only that self._settings.set([], diff) def on_settings_initialized(self): """ Called after the settings have been initialized and - if necessary - also been migrated through a call to func:`on_settings_migrate`. This method will always be called after the `initialize` method. """ pass class EventHandlerPlugin(OctoPrintPlugin): """ The ``EventHandlerPlugin`` mixin allows OctoPrint plugins to react to any of :ref:`OctoPrint's events <sec-events>`. OctoPrint will call the :func:`on_event` method for any event fired on its internal event bus, supplying the event type and the associated payload. Please note that until your plugin returns from that method, further event processing within OctoPrint will block - the event queue itself is run asynchronously from the rest of OctoPrint, but the processing of the events within the queue itself happens consecutively. This mixin is especially interesting for plugins which want to react on things like print jobs finishing, timelapse videos rendering etc. """ # noinspection PyMethodMayBeStatic def on_event(self, event, payload): """ Called by OctoPrint upon processing of a fired event on the platform. .. warning:: Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. Arguments: event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>` for possible values payload (dict): The payload as provided with the event """ pass class SlicerPlugin(OctoPrintPlugin): """ Via the ``SlicerPlugin`` mixin plugins can add support for slicing engines to be used by OctoPrint. """ # noinspection PyMethodMayBeStatic def is_slicer_configured(self): """ Unless the return value of this method is ``True``, OctoPrint will not register the slicer within the slicing sub system upon startup. Plugins may use this to do some start up checks to verify that e.g. the path to a slicing binary as set and the binary is executable, or credentials of a cloud slicing platform are properly entered etc. """ return False # noinspection PyMethodMayBeStatic def get_slicer_properties(self): """ Plugins should override this method to return a ``dict`` containing a bunch of meta data about the implemented slicer. The expected keys in the returned ``dict`` have the following meaning: type The type identifier to use for the slicer. This should be a short unique lower case string which will be used to store slicer profiles under or refer to the slicer programmatically or from the API. name The human readable name of the slicer. This will be displayed to the user during slicer selection. same_device True if the slicer runs on the same device as OctoPrint, False otherwise. Slicers running on the same device will not be allowed to slice on systems with less than two CPU cores (or an unknown number) while a print is running due to performance reasons. Slice requests against slicers running on the same device and less than two cores will result in an error. progress_report ``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise. source_file_types A list of file types this slicer supports as valid origin file types. These are file types as found in the paths within the extension tree. Plugins may add additional file types through the :ref:`sec-plugins-hook-filemanager-extensiontree` hook. The system will test source files contains in incoming slicing requests via :meth:`octoprint.filemanager.valid_file_type` against the targeted slicer's ``source_file_types``. destination_extension The possible extensions of slicing result files. Returns: dict: A dict describing the slicer as outlined above. """ return { "type": None, "name": None, "same_device": True, "progress_report": False, "source_file_types": ["model"], "destination_extensions": ["gco", "gcode", "g"], } # noinspection PyMethodMayBeStatic def get_slicer_extension_tree(self): """ Fetch additional entries to put into the extension tree for accepted files By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support additional/other file types will want to override this. For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook <sec-plugins-hook-filemanager-extensiontree>`. Returns: (dict) a dictionary containing a valid extension subtree. .. versionadded:: 1.3.11 """ from octoprint.filemanager import ContentTypeMapping return {"model": {"stl": ContentTypeMapping(["stl"], "application/sla")}} def get_slicer_profiles(self, profile_path): """ Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer. For compatibility reasons with existing slicing plugins this method defaults to returning profiles parsed from .profile files in the plugin's ``profile_path``, utilizing the :func:`SlicingPlugin.get_slicer_profile` method of the plugin implementation. Arguments: profile_path (str): The base folder where OctoPrint stores this slicer plugin's profiles .. versionadded:: 1.3.7 """ from os import scandir import octoprint.util profiles = {} for entry in scandir(profile_path): if not entry.name.endswith(".profile") or octoprint.util.is_hidden_path( entry.name ): # we are only interested in profiles and no hidden files continue profile_name = entry.name[: -len(".profile")] profiles[profile_name] = self.get_slicer_profile(entry.path) return profiles # noinspection PyMethodMayBeStatic def get_slicer_profiles_lastmodified(self, profile_path): """ .. versionadded:: 1.3.0 """ import os lms = [os.stat(profile_path).st_mtime] lms += [ os.stat(entry.path).st_mtime for entry in os.scandir(profile_path) if entry.name.endswith(".profile") ] return max(lms) # noinspection PyMethodMayBeStatic def get_slicer_default_profile(self): """ Should return a :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile to use with this slicer if no other profile has been selected. Returns: SlicingProfile: The :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile for this slicer. """ return None # noinspection PyMethodMayBeStatic def get_slicer_profile(self, path): """ Should return a :class:`~octoprint.slicing.SlicingProfile` parsed from the slicing profile stored at the indicated ``path``. Arguments: path (str): The absolute path from which to read the slicing profile. Returns: SlicingProfile: The specified slicing profile. """ return None # noinspection PyMethodMayBeStatic def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None): """ Should save the provided :class:`~octoprint.slicing.SlicingProfile` to the indicated ``path``, after applying any supplied ``overrides``. If a profile is already saved under the indicated path and ``allow_overwrite`` is set to False (defaults to True), an :class:`IOError` should be raised. Arguments: path (str): The absolute path to which to save the profile. profile (SlicingProfile): The profile to save. allow_overwrite (boolean): Whether to allow to overwrite an existing profile at the indicated path (True, default) or not (False). If a profile already exists on the path and this is False an :class:`IOError` should be raised. overrides (dict): Profile overrides to apply to the ``profile`` before saving it """ pass # noinspection PyMethodMayBeStatic def do_slice( self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None, ): """ Called by OctoPrint to slice ``model_path`` for the indicated ``printer_profile``. If the ``machinecode_path`` is ``None``, slicer implementations should generate it from the provided ``model_path``. If provided, the ``profile_path`` is guaranteed by OctoPrint to be a serialized slicing profile created through the slicing plugin's own :func:`save_slicer_profile` method. If provided, ``position`` will be a ``dict`` containing and ``x`` and a ``y`` key, indicating the position the center of the model on the print bed should have in the final sliced machine code. If not provided, slicer implementations should place the model in the center of the print bed. ``on_progress`` will be a callback which expects an additional keyword argument ``_progress`` with the current slicing progress which - if progress reporting is supported - the slicing plugin should call like the following: .. code-block:: python if on_progress is not None: if on_progress_args is None: on_progress_args = () if on_progress_kwargs is None: on_progress_kwargs = dict() on_progress_kwargs["_progress"] = your_plugins_slicing_progress on_progress(*on_progress_args, **on_progress_kwargs) Please note that both ``on_progress_args`` and ``on_progress_kwargs`` as supplied by OctoPrint might be ``None``, so always make sure to initialize those values to sane defaults like depicted above before invoking the callback. In order to support external cancellation of an ongoing slicing job via :func:`cancel_slicing`, implementations should make sure to track the started jobs via the ``machinecode_path``, if provided. The method should return a 2-tuple consisting of a boolean ``flag`` indicating whether the slicing job was finished successfully (True) or not (False) and a ``result`` depending on the success of the slicing job. For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information about the slicing job under the following keys: analysis Analysis result of the generated machine code as returned by the slicer itself. This should match the data structure described for the analysis queue of the matching machine code format, e.g. :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files. For jobs that did not finish successfully (but not due to being cancelled!), ``result`` should be a :class:`str` containing a human readable reason for the error. If the job gets cancelled, a :class:`~octoprint.slicing.SlicingCancelled` exception should be raised. Returns: tuple: A 2-tuple (boolean, object) as outlined above. Raises: SlicingCancelled: The slicing job was cancelled (via :meth:`cancel_slicing`). """ pass # noinspection PyMethodMayBeStatic def cancel_slicing(self, machinecode_path): """ Cancels the slicing to the indicated file. Arguments: machinecode_path (str): The absolute path to the machine code file to which to stop slicing to. """ pass class ProgressPlugin(OctoPrintPlugin): """ Via the ``ProgressPlugin`` mixing plugins can let themselves be called upon progress in print jobs or slicing jobs, limited to minimally 1% steps. """ # noinspection PyMethodMayBeStatic def on_print_progress(self, storage, path, progress): """ Called by OctoPrint on minimally 1% increments during a running print job. :param string storage: Location of the file :param string path: Path of the file :param int progress: Current progress as a value between 0 and 100 """ pass # noinspection PyMethodMayBeStatic def on_slicing_progress( self, slicer, source_location, source_path, destination_location, destination_path, progress, ): """ Called by OctoPrint on minimally 1% increments during a running slicing job. :param string slicer: Key of the slicer reporting the progress :param string source_location: Location of the source file :param string source_path: Path of the source file :param string destination_location: Location the destination file :param string destination_path: Path of the destination file :param int progress: Current progress as a value between 0 and 100 """ pass class WebcamProviderPlugin(OctoPrintPlugin): """ The ``WebcamProviderPlugin`` can be used to provide one or more webcams visible on the frontend and used for snapshots/timelapses. For an example of how to utilize this, see the bundled ``classicwebcam`` plugin, or the ``testpicture`` plugin available `here <https://github.com/OctoPrint/OctoPrint-Testpicture>`_. """ def get_webcam_configurations(self): """ Used to retrieve a list of available webcams Returns: A list of :class:`~octoprint.schema.webcam.Webcam`: The available webcams, can be empty if none available. """ return [] def take_webcam_snapshot(self, webcamName): """ Used to take a JPEG snapshot of the webcam. This method may raise an exception, you can expect failures to be handled. :param string webcamName: The name of the webcam to take a snapshot of as given by the configurations Returns: An iterator over bytes of the JPEG image """ raise NotImplementedError()
107,308
Python
.py
1,834
48.009269
188
0.66166
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,859
client.py
OctoPrint_OctoPrint/src/octoprint/cli/client.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import json import click import octoprint_client from octoprint import FatalStartupError, init_settings from octoprint.cli import bulk_options, get_ctx_obj_option from octoprint.util import yaml click.disable_unicode_literals_warning = True class JsonStringParamType(click.ParamType): name = "json" def convert(self, value, param, ctx): try: return json.loads(value) except Exception: self.fail("%s is not a valid json string" % value, param, ctx) def create_client( settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None, ): assert host is not None or settings is not None assert port is not None or settings is not None assert apikey is not None or settings is not None if not host: host = settings.get(["server", "host"]) host = host if host != "0.0.0.0" else "127.0.0.1" if not port: port = settings.getInt(["server", "port"]) if not apikey: apikey = settings.get(["api", "key"]) baseurl = octoprint_client.build_base_url( https=https, httpuser=httpuser, httppass=httppass, host=host, port=port, prefix=prefix, ) return octoprint_client.Client(baseurl, apikey) client_options = bulk_options( [ click.option("--apikey", "-a", type=click.STRING), click.option("--host", "-h", type=click.STRING), click.option("--port", "-p", type=click.INT), click.option("--httpuser", type=click.STRING), click.option("--httppass", type=click.STRING), click.option("--https", is_flag=True), click.option("--prefix", type=click.STRING), ] ) """Common options to configure an API client.""" @click.group(context_settings={"ignore_unknown_options": True}) @client_options @click.pass_context def cli(ctx, apikey, host, port, httpuser, httppass, https, prefix): """Basic API client.""" try: settings = None if not host or not port or not apikey: settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), ) ctx.obj.client = create_client( settings=settings, apikey=apikey, host=host, port=port, httpuser=httpuser, httppass=httppass, https=https, prefix=prefix, ) except FatalStartupError as e: click.echo(str(e), err=True) click.echo("There was a fatal error initializing the client.", err=True) ctx.exit(-1) def log_response(response, status_code=True, body=True, headers=False): if status_code: click.echo(f"Status Code: {response.status_code}") if headers: for header, value in response.headers.items(): click.echo(f"{header}: {value}") click.echo() if body: click.echo(response.text) @cli.command("get") @click.argument("path") @click.option("--timeout", type=float, default=None) @click.pass_context def get(ctx, path, timeout): """Performs a GET request against the specified server path.""" r = ctx.obj.client.get(path, timeout=timeout) log_response(r) @cli.command("post_json") @click.argument("path") @click.argument("data", type=JsonStringParamType()) @click.option("--timeout", type=float, default=None) @click.pass_context def post_json(ctx, path, data, timeout): """POSTs JSON data to the specified server path.""" r = ctx.obj.client.post_json(path, data, timeout=timeout) log_response(r) @cli.command("patch_json") @click.argument("path") @click.argument("data", type=JsonStringParamType()) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def patch_json(ctx, path, data, timeout): """PATCHes JSON data to the specified server path.""" r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout) log_response(r) @cli.command("post_from_file") @click.argument("path") @click.argument( "file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True) ) @click.option("--json", is_flag=True) @click.option("--yaml", is_flag=True) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): """POSTs JSON data to the specified server path, taking the data from the specified file.""" if json_flag or yaml_flag: if json_flag: with open(file_path) as fp: data = json.load(fp) else: data = yaml.load_from_file(path=file_path) r = ctx.obj.client.post_json(path, data, timeout=timeout) else: with open(file_path, "rb") as fp: data = fp.read() r = ctx.obj.client.post(path, data, timeout=timeout) log_response(r) @cli.command("command") @click.argument("path") @click.argument("command") @click.option( "--str", "-s", "str_params", multiple=True, nargs=2, type=click.Tuple([str, str]), ) @click.option( "--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([str, int]) ) @click.option( "--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([str, float]), ) @click.option( "--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([str, bool]), ) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def command( ctx, path, command, str_params, int_params, float_params, bool_params, timeout ): """Sends a JSON command to the specified server path.""" data = {} params = str_params + int_params + float_params + bool_params for param in params: data[param[0]] = param[1] r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout) log_response(r, body=False) @cli.command("upload") @click.argument("path") @click.argument( "file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True) ) @click.option( "--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([str, str]), ) @click.option("--file-name", type=click.STRING) @click.option("--content-type", type=click.STRING) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def upload(ctx, path, file_path, params, file_name, content_type, timeout): """Uploads the specified file to the specified server path.""" data = {} for param in params: data[param[0]] = param[1] r = ctx.obj.client.upload( path, file_path, additional=data, file_name=file_name, content_type=content_type, timeout=timeout, ) log_response(r) @cli.command("delete") @click.argument("path") @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context def delete(ctx, path, timeout): """Sends a DELETE request to the specified server path.""" r = ctx.obj.client.delete(path, timeout=timeout) log_response(r) @cli.command("listen") @click.pass_context def listen(ctx): def on_connect(ws): click.echo("--- Connected!") def on_close(ws): click.echo("--- Connection closed!") def on_error(ws, error): click.echo(f"!!! Error: {error}") def on_sent(ws, data): click.echo(f">>> {json.dumps(data)}") def on_heartbeat(ws): click.echo("<3") def on_message(ws, message_type, message_payload): click.echo(f"<<< {message_type}, Payload: {json.dumps(message_payload)}") socket = ctx.obj.client.create_socket( on_connect=on_connect, on_close=on_close, on_error=on_error, on_sent=on_sent, on_heartbeat=on_heartbeat, on_message=on_message, ) click.echo("--- Waiting for client to exit") try: socket.wait() finally: click.echo("--- Goodbye...")
8,411
Python
.py
250
28.164
103
0.649698
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,860
analysis.py
OctoPrint_OctoPrint/src/octoprint/cli/analysis.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import sys import click from octoprint.util import yaml click.disable_unicode_literals_warning = True # ~~ "octoprint util" commands dimensions = ("depth", "height", "width") area = ("maxX", "maxY", "maxZ", "minX", "minY", "minZ") def empty_result(result): dims = result.get("dimensions", {}) return all(map(lambda x: dims.get(x) == 0.0, dimensions)) def validate_result(result): def validate_list(data): return not any(map(invalid_float, data)) def validate_dict(data, keys): for k in keys: if k not in data or invalid_float(data[k]): return False return True def invalid_float(value): return value is None or value == float("inf") or value == float("-inf") if "dimensions" not in result or not validate_dict(result["dimensions"], dimensions): return False if "travel_dimensions" not in result or not validate_dict( result["travel_dimensions"], dimensions ): return False if "extrusion_length" not in result or not validate_list(result["extrusion_length"]): return False if "extrusion_volume" not in result or not validate_list(result["extrusion_volume"]): return False if "printing_area" not in result or not validate_dict(result["printing_area"], area): return False if "travel_area" not in result or not validate_dict(result["travel_area"], area): return False if "total_time" not in result or invalid_float(result["total_time"]): return False return True @click.group() def cli(): """Analysis tools.""" pass @cli.command(name="gcode") @click.option("--throttle", "throttle", type=float, default=None) @click.option("--throttle-lines", "throttle_lines", type=int, default=None) @click.option("--speed-x", "speedx", type=float, default=6000) @click.option("--speed-y", "speedy", type=float, default=6000) @click.option("--speed-z", "speedz", type=float, default=300) @click.option("--offset", "offset", type=(float, float), multiple=True) @click.option("--max-t", "maxt", type=int, default=10) @click.option("--g90-extruder", "g90_extruder", is_flag=True) @click.option("--bed-z", "bedz", type=float, default=0) @click.option("--progress", "progress", is_flag=True) @click.option("--layers", "layers", is_flag=True) @click.argument("path", type=click.Path()) def gcode_command( path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, bedz, progress, layers, ): """Runs a GCODE file analysis.""" import time from octoprint.util.gcodeInterpreter import gcode throttle_callback = None if throttle: def throttle_callback(filePos, readBytes): if filePos % throttle_lines == 0: # only apply throttle every $throttle_lines lines time.sleep(throttle) offsets = offset if offsets is None: offsets = [] elif isinstance(offset, tuple): offsets = list(offsets) offsets = [(0, 0)] + offsets if len(offsets) < maxt: offsets += [(0, 0)] * (maxt - len(offsets)) start_time = time.monotonic() progress_callback = None if progress: def progress_callback(percentage): click.echo(f"PROGRESS:{percentage}") interpreter = gcode(progress_callback=progress_callback, incl_layers=layers) interpreter.load( path, speedx=speedx, speedy=speedy, offsets=offsets, throttle=throttle_callback, max_extruders=maxt, g90_extruder=g90_extruder, bed_z=bedz, ) click.echo(f"DONE:{time.monotonic() - start_time}s") result = interpreter.get_result() if empty_result(result): click.echo("EMPTY:There are no extrusions in the file, nothing to analyse") sys.exit(0) if not validate_result(result): click.echo( "ERROR:Invalid analysis result, please create a bug report in OctoPrint's " "issue tracker and be sure to also include the GCODE file with which this " "happened" ) sys.exit(-1) click.echo("RESULTS:") click.echo(yaml.dump(interpreter.get_result(), pretty=True)) if __name__ == "__main__": gcode_command()
4,500
Python
.py
119
31.731092
103
0.655991
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,861
dev.py
OctoPrint_OctoPrint/src/octoprint/cli/dev.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import sys import click click.disable_unicode_literals_warning = True class OctoPrintDevelCommands(click.MultiCommand): """ Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_ implementation that provides commands relevant for (plugin) development based on availability of development dependencies. """ sep = ":" groups = ("plugin", "css") def __init__(self, *args, **kwargs): click.MultiCommand.__init__(self, *args, **kwargs) from functools import partial from octoprint.util.commandline import CommandlineCaller def log_util(f): def log(*lines): for line in lines: f(line) return log self.command_caller = CommandlineCaller() self.command_caller.on_log_call = log_util(lambda x: click.echo(f">> {x}")) self.command_caller.on_log_stdout = log_util(click.echo) self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True)) def _get_prefix_methods(self, method_prefix): for name in [x for x in dir(self) if x.startswith(method_prefix)]: method = getattr(self, name) yield method def _get_commands_from_prefix_methods(self, method_prefix): for method in self._get_prefix_methods(method_prefix): result = method() if result is not None and isinstance(result, click.Command): yield result def _get_commands(self): result = {} for group in self.groups: for command in self._get_commands_from_prefix_methods(f"{group}_"): result[group + self.sep + command.name] = command return result def list_commands(self, ctx): result = [name for name in self._get_commands()] result.sort() return result def get_command(self, ctx, cmd_name): commands = self._get_commands() return commands.get(cmd_name, None) def plugin_new(self): try: import cookiecutter.main except ImportError: return None import contextlib @contextlib.contextmanager def custom_cookiecutter_config(config): """ Allows overriding cookiecutter's user config with a custom dict with fallback to the original data. """ from octoprint.util import fallback_dict original_get_user_config = cookiecutter.main.get_user_config try: def f(*args, **kwargs): original_config = original_get_user_config(*args, **kwargs) return fallback_dict(config, original_config) cookiecutter.main.get_user_config = f yield finally: cookiecutter.main.get_user_config = original_get_user_config @contextlib.contextmanager def custom_cookiecutter_prompt(options): """ Custom cookiecutter prompter for the template config. If a setting is available in the provided options (read from the CLI) that will be used, otherwise the user will be prompted for a value via click. """ original_prompt_for_config = cookiecutter.main.prompt_for_config def custom_prompt_for_config(context, no_input=False): from cookiecutter.environment import StrictEnvironment cookiecutter_dict = {} env = StrictEnvironment() for key, raw in context["cookiecutter"].items(): if key in options: val = options[key] else: if not isinstance(raw, str): raw = str(raw) val = env.from_string(raw).render(cookiecutter=cookiecutter_dict) if not no_input: val = click.prompt(key, default=val) cookiecutter_dict[key] = val return cookiecutter_dict try: cookiecutter.main.prompt_for_config = custom_prompt_for_config yield finally: cookiecutter.main.prompt_for_config = original_prompt_for_config @click.command("new") @click.option("--name", "-n", help="The name of the plugin") @click.option("--package", "-p", help="The plugin package") @click.option("--author", "-a", help="The plugin author's name") @click.option("--email", "-e", help="The plugin author's mail address") @click.option("--license", "-l", help="The plugin's license") @click.option("--description", "-d", help="The plugin's description") @click.option("--homepage", help="The plugin's homepage URL") @click.option("--source", "-s", help="The URL to the plugin's source") @click.option("--installurl", "-i", help="The plugin's install URL") @click.argument("identifier", required=False) def command( name, package, author, email, description, license, homepage, source, installurl, identifier, ): """Creates a new plugin based on the OctoPrint Plugin cookiecutter template.""" from octoprint.util import tempdir # deleting a git checkout folder might run into access errors due # to write-protected sub folders, so we use a custom onerror handler # that tries to fix such permissions def onerror(func, path, exc_info): """Originally from http://stackoverflow.com/a/2656405/2028598""" import os import stat if not os.access(path, os.W_OK): os.chmod(path, stat.S_IWUSR) func(path) else: raise with tempdir(onerror=onerror) as path: custom = {"cookiecutters_dir": path} with custom_cookiecutter_config(custom): raw_options = { "plugin_identifier": identifier, "plugin_package": package, "plugin_name": name, "full_name": author, "email": email, "plugin_description": description, "plugin_license": license, "plugin_homepage": homepage, "plugin_source": source, "plugin_installurl": installurl, } options = {k: v for k, v in raw_options.items() if v is not None} with custom_cookiecutter_prompt(options): cookiecutter.main.cookiecutter( "gh:OctoPrint/cookiecutter-octoprint-plugin" ) return command def plugin_install(self): @click.command("install") @click.option( "--path", help="Path of the local plugin development folder to install" ) def command(path): """ Installs the local plugin in development mode. Note: This can NOT be used to install plugins from remote locations such as the plugin repository! It is strictly for local development of plugins, to ensure the plugin is installed (editable) into the same python environment that OctoPrint is installed under. """ import os if not path: path = os.getcwd() # check if this really looks like a plugin if not os.path.isfile(os.path.join(path, "setup.py")): click.echo("This doesn't look like an OctoPrint plugin folder") sys.exit(1) self.command_caller.call( [sys.executable, "-m", "pip", "install", "-e", "."], cwd=path ) return command def plugin_uninstall(self): @click.command("uninstall") @click.argument("name") def command(name): """Uninstalls the plugin with the given name.""" lower_name = name.lower() if not lower_name.startswith("octoprint_") and not lower_name.startswith( "octoprint-" ): click.echo("This doesn't look like an OctoPrint plugin name") sys.exit(1) call = [sys.executable, "-m", "pip", "uninstall", "--yes", name] self.command_caller.call(call) return command def css_build(self): @click.command("build") @click.option( "--file", "-f", "files", multiple=True, help="Specify files to build, for a list of options use --list", ) @click.option("--all", "all_files", is_flag=True, help="Build all less files") @click.option( "--list", "list_files", is_flag=True, help="List all available files and exit", ) def command(files, all_files, list_files): import shutil from pathlib import Path # src/octoprint octoprint_base = Path(__file__).parent.parent available_files = {} for less_file in Path(octoprint_base, "static", "less").glob("*.less"): # Check corresponding css file exists # Less files can be imported, not all need building css_file = Path(less_file.parent.parent, "css", f"{less_file.stem}.css") if css_file.exists(): available_files[less_file.stem] = { "source": str(less_file), "output": str(css_file), } path_to_plugins = Path(octoprint_base, "plugins") for plugin in Path(path_to_plugins).iterdir(): for less_file in Path(plugin, "static", "less").glob("*.less"): name = f"plugin_{plugin.name}" if less_file.stem != plugin.name: name += f"_{less_file.stem}" # Check there is a corresponding CSS file first css_file = Path( less_file.parent.parent, "css", f"{less_file.stem}.css" ) if css_file.exists(): available_files[name] = { "source": str(less_file), "output": str(css_file), } if list_files: click.echo("Available files to build:") for name in available_files.keys(): click.echo(f"- {name}") sys.exit(0) if all_files: files = available_files.keys() if not files: click.echo( "No files specified. Use `--file <file>` to specify individual files, or `--all` to build all." ) sys.exit(1) # Check that lessc is installed less = shutil.which("lessc") # Check that less-plugin-clean-css is installed if less: _, _, stderr = self.command_caller.call( [less, "--clean-css"], logged=False ) clean_css = not any( map(lambda x: "Unable to load plugin clean-css" in x, stderr) ) else: clean_css = False if not less or not clean_css: click.echo( "lessc or less-plugin-clean-css is not installed/not available, please install it first" ) click.echo( "Try `npm i -g less less-plugin-clean-css` to install both (note that it does NOT say 'lessc' in this command!)" ) sys.exit(1) for less_file in files: if less_file not in available_files.keys(): click.echo(f"Unknown file {less_file}") sys.exit(1) # Build command line, with necessary options less_command = [ less, "--clean-css=--s1 --advanced --compatibility=ie8", available_files[less_file]["source"], available_files[less_file]["output"], ] self.command_caller.call(less_command) return command @click.group(cls=OctoPrintDevelCommands) def cli(): """Additional commands for development tasks.""" pass
13,178
Python
.py
291
30.859107
132
0.534633
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,862
user.py
OctoPrint_OctoPrint/src/octoprint/cli/user.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import click from octoprint import init_settings from octoprint.access.groups import FilebasedGroupManager from octoprint.access.users import ( CorruptUserStorage, FilebasedUserManager, InvalidUsername, UnknownUser, UserAlreadyExists, ) from octoprint.cli import get_ctx_obj_option from octoprint.util import get_class, sv click.disable_unicode_literals_warning = True # ~~ "octoprint user" commands @click.group() @click.pass_context def cli(ctx): """ User management. Note that this currently only supports managing user accounts stored in the configured user manager, not any user managers added through plugins and the "octoprint.users.factory" hook. """ try: logging.basicConfig( level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN ) settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), overlays=get_ctx_obj_option(ctx, "overlays", None), ) group_manager_name = settings.get(["accessControl", "groupManager"]) try: clazz = get_class(group_manager_name) group_manager = clazz() except AttributeError: click.echo( "Could not instantiate group manager {}, " "falling back to FilebasedGroupManager!".format(group_manager_name), err=True, ) group_manager = FilebasedGroupManager() ctx.obj.group_manager = group_manager name = settings.get(["accessControl", "userManager"]) try: clazz = get_class(name) user_manager = clazz(group_manager=group_manager, settings=settings) except CorruptUserStorage: raise except Exception: click.echo( "Could not instantiate user manager {}, falling back to FilebasedUserManager!".format( name ), err=True, ) user_manager = FilebasedUserManager(group_manager, settings=settings) ctx.obj.user_manager = user_manager except Exception: click.echo("Could not instantiate user manager", err=True) ctx.exit(-1) @cli.command(name="list") @click.pass_context def list_users_command(ctx): """Lists user information""" users = ctx.obj.user_manager.get_all_users() _print_list(users) @cli.command(name="add") @click.argument("username", type=click.STRING, required=True) @click.password_option("--password", "password", help="Password for the user") @click.option("-g", "--group", "groups", multiple=True, help="Groups to set on the user") @click.option( "-p", "--permission", "permissions", multiple=True, help="Individual permissions to set on the user", ) @click.option( "--admin", "is_admin", type=click.BOOL, is_flag=True, default=False, help="Adds user to admin group", ) @click.pass_context def add_user_command(ctx, username, password, groups, permissions, is_admin): """Add a new user.""" if not groups: groups = [] if is_admin: groups.append(ctx.obj.group_manager.admin_group) try: ctx.obj.user_manager.add_user( username, password, groups=groups, permissions=permissions, active=True ) user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") click.echo(f"\t{_user_to_line(user.as_dict())}") except UserAlreadyExists: click.echo(f"A user with the name {username} does already exist!", err=True) except InvalidUsername: click.echo(f"The username '{username}' is invalid!", err=True) @cli.command(name="remove") @click.argument("username", type=click.STRING) @click.pass_context def remove_user_command(ctx, username): """Remove an existing user.""" confirm = click.prompt( "This is will irreversibly destroy the user account! Enter 'yes' to confirm", type=click.STRING, ) if confirm.lower() == "yes": ctx.obj.user_manager.remove_user(username) click.echo(f"User {username} removed.") else: click.echo(f"User {username} not removed.") @cli.command(name="password") @click.argument("username", type=click.STRING) @click.password_option("--password", "password", help="New password for user") @click.pass_context def change_password_command(ctx, username, password): """Change an existing user's password.""" try: ctx.obj.user_manager.change_user_password(username, password) click.echo(f"Password changed for user {username}.") except UnknownUser: click.echo(f"User {username} does not exist!", err=True) @cli.command(name="activate") @click.argument("username", type=click.STRING) @click.pass_context def activate_command(ctx, username): """Activate a user account.""" try: ctx.obj.user_manager.change_user_activation(username, True) click.echo(f"User {username} activated.") user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") click.echo(f"\t{_user_to_line(user.asDict())}") except UnknownUser: click.echo(f"User {username} does not exist!", err=True) @cli.command(name="deactivate") @click.argument("username", type=click.STRING) @click.pass_context def deactivate_command(ctx, username): """Activate a user account.""" try: ctx.obj.user_manager.change_user_activation(username, False) click.echo(f"User {username} activated.") user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") click.echo(f"\t{_user_to_line(user.asDict())}") except UnknownUser: click.echo(f"User {username} does not exist!", err=True) def _print_list(users): click.echo(f"{len(users)} users registered in the system:") for user in sorted( map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name")) ): click.echo(f"\t{_user_to_line(user)}") def _user_to_line(user): return ( "{name}" "\n\t\tactive: {active}" "\n\t\tgroups: {groups}" "\n\t\tpermissions: {permissions}".format( name=user.get("name"), active=user.get("active", "False"), groups=", ".join(user.get("groups", [])), permissions=", ".join(user.get("permissions", [])), ) )
6,813
Python
.py
181
30.696133
112
0.647514
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,863
config.py
OctoPrint_OctoPrint/src/octoprint/cli/config.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import json import logging import pprint import click from octoprint import FatalStartupError, init_pluginsystem, init_settings from octoprint.cli import get_ctx_obj_option, standard_options from octoprint.util import yaml click.disable_unicode_literals_warning = True def _to_settings_path(path): if not isinstance(path, (list, tuple)): path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))) return path def _set_helper(settings, path, value, data_type=None): path = _to_settings_path(path) method = settings.set if data_type is not None: name = None if data_type == bool: name = "setBoolean" elif data_type == float: name = "setFloat" elif data_type == int: name = "setInt" if name is not None: method = getattr(settings, name) method(path, value, force=True) settings.save() def _init_pluginsettings(ctx): try: ctx.obj.plugin_manager = init_pluginsystem( ctx.obj.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False) ) except FatalStartupError as e: click.echo(str(e), err=True) click.echo("There was a fatal error initializing the plugin manager.", err=True) ctx.exit(-1) # ~~ "octoprint config" commands @click.group() @click.pass_context def cli(ctx): """Basic config manipulation.""" logging.basicConfig( level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN ) try: ctx.obj.settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), overlays=get_ctx_obj_option(ctx, "overlays", None), ) except FatalStartupError as e: click.echo(str(e), err=True) click.echo("There was a fatal error initializing the settings manager.", err=True) ctx.exit(-1) @cli.command(name="set") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.argument("value", type=click.STRING) @click.option("--bool", "as_bool", is_flag=True, help="Interpret value as bool") @click.option("--float", "as_float", is_flag=True, help="Interpret value as float") @click.option("--int", "as_int", is_flag=True, help="Interpret value as int") @click.option("--json", "as_json", is_flag=True, help="Parse value from json") @click.pass_context def set_command(ctx, path, value, as_bool, as_float, as_int, as_json): """Sets a config path to the provided value.""" if as_json: try: value = json.loads(value) except Exception as e: click.echo(str(e), err=True) ctx.exit(-1) data_type = None if as_bool: data_type = bool elif as_float: data_type = float elif as_int: data_type = int _set_helper(ctx.obj.settings, path, value, data_type=data_type) @cli.command(name="remove") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.pass_context def remove_command(ctx, path): """Removes a config path.""" _set_helper(ctx.obj.settings, path, None) @cli.command(name="append_value") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.argument("value", type=click.STRING) @click.option("--json", "as_json", is_flag=True) @click.pass_context def append_value_command(ctx, path, value, as_json=False): """Appends value to list behind config path.""" path = _to_settings_path(path) if len(path) == 0 or path[0] == "plugins": _init_pluginsettings(ctx) if as_json: try: value = json.loads(value) except Exception as e: click.echo(str(e), err=True) ctx.exit(-1) current = ctx.obj.settings.get(path) if current is None: current = [] if not isinstance(current, list): click.echo("Cannot append to non-list value at given path", err=True) ctx.exit(-1) current.append(value) _set_helper(ctx.obj.settings, path, current) @cli.command(name="insert_value") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.argument("index", type=click.INT) @click.argument("value", type=click.STRING) @click.option("--json", "as_json", is_flag=True) @click.pass_context def insert_value_command(ctx, path, index, value, as_json=False): """Inserts value at index of list behind config key.""" path = _to_settings_path(path) if len(path) == 0 or path[0] == "plugins": _init_pluginsettings(ctx) if as_json: try: value = json.loads(value) except Exception as e: click.echo(str(e), err=True) ctx.exit(-1) current = ctx.obj.settings.get(path) if current is None: current = [] if not isinstance(current, list): click.echo("Cannot insert into non-list value at given path", err=True) ctx.exit(-1) current.insert(index, value) _set_helper(ctx.obj.settings, path, current) @cli.command(name="remove_value") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.argument("value", type=click.STRING) @click.option("--json", "as_json", is_flag=True) @click.pass_context def remove_value_command(ctx, path, value, as_json=False): """Removes value from list at config path.""" path = _to_settings_path(path) if len(path) == 0 or path[0] == "plugins": _init_pluginsettings(ctx) if as_json: try: value = json.loads(value) except Exception as e: click.echo(str(e), err=True) ctx.exit(-1) current = ctx.obj.settings.get(path) if current is None: current = [] if not isinstance(current, list): click.echo("Cannot remove value from non-list value at given path", err=True) ctx.exit(-1) if value not in current: click.echo("Value is not contained in list at given path") ctx.exit() current.remove(value) _set_helper(ctx.obj.settings, path, current) @cli.command(name="get") @click.argument("path", type=click.STRING) @click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON") @click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML") @click.option( "--raw", "as_raw", is_flag=True, help="Output value as raw string representation" ) @standard_options(hidden=True) @click.pass_context def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False): """Retrieves value from config path.""" path = _to_settings_path(path) if len(path) == 0 or path[0] == "plugins": _init_pluginsettings(ctx) value = ctx.obj.settings.get(path, merged=True) if as_json: output = json.dumps(value) elif as_yaml: output = yaml.dump(value, pretty=True) elif as_raw: output = value else: output = pprint.pformat(value) click.echo(output) @cli.command(name="effective") @click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON") @click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML") @click.option( "--raw", "as_raw", is_flag=True, help="Output value as raw string representation" ) @standard_options(hidden=True) @click.pass_context def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False): """Retrieves the full effective config.""" _init_pluginsettings(ctx) value = ctx.obj.settings.effective if as_json: output = json.dumps(value) elif as_yaml: output = yaml.dump(value, pretty=True) elif as_raw: output = value else: output = pprint.pformat(value) click.echo(output)
8,033
Python
.py
214
31.901869
103
0.659246
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,864
plugins.py
OctoPrint_OctoPrint/src/octoprint/cli/plugins.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import logging.config import click from octoprint.cli import OctoPrintContext, get_ctx_obj_option, pass_octoprint_ctx from octoprint.util import dict_merge click.disable_unicode_literals_warning = True LOGGING_CONFIG = { "version": 1, "formatters": {"brief": {"format": "%(message)s"}}, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "brief", "stream": "ext://sys.stdout", } }, "loggers": {"octoprint.plugin.core": {"level": logging.ERROR}}, "root": {"level": logging.WARNING}, } # ~~ "octoprint plugin:command" commands class OctoPrintPluginCommands(click.MultiCommand): """ Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_ implementation that collects commands from the plugin hook :ref:`octoprint.cli.commands <sec-plugins-hook-cli-commands>`. .. attribute:: settings The global :class:`~octoprint.settings.Settings` instance. .. attribute:: plugin_manager The :class:`~octoprint.plugin.core.PluginManager` instance. """ sep = ":" def __init__(self, *args, **kwargs): click.MultiCommand.__init__(self, *args, **kwargs) self.settings = None self.plugin_manager = None self.hooks = {} self._logger = logging.getLogger(__name__) self._initialized = False def _initialize(self, ctx): if self._initialized: return click.echo("Initializing settings & plugin subsystem...") if ctx.obj is None: ctx.obj = OctoPrintContext() logging_config = dict_merge( LOGGING_CONFIG, { "root": { "level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING } }, ) logging.config.dictConfig(logging_config) # initialize settings and plugin manager based on provided # context (basedir and configfile) from octoprint import FatalStartupError, init_pluginsystem, init_settings try: self.settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), overlays=get_ctx_obj_option(ctx, "overlays", None), ) self.plugin_manager = init_pluginsystem( self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False) ) except FatalStartupError as e: click.echo(str(e), err=True) click.echo( "There was a fatal error initializing the settings or the plugin system.", err=True, ) ctx.exit(-1) # fetch registered hooks self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands") self._initialized = True def list_commands(self, ctx): self._initialize(ctx) result = [name for name in self._get_commands()] result.sort() return result def get_command(self, ctx, cmd_name): self._initialize(ctx) commands = self._get_commands() return commands.get(cmd_name, None) def _get_commands(self): """Fetch all commands from plugins providing any.""" import collections result = collections.OrderedDict() for name, hook in self.hooks.items(): try: commands = hook(self, pass_octoprint_ctx) for command in commands: if not isinstance(command, click.Command): self._logger.warning( "Plugin {} provided invalid CLI command, ignoring it: {!r}".format( name, command ) ) continue result[name + self.sep + command.name] = command except Exception: self._logger.exception( f"Error while retrieving cli commands for plugin {name}", extra={"plugin": name}, ) return result @click.group(cls=OctoPrintPluginCommands) @pass_octoprint_ctx def cli(obj): """Additional commands provided by plugins.""" pass
4,553
Python
.py
113
29.823009
103
0.588249
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,865
timelapse.py
OctoPrint_OctoPrint/src/octoprint/cli/timelapse.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os from concurrent.futures import ThreadPoolExecutor, wait import click from octoprint import FatalStartupError, init_pluginsystem, init_settings from octoprint.cli import get_ctx_obj_option, standard_options from octoprint.timelapse import create_thumbnail_path, valid_timelapse from octoprint.util import is_hidden_path click.disable_unicode_literals_warning = True @click.group() @click.pass_context def cli(ctx): """Basic config manipulation.""" logging.basicConfig( level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN ) try: ctx.obj.settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), overlays=get_ctx_obj_option(ctx, "overlays", None), ) ctx.obj.plugin_manager = init_pluginsystem( ctx.obj.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False) ) except FatalStartupError as e: click.echo(str(e), err=True) click.echo("There was a fatal error initializing the settings manager.", err=True) ctx.exit(-1) @cli.command(name="create_thumbnails") @standard_options(hidden=True) @click.option( "--missing", is_flag=True, help="Create thumbnails for all timelapses that don't yet have one", ) @click.option( "--processes", type=int, help="Number of processes to use for creating thumbnails", default=1, ) @click.argument("paths", nargs=-1, type=click.Path()) @click.pass_context def extract_thumbnails(ctx, missing, processes, paths): """Extract missing thumbnails from timelapses.""" if not paths and not missing: click.echo( "No paths specified and no --missing flag either, nothing to do.", err=True ) ctx.exit(-1) if missing: paths = [] timelapse_folder = ctx.obj.settings.getBaseFolder("timelapse") for entry in os.scandir(timelapse_folder): if is_hidden_path(entry.path) or not valid_timelapse(entry.path): continue thumb = create_thumbnail_path(entry.path) if not os.path.isfile(thumb): paths.append(entry.path) ffmpeg = ctx.obj.settings.get(["webcam", "ffmpeg"]) click.echo(f"Creating thumbnails for {len(paths)} timelapses") executor = ThreadPoolExecutor(max_workers=processes) futures = [executor.submit(_create_thumbnail, ffmpeg, path) for path in paths] wait(futures) click.echo("Done!") def _create_thumbnail(ffmpeg, path): from octoprint.timelapse import TimelapseRenderJob click.echo(f"Creating thumbnail for {path}...") return TimelapseRenderJob._try_generate_thumbnail(ffmpeg, path)
2,985
Python
.py
74
34.351351
103
0.693158
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,866
systeminfo.py
OctoPrint_OctoPrint/src/octoprint/cli/systeminfo.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" import datetime import logging import os import click from zipstream.ng import ZIP_DEFLATED, ZipStream from octoprint.cli import init_platform_for_cli, standard_options click.disable_unicode_literals_warning = True def get_systeminfo( environment_detector, connectivity_checker, settings, additional_fields=None ): from octoprint import __version__ from octoprint.util import dict_flatten if additional_fields is None: additional_fields = {} environment_detector.run_detection(notify_plugins=False) safe_mode_file = os.path.join(settings.getBaseFolder("data"), "last_safe_mode") last_safe_mode = {"date": "unknown", "reason": "unknown"} try: if os.path.exists(safe_mode_file): with open(safe_mode_file) as f: last_safe_mode["reason"] = f.readline().strip() last_safe_mode["date"] = ( datetime.datetime.utcfromtimestamp( os.path.getmtime(safe_mode_file) ).isoformat()[:19] + "Z" ) except Exception as ex: logging.getLogger(__name__).error( "Error while retrieving last safe mode information from {}: {}".format( safe_mode_file, ex ) ) systeminfo = { "octoprint": {"version": __version__, "last_safe_mode": last_safe_mode}, "connectivity": connectivity_checker.as_dict(), "env": environment_detector.environment, "systeminfo": {"generated": datetime.datetime.utcnow().isoformat()[:19] + "Z"}, } # flatten and filter flattened = dict_flatten(systeminfo) flattened["env.python.virtualenv"] = "env.python.virtualenv" in flattened for k, v in additional_fields.items(): if k not in flattened: flattened[k] = v return flattened def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None): from octoprint.util import to_bytes try: z = ZipStream(compress_type=ZIP_DEFLATED) except RuntimeError: # no zlib support z = ZipStream(sized=True) if printer and printer.is_operational(): firmware_info = printer.firmware_info if firmware_info: # add firmware to systeminfo so it's included in systeminfo.txt systeminfo["printer.firmware"] = firmware_info["name"] # Add printer log, if available if hasattr(printer, "_log"): z.add(to_bytes("\n".join(printer._log)), arcname="terminal.txt") # Add reconstructed M115 response, if available if printer._comm and printer._comm._firmware_info: comm = printer._comm m115 = "Reconstructed M115 response:\n\n>>> M115\n<<< " m115 += " ".join([f"{k}:{v}" for k, v in comm._firmware_info.items()]) if comm._firmware_capabilities: m115 += ( "\n<<< " + "\n<<< ".join( [ f"Cap:{k}:{'1' if v else '0'}" for k, v in comm._firmware_capabilities.items() ] ) + "\n\n" ) z.add(to_bytes(m115), arcname="m115.txt") # add systeminfo systeminfotxt = [] for k in sorted(systeminfo.keys()): systeminfotxt.append(f"{k}: {systeminfo[k]}") z.add(to_bytes("\n".join(systeminfotxt)), arcname="systeminfo.txt") # add logs for log in ( "octoprint.log", "serial.log", "tornado.log", ): logpath = os.path.join(logbase, log) if os.path.exists(logpath): z.add_path(logpath, arcname=log) # add additional bundle contents from bundled plugins if plugin_manager: for name, hook in plugin_manager.get_hooks( "octoprint.systeminfo.additional_bundle_files" ).items(): try: plugin = plugin_manager.get_plugin_info(name) if not plugin.bundled: # we only support this for bundled plugins because we don't want # third party logs to blow up the bundles continue logs = hook() for log, content in logs.items(): if isinstance(content, str): # log path if os.path.exists(content) and os.access(content, os.R_OK): z.add_path(content, arcname=log) elif callable(content): # content generating callable try: z.add(to_bytes(content()), arcname=log) except Exception: logging.getLogger(__name__).exception( f"Error while executing callable for additional bundle content {log} for plugin {name}", extra={"plugin": name}, ) except Exception: logging.getLogger(__name__).exception( f"Error while retrieving additional bundle contents for plugin {name}", extra={"plugin": name}, ) return z def get_systeminfo_bundle_name(): import time return "octoprint-systeminfo-{}.zip".format(time.strftime("%Y%m%d%H%M%S")) @click.group() def cli(): pass @cli.command(name="systeminfo") @standard_options() @click.option( "--short", is_flag=True, help="Only output an abridged version of the systeminfo.", ) @click.argument( "path", nargs=1, required=False, type=click.Path(writable=True, dir_okay=True, resolve_path=True), ) @click.pass_context def systeminfo_command(ctx, short, path, **kwargs): """ Creates a system info bundle at PATH. If PATH is not provided, the system info bundle will be created in the current working directory. If --short is provided, only an abridged version of the systeminfo will be output to the console. """ logging.disable(logging.ERROR) try: ( settings, logger, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector, ) = init_platform_for_cli(ctx) except Exception as e: click.echo(str(e), err=True) click.echo("There was a fatal error initializing the platform.", err=True) ctx.exit(-1) else: systeminfo = get_systeminfo( environment_detector, connectivity_checker, settings, additional_fields={"systeminfo.generator": "cli"}, ) if short: # output abridged systeminfo to console for k in sorted(systeminfo.keys()): click.echo(f"{k}: {systeminfo[k]}") else: if not path: path = "." # create zip at path zipfilename = os.path.abspath( os.path.join(path, get_systeminfo_bundle_name()) ) click.echo(f"Writing systeminfo bundle to {zipfilename}...") z = get_systeminfo_bundle( systeminfo, settings.getBaseFolder("logs"), plugin_manager=plugin_manager ) try: with open(zipfilename, "wb") as f: f.writelines(z) except Exception as e: click.echo(str(e), err=True) click.echo(f"There was an error writing to {zipfilename}.", err=True) ctx.exit(-1) click.echo("Done!") click.echo(zipfilename) ctx.exit(0)
7,966
Python
.py
201
28.527363
120
0.568247
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,867
__init__.py
OctoPrint_OctoPrint/src/octoprint/cli/__init__.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import sys import click import octoprint from octoprint.cli.common import LazyGroup click.disable_unicode_literals_warning = True # ~~ click context class OctoPrintContext: """Custom context wrapping the standard options.""" def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False): self.configfile = configfile self.basedir = basedir self.verbosity = verbosity self.safe_mode = safe_mode pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True) """Decorator to pass in the :class:`OctoPrintContext` instance.""" # ~~ Basic CLI initialization for plugins def init_platform_for_cli(ctx): """ Performs a basic platform initialization for the CLI. Plugin implementations will be initialized, but only with a subset of the usual property injections: * _identifier and everything else parsed from metadata * _logger * _connectivity_checker * _environment_detector * _event_bus * _plugin_manager * _settings Returns: the same list of components as returned by ``init_platform`` """ from octoprint import ( init_custom_events, init_platform, init_settings_plugin_config_migration_and_cleanup, init_webcam_compat_overlay, ) from octoprint import octoprint_plugin_inject_factory as opif from octoprint import settings_plugin_inject_factory as spif components = init_platform( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), overlays=get_ctx_obj_option(ctx, "overlays", None), safe_mode=True, disable_color=get_ctx_obj_option(ctx, "no_color", False), ) ( settings, logger, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector, ) = components init_custom_events(plugin_manager) octoprint_plugin_inject_factory = opif( settings, { "plugin_manager": plugin_manager, "event_bus": event_manager, "connectivity_checker": connectivity_checker, "environment_detector": environment_detector, }, ) settings_plugin_inject_factory = spif(settings) plugin_manager.implementation_inject_factories = [ octoprint_plugin_inject_factory, settings_plugin_inject_factory, ] plugin_manager.initialize_implementations() init_settings_plugin_config_migration_and_cleanup(plugin_manager) init_webcam_compat_overlay(settings, plugin_manager) return components # ~~ Custom click option to hide from help class HiddenOption(click.Option): """Custom option sub class with empty help.""" def get_help_record(self, ctx): pass def hidden_option(*param_decls, **attrs): """Attaches a hidden option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged. This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. """ import inspect from click.decorators import _param_memo def decorator(f): if "help" in attrs: attrs["help"] = inspect.cleandoc(attrs["help"]) _param_memo(f, HiddenOption(param_decls, **attrs)) return f return decorator # ~~ helper for setting context options def set_ctx_obj_option(ctx, param, value): """Helper for setting eager options on the context.""" if ctx.obj is None: ctx.obj = OctoPrintContext() if value != param.default: setattr(ctx.obj, param.name, value) elif param.default is not None: setattr(ctx.obj, param.name, param.default) # ~~ helper for retrieving context options def get_ctx_obj_option(ctx, key, default, include_parents=True): if include_parents and hasattr(ctx, "parent") and ctx.parent: fallback = get_ctx_obj_option(ctx.parent, key, default) else: fallback = default return getattr(ctx.obj, key, fallback) # ~~ helper for setting a lot of bulk options def bulk_options(options): """ Utility decorator to decorate a function with a list of click decorators. The provided list of ``options`` will be reversed to ensure correct processing order (inverse from what would be intuitive). """ def decorator(f): options.reverse() for option in options: option(f) return f return decorator # ~~ helper for setting --basedir, --config and --verbose options def standard_options(hidden=False): """ Decorator to add the standard options shared among all "octoprint" commands. If ``hidden`` is set to ``True``, the options will be available on the command but not listed in its help page. """ factory = click.option if hidden: factory = hidden_option options = [ factory( "--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False, help="Specify the basedir to use for configs, uploads, timelapses etc.", ), factory( "--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False, help="Specify the config file to use.", ), factory( "--overlay", "overlays", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, multiple=True, expose_value=False, help="Specify additional config overlays to use.", ), factory( "--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, help="Increase logging verbosity.", ), factory( "--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, help="Enable safe mode; disables all third party plugins.", ), factory( "--no-color", "no_color", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, help="Disable colored console output. Alternatively set the NO_COLOR environment variable to a value of 1.", ), ] return bulk_options(options) # ~~ helper for settings legacy options we still have to support on "octoprint" legacy_options = bulk_options( [ hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option), hidden_option("--port", type=click.INT, callback=set_ctx_obj_option), hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option), hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option), hidden_option( "--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option, ), hidden_option( "--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option, ), hidden_option( "--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option ), hidden_option( "--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option, ), ] ) """Legacy options available directly on the "octoprint" command in earlier versions. Kept available for reasons of backwards compatibility, but hidden from the generated help pages.""" # ~~ command groups from sub modules @click.group() def subcommands(): pass @subcommands.group( name="analysis", cls=LazyGroup, import_name="octoprint.cli.analysis:cli" ) def analysis(): """Analysis tools.""" pass @subcommands.group(name="client", cls=LazyGroup, import_name="octoprint.cli.client:cli") def client(): """Basic API client.""" pass @subcommands.group(name="config", cls=LazyGroup, import_name="octoprint.cli.config:cli") def config(): """Basic config manipulation.""" pass @subcommands.group(name="dev", cls=LazyGroup, import_name="octoprint.cli.dev:cli") def dev(): """Additional commands for development tasks.""" pass @subcommands.group(name="plugins", cls=LazyGroup, import_name="octoprint.cli.plugins:cli") def plugins(): """Additional commands provided by plugins.""" pass @subcommands.group( name="timelapse", cls=LazyGroup, import_name="octoprint.cli.timelapse:cli" ) def timelapse(): """Timelapse related commands.""" pass @subcommands.group(name="user", cls=LazyGroup, import_name="octoprint.cli.user:cli") def user(): """User management.""" pass # ~~ "octoprint" command, merges server_commands and plugin_commands groups from .server import cli as server_commands # noqa: E402 from .systeminfo import cli as systeminfo_commands # noqa: E402 @click.group( name="octoprint", invoke_without_command=True, cls=click.CommandCollection, sources=[ subcommands, server_commands, systeminfo_commands, ], ) @standard_options() @legacy_options @click.version_option(version=octoprint.__version__, allow_from_autoenv=False) @click.pass_context def octo(ctx, **kwargs): if ctx.invoked_subcommand is None: # We have to support calling the octoprint command without any # sub commands to remain backwards compatible. # # But better print a message to inform people that they should # use the sub commands instead. def get_value(key): return get_ctx_obj_option(ctx, key, kwargs.get(key)) daemon = get_value("daemon") if daemon: click.echo( 'Daemon operation via "octoprint --daemon ' 'start|stop|restart" is deprecated, please use ' '"octoprint daemon start|stop|restart" from now on' ) if sys.platform == "win32" or sys.platform == "darwin": click.echo( "Sorry, daemon mode is not supported under your operating system right now" ) else: from octoprint.cli.server import daemon_command ctx.invoke(daemon_command, command=daemon, **kwargs) else: click.echo( 'Starting the server via "octoprint" is deprecated, ' 'please use "octoprint serve" from now on.' ) from octoprint.cli.server import serve_command ctx.invoke(serve_command, **kwargs)
11,314
Python
.py
309
28.773463
120
0.637072
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,868
common.py
OctoPrint_OctoPrint/src/octoprint/cli/common.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" from importlib import import_module import click from werkzeug.utils import cached_property class LazyGroup(click.Group): """ A click Group that imports the actual implementation only when needed. This allows for more resilient CLIs where the top-level command does not fail when a subcommand is broken enough to fail at import time. """ # shared by https://github.com/indico/indico in pallets/click#945 def __init__(self, import_name, **kwargs): self._import_name = import_name click.Group.__init__(self, **kwargs) @cached_property def _impl(self): module, name = self._import_name.split(":", 1) return getattr(import_module(module), name) def get_command(self, ctx, cmd_name): return self._impl.get_command(ctx, cmd_name) def list_commands(self, ctx): return self._impl.list_commands(ctx) def invoke(self, ctx): return self._impl.invoke(ctx) def get_usage(self, ctx): return self._impl.get_usage(ctx) def get_params(self, ctx): return self._impl.get_params(ctx)
1,302
Python
.py
30
37.566667
103
0.691819
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,869
server.py
OctoPrint_OctoPrint/src/octoprint/cli/server.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import sys import click from octoprint.cli import ( bulk_options, get_ctx_obj_option, set_ctx_obj_option, standard_options, ) click.disable_unicode_literals_warning = True def run_server( basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode, ignore_blacklist, octoprint_daemon=None, overlays=None, disable_color=False, ): """Initializes the environment and starts up the server.""" from octoprint import FatalStartupError, __display_version__, init_platform def log_startup(recorder=None, safe_mode=None, **kwargs): from octoprint.logging import get_divider_line from octoprint.logging.handlers import PluginTimingsLogHandler logger = logging.getLogger("octoprint.startup") PluginTimingsLogHandler.arm_rollover() logger.info(get_divider_line("*")) logger.info(f"Starting OctoPrint {__display_version__}") if safe_mode: logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") if safe_mode == "flag": reason = "command line flag" elif safe_mode == "settings": reason = "setting in config.yaml" elif safe_mode == "incomplete_startup": reason = "problem during last startup" else: reason = "unknown" logger.info(f"Reason for safe mode: {reason}") if recorder and len(recorder): logger.info(get_divider_line("-", "Logged during platform initialization:")) from octoprint.logging.handlers import CombinedLogHandler handler = CombinedLogHandler(*logging.getLogger().handlers) recorder.setTarget(handler) recorder.flush() logger.info(get_divider_line("-")) from octoprint import urllib3_ssl if not urllib3_ssl: logging.getLogger("octoprint.server").warning( "requests/urllib3 will run in an insecure SSL environment. " "You might see corresponding warnings logged later " '("InsecurePlatformWarning"). It is recommended to either ' "update to a Python version >= 2.7.9 or alternatively " "install PyOpenSSL plus its dependencies. For details see " "https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl" ) logger.info(get_divider_line("*")) def log_register_rollover( safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs ): from octoprint.logging import get_divider_line, get_handler, log_to_handler from octoprint.logging.handlers import OctoPrintLogHandler def rollover_callback(): handler = get_handler("file") if handler is None: return logger = logging.getLogger("octoprint.server") def _log(message, level=logging.INFO): log_to_handler(logger, handler, level, message) _log(get_divider_line("-", "Log roll over detected")) _log(f"OctoPrint {__display_version__}") if safe_mode: _log("SAFE MODE is active. Third party plugins are disabled!") plugin_manager.log_all_plugins(only_to_handler=handler) environment_detector.log_detected_environment(only_to_handler=handler) _log(get_divider_line("-")) OctoPrintLogHandler.registerRolloverCallback(rollover_callback) try: components = init_platform( basedir, configfile, overlays=overlays, logging_file=logging_config, debug=debug, verbosity=verbosity, uncaught_logger=__name__, safe_mode=safe_mode, ignore_blacklist=ignore_blacklist, after_safe_mode=log_startup, after_environment_detector=log_register_rollover, disable_color=disable_color, ) ( settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector, ) = components except FatalStartupError as e: logger = logging.getLogger("octoprint.startup").fatal echo = lambda x: click.echo(x, err=True) for method in logger, echo: method(str(e)) method("There was a fatal error starting up OctoPrint.") else: from octoprint.server import CannotStartServerException, Server octoprint_server = Server( settings=settings, plugin_manager=plugin_manager, event_manager=event_manager, connectivity_checker=connectivity_checker, environment_detector=environment_detector, host=host, port=port, v6_only=v6_only, debug=debug, safe_mode=safe_mode, allow_root=allow_root, octoprint_daemon=octoprint_daemon, ) try: octoprint_server.run() except CannotStartServerException as e: logger = logging.getLogger("octoprint.startup").fatal echo = lambda x: click.echo(x, err=True) for method in logger, echo: method(str(e)) method("There was a fatal error starting up OctoPrint.") # ~~ server options server_options = bulk_options( [ click.option( "--host", type=click.STRING, callback=set_ctx_obj_option, help="Specify the host address on which to bind the server.", ), click.option( "--port", type=click.INT, callback=set_ctx_obj_option, help="Specify the port on which to bind the server.", ), click.option( "-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option, help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present.", ), click.option( "-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option, help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present.", ), click.option( "--logging", type=click.Path(), callback=set_ctx_obj_option, help="Specify the config file to use for configuring logging.", ), click.option( "--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option, help="Allow OctoPrint to run as user root.", ), click.option( "--debug", is_flag=True, callback=set_ctx_obj_option, help="Enable debug mode.", ), click.option( "--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option, help="Disable processing of the plugin blacklist.", ), ] ) """Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6`` ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" daemon_options = bulk_options( [ click.option( "--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option, help="Pidfile to use for daemonizing.", ) ] ) """Decorator to add the options for the daemon subcommand: ``--pid``.""" # ~~ "octoprint serve" and "octoprint daemon" commands @click.group() def cli(): pass @cli.command(name="safemode") @standard_options() @click.pass_context def enable_safemode(ctx, **kwargs): """Sets the safe mode flag for the next start.""" from octoprint import FatalStartupError, init_settings logging.basicConfig( level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN ) try: settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), overlays=get_ctx_obj_option(ctx, "overlays", None), ) except FatalStartupError as e: click.echo(str(e), err=True) click.echo("There was a fatal error initializing the settings manager.", err=True) ctx.exit(-1) else: settings.setBoolean(["server", "startOnceInSafeMode"], True) settings.save() click.echo( "Safe mode flag set, OctoPrint will start in safe mode on next restart." ) @cli.command(name="serve") @standard_options() @server_options @click.pass_context def serve_command(ctx, **kwargs): """Starts the OctoPrint server.""" def get_value(key): return get_ctx_obj_option(ctx, key, kwargs.get(key)) host = get_value("host") port = get_value("port") v4 = get_value("v4") v6 = get_value("v6") logging = get_value("logging") allow_root = get_value("allow_root") debug = get_value("debug") basedir = get_value("basedir") configfile = get_value("configfile") verbosity = get_value("verbosity") safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") overlays = get_value("overlays") no_color = get_value("no_color") if v4 and not host: host = "0.0.0.0" run_server( basedir, configfile, host, port, v6, debug, allow_root, logging, verbosity, safe_mode, ignore_blacklist, overlays=overlays, disable_color=no_color, ) if sys.platform != "win32" and sys.platform != "darwin": # we do not support daemon mode under windows or macosx @cli.command(name="daemon") @standard_options() @server_options @daemon_options @click.argument( "command", type=click.Choice(["start", "stop", "restart", "status"]), metavar="start|stop|restart|status", ) @click.pass_context def daemon_command(ctx, command, **kwargs): """ Starts, stops or restarts in daemon mode. Please note that daemon mode is not supported under Windows and MacOSX right now. """ def get_value(key): return get_ctx_obj_option(ctx, key, kwargs.get(key)) host = get_value("host") port = get_value("port") v4 = get_value("v4") v6 = get_value("v6") logging = get_value("logging") allow_root = get_value("allow_root") debug = get_value("debug") pid = get_value("pid") basedir = get_value("basedir") configfile = get_value("configfile") overlays = get_value("overlays") verbosity = get_value("verbosity") safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") if v4 and not host: host = "0.0.0.0" if pid is None: click.echo("No path to a pidfile set", file=sys.stderr) sys.exit(1) from octoprint.daemon import Daemon class OctoPrintDaemon(Daemon): def __init__( self, pidfile, basedir, configfile, overlays, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode, ignore_blacklist, ): Daemon.__init__(self, pidfile) self._basedir = basedir self._configfile = configfile self._overlays = overlays self._host = host self._port = port self._v6_only = v6_only self._debug = debug self._allow_root = allow_root self._logging_config = logging_config self._verbosity = verbosity self._safe_mode = safe_mode self._ignore_blacklist = ignore_blacklist def run(self): run_server( self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug, self._allow_root, self._logging_config, self._verbosity, self._safe_mode, self._ignore_blacklist, octoprint_daemon=self, overlays=self._overlays, ) octoprint_daemon = OctoPrintDaemon( pid, basedir, configfile, overlays, host, port, v6, debug, allow_root, logging, verbosity, safe_mode, ignore_blacklist, ) if command == "start": octoprint_daemon.start() elif command == "stop": octoprint_daemon.stop() elif command == "restart": octoprint_daemon.restart() elif command == "status": octoprint_daemon.status()
13,924
Python
.py
391
25.102302
137
0.565182
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,870
users.py
OctoPrint_OctoPrint/src/octoprint/access/users.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import hashlib import logging import os import shutil import time import uuid import wrapt from flask_login import AnonymousUserMixin, UserMixin from passlib.hash import pbkdf2_sha256 from werkzeug.local import LocalProxy from octoprint.access.groups import Group, GroupChangeListener from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.settings import settings as s from octoprint.util import atomic_write, deprecated, generate_api_key from octoprint.util import get_fully_qualified_classname as fqcn from octoprint.util import to_bytes, yaml password_hashers = [] try: from passlib.hash import argon2 # test if we can actually hash and verify, if not we won't use this backend hash = argon2.hash("test") assert argon2.verify("test", hash) password_hashers.append(argon2) except Exception: logging.getLogger(__name__).warning( "Argon2 passlib backend is not available, not using it for password hashing" ) password_hashers.append(pbkdf2_sha256) class UserManager(GroupChangeListener): def __init__(self, group_manager, settings=None): self._group_manager = group_manager self._group_manager.register_listener(self) self._logger = logging.getLogger(__name__) self._session_users_by_session = {} self._sessionids_by_userid = {} if settings is None: settings = s() self._settings = settings self._login_status_listeners = [] def register_login_status_listener(self, listener): self._login_status_listeners.append(listener) def unregister_login_status_listener(self, listener): self._login_status_listeners.remove(listener) def anonymous_user_factory(self): return AnonymousUser([self._group_manager.guest_group]) def api_user_factory(self): return ApiUser([self._group_manager.admin_group, self._group_manager.user_group]) @property def enabled(self): return True def login_user(self, user): self._cleanup_sessions() if user is None or user.is_anonymous: return if isinstance(user, LocalProxy): # noinspection PyProtectedMember user = user._get_current_object() if not isinstance(user, User): return None if not isinstance(user, SessionUser): user = SessionUser(user) self._session_users_by_session[user.session] = user userid = user.get_id() if userid not in self._sessionids_by_userid: self._sessionids_by_userid[userid] = set() self._sessionids_by_userid[userid].add(user.session) for listener in self._login_status_listeners: try: listener.on_user_logged_in(user) except Exception: self._logger.exception( f"Error in on_user_logged_in on {listener!r}", extra={"callback": fqcn(listener)}, ) self._logger.info(f"Logged in user: {user.get_id()}") return user def logout_user(self, user, stale=False): if user is None or user.is_anonymous: return if isinstance(user, LocalProxy): user = user._get_current_object() if not isinstance(user, SessionUser): return userid = user.get_id() sessionid = user.session if userid in self._sessionids_by_userid: try: self._sessionids_by_userid[userid].remove(sessionid) except KeyError: pass if sessionid in self._session_users_by_session: try: del self._session_users_by_session[sessionid] except KeyError: pass for listener in self._login_status_listeners: try: listener.on_user_logged_out(user, stale=stale) except Exception: self._logger.exception( f"Error in on_user_logged_out on {listener!r}", extra={"callback": fqcn(listener)}, ) self._logger.info(f"Logged out user: {user.get_id()}") def _cleanup_sessions(self): for session, user in list(self._session_users_by_session.items()): if not isinstance(user, SessionUser): continue if user.touched + (15 * 60) < time.monotonic(): self._logger.info( f"Cleaning up user session {session} for user {user.get_id()}" ) self.logout_user(user, stale=True) @staticmethod def create_password_hash(password, *args, **kwargs): return password_hashers[0].hash(password) @staticmethod def create_legacy_password_hash(password, salt): return hashlib.sha512( to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt) ).hexdigest() def check_password(self, username, password): user = self.find_user(username) if not user: return False if user.check_password(password): # password matches, correct password return True else: # new hash doesn't match, check legacy hash salt = self._settings.get(["accessControl"], asdict=True, merged=True).get( "salt", None ) if salt is None: return False legacy_hash = UserManager.create_legacy_password_hash(password, salt) if user.check_password(legacy_hash, legacy=True): # legacy hash matches, we migrate the stored password hash to the new one and return True since it's the correct password self.change_user_password(username, password) return True else: # legacy hash doesn't match either, wrong password return False def cleanup_legacy_hashes(self): pass def signature_key_for_user(self, username, secret): return hashlib.sha512( to_bytes(username, encoding="utf-8", errors="replace") + to_bytes(secret) ).hexdigest() def add_user(self, username, password, active, permissions, groups, overwrite=False): pass def change_user_activation(self, username, active): pass def change_user_permissions(self, username, permissions): pass def add_permissions_to_user(self, username, permissions): pass def remove_permissions_from_user(self, username, permissions): pass def change_user_groups(self, username, groups): pass def add_groups_to_user(self, username, groups): pass def remove_groups_from_user(self, username, groups): pass def remove_groups_from_users(self, group): pass def change_user_password(self, username, password): pass def get_user_setting(self, username, key): return None def get_all_user_settings(self, username): return {} def change_user_setting(self, username, key, value): pass def change_user_settings(self, username, new_settings): pass def remove_user(self, username): if username in self._sessionids_by_userid: sessions = self._sessionids_by_userid[username] for session in sessions: if session in self._session_users_by_session: del self._session_users_by_session[session] del self._sessionids_by_userid[username] def validate_user_session(self, userid, session): self._cleanup_sessions() if session in self._session_users_by_session: user = self._session_users_by_session[session] return userid == user.get_id() return False def find_user(self, userid=None, session=None, fresh=False): self._cleanup_sessions() if session is not None and session in self._session_users_by_session: user = self._session_users_by_session[session] if userid is None or userid == user.get_id(): user.touch() return user return None def find_sessions_for(self, matcher): self._cleanup_sessions() result = [] for user in self.get_all_users(): if matcher(user): try: session_ids = self._sessionids_by_userid[user.get_id()] for session_id in session_ids: try: session_user = self._session_users_by_session[session_id] session_user.touch() result.append(session_user) except KeyError: # unknown session after all continue except KeyError: # no session for user pass return result def get_all_users(self): return [] def has_been_customized(self): return False def on_group_removed(self, group): self._logger.debug(f"Group {group.key} got removed, removing from all users") self.remove_groups_from_users([group]) def on_group_permissions_changed(self, group, added=None, removed=None): users = self.find_sessions_for(lambda u: group in u.groups) for listener in self._login_status_listeners: try: for user in users: listener.on_user_modified(user) except Exception: self._logger.exception( f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) def on_group_subgroups_changed(self, group, added=None, removed=None): users = self.find_sessions_for(lambda u: group in u.groups) for listener in self._login_status_listeners: # noinspection PyBroadException try: for user in users: listener.on_user_modified(user) except Exception: self._logger.exception( f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) def _trigger_on_user_modified(self, user): if isinstance(user, str): # user id users = [] try: session_ids = self._sessionids_by_userid[user] for session_id in session_ids: try: users.append(self._session_users_by_session[session_id]) except KeyError: # unknown session id continue except KeyError: # no session for user return elif isinstance(user, User) and not isinstance(user, SessionUser): users = self.find_sessions_for(lambda u: u.get_id() == user.get_id()) elif isinstance(user, User): users = [user] else: return for listener in self._login_status_listeners: try: for user in users: listener.on_user_modified(user) except Exception: self._logger.exception( f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) def _trigger_on_user_removed(self, username): for listener in self._login_status_listeners: try: listener.on_user_removed(username) except Exception: self._logger.exception( f"Error in on_user_removed on {listener!r}", extra={"callback": fqcn(listener)}, ) # ~~ Deprecated methods follow # TODO: Remove deprecated methods in OctoPrint 1.5.0 @deprecated( "changeUserRoles has been replaced by change_user_permissions", includedoc="Replaced by :func:`change_user_permissions`", since="1.4.0", ) def changeUserRoles(self, username, roles): user = self.find_user(username) if user is None: raise UnknownUser(username) removed_roles = set(user._roles) - set(roles) self.removeRolesFromUser(username, removed_roles, user=user) added_roles = set(roles) - set(user._roles) self.addRolesToUser(username, added_roles, user=user) @deprecated( "addRolesToUser has been replaced by add_permissions_to_user", includedoc="Replaced by :func:`add_permissions_to_user`", since="1.4.0", ) def addRolesToUser(self, username, roles, user=None): if user is None: user = self.find_user(username) if user is None: raise UnknownUser(username) if "admin" in roles: self.add_groups_to_user(username, self._group_manager.admin_group) if "user" in roles: self.remove_groups_from_user(username, self._group_manager.user_group) @deprecated( "removeRolesFromUser has been replaced by remove_permissions_from_user", includedoc="Replaced by :func:`remove_permissions_from_user`", since="1.4.0", ) def removeRolesFromUser(self, username, roles, user=None): if user is None: user = self.find_user(username) if user is None: raise UnknownUser(username) if "admin" in roles: self.remove_groups_from_user(username, self._group_manager.admin_group) self.remove_permissions_from_user(username, Permissions.ADMIN) if "user" in roles: self.remove_groups_from_user(username, self._group_manager.user_group) checkPassword = deprecated( "checkPassword has been renamed to check_password", includedoc="Replaced by :func:`check_password`", since="1.4.0", )(check_password) addUser = deprecated( "addUser has been renamed to add_user", includedoc="Replaced by :func:`add_user`", since="1.4.0", )(add_user) changeUserActivation = deprecated( "changeUserActivation has been renamed to change_user_activation", includedoc="Replaced by :func:`change_user_activation`", since="1.4.0", )(change_user_activation) changeUserPassword = deprecated( "changeUserPassword has been renamed to change_user_password", includedoc="Replaced by :func:`change_user_password`", since="1.4.0", )(change_user_password) getUserSetting = deprecated( "getUserSetting has been renamed to get_user_setting", includedoc="Replaced by :func:`get_user_setting`", since="1.4.0", )(get_user_setting) getAllUserSettings = deprecated( "getAllUserSettings has been renamed to get_all_user_settings", includedoc="Replaced by :func:`get_all_user_settings`", since="1.4.0", )(get_all_user_settings) changeUserSetting = deprecated( "changeUserSetting has been renamed to change_user_setting", includedoc="Replaced by :func:`change_user_setting`", since="1.4.0", )(change_user_setting) changeUserSettings = deprecated( "changeUserSettings has been renamed to change_user_settings", includedoc="Replaced by :func:`change_user_settings`", since="1.4.0", )(change_user_settings) removeUser = deprecated( "removeUser has been renamed to remove_user", includedoc="Replaced by :func:`remove_user`", since="1.4.0", )(remove_user) findUser = deprecated( "findUser has been renamed to find_user", includedoc="Replaced by :func:`find_user`", since="1.4.0", )(find_user) getAllUsers = deprecated( "getAllUsers has been renamed to get_all_users", includedoc="Replaced by :func:`get_all_users`", since="1.4.0", )(get_all_users) hasBeenCustomized = deprecated( "hasBeenCustomized has been renamed to has_been_customized", includedoc="Replaced by :func:`has_been_customized`", since="1.4.0", )(has_been_customized) class LoginStatusListener: def on_user_logged_in(self, user): pass def on_user_logged_out(self, user, stale=False): pass def on_user_modified(self, user): pass def on_user_removed(self, userid): pass ##~~ FilebasedUserManager, takes available users from users.yaml file class FilebasedUserManager(UserManager): FILE_VERSION = 2 def __init__(self, group_manager, path=None, settings=None): UserManager.__init__(self, group_manager, settings=settings) self._logger = logging.getLogger(__name__) if path is None: path = self._settings.get(["accessControl", "userfile"]) if path is None: path = os.path.join(s().getBaseFolder("base"), "users.yaml") self._userfile = path self._users = {} self._dirty = False self._customized = None self._load() def _load(self): if os.path.exists(self._userfile) and os.path.isfile(self._userfile): data = yaml.load_from_file(path=self._userfile) if not data or not isinstance(data, dict): self._logger.fatal( "{} does not contain a valid map of users. Fix " "the file, or remove it, then restart OctoPrint.".format( self._userfile ) ) raise CorruptUserStorage() version = data.pop("_version", 1) if version != self.FILE_VERSION: self._logger.info( f"Making a backup of the users.yaml file before migrating from version {version} to {self.FILE_VERSION}" ) shutil.copy( self._userfile, os.path.splitext(self._userfile)[0] + f".v{version}.yaml", ) self._dirty = True for name, attributes in data.items(): if not isinstance(attributes, dict): continue permissions = [] if "permissions" in attributes: permissions = attributes["permissions"] if "groups" in attributes: groups = set(attributes["groups"]) else: groups = {self._group_manager.user_group} # migrate from roles to permissions if "roles" in attributes and "permissions" not in attributes: self._logger.info( f"Migrating user {name} to new granular permission system" ) groups |= set(self._migrate_roles_to_groups(attributes["roles"])) self._dirty = True apikey = None if "apikey" in attributes: apikey = attributes["apikey"] settings = {} if "settings" in attributes: settings = attributes["settings"] self._users[name] = User( username=name, passwordHash=attributes["password"], active=attributes["active"], permissions=self._to_permissions(*permissions), groups=self._to_groups(*groups), apikey=apikey, settings=settings, ) for sessionid in self._sessionids_by_userid.get(name, set()): if sessionid in self._session_users_by_session: self._session_users_by_session[sessionid].update_user( self._users[name] ) if self._dirty: self._save() self.cleanup_legacy_hashes() self._customized = True else: self._customized = False def _save(self, force=False): if not self._dirty and not force: return data = {"_version": self.FILE_VERSION} for name, user in self._users.items(): if not user or not isinstance(user, User): continue data[name] = { "password": user._passwordHash, "active": user._active, "groups": self._from_groups(*user._groups), "permissions": self._from_permissions(*user._permissions), "apikey": user._apikey, "settings": user._settings, # TODO: deprecated, remove in 1.5.0 "roles": user._roles, } with atomic_write( self._userfile, mode="wt", permissions=0o600, max_permissions=0o666 ) as f: yaml.save_to_file(data, file=f, pretty=True) self._dirty = False self._load() def _migrate_roles_to_groups(self, roles): # If admin is inside the roles, just return admin group if "admin" in roles: return [self._group_manager.admin_group, self._group_manager.user_group] else: return [self._group_manager.user_group] def _refresh_groups(self, user): user._groups = self._to_groups(*map(lambda g: g.key, user.groups)) def add_user( self, username, password, active=False, permissions=None, groups=None, apikey=None, overwrite=False, ): if permissions is None: permissions = [] permissions = self._to_permissions(*permissions) if groups is None: groups = self._group_manager.default_groups groups = self._to_groups(*groups) if username in self._users and not overwrite: raise UserAlreadyExists(username) if not username.strip() or username != username.strip(): raise InvalidUsername(username) self._users[username] = User( username, UserManager.create_password_hash(password, settings=self._settings), active, permissions, groups, apikey=apikey, ) self._dirty = True self._save() def change_user_activation(self, username, active): if username not in self._users: raise UnknownUser(username) if self._users[username].is_active != active: self._users[username]._active = active self._dirty = True self._save() self._trigger_on_user_modified(username) def change_user_permissions(self, username, permissions): if username not in self._users: raise UnknownUser(username) user = self._users[username] permissions = self._to_permissions(*permissions) removed_permissions = list(set(user._permissions) - set(permissions)) added_permissions = list(set(permissions) - set(user._permissions)) if len(removed_permissions) > 0: user.remove_permissions_from_user(removed_permissions) self._dirty = True if len(added_permissions) > 0: user.add_permissions_to_user(added_permissions) self._dirty = True if self._dirty: self._save() self._trigger_on_user_modified(username) def add_permissions_to_user(self, username, permissions): if username not in self._users: raise UnknownUser(username) if self._users[username].add_permissions_to_user( self._to_permissions(*permissions) ): self._dirty = True self._save() self._trigger_on_user_modified(username) def remove_permissions_from_user(self, username, permissions): if username not in self._users: raise UnknownUser(username) if self._users[username].remove_permissions_from_user( self._to_permissions(*permissions) ): self._dirty = True self._save() self._trigger_on_user_modified(username) def remove_permissions_from_users(self, permissions): modified = [] for user in self._users: dirty = user.remove_permissions_from_user(self._to_permissions(*permissions)) if dirty: self._dirty = True modified.append(user.get_id()) if self._dirty: self._save() for username in modified: self._trigger_on_user_modified(username) def change_user_groups(self, username, groups): if username not in self._users: raise UnknownUser(username) user = self._users[username] groups = self._to_groups(*groups) removed_groups = list(set(user._groups) - set(groups)) added_groups = list(set(groups) - set(user._groups)) if len(removed_groups): self._dirty |= user.remove_groups_from_user(removed_groups) if len(added_groups): self._dirty |= user.add_groups_to_user(added_groups) if self._dirty: self._save() self._trigger_on_user_modified(username) def add_groups_to_user(self, username, groups, save=True, notify=True): if username not in self._users: raise UnknownUser(username) if self._users[username].add_groups_to_user(self._to_groups(*groups)): self._dirty = True if save: self._save() if notify: self._trigger_on_user_modified(username) def remove_groups_from_user(self, username, groups, save=True, notify=True): if username not in self._users: raise UnknownUser(username) if self._users[username].remove_groups_from_user(self._to_groups(*groups)): self._dirty = True if save: self._save() if notify: self._trigger_on_user_modified(username) def remove_groups_from_users(self, groups): modified = [] for username, user in self._users.items(): dirty = user.remove_groups_from_user(self._to_groups(*groups)) if dirty: self._dirty = True modified.append(username) if self._dirty: self._save() for username in modified: self._trigger_on_user_modified(username) def change_user_password(self, username, password): if username not in self._users: raise UnknownUser(username) user = self._users[username] user._passwordHash = UserManager.create_password_hash(password) self._dirty = True self._save() self._trigger_on_user_modified(user) def cleanup_legacy_hashes(self): no_legacy = all( map( lambda u: u._passwordHash.startswith("$argon2id$") or u._passwordHash.startswith("$pbkdf2-"), self._users.values(), ) ) salt = self._settings.get(["accessControl"], asdict=True, merged=True).get( "salt", None ) if no_legacy and salt: # no legacy hashes left, kill salt self._settings.backup("cleanup_legacy_hashes") self._settings.remove(["accessControl", "salt"]) self._settings.save() def signature_key_for_user(self, username, secret): if username == "_api": return super().signature_key_for_user(username, secret) if username not in self._users: raise UnknownUser(username) user = self._users[username] return hashlib.sha512( to_bytes(username + user._passwordHash, encoding="utf-8", errors="replace") + to_bytes(secret) ).hexdigest() def change_user_setting(self, username, key, value): if username not in self._users: raise UnknownUser(username) user = self._users[username] 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() def change_user_settings(self, username, new_settings): if username not in self._users: raise UnknownUser(username) user = self._users[username] for key, value in new_settings.items(): old_value = user.get_setting(key) user.set_setting(key, value) self._dirty = self._dirty or old_value != value self._save() def get_all_user_settings(self, username): if username not in self._users: raise UnknownUser(username) user = self._users[username] return user.get_all_settings() def get_user_setting(self, username, key): if username not in self._users: raise UnknownUser(username) user = self._users[username] return user.get_setting(key) def generate_api_key(self, username): if username not in self._users: raise UnknownUser(username) user = self._users[username] user._apikey = generate_api_key() self._dirty = True self._save() return user._apikey def delete_api_key(self, username): if username not in self._users: raise UnknownUser(username) user = self._users[username] user._apikey = None self._dirty = True self._save() def remove_user(self, username): UserManager.remove_user(self, username) if username not in self._users: raise UnknownUser(username) del self._users[username] self._dirty = True self._save() def find_user(self, userid=None, apikey=None, session=None, fresh=False): user = UserManager.find_user(self, userid=userid, session=session) if user is not None or (session and fresh): return user if userid is not None: if userid not in self._users: return None return self._users[userid] elif apikey is not None: for user in self._users.values(): if apikey == user._apikey: return user return None else: return None def get_all_users(self): return list(self._users.values()) def has_been_customized(self): return self._customized def on_group_permissions_changed(self, group, added=None, removed=None): # refresh our group references for user in self.get_all_users(): if group in user.groups: self._refresh_groups(user) # call parent UserManager.on_group_permissions_changed( self, group, added=added, removed=removed ) def on_group_subgroups_changed(self, group, added=None, removed=None): # refresh our group references for user in self.get_all_users(): if group in user.groups: self._refresh_groups(user) # call parent UserManager.on_group_subgroups_changed(self, group, added=added, removed=removed) # ~~ Helpers def _to_groups(self, *groups): return list( set( filter( lambda x: x is not None, (self._group_manager._to_group(group) for group in groups), ) ) ) def _to_permissions(self, *permissions): return list( set( filter( lambda x: x is not None, (Permissions.find(permission) for permission in permissions), ) ) ) def _from_groups(self, *groups): return list({group.key for group in groups}) def _from_permissions(self, *permissions): return list({permission.key for permission in permissions}) # ~~ Deprecated methods follow # TODO: Remove deprecated methods in OctoPrint 1.5.0 generateApiKey = deprecated( "generateApiKey has been renamed to generate_api_key", includedoc="Replaced by :func:`generate_api_key`", since="1.4.0", )(generate_api_key) deleteApiKey = deprecated( "deleteApiKey has been renamed to delete_api_key", includedoc="Replaced by :func:`delete_api_key`", since="1.4.0", )(delete_api_key) addUser = deprecated( "addUser has been renamed to add_user", includedoc="Replaced by :func:`add_user`", since="1.4.0", )(add_user) changeUserActivation = deprecated( "changeUserActivation has been renamed to change_user_activation", includedoc="Replaced by :func:`change_user_activation`", since="1.4.0", )(change_user_activation) changeUserPassword = deprecated( "changeUserPassword has been renamed to change_user_password", includedoc="Replaced by :func:`change_user_password`", since="1.4.0", )(change_user_password) getUserSetting = deprecated( "getUserSetting has been renamed to get_user_setting", includedoc="Replaced by :func:`get_user_setting`", since="1.4.0", )(get_user_setting) getAllUserSettings = deprecated( "getAllUserSettings has been renamed to get_all_user_settings", includedoc="Replaced by :func:`get_all_user_settings`", since="1.4.0", )(get_all_user_settings) changeUserSetting = deprecated( "changeUserSetting has been renamed to change_user_setting", includedoc="Replaced by :func:`change_user_setting`", since="1.4.0", )(change_user_setting) changeUserSettings = deprecated( "changeUserSettings has been renamed to change_user_settings", includedoc="Replaced by :func:`change_user_settings`", since="1.4.0", )(change_user_settings) removeUser = deprecated( "removeUser has been renamed to remove_user", includedoc="Replaced by :func:`remove_user`", since="1.4.0", )(remove_user) findUser = deprecated( "findUser has been renamed to find_user", includedoc="Replaced by :func:`find_user`", since="1.4.0", )(find_user) getAllUsers = deprecated( "getAllUsers has been renamed to get_all_users", includedoc="Replaced by :func:`get_all_users`", since="1.4.0", )(get_all_users) hasBeenCustomized = deprecated( "hasBeenCustomized has been renamed to has_been_customized", includedoc="Replaced by :func:`has_been_customized`", since="1.4.0", )(has_been_customized) ##~~ Exceptions class UserAlreadyExists(Exception): def __init__(self, username): Exception.__init__(self, "User %s already exists" % username) class InvalidUsername(Exception): def __init__(self, username): Exception.__init__(self, "Username '%s' is invalid" % username) class UnknownUser(Exception): def __init__(self, username): Exception.__init__(self, "Unknown user: %s" % username) class UnknownRole(Exception): def __init__(self, role): Exception.__init__(self, "Unknown role: %s" % role) class CorruptUserStorage(Exception): pass ##~~ Refactoring helpers class MethodReplacedByBooleanProperty: 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) ##~~ User object class User(UserMixin): def __init__( self, username, passwordHash, active, permissions=None, groups=None, apikey=None, settings=None, ): if permissions is None: permissions = [] if groups is None: groups = [] self._username = username self._passwordHash = passwordHash self._active = active self._permissions = permissions self._groups = groups self._apikey = apikey if settings is None: settings = {} self._settings = settings def as_dict(self): from octoprint.access.permissions import OctoPrintPermission return { "name": self._username, "active": bool(self.is_active), "permissions": list(map(lambda p: p.key, self._permissions)), "groups": list(map(lambda g: g.key, self._groups)), "needs": OctoPrintPermission.convert_needs_to_dict(self.needs), "apikey": self._apikey, "settings": self._settings, # TODO: deprecated, remove in 1.5.0 "admin": self.has_permission(Permissions.ADMIN), "user": not self.is_anonymous, "roles": self._roles, } def check_password(self, password, legacy=False): if legacy: return self._passwordHash == password for password_hash in password_hashers: if password_hash.identify(self._passwordHash): try: return password_hash.verify(password, self._passwordHash) except ValueError: pass return False def get_id(self): return self.get_name() 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 FlaskLoginMethodReplacedByBooleanProperty( "is_active", lambda: self._active ) def get_all_settings(self): return self._settings def get_setting(self, key): if not isinstance(key, (tuple, list)): path = [key] else: path = key return self._get_setting(path) def set_setting(self, key, value): if not isinstance(key, (tuple, list)): path = [key] else: path = key return self._set_setting(path, value) def _get_setting(self, path): s = self._settings for p in path: if isinstance(s, dict) and p in s: s = s[p] else: return None return s def _set_setting(self, path, value): s = self._settings for p in path[:-1]: if p not in s: s[p] = {} if not isinstance(s[p], dict): s[p] = {} s = s[p] key = path[-1] s[key] = value return True def add_permissions_to_user(self, permissions): # Make sure the permissions variable is of type list if not isinstance(permissions, list): permissions = [permissions] assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) dirty = False for permission in permissions: if permissions not in self._permissions: self._permissions.append(permission) dirty = True return dirty def remove_permissions_from_user(self, permissions): # Make sure the permissions variable is of type list if not isinstance(permissions, list): permissions = [permissions] assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) dirty = False for permission in permissions: if permission in self._permissions: self._permissions.remove(permission) dirty = True return dirty def add_groups_to_user(self, groups): # Make sure the groups variable is of type list if not isinstance(groups, list): groups = [groups] assert all(map(lambda p: isinstance(p, Group), groups)) dirty = False for group in groups: if group.is_toggleable() and group not in self._groups: self._groups.append(group) dirty = True return dirty def remove_groups_from_user(self, groups): # Make sure the groups variable is of type list if not isinstance(groups, list): groups = [groups] assert all(map(lambda p: isinstance(p, Group), groups)) dirty = False for group in groups: if group.is_toggleable() and group in self._groups: self._groups.remove(group) dirty = True return dirty @property def permissions(self): if self._permissions is None: return [] if Permissions.ADMIN in self._permissions: return Permissions.all() return list(filter(lambda p: p is not None, self._permissions)) @property def groups(self): return list(self._groups) @property def effective_permissions(self): if self._permissions is None: return [] return list( filter(lambda p: p is not None and self.has_permission(p), Permissions.all()) ) @property def needs(self): needs = set() for permission in self.permissions: if permission is not None: needs = needs.union(permission.needs) for group in self.groups: if group is not None: needs = needs.union(group.needs) return needs def has_permission(self, permission): return self.has_needs(*permission.needs) def has_needs(self, *needs): return set(needs).issubset(self.needs) def __repr__(self): return ( "User(id=%s,name=%s,active=%r,user=True,admin=%r,permissions=%s,groups=%s)" % ( self.get_id(), self.get_name(), bool(self.is_active), self.has_permission(Permissions.ADMIN), self._permissions, self._groups, ) ) # ~~ Deprecated methods & properties follow # TODO: Remove deprecated methods & properties in OctoPrint 1.5.0 asDict = deprecated( "asDict has been renamed to as_dict", includedoc="Replaced by :func:`as_dict`", since="1.4.0", )(as_dict) @property @deprecated("is_user is deprecated, please use has_permission", since="1.4.0") def is_user(self): return OctoPrintUserMethodReplacedByBooleanProperty( "is_user", lambda: not self.is_anonymous ) @property @deprecated("is_admin is deprecated, please use has_permission", since="1.4.0") def is_admin(self): return OctoPrintUserMethodReplacedByBooleanProperty( "is_admin", lambda: self.has_permission(Permissions.ADMIN) ) @property @deprecated("roles is deprecated, please use has_permission", since="1.4.0") def roles(self): return self._roles @property def _roles(self): """Helper for the deprecated self.roles and serializing to yaml""" if self.has_permission(Permissions.ADMIN): return ["user", "admin"] elif not self.is_anonymous: return ["user"] else: return [] class AnonymousUser(AnonymousUserMixin, User): def __init__(self, groups): User.__init__(self, None, "", True, [], groups) @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: self._active ) def check_password(self, passwordHash): return True def as_dict(self): from octoprint.access.permissions import OctoPrintPermission return {"needs": OctoPrintPermission.convert_needs_to_dict(self.needs)} def __repr__(self): return "AnonymousUser(groups=%s)" % self._groups class SessionUser(wrapt.ObjectProxy): def __init__(self, user): wrapt.ObjectProxy.__init__(self, user) self._self_session = "".join("%02X" % z for z in bytes(uuid.uuid4().bytes)) self._self_created = self._self_touched = time.monotonic() @property def session(self): return self._self_session @property def created(self): return self._self_created @property def touched(self): return self._self_touched def touch(self): self._self_touched = time.monotonic() @deprecated( "SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5", ) def get_session(self): return self.session def update_user(self, user): self.__wrapped__ = user def as_dict(self): result = self.__wrapped__.as_dict() result.update({"session": self.session}) return result def __repr__(self): return "SessionUser({!r},session={},created={})".format( self.__wrapped__, self.session, self.created ) ##~~ User object to use when global api key is used to access the API class ApiUser(User): def __init__(self, groups): User.__init__(self, "_api", "", True, [], groups)
47,899
Python
.py
1,185
29.913924
137
0.596
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,871
__init__.py
OctoPrint_OctoPrint/src/octoprint/access/__init__.py
import logging ADMIN_GROUP = "admins" USER_GROUP = "users" GUEST_GROUP = "guests" READONLY_GROUP = "readonly" def auth_log(message): logging.getLogger("AUTH").info(message)
180
Python
.py
7
23.714286
43
0.752941
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,872
groups.py
OctoPrint_OctoPrint/src/octoprint/access/groups.py
__author__ = "Marc Hannappel <salandora@gmail.com>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os from functools import partial from octoprint.access import ADMIN_GROUP, GUEST_GROUP, READONLY_GROUP, USER_GROUP from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.settings import settings from octoprint.util import atomic_write, yaml from octoprint.vendor.flask_principal import Need, Permission GroupNeed = partial(Need, "group") GroupNeed.__doc__ = """A need with the method preset to `"group"`.""" class GroupPermission(Permission): def __init__(self, key): need = GroupNeed(key) super().__init__(need) class GroupManager: @classmethod def default_permissions_for_group(cls, group): result = [] for permission in Permissions.all(): if group in permission.default_groups: result.append(permission) return result def __init__(self): self._logger = logging.getLogger(__name__) self._group_change_listeners = [] self._default_groups = [] self._init_defaults() @property def groups(self): return [] @property def admin_group(self): return self.find_group(ADMIN_GROUP) @property def user_group(self): return self.find_group(USER_GROUP) @property def guest_group(self): return self.find_group(GUEST_GROUP) def _init_defaults(self): self._default_groups = { ADMIN_GROUP: { "name": "Admins", "description": "Administrators", "permissions": self.default_permissions_for_group(ADMIN_GROUP), "subgroups": [], "changeable": False, "removable": False, "default": False, "toggleable": True, }, USER_GROUP: { "name": "Operator", "description": "Group to gain operator access", "permissions": self.default_permissions_for_group(USER_GROUP), "subgroups": [], "changeable": True, "default": True, "removable": False, "toggleable": True, }, GUEST_GROUP: { "name": "Guests", "description": "Anyone who is not currently logged in", "permissions": self.default_permissions_for_group(GUEST_GROUP), "subgroups": [], "changeable": True, "default": False, "removable": False, "toggleable": False, }, READONLY_GROUP: { "name": "Read-only Access", "description": "Group to gain read-only access", "permissions": self.default_permissions_for_group(READONLY_GROUP), "subgroups": [], "changeable": False, "removable": False, "default": False, "toggleable": True, }, } for key, g in self._default_groups.items(): self.add_group( key, g["name"], g["description"], g["permissions"], g["subgroups"], changeable=g.get("changeable", True), removable=g.get("removable", True), default=g.get("default", False), toggleable=g.get("toggleable", True), save=False, ) def register_listener(self, listener): self._group_change_listeners.append(listener) def unregister_listener(self, listener): self._group_change_listeners.remove(listener) def add_group( self, key, name, description, permissions, subgroups, default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True, ): pass def update_group( self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True, ): pass def remove_group(self, key, save=True, notify=True): pass def find_group(self, key): return None def _to_permissions(self, *permissions): return list( filter( lambda x: x is not None, [Permissions.find(permission) for permission in permissions], ) ) def _from_permissions(self, *permissions): return [permission.key for permission in permissions] def _from_groups(self, *groups): return [group.key for group in groups] def _to_groups(self, *groups): return list(filter(lambda x: x is not None, [self._to_group(g) for g in groups])) def _to_group(self, group): if isinstance(group, Group): return group elif isinstance(group, str): return self.find_group(group) elif isinstance(group, dict): return self.find_group(group.get("key")) else: return None def _notify_listeners(self, action, group, *args, **kwargs): method = f"on_group_{action}" for listener in self._group_change_listeners: try: getattr(listener, method)(group, *args, **kwargs) except Exception: self._logger.exception( f"Error notifying listener {listener!r} via {method}" ) class GroupChangeListener: def on_group_added(self, group): pass def on_group_removed(self, group): pass def on_group_permissions_changed(self, group, added=None, removed=None): pass def on_group_subgroups_changed(self, group, added=None, removed=None): pass class FilebasedGroupManager(GroupManager): FILE_VERSION = 2 def __init__(self, path=None): if path is None: path = settings().get(["accessControl", "groupfile"]) if path is None: path = os.path.join(settings().getBaseFolder("base"), "groups.yaml") self._groupfile = path self._groups = {} self._dirty = False GroupManager.__init__(self) self._load() def _load(self): if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): try: data = yaml.load_from_file(path=self._groupfile) if "groups" not in data: groups = data data = {"groups": groups} file_version = data.get("_version", 1) if file_version < self.FILE_VERSION: # make sure we migrate the file on disk after loading self._logger.info( "Detected file version {} on group " "storage, migrating to version {}".format( file_version, self.FILE_VERSION ) ) self._dirty = True groups = data.get("groups", {}) tracked_permissions = data.get("tracked", list()) for key, attributes in groups.items(): if key in self._default_groups: # group is a default group if not self._default_groups[key].get("changeable", True): # group may not be changed -> bail continue name = self._default_groups[key].get("name", "") description = self._default_groups[key].get("description", "") removable = self._default_groups[key].get("removable", True) changeable = self._default_groups[key].get("changeable", True) toggleable = self._default_groups[key].get("toggleable", True) if file_version == 1: # 1.4.0/file version 1 has a bug that resets default to True for users group on modification set_default = self._default_groups[key].get("default", False) else: set_default = attributes.get("default", False) else: name = attributes.get("name", "") description = attributes.get("description", "") removable = True changeable = True toggleable = True set_default = attributes.get("default", False) permissions = self._to_permissions(*attributes.get("permissions", [])) default_permissions = self.default_permissions_for_group(key) for permission in default_permissions: if ( permission.key not in tracked_permissions and permission not in permissions ): permissions.append(permission) subgroups = self._to_groups(*attributes.get("subgroups", [])) group = Group( key, name, description=description, permissions=permissions, subgroups=subgroups, default=set_default, removable=removable, changeable=changeable, toggleable=toggleable, ) if key == GUEST_GROUP and ( len(group.permissions) != len(permissions) or len(group.subgroups) != len(subgroups) ): self._logger.warning( "Dangerous permissions and/or subgroups stripped from guests group" ) self._dirty = True self._groups[key] = group for group in self._groups.values(): group._subgroups = self._to_groups(*group._subgroups) if self._dirty: self._save() except Exception: self._logger.exception( f"Error while loading groups from file {self._groupfile}" ) def _save(self, force=False): if self._groupfile is None or not self._dirty and not force: return groups = {} for key in self._groups.keys(): group = self._groups[key] groups[key] = { "permissions": self._from_permissions(*group._permissions), "subgroups": self._from_groups(*group._subgroups), "default": group._default, } if key not in self._default_groups: groups[key]["name"] = group.get_name() groups[key]["description"] = group.get_description() data = { "_version": self.FILE_VERSION, "groups": groups, "tracked": [x.key for x in Permissions.all()], } with atomic_write( self._groupfile, mode="wt", permissions=0o600, max_permissions=0o666 ) as f: yaml.save_to_file(data, file=f, pretty=True) self._dirty = False self._load() @property def groups(self): return list(self._groups.values()) @property def default_groups(self): return [group for group in self._groups.values() if group.is_default()] def find_group(self, key): if key is None: return None return self._groups.get(key) def add_group( self, key, name, description, permissions, subgroups, default=False, removable=True, changeable=True, toggleable=True, overwrite=False, notify=True, save=True, ): if key in self._groups and not overwrite: raise GroupAlreadyExists(key) if not permissions: permissions = [] permissions = self._to_permissions(*permissions) assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) subgroups = self._to_groups(*subgroups) assert all(map(lambda g: isinstance(g, Group), subgroups)) group = Group( key, name, description=description, permissions=permissions, subgroups=subgroups, default=default, changeable=changeable, removable=removable, toggleable=toggleable, ) self._groups[key] = group if save: self._dirty = True self._save() if notify: self._notify_listeners("added", group) def remove_group(self, key, save=True, notify=True): """Removes a Group by key""" group = self._to_group(key) if group is None: raise UnknownGroup(key) if not group.is_removable(): raise GroupUnremovable(key) del self._groups[key] self._dirty = True if save: self._save() if notify: self._notify_listeners("removed", group) def update_group( self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True, ): group = self._to_group(key) if group is None: raise UnknownGroup(key) if not group.is_changeable(): raise GroupCantBeChanged(key) if description is not None and description != group.get_description(): group.change_description(description) self._dirty = True notifications = [] if permissions is not None: permissions = self._to_permissions(*permissions) assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) removed_permissions = list(set(group._permissions) - set(permissions)) added_permissions = list(set(permissions) - set(group._permissions)) if removed_permissions: self._dirty |= group.remove_permissions_from_group(removed_permissions) if added_permissions: self._dirty |= group.add_permissions_to_group(added_permissions) notifications.append( ( ("permissions_changed", group), {"added": added_permissions, "removed": removed_permissions}, ) ) if subgroups is not None: subgroups = self._to_groups(*subgroups) assert all(map(lambda g: isinstance(g, Group), subgroups)) removed_subgroups = list(set(group._subgroups) - set(subgroups)) added_subgroups = list(set(subgroups) - set(group._subgroups)) if removed_subgroups: self._dirty = group.remove_subgroups_from_group(removed_subgroups) if added_subgroups: self._dirty = group.add_subgroups_to_group(added_subgroups) notifications.append( ( ("subgroups_changed", group), {"added": added_subgroups, "removed": removed_subgroups}, ) ) if default is not None: group.change_default(default) self._dirty = True if self._dirty: if save: self._save() if notify: for args, kwargs in notifications: self._notify_listeners(*args, **kwargs) class GroupAlreadyExists(Exception): def __init__(self, key): Exception.__init__(self, "Group %s already exists" % key) class UnknownGroup(Exception): def __init__(self, key): Exception.__init__(self, "Unknown group: %s" % key) class GroupUnremovable(Exception): def __init__(self, key): Exception.__init__(self, "Group can't be removed: %s" % key) class GroupCantBeChanged(Exception): def __init__(self, key): Exception.__init__(self, "Group can't be changed: %s" % key) class Group: def __init__( self, key, name, description="", permissions=None, subgroups=None, default=False, removable=True, changeable=True, toggleable=True, ): if permissions is None: permissions = [] if subgroups is None: subgroups = [] if key == GUEST_GROUP: # guests may not have any dangerous permissions permissions = list(filter(lambda p: not p.dangerous, permissions)) subgroups = list(filter(lambda g: not g.dangerous, subgroups)) self._key = key self._name = name self._description = description self._permissions = permissions self._subgroups = subgroups self._default = default self._removable = removable self._changeable = changeable self._toggleable = toggleable def as_dict(self): from octoprint.access.permissions import OctoPrintPermission return { "key": self.key, "name": self.get_name(), "description": self._description, "permissions": list(map(lambda p: p.key, self._permissions)), "subgroups": list(map(lambda g: g.key, self._subgroups)), "needs": OctoPrintPermission.convert_needs_to_dict(self.needs), "default": self._default, "removable": self._removable, "changeable": self._changeable, "toggleable": self._toggleable, "dangerous": self.dangerous, } @property def key(self): return self._key def get_name(self): return self._name def get_description(self): return self._description def is_default(self): return self._default def is_changeable(self): return self._changeable def is_removable(self): return self._removable def is_toggleable(self): return self._toggleable @property def dangerous(self): return any(map(lambda p: p.dangerous, self._permissions)) or any( map(lambda g: g.dangerous, self._subgroups) ) def add_permissions_to_group(self, permissions): """Adds a list of permissions to a group""" if not self.is_changeable(): raise GroupCantBeChanged(self.key) # Make sure the permissions variable is of type list if not isinstance(permissions, list): permissions = [permissions] assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) if self.key == GUEST_GROUP: # don't allow dangerous permissions on the guests group permissions = list(filter(lambda p: not p.dangerous, permissions)) dirty = False for permission in permissions: if permissions not in self.permissions: self._permissions.append(permission) dirty = True return dirty def remove_permissions_from_group(self, permissions): """Removes a list of permissions from a group""" if not self.is_changeable(): raise GroupCantBeChanged(self.key) # Make sure the permissions variable is of type list if not isinstance(permissions, list): permissions = [permissions] assert all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)) dirty = False for permission in permissions: if permission in self._permissions: self._permissions.remove(permission) dirty = True return dirty def add_subgroups_to_group(self, subgroups): """Adds a list of subgroups to a group""" if not self.is_changeable(): raise GroupCantBeChanged(self.key) # Make sure the subgroups variable is of type list if not isinstance(subgroups, list): subgroups = [subgroups] assert all(map(lambda g: isinstance(g, Group), subgroups)) if self.key == GUEST_GROUP: # don't allow dangerous subgroups on the guests group subgroups = list(filter(lambda g: not g.dangerous, subgroups)) dirty = False for group in subgroups: if group.is_toggleable() and group not in self._subgroups: self._subgroups.append(group) dirty = True return dirty def remove_subgroups_from_group(self, subgroups): """Removes a list of subgroups from a group""" if not self.is_changeable(): raise GroupCantBeChanged(self.key) # Make sure the subgroups variable is of type list if not isinstance(subgroups, list): subgroups = [subgroups] assert all(map(lambda g: isinstance(g, Group), subgroups)) dirty = False for group in subgroups: if group.is_toggleable() and group in self._subgroups: self._subgroups.remove(group) dirty = True return dirty def change_default(self, default): """Changes the default flag of a Group""" if not self.is_changeable(): raise GroupCantBeChanged(self.key) self._default = default def change_description(self, description): """Changes the description of a group""" self._description = description @property def permissions(self): if Permissions.ADMIN in self._permissions: return Permissions.all() return list(filter(lambda p: p is not None, self._permissions)) @property def subgroups(self): return list(filter(lambda g: g is not None, self._subgroups)) @property def needs(self): needs = set() needs.add(GroupNeed(self.key)) for p in self.permissions: needs = needs.union(p.needs) for g in self.subgroups: needs = needs.union(g.needs) return needs def has_permission(self, permission): if Permissions.ADMIN.get_name() in self._permissions: return True return permission.needs.issubset(self.needs) def __repr__(self): return ( '{}("{}", "{}", description="{}", permissions={!r}, ' "default={}, removable={}, changeable={})".format( self.__class__.__name__, self._key, self._name, self._description, self._permissions, bool(self._default), bool(self._removable), bool(self._changeable), ) ) def __hash__(self): return self.key.__hash__() def __eq__(self, other): return isinstance(other, Group) and other.key == self.key
23,546
Python
.py
595
27.359664
120
0.552725
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,873
permissions.py
OctoPrint_OctoPrint/src/octoprint/access/permissions.py
__author__ = "Marc Hannappel <salandora@gmail.com>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" from collections import OrderedDict, defaultdict from functools import wraps from flask import abort, g from flask_babel import gettext from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP from octoprint.vendor.flask_principal import Need, Permission, PermissionDenied, RoleNeed class OctoPrintPermission(Permission): @classmethod def convert_needs_to_dict(cls, needs): ret_needs = defaultdict(list) for need in needs: if need.value not in ret_needs[need.method]: ret_needs[need.method].append(need.value) return ret_needs @classmethod def convert_to_needs(cls, needs): result = [] for need in needs: if isinstance(need, Need): result.append(need) elif isinstance(need, Permission): result += need.needs elif isinstance(need, str): result.append(RoleNeed(need)) return result def __init__(self, name, description, *needs, **kwargs): self._name = name self._description = description self._dangerous = kwargs.pop("dangerous", False) self._default_groups = kwargs.pop("default_groups", []) self._key = None Permission.__init__(self, *self.convert_to_needs(needs)) def as_dict(self): return { "key": self.key, "name": self.get_name(), "dangerous": self._dangerous, "default_groups": self._default_groups, "description": self.get_description(), "needs": self.convert_needs_to_dict(self.needs), } @property def key(self): return self._key @key.setter def key(self, value): self._key = value @property def dangerous(self): return self._dangerous @property def default_groups(self): return self._default_groups def get_name(self): return self._name def get_description(self): return self._description def allows(self, identity): """Whether the identity can access this permission. Overridden from Permission.allows to make sure the Identity provides ALL required needs instead of ANY required need. :param identity: The identity """ if self.needs and len(self.needs.intersection(identity.provides)) != len( self.needs ): return False if self.excludes and self.excludes.intersection(identity.provides): return False return True def union(self, other): """Create a new OctoPrintPermission with the requirements of the union of this and other. :param other: The other permission """ p = self.__class__(self._name, self._description, *self.needs.union(other.needs)) p.excludes.update(self.excludes.union(other.excludes)) return p def difference(self, other): """Create a new OctoPrintPermission consisting of requirements in this permission and not in the other. """ p = self.__class__( self._name, self._description, *self.needs.difference(other.needs) ) p.excludes.update(self.excludes.difference(other.excludes)) return p def __repr__(self): return "{}({!r}, {!r}, {})".format( self.__class__.__name__, self.get_name(), self.get_description(), ", ".join(map(repr, self.needs)), ) def __hash__(self): return self.get_name().__hash__() def __eq__(self, other): return ( isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name() ) class PluginOctoPrintPermission(OctoPrintPermission): def __init__(self, *args, **kwargs): self.plugin = kwargs.pop("plugin", None) OctoPrintPermission.__init__(self, *args, **kwargs) def as_dict(self): result = OctoPrintPermission.as_dict(self) result["plugin"] = self.plugin return result class PluginIdentityContext: """Identity context for not initialized Permissions Needed to support @Permissions.PLUGIN_X_Y.require() Will search the permission when needed """ def __init__(self, key, http_exception=None): self.key = key self.http_exception = http_exception """The permission of this principal """ @property def identity(self): """The identity of this principal""" return g.identity def can(self): """Whether the identity has access to the permission""" permission = getattr(Permissions, self.key) if permission is None or isinstance(permission, PluginPermissionDecorator): raise UnknownPermission(self.key) return permission.can() def __call__(self, f): @wraps(f) def _decorated(*args, **kw): with self: rv = f(*args, **kw) return rv return _decorated def __enter__(self): permission = getattr(Permissions, self.key) if permission is None or isinstance(permission, PluginPermissionDecorator): raise UnknownPermission(self.key) # check the permission here if not permission.can(): if self.http_exception: abort(self.http_exception) raise PermissionDenied(permission) def __exit__(self, *args): return False class PluginPermissionDecorator(Permission): """Decorator Class for not initialized Permissions Needed to support @Permissions.PLUGIN_X_Y.require() """ def __init__(self, key): self.key = key def require(self, http_exception=None): return PluginIdentityContext(self.key, http_exception) class PermissionsMetaClass(type): permissions = OrderedDict() def __new__(mcs, name, bases, args): cls = type.__new__(mcs, name, bases, args) for key, value in args.items(): if isinstance(value, OctoPrintPermission): value.key = key mcs.permissions[key] = value delattr(cls, key) return cls def __setattr__(cls, key, value): if isinstance(value, OctoPrintPermission): if key in cls.permissions: raise PermissionAlreadyExists(key) value.key = key cls.permissions[key] = value def __getattr__(cls, key): permission = cls.permissions.get(key) if key.startswith("PLUGIN_") and permission is None: return PluginPermissionDecorator(key) return permission def all(cls): return list(cls.permissions.values()) def filter(cls, cb): return list(filter(cb, cls.all())) def find(cls, p, filter=None): key = None if isinstance(p, OctoPrintPermission): key = p.key elif isinstance(p, dict): key = p.get("key") elif isinstance(p, str): key = p if key is None: return None return cls.match(lambda p: p.key == key, filter=filter) def match(cls, match, filter=None): if callable(filter): permissions = cls.filter(filter) else: permissions = cls.all() for permission in permissions: if match(permission): return permission return None class Permissions(metaclass=PermissionsMetaClass): # Special permission ADMIN = OctoPrintPermission( "Admin", gettext("Admin is allowed to do everything"), RoleNeed("admin"), dangerous=True, default_groups=[ADMIN_GROUP], ) STATUS = OctoPrintPermission( "Status", gettext( "Allows to gather basic status information, e.g. job progress, " "printer state, temperatures, ... Mandatory for the default UI " "to work" ), RoleNeed("status"), default_groups=[USER_GROUP, READONLY_GROUP], ) CONNECTION = OctoPrintPermission( "Connection", gettext("Allows to connect to and disconnect from a printer"), RoleNeed("connection"), default_groups=[USER_GROUP], ) WEBCAM = OctoPrintPermission( "Webcam", gettext("Allows to watch the webcam stream"), RoleNeed("webcam"), default_groups=[USER_GROUP, READONLY_GROUP], ) SYSTEM = OctoPrintPermission( "System", gettext( "Allows to run system commands, e.g. restart OctoPrint, " "shutdown or reboot the system, and to retrieve system and usage information" ), RoleNeed("system"), dangerous=True, ) FILES_LIST = OctoPrintPermission( "File List", gettext( "Allows to retrieve a list of all uploaded files and folders, including" "their metadata (e.g. date, file size, analysis results, ...)" ), RoleNeed("files_list"), default_groups=[USER_GROUP, READONLY_GROUP], ) FILES_UPLOAD = OctoPrintPermission( "File Upload", gettext( "Allows users to upload new files, create new folders and copy existing ones. If " "the File Delete permission is also set, File Upload also allows " "moving files and folders." ), RoleNeed("files_upload"), default_groups=[USER_GROUP], ) FILES_DOWNLOAD = OctoPrintPermission( "File Download", gettext( "Allows users to download files. The GCODE viewer is " "affected by this as well." ), RoleNeed("files_download"), default_groups=[USER_GROUP, READONLY_GROUP], ) FILES_DELETE = OctoPrintPermission( "File Delete", gettext( "Allows users to delete files and folders. If the File Upload permission is " "also set, File Delete also allows moving files and folders." ), RoleNeed("files_delete"), default_groups=[USER_GROUP], ) FILES_SELECT = OctoPrintPermission( "File Select", gettext("Allows to select a file for printing"), RoleNeed("files_select"), default_groups=[USER_GROUP], ) PRINT = OctoPrintPermission( "Print", gettext("Allows to start, pause and cancel a print job"), RoleNeed("print"), default_groups=[USER_GROUP], ) GCODE_VIEWER = OctoPrintPermission( "GCODE viewer", gettext( 'Allows access to the GCODE viewer if the "File Download"' "permission is also set." ), RoleNeed("gcodeviewer"), default_groups=[USER_GROUP, READONLY_GROUP], ) MONITOR_TERMINAL = OctoPrintPermission( "Terminal", gettext( "Allows to watch the terminal tab but not to send commands " "to the printer from it" ), RoleNeed("monitor_terminal"), default_groups=[USER_GROUP, READONLY_GROUP], ) CONTROL = OctoPrintPermission( "Control", gettext( "Allows to control of the printer by using the temperature controls," "the control tab or sending commands through the terminal." ), RoleNeed("control"), default_groups=[USER_GROUP], ) SLICE = OctoPrintPermission( "Slice", gettext("Allows to slice files"), RoleNeed("slice"), default_groups=[USER_GROUP], ) TIMELAPSE_LIST = OctoPrintPermission( "Timelapse List", gettext("Allows to list timelapse videos"), RoleNeed("timelapse_list"), default_groups=[USER_GROUP, READONLY_GROUP], ) TIMELAPSE_DOWNLOAD = OctoPrintPermission( "Timelapse Download", gettext("Allows to download timelapse videos"), RoleNeed("timelapse_download"), default_groups=[USER_GROUP, READONLY_GROUP], ) TIMELAPSE_DELETE = OctoPrintPermission( "Timelapse Delete", gettext("Allows to delete timelapse videos"), RoleNeed("timelapse_delete"), default_groups=[USER_GROUP], ) TIMELAPSE_MANAGE_UNRENDERED = OctoPrintPermission( "Timelapse Manage Unrendered", gettext("Allows to list, delete and render unrendered timelapses"), RoleNeed("timelapse_manage_unrendered"), default_groups=[USER_GROUP], ) TIMELAPSE_ADMIN = OctoPrintPermission( "Timelapse Admin", gettext("Allows to change the timelapse settings."), RoleNeed("timelapse_admin"), default_groups=[USER_GROUP], ) SETTINGS_READ = OctoPrintPermission( "Settings Access", gettext( "Allows to read non sensitive settings. Mandatory for the " "default UI to work." ), RoleNeed("settings_read"), default_groups=[USER_GROUP, READONLY_GROUP], ) SETTINGS = OctoPrintPermission( "Settings Admin", gettext("Allows to manage settings and also to read sensitive settings"), RoleNeed("settings"), dangerous=True, ) class PermissionAlreadyExists(Exception): def __init__(self, permission): Exception.__init__(self, "Permission %s already exists" % permission) class UnknownPermission(Exception): def __init__(self, permissionname): Exception.__init__(self, "Unknown permission: %s" % permissionname)
13,791
Python
.py
375
28.066667
103
0.618015
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,874
__init__.py
OctoPrint_OctoPrint/src/octoprint/slicing/__init__.py
""" In this module the slicing support of OctoPrint is encapsulated. .. autoclass:: SlicingProfile :members: .. autoclass:: TemporaryProfile :members: .. autoclass:: SlicingManager :members: """ __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os import octoprint.events import octoprint.plugin import octoprint.util from octoprint.settings import settings from .exceptions import ( CouldNotDeleteProfile, ProfileAlreadyExists, ProfileException, SlicerNotConfigured, SlicingCancelled, UnknownProfile, UnknownSlicer, ) class SlicingProfile: """ A wrapper for slicing profiles, both meta data and actual profile data. Arguments: slicer (str): Identifier of the slicer this profile belongs to. name (str): Identifier of this slicing profile. data (object): Profile data, actual structure depends on individual slicer implementation. display_name (str): Displayable name for this slicing profile. description (str): Description of this slicing profile. default (bool): Whether this is the default slicing profile for the slicer. """ def __init__( self, slicer, name, data, display_name=None, description=None, default=False ): self.slicer = slicer self.name = name self.data = data self.display_name = display_name self.description = description self.default = default class TemporaryProfile: """ A wrapper for a temporary slicing profile to be used for a slicing job, based on a :class:`SlicingProfile` with optional ``overrides`` applied through the supplied ``save_profile`` method. Usage example: .. code-block:: python temporary = TemporaryProfile(my_slicer.save_slicer_profile, my_default_profile, overrides=my_overrides) with (temporary) as profile_path: my_slicer.do_slice(..., profile_path=profile_path, ...) Arguments: save_profile (callable): Method to use for saving the temporary profile, also responsible for applying the supplied ``overrides``. This will be called according to the method signature of :meth:`~octoprint.plugin.SlicerPlugin.save_slicer_profile`. profile (SlicingProfile): The profile from which to derive the temporary profile. overrides (dict): Optional overrides to apply to the ``profile`` for creation of the temporary profile. """ def __init__(self, save_profile, profile, overrides=None): self.save_profile = save_profile self.profile = profile self.overrides = overrides def __enter__(self): import tempfile temp_profile = tempfile.NamedTemporaryFile( prefix="slicing-profile-temp-", suffix=".profile", delete=False ) temp_profile.close() self.temp_path = temp_profile.name self.save_profile(self.temp_path, self.profile, overrides=self.overrides) return self.temp_path def __exit__(self, type, value, traceback): import os try: os.remove(self.temp_path) except Exception: pass class SlicingManager: """ The :class:`SlicingManager` is responsible for managing available slicers and slicing profiles. Arguments: profile_path (str): Absolute path to the base folder where all slicing profiles are stored. printer_profile_manager (~octoprint.printer.profile.PrinterProfileManager): :class:`~octoprint.printer.profile.PrinterProfileManager` instance to use for accessing available printer profiles, most importantly the currently selected one. """ def __init__(self, profile_path, printer_profile_manager): self._logger = logging.getLogger(__name__) self._profile_path = profile_path self._printer_profile_manager = printer_profile_manager self._slicers = {} self._slicer_names = {} def initialize(self): """ Initializes the slicing manager by loading and initializing all available :class:`~octoprint.plugin.SlicerPlugin` implementations. """ self.reload_slicers() def reload_slicers(self): """ Retrieves all registered :class:`~octoprint.plugin.SlicerPlugin` implementations and registers them as available slicers. """ plugins = octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.SlicerPlugin ) slicers = {} for plugin in plugins: try: slicers[plugin.get_slicer_properties()["type"]] = plugin except Exception: self._logger.exception( "Error while getting properties from slicer {}, ignoring it".format( plugin._identifier ), extra={"plugin": plugin._identifier}, ) continue self._slicers = slicers @property def slicing_enabled(self): """ Returns: (boolean) True if there is at least one configured slicer available, False otherwise. """ return len(self.configured_slicers) > 0 @property def registered_slicers(self): """ Returns: (list of str) Identifiers of all available slicers. """ return list(self._slicers.keys()) @property def configured_slicers(self): """ Returns: (list of str) Identifiers of all available configured slicers. """ return list( map( lambda slicer: slicer.get_slicer_properties()["type"], filter( lambda slicer: slicer.is_slicer_configured(), self._slicers.values() ), ) ) @property def default_slicer(self): """ Retrieves the default slicer. Returns: (str) The identifier of the default slicer or ``None`` if the default slicer is not registered in the system. """ slicer_name = settings().get(["slicing", "defaultSlicer"]) if slicer_name in self.registered_slicers: return slicer_name else: return None def get_slicer(self, slicer, require_configured=True): """ Retrieves the slicer named ``slicer``. If ``require_configured`` is set to True (the default) an exception will be raised if the slicer is not yet configured. Arguments: slicer (str): Identifier of the slicer to return require_configured (boolean): Whether to raise an exception if the slicer has not been configured yet (True, the default), or also return an unconfigured slicer (False). Raises: ~octoprint.slicing.exceptions.UnknownSlicer: The ``slicer`` is unknown. ~octoprint.slicing.exceptions.SlicerNotConfigured: The ``slicer`` is not yet configured and ``require_configured`` was set to True. """ if slicer not in self._slicers: raise UnknownSlicer(slicer) if require_configured and not self._slicers[slicer].is_slicer_configured(): raise SlicerNotConfigured(slicer) return self._slicers[slicer] def slice( self, slicer_name, source_path, dest_path, profile_name, callback, callback_args=None, callback_kwargs=None, overrides=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None, printer_profile_id=None, position=None, ): """ Slices ``source_path`` to ``dest_path`` using slicer ``slicer_name`` and slicing profile ``profile_name``. Since slicing happens asynchronously, ``callback`` will be called when slicing has finished (either successfully or not), with ``callback_args`` and ``callback_kwargs`` supplied. If ``callback_args`` is left out, an empty argument list will be assumed for the callback. If ``callback_kwargs`` is left out, likewise an empty keyword argument list will be assumed for the callback. Note that in any case the callback *must* support being called with the following optional keyword arguments: _analysis If the slicer returned analysis data of the created machine code as part of its slicing result, this keyword argument will contain that data. _error If there was an error while slicing this keyword argument will contain the error message as returned from the slicer. _cancelled If the slicing job was cancelled this keyword argument will be set to True. Additionally callees may specify ``overrides`` for the specified slicing profile, e.g. a different extrusion temperature than defined in the profile or a different layer height. With ``on_progress``, ``on_progress_args`` and ``on_progress_kwargs``, callees may specify a callback plus arguments and keyword arguments to call upon progress reports from the slicing job. The progress callback will be called with a keyword argument ``_progress`` containing the current slicing progress as a value between 0 and 1 plus all additionally specified args and kwargs. If a different printer profile than the currently selected one is to be used for slicing, its id can be provided via the keyword argument ``printer_profile_id``. If the ``source_path`` is to be a sliced at a different position than the print bed center, this ``position`` can be supplied as a dictionary defining the ``x`` and ``y`` coordinate in print bed coordinates of the model's center. Arguments: slicer_name (str): The identifier of the slicer to use for slicing. source_path (str): The absolute path to the source file to slice. dest_path (str): The absolute path to the destination file to slice to. profile_name (str): The name of the slicing profile to use. callback (callable): A callback to call after slicing has finished. callback_args (list or tuple): Arguments of the callback to call after slicing has finished. Defaults to an empty list. callback_kwargs (dict): Keyword arguments for the callback to call after slicing has finished, will be extended by ``_analysis``, ``_error`` or ``_cancelled`` as described above! Defaults to an empty dictionary. overrides (dict): Overrides for the printer profile to apply. on_progress (callable): Callback to call upon slicing progress. on_progress_args (list or tuple): Arguments of the progress callback. Defaults to an empty list. on_progress_kwargs (dict): Keyword arguments of the progress callback, will be extended by ``_progress`` as described above! Defaults to an empty dictionary. printer_profile_id (str): Identifier of the printer profile for which to slice, if another than the one currently selected is to be used. position (dict): Dictionary containing the ``x`` and ``y`` coordinate in the print bed's coordinate system of the sliced model's center. If not provided the model will be positioned at the print bed's center. Example: ``dict(x=10,y=20)``. Raises: ~octoprint.slicing.exceptions.UnknownSlicer: The slicer specified via ``slicer_name`` is unknown. ~octoprint.slicing.exceptions.SlicerNotConfigured: The slice specified via ``slicer_name`` is not configured yet. """ if callback_args is None: callback_args = () if callback_kwargs is None: callback_kwargs = {} if slicer_name not in self.configured_slicers: if slicer_name not in self.registered_slicers: error = f"No such slicer: {slicer_name}" exc = UnknownSlicer(slicer_name) else: error = f"Slicer not configured: {slicer_name}" exc = SlicerNotConfigured(slicer_name) callback_kwargs.update({"_error": error, "_exc": exc}) callback(*callback_args, **callback_kwargs) raise exc slicer = self.get_slicer(slicer_name) printer_profile = None if printer_profile_id is not None: printer_profile = self._printer_profile_manager.get(printer_profile_id) if printer_profile is None: printer_profile = self._printer_profile_manager.get_current_or_default() def slicer_worker( slicer, model_path, machinecode_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs, ): try: slicer_name = slicer.get_slicer_properties()["type"] with self._temporary_profile( slicer_name, name=profile_name, overrides=overrides ) as profile_path: ok, result = slicer.do_slice( model_path, printer_profile, machinecode_path=machinecode_path, profile_path=profile_path, position=position, on_progress=on_progress, on_progress_args=on_progress_args, on_progress_kwargs=on_progress_kwargs, ) if not ok: callback_kwargs.update({"_error": result}) elif ( result is not None and isinstance(result, dict) and "analysis" in result ): callback_kwargs.update({"_analysis": result["analysis"]}) except SlicingCancelled: callback_kwargs.update({"_cancelled": True}) finally: callback(*callback_args, **callback_kwargs) import threading slicer_worker_thread = threading.Thread( target=slicer_worker, args=( slicer, source_path, dest_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs, ), ) slicer_worker_thread.daemon = True slicer_worker_thread.start() def cancel_slicing(self, slicer_name, source_path, dest_path): """ Cancels the slicing job on slicer ``slicer_name`` from ``source_path`` to ``dest_path``. Arguments: slicer_name (str): Identifier of the slicer on which to cancel the job. source_path (str): The absolute path to the source file being sliced. dest_path (str): The absolute path to the destination file being sliced to. Raises: ~octoprint.slicing.exceptions.UnknownSlicer: The slicer specified via ``slicer_name`` is unknown. """ slicer = self.get_slicer(slicer_name) slicer.cancel_slicing(dest_path) def load_profile(self, slicer, name, require_configured=True): """ Loads the slicing profile for ``slicer`` with the given profile ``name`` and returns it. If it can't be loaded due to an :class:`IOError` ``None`` will be returned instead. If ``require_configured`` is True (the default) a :class:`SlicerNotConfigured` exception will be raised if the indicated ``slicer`` has not yet been configured. Returns: SlicingProfile: The requested slicing profile or None if it could not be loaded. Raises: ~octoprint.slicing.exceptions.UnknownSlicer: The slicer specified via ``slicer`` is unknown. ~octoprint.slicing.exceptions.SlicerNotConfigured: The slicer specified via ``slicer`` has not yet been configured and ``require_configured`` was True. ~octoprint.slicing.exceptions.UnknownProfile: The profile for slicer ``slicer`` named ``name`` does not exist. """ if slicer not in self.registered_slicers: raise UnknownSlicer(slicer) try: path = self.get_profile_path(slicer, name, must_exist=True) except OSError: return None return self._load_profile_from_path( slicer, path, require_configured=require_configured ) def save_profile( self, slicer, name, profile, overrides=None, allow_overwrite=True, display_name=None, description=None, ): """ Saves the slicer profile ``profile`` for slicer ``slicer`` under name ``name``. ``profile`` may be either a :class:`SlicingProfile` or a :class:`dict`. If it's a :class:`SlicingProfile`, its :attr:`~SlicingProfile.slicer``, :attr:`~SlicingProfile.name` and - if provided - :attr:`~SlicingProfile.display_name` and :attr:`~SlicingProfile.description` attributes will be overwritten with the supplied values. If it's a :class:`dict`, a new :class:`SlicingProfile` instance will be created with the supplied meta data and the profile data as the :attr:`~SlicingProfile.data` attribute. .. note:: If the profile is the first profile to be saved for the slicer, it will automatically be marked as default. Arguments: slicer (str): Identifier of the slicer for which to save the ``profile``. name (str): Identifier under which to save the ``profile``. profile (SlicingProfile or dict): The :class:`SlicingProfile` or a :class:`dict` containing the profile data of the profile the save. overrides (dict): Overrides to apply to the ``profile`` before saving it. allow_overwrite (boolean): If True (default) if a profile for the same ``slicer`` of the same ``name`` already exists, it will be overwritten. Otherwise an exception will be thrown. display_name (str): The name to display to the user for the profile. description (str): A description of the profile. Returns: SlicingProfile: The saved profile (including the applied overrides). Raises: ValueError: The supplied ``profile`` is neither a :class:`SlicingProfile` nor a :class:`dict`. ~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown. ~octoprint.slicing.exceptions.ProfileAlreadyExists: A profile with name ``name`` already exists for ``slicer`` and ``allow_overwrite`` is False. """ if slicer not in self.registered_slicers: raise UnknownSlicer(slicer) if not isinstance(profile, SlicingProfile): if isinstance(profile, dict): profile = SlicingProfile( slicer, name, profile, display_name=display_name, description=description, ) else: raise ValueError("profile must be a SlicingProfile or a dict") else: profile.slicer = slicer profile.name = name if display_name is not None: profile.display_name = display_name if description is not None: profile.description = description first_profile = len(self.all_profiles(slicer, require_configured=False)) == 0 path = self.get_profile_path(slicer, name) is_overwrite = os.path.exists(path) if is_overwrite and not allow_overwrite: raise ProfileAlreadyExists(slicer, profile.name) self._save_profile_to_path( slicer, path, profile, overrides=overrides, allow_overwrite=allow_overwrite ) payload = {"slicer": slicer, "profile": name} event = ( octoprint.events.Events.SLICING_PROFILE_MODIFIED if is_overwrite else octoprint.events.Events.SLICING_PROFILE_ADDED ) octoprint.events.eventManager().fire(event, payload) if first_profile: # enforce the first profile we add for this slicer is set as default self.set_default_profile(slicer, name) return profile def _temporary_profile(self, slicer, name=None, overrides=None): if slicer not in self.registered_slicers: raise UnknownSlicer(slicer) profile = self._get_default_profile(slicer) if name: try: profile = self.load_profile(slicer, name) except (UnknownProfile, OSError): # in that case we'll use the default profile pass return TemporaryProfile( self.get_slicer(slicer).save_slicer_profile, profile, overrides=overrides ) def delete_profile(self, slicer, name): """ Deletes the profile ``name`` for the specified ``slicer``. If the profile does not exist, nothing will happen. Arguments: slicer (str): Identifier of the slicer for which to delete the profile. name (str): Identifier of the profile to delete. Raises: ~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown. ~octoprint.slicing.exceptions.CouldNotDeleteProfile: There was an error while deleting the profile. """ if slicer not in self.registered_slicers: raise UnknownSlicer(slicer) if not name: raise ValueError("name must be set") try: try: path = self.get_profile_path(slicer, name, must_exist=True) except UnknownProfile: return os.remove(path) except ProfileException as e: raise e except Exception as e: raise CouldNotDeleteProfile(slicer, name, cause=e) else: octoprint.events.eventManager().fire( octoprint.events.Events.SLICING_PROFILE_DELETED, {"slicer": slicer, "profile": name}, ) def set_default_profile( self, slicer, name, require_configured=False, require_exists=True ): """ Sets the given profile as default profile for the slicer. Arguments: slicer (str): Identifier of the slicer for which to set the default profile. name (str): Identifier of the profile to set as default. require_configured (bool): Whether the slicer needs to be configured for the action to succeed. Defaults to false. Will raise a SlicerNotConfigured error if true and the slicer has not been configured yet. require_exists (bool): Whether the profile is required to exist in order to be set as default. Defaults to true. Will raise a UnknownProfile error if true and the profile is unknown. Raises: ~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown ~octoprint.slicing.exceptions.SlicerNotConfigured: The slicer ``slicer`` has not yet been configured and ``require_configured`` was true. ~octoprint.slicing.exceptions.UnknownProfile: The profile ``name`` was unknown for slicer ``slicer`` and ``require_exists`` was true. """ if slicer not in self.registered_slicers: raise UnknownSlicer(slicer) if require_configured and slicer not in self.configured_slicers: raise SlicerNotConfigured(slicer) if not name: raise ValueError("name must be set") if require_exists and name not in self.all_profiles( slicer, require_configured=require_configured ): raise UnknownProfile(slicer, name) default_profiles = settings().get(["slicing", "defaultProfiles"]) if not default_profiles: default_profiles = {} default_profiles[slicer] = name settings().set(["slicing", "defaultProfiles"], default_profiles) settings().save(force=True) def all_profiles(self, slicer, require_configured=False): """ Retrieves all profiles for slicer ``slicer``. If ``require_configured`` is set to True (default is False), only will return the profiles if the ``slicer`` is already configured, otherwise a :class:`SlicerNotConfigured` exception will be raised. Arguments: slicer (str): Identifier of the slicer for which to retrieve all slicer profiles require_configured (boolean): Whether to require the slicer ``slicer`` to be already configured (True) or not (False, default). If False and the slicer is not yet configured, a :class:`~octoprint.slicing.exceptions.SlicerNotConfigured` exception will be raised. Returns: dict of SlicingProfile: A dict of all :class:`SlicingProfile` instances available for the slicer ``slicer``, mapped by the identifier. Raises: ~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown. ~octoprint.slicing.exceptions.SlicerNotConfigured: The slicer ``slicer`` is not configured and ``require_configured`` was True. """ if slicer not in self.registered_slicers: raise UnknownSlicer(slicer) if require_configured and slicer not in self.configured_slicers: raise SlicerNotConfigured(slicer) slicer_profile_path = self.get_slicer_profile_path(slicer) return self.get_slicer(slicer, require_configured=False).get_slicer_profiles( slicer_profile_path ) def profiles_last_modified(self, slicer): """ Retrieves the last modification date of ``slicer``'s profiles. Args: slicer (str): the slicer for which to retrieve the last modification date Returns: (float) the time stamp of the last modification of the slicer's profiles """ if slicer not in self.registered_slicers: raise UnknownSlicer(slicer) slicer_profile_path = self.get_slicer_profile_path(slicer) return self.get_slicer( slicer, require_configured=False ).get_slicer_profiles_lastmodified(slicer_profile_path) def get_slicer_profile_path(self, slicer): """ Retrieves the path where the profiles for slicer ``slicer`` are stored. Arguments: slicer (str): Identifier of the slicer for which to retrieve the path. Returns: str: The absolute path to the folder where the slicer's profiles are stored. Raises: ~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown. """ if slicer not in self.registered_slicers: raise UnknownSlicer(slicer) path = os.path.join(self._profile_path, slicer) if not os.path.exists(path): os.makedirs(path) return path def get_profile_path(self, slicer, name, must_exist=False): """ Retrieves the path to the profile named ``name`` for slicer ``slicer``. If ``must_exist`` is set to True (defaults to False) a :class:`UnknownProfile` exception will be raised if the profile doesn't exist yet. Arguments: slicer (str): Identifier of the slicer to which the profile belongs to. name (str): Identifier of the profile for which to retrieve the path. must_exist (boolean): Whether the path must exist (True) or not (False, default). Returns: str: The absolute path to the profile identified by ``name`` for slicer ``slicer``. Raises: ~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown. ~octoprint.slicing.exceptions.UnknownProfile: The profile named ``name`` doesn't exist and ``must_exist`` was True. """ if slicer not in self.registered_slicers: raise UnknownSlicer(slicer) if not name: raise ValueError("name must be set") name = self._sanitize(name) path = os.path.join(self.get_slicer_profile_path(slicer), f"{name}.profile") if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)): raise OSError(f"Path to profile {name} tried to break out of allows sub path") if must_exist and not (os.path.exists(path) and os.path.isfile(path)): raise UnknownProfile(slicer, name) return path def _sanitize(self, name): if name is None: return None if "/" in name or "\\" in name: raise ValueError("name must not contain / or \\") import string valid_chars = "-_.() {ascii}{digits}".format( ascii=string.ascii_letters, digits=string.digits ) sanitized_name = "".join(c for c in name if c in valid_chars) sanitized_name = sanitized_name.replace(" ", "_") return sanitized_name def _load_profile_from_path(self, slicer, path, require_configured=False): profile = self.get_slicer( slicer, require_configured=require_configured ).get_slicer_profile(path) default_profiles = settings().get(["slicing", "defaultProfiles"]) if default_profiles and slicer in default_profiles: profile.default = default_profiles[slicer] == profile.name return profile def _save_profile_to_path( self, slicer, path, profile, allow_overwrite=True, overrides=None, require_configured=False, ): self.get_slicer( slicer, require_configured=require_configured ).save_slicer_profile( path, profile, allow_overwrite=allow_overwrite, overrides=overrides ) def _get_default_profile(self, slicer): default_profiles = settings().get(["slicing", "defaultProfiles"]) if default_profiles and slicer in default_profiles: try: return self.load_profile(slicer, default_profiles[slicer]) except (UnknownProfile, OSError): # in that case we'll use the slicers predefined default profile pass return self.get_slicer(slicer).get_slicer_default_profile()
31,325
Python
.py
644
37.546584
149
0.629142
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,875
exceptions.py
OctoPrint_OctoPrint/src/octoprint/slicing/exceptions.py
""" Slicing related exceptions. .. autoclass:: SlicingException .. autoclass:: SlicingCancelled :show-inheritance: .. autoclass:: SlicerException :show-inheritance: .. autoclass:: UnknownSlicer :show-inheritance: .. autoclass:: SlicerNotConfigured :show-inheritance: .. autoclass:: ProfileException .. autoclass:: UnknownProfile :show-inheritance: .. autoclass:: ProfileAlreadyExists :show-inheritance: """ __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" class SlicingException(Exception): """ Base exception of all slicing related exceptions. """ pass class SlicingCancelled(SlicingException): """ Raised if a slicing job was cancelled. """ pass class SlicerException(SlicingException): """ Base exception of all slicer related exceptions. .. attribute:: slicer Identifier of the slicer for which the exception was raised. """ def __init__(self, slicer, *args, **kwargs): SlicingException.__init__(self, *args, **kwargs) self.slicer = slicer class SlicerNotConfigured(SlicerException): """ Raised if a slicer is not yet configured but must be configured to proceed. """ def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) self.message = f"Slicer not configured: {slicer}" class UnknownSlicer(SlicerException): """ Raised if a slicer is unknown. """ def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) self.message = f"No such slicer: {slicer}" class ProfileException(Exception): """ Base exception of all slicing profile related exceptions. .. attribute:: slicer Identifier of the slicer to which the profile belongs. .. attribute:: profile Identifier of the profile for which the exception was raised. """ def __init__(self, slicer, profile, *args, **kwargs): Exception.__init__(self, *args, **kwargs) self.slicer = slicer self.profile = profile class UnknownProfile(ProfileException): """ Raised if a slicing profile does not exist but must exist to proceed. """ def __init__(self, slicer, profile, *args, **kwargs): ProfileException.__init__(self, slicer, profile, *args, **kwargs) self.message = "Profile {profile} for slicer {slicer} does not exist".format( profile=profile, slicer=slicer ) class ProfileAlreadyExists(ProfileException): """ Raised if a slicing profile already exists and must not be overwritten. """ def __init__(self, slicer, profile, *args, **kwargs): ProfileException.__init__(self, slicer, profile, *args, **kwargs) self.message = "Profile {profile} for slicer {slicer} already exists".format( profile=profile, slicer=slicer ) class CouldNotDeleteProfile(ProfileException): """ Raised if there is an unexpected error trying to delete a known profile. """ def __init__(self, slicer, profile, cause=None, *args, **kwargs): ProfileException.__init__(self, slicer, profile, *args, **kwargs) self.cause = cause if cause: self.message = ( "Could not delete profile {profile} for slicer {slicer}: {cause}".format( profile=profile, slicer=slicer, cause=str(cause) ) ) else: self.message = ( "Could not delete profile {profile} for slicer {slicer}".format( profile=profile, slicer=slicer ) )
3,865
Python
.py
102
31.313725
103
0.655905
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,876
__init__.py
OctoPrint_OctoPrint/src/octoprint/server/__init__.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import atexit import base64 import functools import logging import logging.config import mimetypes import os import pathlib import re import signal import sys import time import uuid # noqa: F401 from collections import OrderedDict, defaultdict from babel import Locale from flask import ( # noqa: F401 Blueprint, Flask, Request, Response, current_app, g, make_response, request, session, ) from flask_assets import Bundle, Environment from flask_babel import Babel, gettext, ngettext # noqa: F401 from flask_login import ( # noqa: F401 LoginManager, current_user, session_protected, user_loaded_from_cookie, user_logged_out, ) from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver from werkzeug.exceptions import HTTPException import octoprint.events import octoprint.filemanager import octoprint.util import octoprint.util.net from octoprint.server import util from octoprint.systemcommands import system_command_manager from octoprint.util.json import JsonEncoding from octoprint.vendor.flask_principal import ( # noqa: F401 AnonymousIdentity, Identity, Permission, Principal, RoleNeed, UserNeed, identity_changed, identity_loaded, ) from octoprint.vendor.sockjs.tornado import SockJSRouter try: import fcntl except ImportError: fcntl = None SUCCESS = {} NO_CONTENT = ("", 204, {"Content-Type": "text/plain"}) NOT_MODIFIED = ("Not Modified", 304, {"Content-Type": "text/plain"}) app = Flask("octoprint") assets = None babel = None limiter = None debug = False safe_mode = False printer = None printerProfileManager = None fileManager = None slicingManager = None analysisQueue = None userManager = None permissionManager = None groupManager = None eventManager = None loginManager = None pluginManager = None pluginLifecycleManager = None preemptiveCache = None jsonEncoder = None jsonDecoder = None connectivityChecker = None environmentDetector = None class OctoPrintAnonymousIdentity(AnonymousIdentity): def __init__(self): super().__init__() user = userManager.anonymous_user_factory() self.provides.add(UserNeed(user.get_id())) for need in user.needs: self.provides.add(need) principals = Principal(app, anonymous_identity=OctoPrintAnonymousIdentity) import octoprint.access.groups as groups # noqa: E402 import octoprint.access.permissions as permissions # noqa: E402 # we set admin_permission to a GroupPermission with the default admin group admin_permission = octoprint.util.variable_deprecated( "admin_permission has been deprecated, " "please use individual Permissions instead", since="1.4.0", )(groups.GroupPermission(groups.ADMIN_GROUP)) # we set user_permission to a GroupPermission with the default user group user_permission = octoprint.util.variable_deprecated( "user_permission has been deprecated, " "please use individual Permissions instead", since="1.4.0", )(groups.GroupPermission(groups.USER_GROUP)) import octoprint._version # noqa: E402 import octoprint.access.groups as groups # noqa: E402 import octoprint.access.users as users # noqa: E402 import octoprint.events as events # noqa: E402 import octoprint.filemanager.analysis # noqa: E402 import octoprint.filemanager.storage # noqa: E402 import octoprint.plugin # noqa: E402 import octoprint.slicing # noqa: E402 import octoprint.timelapse # noqa: E402 # only import further octoprint stuff down here, as it might depend on things defined above to be initialized already from octoprint import __branch__, __display_version__, __revision__, __version__ from octoprint.printer.profile import PrinterProfileManager from octoprint.printer.standard import Printer from octoprint.server.util import ( corsRequestHandler, corsResponseHandler, csrfRequestHandler, loginFromApiKeyRequestHandler, requireLoginRequestHandler, ) from octoprint.server.util.flask import PreemptiveCache, validate_session_signature from octoprint.settings import settings VERSION = __version__ BRANCH = __branch__ DISPLAY_VERSION = __display_version__ REVISION = __revision__ LOCALES = [] LANGUAGES = set() @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): user = load_user(identity.id) if user is None: user = userManager.anonymous_user_factory() identity.provides.add(UserNeed(user.get_id())) for need in user.needs: identity.provides.add(need) def _clear_identity(sender): # Remove session keys set by Flask-Principal for key in ("identity.id", "identity.name", "identity.auth_type"): session.pop(key, None) # switch to anonymous identity identity_changed.send(sender, identity=AnonymousIdentity()) @session_protected.connect_via(app) def on_session_protected(sender): # session was deleted by session protection, that means the user is no more and we need to clear our identity if session.get("remember", None) == "clear": _clear_identity(sender) @user_logged_out.connect_via(app) def on_user_logged_out(sender, user=None): # user was logged out, clear identity _clear_identity(sender) @user_loaded_from_cookie.connect_via(app) def on_user_loaded_from_cookie(sender, user=None): if user: session["login_mechanism"] = util.LoginMechanism.REMEMBER_ME session["credentials_seen"] = False def load_user(id): if id is None: return None if id == "_api": return userManager.api_user_factory() if session and "usersession.id" in session: sessionid = session["usersession.id"] else: sessionid = None if session and "usersession.signature" in session: sessionsig = session["usersession.signature"] else: sessionsig = "" if sessionid: # session["_fresh"] is False if the session comes from a remember me cookie, # True if it came from a use of the login dialog user = userManager.find_user( userid=id, session=sessionid, fresh=session.get("_fresh", False) ) else: user = userManager.find_user(userid=id) if ( user and user.is_active and (not sessionid or validate_session_signature(sessionsig, id, sessionid)) ): return user return None def load_user_from_request(request): user = None if settings().getBoolean(["accessControl", "trustBasicAuthentication"]): # Basic Authentication? user = util.get_user_for_authorization_header( request.headers.get("Authorization") ) if settings().getBoolean(["accessControl", "trustRemoteUser"]): # Remote user header? user = util.get_user_for_remote_user_header(request) return user def unauthorized_user(): from flask import abort abort(403) # ~~ startup code class Server: def __init__( self, settings=None, plugin_manager=None, connectivity_checker=None, environment_detector=None, event_manager=None, host=None, port=None, v6_only=False, debug=False, safe_mode=False, allow_root=False, octoprint_daemon=None, ): self._settings = settings self._plugin_manager = plugin_manager self._connectivity_checker = connectivity_checker self._environment_detector = environment_detector self._event_manager = event_manager self._host = host self._port = port self._v6_only = v6_only self._debug = debug self._safe_mode = safe_mode self._allow_root = allow_root self._octoprint_daemon = octoprint_daemon self._server = None self._logger = None self._lifecycle_callbacks = defaultdict(list) self._intermediary_server = None def run(self): if not self._allow_root: self._check_for_root() if self._settings is None: self._settings = settings() incomplete_startup_flag = ( pathlib.Path(self._settings._basedir) / ".incomplete_startup" ) if not self._settings.getBoolean(["server", "ignoreIncompleteStartup"]): try: incomplete_startup_flag.touch() except Exception: self._logger.exception("Could not create startup triggered safemode flag") if self._plugin_manager is None: self._plugin_manager = octoprint.plugin.plugin_manager() global app global babel global printer global printerProfileManager global fileManager global slicingManager global analysisQueue global userManager global permissionManager global groupManager global eventManager global loginManager global pluginManager global pluginLifecycleManager global preemptiveCache global jsonEncoder global jsonDecoder global connectivityChecker global environmentDetector global debug global safe_mode from tornado.ioloop import IOLoop from tornado.web import Application debug = self._debug safe_mode = self._safe_mode if safe_mode: self._log_safe_mode_start(safe_mode) if self._v6_only and not octoprint.util.net.HAS_V6: raise RuntimeError( "IPv6 only mode configured but system doesn't support IPv6" ) if self._host is None: host = self._settings.get(["server", "host"]) if host is None: if octoprint.util.net.HAS_V6: host = "::" else: host = "0.0.0.0" self._host = host if ":" in self._host and not octoprint.util.net.HAS_V6: raise RuntimeError( "IPv6 host address {!r} configured but system doesn't support IPv6".format( self._host ) ) if self._port is None: self._port = self._settings.getInt(["server", "port"]) if self._port is None: self._port = 5000 self._logger = logging.getLogger(__name__) self._setup_heartbeat_logging() pluginManager = self._plugin_manager # monkey patch/fix some stuff util.tornado.fix_json_encode() util.tornado.fix_websocket_check_origin() util.tornado.enable_per_message_deflate_extension() util.tornado.fix_tornado_xheader_handling() self._setup_mimetypes() # setup app self._setup_app(app) # setup i18n additional_translation_folders = [] if not safe_mode: additional_translation_folders += [ self._settings.getBaseFolder("translations") ] self._setup_i18n(app, additional_folders=additional_translation_folders) if self._settings.getBoolean(["serial", "log"]): # enable debug logging to serial.log logging.getLogger("SERIAL").setLevel(logging.DEBUG) if self._settings.getBoolean(["devel", "pluginTimings"]): # enable plugin timings log logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.DEBUG) # start the intermediary server self._start_intermediary_server() ### IMPORTANT! ### ### Best do not start any subprocesses until the intermediary server shuts down again or they MIGHT inherit the ### open port and prevent us from firing up Tornado later. ### ### The intermediary server's socket should have the CLOSE_EXEC flag (or its equivalent) set where possible, but ### we can only do that if fcntl is available or we are on Windows, so better safe than sorry. ### ### See also issues #2035 and #2090 systemCommandManager = system_command_manager() printerProfileManager = PrinterProfileManager() eventManager = self._event_manager analysis_queue_factories = { "gcode": octoprint.filemanager.analysis.GcodeAnalysisQueue } analysis_queue_hooks = pluginManager.get_hooks( "octoprint.filemanager.analysis.factory" ) for name, hook in analysis_queue_hooks.items(): try: additional_factories = hook() analysis_queue_factories.update(**additional_factories) except Exception: self._logger.exception( f"Error while processing analysis queues from {name}", extra={"plugin": name}, ) analysisQueue = octoprint.filemanager.analysis.AnalysisQueue( analysis_queue_factories ) slicingManager = octoprint.slicing.SlicingManager( self._settings.getBaseFolder("slicingProfiles"), printerProfileManager ) storage_managers = {} storage_managers[ octoprint.filemanager.FileDestinations.LOCAL ] = octoprint.filemanager.storage.LocalFileStorage( self._settings.getBaseFolder("uploads"), really_universal=self._settings.getBoolean( ["feature", "enforceReallyUniversalFilenames"] ), ) fileManager = octoprint.filemanager.FileManager( analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers, ) pluginLifecycleManager = LifecycleManager(pluginManager) preemptiveCache = PreemptiveCache( os.path.join( self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml" ) ) JsonEncoding.add_encoder(users.User, lambda obj: obj.as_dict()) JsonEncoding.add_encoder(groups.Group, lambda obj: obj.as_dict()) JsonEncoding.add_encoder( permissions.OctoPrintPermission, lambda obj: obj.as_dict() ) # start regular check if we are connected to the internet def on_connectivity_change(old_value, new_value): eventManager.fire( events.Events.CONNECTIVITY_CHANGED, payload={"old": old_value, "new": new_value}, ) connectivityChecker = self._connectivity_checker environmentDetector = self._environment_detector def on_settings_update(*args, **kwargs): # make sure our connectivity checker runs with the latest settings connectivityEnabled = self._settings.getBoolean( ["server", "onlineCheck", "enabled"] ) connectivityInterval = self._settings.getInt( ["server", "onlineCheck", "interval"] ) connectivityHost = self._settings.get(["server", "onlineCheck", "host"]) connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"]) connectivityName = self._settings.get(["server", "onlineCheck", "name"]) if ( connectivityChecker.enabled != connectivityEnabled or connectivityChecker.interval != connectivityInterval or connectivityChecker.host != connectivityHost or connectivityChecker.port != connectivityPort or connectivityChecker.name != connectivityName ): connectivityChecker.enabled = connectivityEnabled connectivityChecker.interval = connectivityInterval connectivityChecker.host = connectivityHost connectivityChecker.port = connectivityPort connectivityChecker.name = connectivityName connectivityChecker.check_immediately() eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update) components = { "plugin_manager": pluginManager, "printer_profile_manager": printerProfileManager, "event_bus": eventManager, "analysis_queue": analysisQueue, "slicing_manager": slicingManager, "file_manager": fileManager, "plugin_lifecycle_manager": pluginLifecycleManager, "preemptive_cache": preemptiveCache, "json_encoder": jsonEncoder, "json_decoder": jsonDecoder, "connectivity_checker": connectivityChecker, "environment_detector": self._environment_detector, "system_commands": systemCommandManager, } # ~~ setup access control # get additional permissions from plugins self._setup_plugin_permissions() # create group manager instance group_manager_factories = pluginManager.get_hooks( "octoprint.access.groups.factory" ) for name, factory in group_manager_factories.items(): try: groupManager = factory(components, self._settings) if groupManager is not None: self._logger.debug( f"Created group manager instance from factory {name}" ) break except Exception: self._logger.exception( "Error while creating group manager instance from factory {}".format( name ) ) else: group_manager_name = self._settings.get(["accessControl", "groupManager"]) try: clazz = octoprint.util.get_class(group_manager_name) groupManager = clazz() except AttributeError: self._logger.exception( "Could not instantiate group manager {}, " "falling back to FilebasedGroupManager!".format(group_manager_name) ) groupManager = octoprint.access.groups.FilebasedGroupManager() components.update({"group_manager": groupManager}) # create user manager instance user_manager_factories = pluginManager.get_hooks( "octoprint.users.factory" ) # legacy, set first so that new wins user_manager_factories.update( pluginManager.get_hooks("octoprint.access.users.factory") ) for name, factory in user_manager_factories.items(): try: userManager = factory(components, self._settings) if userManager is not None: self._logger.debug( f"Created user manager instance from factory {name}" ) break except Exception: self._logger.exception( "Error while creating user manager instance from factory {}".format( name ), extra={"plugin": name}, ) else: user_manager_name = self._settings.get(["accessControl", "userManager"]) try: clazz = octoprint.util.get_class(user_manager_name) userManager = clazz(groupManager) except octoprint.access.users.CorruptUserStorage: raise except Exception: self._logger.exception( "Could not instantiate user manager {}, " "falling back to FilebasedUserManager!".format(user_manager_name) ) userManager = octoprint.access.users.FilebasedUserManager(groupManager) components.update({"user_manager": userManager}) # create printer instance printer_factories = pluginManager.get_hooks("octoprint.printer.factory") for name, factory in printer_factories.items(): try: printer = factory(components) if printer is not None: self._logger.debug(f"Created printer instance from factory {name}") break except Exception: self._logger.exception( f"Error while creating printer instance from factory {name}", extra={"plugin": name}, ) else: printer = Printer(fileManager, analysisQueue, printerProfileManager) components.update({"printer": printer}) from octoprint import ( init_custom_events, init_settings_plugin_config_migration_and_cleanup, init_webcam_compat_overlay, ) from octoprint import octoprint_plugin_inject_factory as opif from octoprint import settings_plugin_inject_factory as spif init_custom_events(pluginManager) octoprint_plugin_inject_factory = opif(self._settings, components) settings_plugin_inject_factory = spif(self._settings) pluginManager.implementation_inject_factories = [ octoprint_plugin_inject_factory, settings_plugin_inject_factory, ] pluginManager.initialize_implementations() init_settings_plugin_config_migration_and_cleanup(pluginManager) init_webcam_compat_overlay(self._settings, pluginManager) pluginManager.log_all_plugins() # log environment data now self._environment_detector.log_detected_environment() # initialize file manager and register it for changes in the registered plugins fileManager.initialize() pluginLifecycleManager.add_callback( ["enabled", "disabled"], lambda name, plugin: fileManager.reload_plugins() ) # initialize slicing manager and register it for changes in the registered plugins slicingManager.initialize() pluginLifecycleManager.add_callback( ["enabled", "disabled"], lambda name, plugin: slicingManager.reload_slicers() ) # setup jinja2 self._setup_jinja2() # setup assets self._setup_assets() # configure timelapse octoprint.timelapse.valid_timelapse("test") octoprint.timelapse.configure_timelapse() # setup command triggers events.CommandTrigger(printer) if self._debug: events.DebugEventListener() # setup login manager self._setup_login_manager() # register API blueprint self._setup_blueprints() ## Tornado initialization starts here ioloop = IOLoop.current() enable_cors = settings().getBoolean(["api", "allowCrossOrigin"]) self._router = SockJSRouter( self._create_socket_connection, "/sockjs", session_kls=util.sockjs.ThreadSafeSession, user_settings={ "websocket_allow_origin": "*" if enable_cors else "", "jsessionid": False, "sockjs_url": "../../static/js/lib/sockjs.min.js", }, ) upload_suffixes = { "name": self._settings.get(["server", "uploads", "nameSuffix"]), "path": self._settings.get(["server", "uploads", "pathSuffix"]), } def mime_type_guesser(path): from octoprint.filemanager import get_mime_type return get_mime_type(path) def download_name_generator(path): metadata = fileManager.get_metadata("local", path) if metadata and "display" in metadata: return metadata["display"] download_handler_kwargs = {"as_attachment": True, "allow_client_caching": False} additional_mime_types = {"mime_type_guesser": mime_type_guesser} ##~~ Permission validators access_validators_from_plugins = [] for plugin, hook in pluginManager.get_hooks( "octoprint.server.http.access_validator" ).items(): try: access_validators_from_plugins.append( util.tornado.access_validation_factory(app, hook) ) except Exception: self._logger.exception( "Error while adding tornado access validator from plugin {}".format( plugin ), extra={"plugin": plugin}, ) timelapse_validators = [ util.tornado.access_validation_factory( app, util.flask.permission_validator, permissions.Permissions.TIMELAPSE_LIST, ), ] + access_validators_from_plugins download_validators = [ util.tornado.access_validation_factory( app, util.flask.permission_validator, permissions.Permissions.FILES_DOWNLOAD, ), ] + access_validators_from_plugins log_validators = [ util.tornado.access_validation_factory( app, util.flask.permission_validator, permissions.Permissions.PLUGIN_LOGGING_MANAGE, ), ] + access_validators_from_plugins camera_validators = [ util.tornado.access_validation_factory( app, util.flask.permission_validator, permissions.Permissions.WEBCAM ), ] + access_validators_from_plugins systeminfo_validators = [ util.tornado.access_validation_factory( app, util.flask.permission_validator, permissions.Permissions.SYSTEM ) ] + access_validators_from_plugins timelapse_permission_validator = { "access_validation": util.tornado.validation_chain(*timelapse_validators) } download_permission_validator = { "access_validation": util.tornado.validation_chain(*download_validators) } log_permission_validator = { "access_validation": util.tornado.validation_chain(*log_validators) } camera_permission_validator = { "access_validation": util.tornado.validation_chain(*camera_validators) } systeminfo_permission_validator = { "access_validation": util.tornado.validation_chain(*systeminfo_validators) } no_hidden_files_validator = { "path_validation": util.tornado.path_validation_factory( lambda path: not octoprint.util.is_hidden_path(path), status_code=404 ) } only_known_types_validator = { "path_validation": util.tornado.path_validation_factory( lambda path: octoprint.filemanager.valid_file_type( os.path.basename(path) ), status_code=404, ) } valid_timelapse = lambda path: not octoprint.util.is_hidden_path(path) and ( octoprint.timelapse.valid_timelapse(path) or octoprint.timelapse.valid_timelapse_thumbnail(path) ) timelapse_path_validator = { "path_validation": util.tornado.path_validation_factory( valid_timelapse, status_code=404, ) } timelapses_path_validator = { "path_validation": util.tornado.path_validation_factory( lambda path: valid_timelapse(path) and os.path.realpath(os.path.abspath(path)).startswith( settings().getBaseFolder("timelapse") ), status_code=400, ) } valid_log = lambda path: not octoprint.util.is_hidden_path( path ) and path.endswith(".log") log_path_validator = { "path_validation": util.tornado.path_validation_factory( valid_log, status_code=404, ) } logs_path_validator = { "path_validation": util.tornado.path_validation_factory( lambda path: valid_log(path) and os.path.realpath(os.path.abspath(path)).startswith( settings().getBaseFolder("logs") ), status_code=400, ) } def joined_dict(*dicts): if not len(dicts): return {} joined = {} for d in dicts: joined.update(d) return joined util.tornado.RequestlessExceptionLoggingMixin.LOG_REQUEST = debug util.tornado.CorsSupportMixin.ENABLE_CORS = enable_cors server_routes = self._router.urls + [ # various downloads # .mpg and .mp4 timelapses: ( r"/downloads/timelapse/(.*)", util.tornado.LargeResponseHandler, joined_dict( {"path": self._settings.getBaseFolder("timelapse")}, timelapse_permission_validator, download_handler_kwargs, timelapse_path_validator, ), ), # zipped timelapse bundles ( r"/downloads/timelapses", util.tornado.DynamicZipBundleHandler, joined_dict( { "as_attachment": True, "attachment_name": "octoprint-timelapses.zip", "path_processor": lambda x: ( x, os.path.join(self._settings.getBaseFolder("timelapse"), x), ), }, timelapse_permission_validator, timelapses_path_validator, ), ), # uploaded printables ( r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict( { "path": self._settings.getBaseFolder("uploads"), "as_attachment": True, "name_generator": download_name_generator, }, download_permission_validator, download_handler_kwargs, no_hidden_files_validator, only_known_types_validator, additional_mime_types, ), ), # log files ( r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict( { "path": self._settings.getBaseFolder("logs"), "mime_type_guesser": lambda *args, **kwargs: "text/plain", "stream_body": True, }, download_handler_kwargs, log_permission_validator, log_path_validator, ), ), # zipped log file bundles ( r"/downloads/logs", util.tornado.DynamicZipBundleHandler, joined_dict( { "as_attachment": True, "attachment_name": "octoprint-logs.zip", "path_processor": lambda x: ( x, os.path.join(self._settings.getBaseFolder("logs"), x), ), }, log_permission_validator, logs_path_validator, ), ), # system info bundle ( r"/downloads/systeminfo.zip", util.tornado.SystemInfoBundleHandler, systeminfo_permission_validator, ), # camera snapshot ( r"/downloads/camera/current", util.tornado.WebcamSnapshotHandler, joined_dict( { "as_attachment": "snapshot", }, camera_permission_validator, ), ), # generated webassets ( r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, { "path": os.path.join( self._settings.getBaseFolder("generated"), "webassets" ), "is_pre_compressed": True, }, ), # online indicators - text file with "online" as content and a transparent gif (r"/online.txt", util.tornado.StaticDataHandler, {"data": "online\n"}), ( r"/online.gif", util.tornado.StaticDataHandler, { "data": bytes( base64.b64decode( "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" ) ), "content_type": "image/gif", }, ), # deprecated endpoints ( r"/api/logs", util.tornado.DeprecatedEndpointHandler, {"url": "/plugin/logging/logs"}, ), ( r"/api/logs/(.*)", util.tornado.DeprecatedEndpointHandler, {"url": "/plugin/logging/logs/{0}"}, ), ] # fetch additional routes from plugins for name, hook in pluginManager.get_hooks("octoprint.server.http.routes").items(): try: result = hook(list(server_routes)) except Exception: self._logger.exception( f"There was an error while retrieving additional " f"server routes from plugin hook {name}", extra={"plugin": name}, ) else: if isinstance(result, (list, tuple)): for entry in result: if not isinstance(entry, tuple) or not len(entry) == 3: continue if not isinstance(entry[0], str): continue if not isinstance(entry[2], dict): continue route, handler, kwargs = entry route = r"/plugin/{name}/{route}".format( name=name, route=route if not route.startswith("/") else route[1:], ) self._logger.debug( f"Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}" ) server_routes.append((route, handler, kwargs)) headers = { "X-Robots-Tag": "noindex, nofollow, noimageindex", "X-Content-Type-Options": "nosniff", } if not settings().getBoolean(["server", "allowFraming"]): headers["X-Frame-Options"] = "sameorigin" removed_headers = ["Server"] from concurrent.futures import ThreadPoolExecutor server_routes.append( ( r".*", util.tornado.UploadStorageFallbackHandler, { "fallback": util.tornado.WsgiInputContainer( app.wsgi_app, executor=ThreadPoolExecutor( thread_name_prefix="WsgiRequestHandler" ), headers=headers, removed_headers=removed_headers, ), "file_prefix": "octoprint-file-upload-", "file_suffix": ".tmp", "suffixes": upload_suffixes, }, ) ) transforms = [ util.tornado.GlobalHeaderTransform.for_headers( "OctoPrintGlobalHeaderTransform", headers=headers, removed_headers=removed_headers, ) ] self._tornado_app = Application(handlers=server_routes, transforms=transforms) max_body_sizes = [ ( "POST", r"/api/files/([^/]*)", self._settings.getInt(["server", "uploads", "maxSize"]), ), ("POST", r"/api/languages", 5 * 1024 * 1024), ] # allow plugins to extend allowed maximum body sizes for name, hook in pluginManager.get_hooks( "octoprint.server.http.bodysize" ).items(): try: result = hook(list(max_body_sizes)) except Exception: self._logger.exception( f"There was an error while retrieving additional " f"upload sizes from plugin hook {name}", extra={"plugin": name}, ) else: if isinstance(result, (list, tuple)): for entry in result: if not isinstance(entry, tuple) or not len(entry) == 3: continue if ( entry[0] not in util.tornado.UploadStorageFallbackHandler.BODY_METHODS ): continue if not isinstance(entry[2], int): continue method, route, size = entry route = r"/plugin/{name}/{route}".format( name=name, route=route if not route.startswith("/") else route[1:], ) self._logger.debug( f"Adding maximum body size of {size}B for {method} requests to {route})" ) max_body_sizes.append((method, route, size)) self._stop_intermediary_server() # initialize and bind the server trusted_downstream = self._settings.get( ["server", "reverseProxy", "trustedDownstream"] ) if not isinstance(trusted_downstream, list): self._logger.warning( "server.reverseProxy.trustedDownstream is not a list, skipping" ) trusted_downstream = [] server_kwargs = { "max_body_sizes": max_body_sizes, "default_max_body_size": self._settings.getInt(["server", "maxSize"]), "xheaders": True, "trusted_downstream": trusted_downstream, } if sys.platform == "win32": # set 10min idle timeout under windows to hopefully make #2916 less likely server_kwargs.update({"idle_connection_timeout": 600}) self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs) listening_address = self._host if self._host == "::" and not self._v6_only: # special case - tornado only listens on v4 _and_ v6 if we use None as address listening_address = None self._server.listen(self._port, address=listening_address) ### From now on it's ok to launch subprocesses again eventManager.fire(events.Events.STARTUP) # analysis backlog fileManager.process_backlog() # auto connect if self._settings.getBoolean(["serial", "autoconnect"]): self._logger.info( "Autoconnect on startup is configured, trying to connect to the printer..." ) try: (port, baudrate) = ( self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"]), ) printer_profile = printerProfileManager.get_default() connectionOptions = printer.__class__.get_connection_options() if port in connectionOptions["ports"] or port == "AUTO" or port is None: self._logger.info( f"Trying to connect to configured serial port {port}" ) printer.connect( port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default", ) else: self._logger.info( "Could not find configured serial port {} in the system, cannot automatically connect to a non existing printer. Is it plugged in and booted up yet?" ) except Exception: self._logger.exception( "Something went wrong while attempting to automatically connect to the printer" ) # auto refresh serial ports while not connected if self._settings.getBoolean(["serial", "autorefresh"]): from octoprint.util.comm import serialList last_ports = None autorefresh = None def refresh_serial_list(): nonlocal last_ports new_ports = sorted(serialList()) if new_ports != last_ports: self._logger.info( "Serial port list was updated, refreshing the port list in the frontend" ) eventManager.fire( events.Events.CONNECTIONS_AUTOREFRESHED, payload={"ports": new_ports}, ) last_ports = new_ports def autorefresh_active(): return printer.is_closed_or_error() def autorefresh_stopped(): nonlocal autorefresh self._logger.info("Autorefresh of serial port list stopped") autorefresh = None def run_autorefresh(): nonlocal autorefresh if autorefresh is not None: autorefresh.cancel() autorefresh = None autorefresh = octoprint.util.RepeatedTimer( self._settings.getInt(["serial", "autorefreshInterval"]), refresh_serial_list, run_first=True, condition=autorefresh_active, on_finish=autorefresh_stopped, ) autorefresh.name = "Serial autorefresh worker" self._logger.info("Starting autorefresh of serial port list") autorefresh.start() run_autorefresh() eventManager.subscribe( octoprint.events.Events.DISCONNECTED, lambda e, p: run_autorefresh() ) # start up watchdogs try: watched = self._settings.getBaseFolder("watched") watchdog_handler = util.watchdog.GcodeWatchdogHandler(fileManager, printer) watchdog_handler.initial_scan(watched) if self._settings.getBoolean(["feature", "pollWatched"]): # use less performant polling observer if explicitly configured observer = PollingObserver() else: # use os default observer = Observer() observer.schedule(watchdog_handler, watched, recursive=True) observer.start() except Exception: self._logger.exception("Error starting watched folder observer") # run our startup plugins octoprint.plugin.call_plugin( octoprint.plugin.StartupPlugin, "on_startup", args=(self._host, self._port), sorting_context="StartupPlugin.on_startup", ) def call_on_startup(name, plugin): implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin) if implementation is None: return implementation.on_startup(self._host, self._port) pluginLifecycleManager.add_callback("enabled", call_on_startup) # prepare our after startup function def on_after_startup(): if self._host == "::": if self._v6_only: # only v6 self._logger.info(f"Listening on http://[::]:{self._port}") else: # all v4 and v6 self._logger.info( "Listening on http://0.0.0.0:{port} and http://[::]:{port}".format( port=self._port ) ) else: self._logger.info( "Listening on http://{}:{}".format( self._host if ":" not in self._host else "[" + self._host + "]", self._port, ) ) if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]): self._logger.info( "Server started successfully in safe mode as requested from config, removing flag" ) self._settings.setBoolean(["server", "startOnceInSafeMode"], False) self._settings.save() # now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for # which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons # or service xmls or the like). While they are working though the ioloop would block. Therefore we'll # create a single use thread in which to perform our after-startup-tasks, start that and hand back # control to the ioloop def work(): octoprint.plugin.call_plugin( octoprint.plugin.StartupPlugin, "on_after_startup", sorting_context="StartupPlugin.on_after_startup", ) def call_on_after_startup(name, plugin): implementation = plugin.get_implementation( octoprint.plugin.StartupPlugin ) if implementation is None: return implementation.on_after_startup() pluginLifecycleManager.add_callback("enabled", call_on_after_startup) # if there was a rogue plugin we wouldn't even have made it here, so remove startup triggered safe mode # flag again... try: if incomplete_startup_flag.exists(): incomplete_startup_flag.unlink() except Exception: self._logger.exception( "Could not clear startup triggered safe mode flag" ) # make a backup of the current config self._settings.backup(ext="backup") # when we are through with that we also run our preemptive cache if settings().getBoolean(["devel", "cache", "preemptive"]): self._execute_preemptive_flask_caching(preemptiveCache) import threading threading.Thread(target=work).start() ioloop.add_callback(on_after_startup) # prepare our shutdown function def on_shutdown(): # will be called on clean system exit and shutdown the watchdog observer and call the on_shutdown methods # on all registered ShutdownPlugins self._logger.info("Shutting down...") observer.stop() observer.join() eventManager.fire(events.Events.SHUTDOWN) self._logger.info("Calling on_shutdown on plugins") octoprint.plugin.call_plugin( octoprint.plugin.ShutdownPlugin, "on_shutdown", sorting_context="ShutdownPlugin.on_shutdown", ) # wait for shutdown event to be processed, but maximally for 15s event_timeout = 15.0 if eventManager.join(timeout=event_timeout): self._logger.warning( "Event loop was still busy processing after {}s, shutting down anyhow".format( event_timeout ) ) if self._octoprint_daemon is not None: self._logger.info("Cleaning up daemon pidfile") self._octoprint_daemon.terminated() self._logger.info("Goodbye!") atexit.register(on_shutdown) def sigterm_handler(*args, **kwargs): # will stop tornado on SIGTERM, making the program exit cleanly def shutdown_tornado(): self._logger.debug("Shutting down tornado's IOLoop...") ioloop.stop() self._logger.debug("SIGTERM received...") ioloop.add_callback_from_signal(shutdown_tornado) signal.signal(signal.SIGTERM, sigterm_handler) try: # this is the main loop - as long as tornado is running, OctoPrint is running ioloop.start() self._logger.debug("Tornado's IOLoop stopped") except (KeyboardInterrupt, SystemExit): pass except Exception: self._logger.fatal( "Now that is embarrassing... Something went really really wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!" ) self._logger.exception("Stacktrace follows:") def _log_safe_mode_start(self, self_mode): self_mode_file = os.path.join( self._settings.getBaseFolder("data"), "last_safe_mode" ) try: with open(self_mode_file, "w+", encoding="utf-8") as f: f.write(self_mode) except Exception as ex: self._logger.warn(f"Could not write safe mode file {self_mode_file}: {ex}") def _create_socket_connection(self, session): global printer, fileManager, analysisQueue, userManager, eventManager, connectivityChecker return util.sockjs.PrinterStateConnection( printer, fileManager, analysisQueue, userManager, groupManager, eventManager, pluginManager, connectivityChecker, session, ) def _check_for_root(self): if "geteuid" in dir(os) and os.geteuid() == 0: exit("You should not run OctoPrint as root!") def _get_locale(self): global LANGUAGES l10n = None default_language = self._settings.get(["appearance", "defaultLanguage"]) if "l10n" in request.values: # request: query param l10n = request.values["l10n"].split(",") elif "X-Locale" in request.headers: # request: header l10n = request.headers["X-Locale"].split(",") elif hasattr(g, "identity") and g.identity: # user setting userid = g.identity.id try: user_language = userManager.get_user_setting( userid, ("interface", "language") ) if user_language is not None and not user_language == "_default": l10n = [user_language] except octoprint.access.users.UnknownUser: pass if ( not l10n and default_language is not None and not default_language == "_default" and default_language in LANGUAGES ): # instance setting l10n = [default_language] if l10n: # canonicalize and get rid of invalid language codes l10n_canonicalized = [] for x in l10n: try: l10n_canonicalized.append(str(Locale.parse(x))) except Exception: # invalid language code, ignore continue return Locale.negotiate(l10n_canonicalized, LANGUAGES) # request: preference return Locale.parse(request.accept_languages.best_match(LANGUAGES, default="en")) def _setup_heartbeat_logging(self): logger = logging.getLogger(__name__ + ".heartbeat") def log_heartbeat(): logger.info("Server heartbeat <3") interval = settings().getFloat(["server", "heartbeat"]) logger.info(f"Starting server heartbeat, {interval}s interval") timer = octoprint.util.RepeatedTimer(interval, log_heartbeat) timer.start() def _setup_app(self, app): global limiter from octoprint.server.util.flask import ( OctoPrintFlaskRequest, OctoPrintFlaskResponse, OctoPrintJsonProvider, OctoPrintSessionInterface, PrefixAwareJinjaEnvironment, ReverseProxiedEnvironment, ) # we must set this here because setting app.debug will access app.jinja_env app.jinja_environment = PrefixAwareJinjaEnvironment app.config["TEMPLATES_AUTO_RELOAD"] = True app.config["REMEMBER_COOKIE_DURATION"] = 90 * 24 * 60 * 60 # 90 days app.config["REMEMBER_COOKIE_HTTPONLY"] = True # REMEMBER_COOKIE_SECURE will be taken care of by our custom cookie handling # we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take app.debug = self._debug # setup octoprint's flask json serialization/deserialization app.json = OctoPrintJsonProvider(app) app.json.compact = False s = settings() secret_key = s.get(["server", "secretKey"]) if not secret_key: import string from random import choice chars = string.ascii_lowercase + string.ascii_uppercase + string.digits secret_key = "".join(choice(chars) for _ in range(32)) s.set(["server", "secretKey"], secret_key) s.save() app.secret_key = secret_key reverse_proxied = ReverseProxiedEnvironment( header_prefix=s.get(["server", "reverseProxy", "prefixHeader"]), header_scheme=s.get(["server", "reverseProxy", "schemeHeader"]), header_host=s.get(["server", "reverseProxy", "hostHeader"]), header_server=s.get(["server", "reverseProxy", "serverHeader"]), header_port=s.get(["server", "reverseProxy", "portHeader"]), prefix=s.get(["server", "reverseProxy", "prefixFallback"]), scheme=s.get(["server", "reverseProxy", "schemeFallback"]), host=s.get(["server", "reverseProxy", "hostFallback"]), server=s.get(["server", "reverseProxy", "serverFallback"]), port=s.get(["server", "reverseProxy", "portFallback"]), ) OctoPrintFlaskRequest.environment_wrapper = reverse_proxied app.request_class = OctoPrintFlaskRequest app.response_class = OctoPrintFlaskResponse app.session_interface = OctoPrintSessionInterface() @app.before_request def before_request(): g.locale = self._get_locale() # used for performance measurement g.start_time = time.monotonic() if self._debug and "perfprofile" in request.args: try: from pyinstrument import Profiler g.perfprofiler = Profiler() g.perfprofiler.start() except ImportError: # profiler dependency not installed, ignore pass @app.after_request def after_request(response): # send no-cache headers with all POST responses if request.method == "POST": response.cache_control.no_cache = True response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett") if hasattr(g, "perfprofiler"): g.perfprofiler.stop() output_html = g.perfprofiler.output_html() return make_response(output_html) if hasattr(g, "start_time"): end_time = time.monotonic() duration_ms = int((end_time - g.start_time) * 1000) response.headers.add("Server-Timing", f"app;dur={duration_ms}") return response from octoprint.util.jinja import MarkdownFilter MarkdownFilter(app) from flask_limiter import Limiter from flask_limiter.util import get_remote_address app.config["RATELIMIT_STRATEGY"] = "fixed-window-elastic-expiry" limiter = Limiter( key_func=get_remote_address, app=app, enabled=s.getBoolean(["devel", "enableRateLimiter"]), storage_uri="memory://", ) def _setup_i18n(self, app, additional_folders=None): global babel global LOCALES global LANGUAGES if additional_folders is None: additional_folders = [] dirs = additional_folders + [os.path.join(app.root_path, "translations")] # translations from plugins plugins = octoprint.plugin.plugin_manager().enabled_plugins for plugin in plugins.values(): plugin_translation_dir = os.path.join(plugin.location, "translations") if not os.path.isdir(plugin_translation_dir): continue dirs.append(plugin_translation_dir) app.config["BABEL_TRANSLATION_DIRECTORIES"] = ";".join(dirs) babel = Babel(app, locale_selector=self._get_locale) def get_available_locale_identifiers(locales): result = set() # add available translations for locale in locales: result.add(str(locale)) return result with app.app_context(): LOCALES = babel.list_translations() LANGUAGES = get_available_locale_identifiers(LOCALES) def _setup_jinja2(self): import re app.jinja_env.add_extension("jinja2.ext.do") app.jinja_env.add_extension("octoprint.util.jinja.trycatch") def regex_replace(s, find, replace): return re.sub(find, replace, s) html_header_regex = re.compile( r"<h(?P<number>[1-6])>(?P<content>.*?)</h(?P=number)>" ) def offset_html_headers(s, offset): def repl(match): number = int(match.group("number")) number += offset if number > 6: number = 6 elif number < 1: number = 1 return "<h{number}>{content}</h{number}>".format( number=number, content=match.group("content") ) return html_header_regex.sub(repl, s) markdown_header_regex = re.compile( r"^(?P<hashes>#+)\s+(?P<content>.*)$", flags=re.MULTILINE ) def offset_markdown_headers(s, offset): def repl(match): number = len(match.group("hashes")) number += offset if number > 6: number = 6 elif number < 1: number = 1 return "{hashes} {content}".format( hashes="#" * number, content=match.group("content") ) return markdown_header_regex.sub(repl, s) html_link_regex = re.compile(r"<(?P<tag>a.*?)>(?P<content>.*?)</a>") def externalize_links(text): def repl(match): tag = match.group("tag") if "href" not in tag: return match.group(0) if "target=" not in tag and "rel=" not in tag: tag += ' target="_blank" rel="noreferrer noopener"' content = match.group("content") return f"<{tag}>{content}</a>" return html_link_regex.sub(repl, text) single_quote_regex = re.compile("(?<!\\\\)'") def escape_single_quote(text): return single_quote_regex.sub("\\'", text) double_quote_regex = re.compile('(?<!\\\\)"') def escape_double_quote(text): return double_quote_regex.sub('\\"', text) app.jinja_env.filters["regex_replace"] = regex_replace app.jinja_env.filters["offset_html_headers"] = offset_html_headers app.jinja_env.filters["offset_markdown_headers"] = offset_markdown_headers app.jinja_env.filters["externalize_links"] = externalize_links app.jinja_env.filters["escape_single_quote"] = app.jinja_env.filters[ "esq" ] = escape_single_quote app.jinja_env.filters["escape_double_quote"] = app.jinja_env.filters[ "edq" ] = escape_double_quote # configure additional template folders for jinja2 import jinja2 import octoprint.util.jinja app.jinja_env.prefix_loader = jinja2.PrefixLoader({}) loaders = [app.jinja_loader, app.jinja_env.prefix_loader] if octoprint.util.is_running_from_source(): root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../..")) allowed = ["AUTHORS.md", "SUPPORTERS.md", "THIRDPARTYLICENSES.md"] files = {"_data/" + name: os.path.join(root, name) for name in allowed} loaders.append(octoprint.util.jinja.SelectedFilesWithConversionLoader(files)) # TODO: Remove this in 2.0.0 warning_message = "Loading plugin template '{template}' from '{filename}' without plugin prefix, this is deprecated and will soon no longer be supported." loaders.append( octoprint.util.jinja.WarningLoader( octoprint.util.jinja.PrefixChoiceLoader(app.jinja_env.prefix_loader), warning_message, ) ) app.jinja_loader = jinja2.ChoiceLoader(loaders) self._register_template_plugins() # make sure plugin lifecycle events relevant for jinja2 are taken care of def template_enabled(name, plugin): if plugin.implementation is None or not isinstance( plugin.implementation, octoprint.plugin.TemplatePlugin ): return self._register_additional_template_plugin(plugin.implementation) def template_disabled(name, plugin): if plugin.implementation is None or not isinstance( plugin.implementation, octoprint.plugin.TemplatePlugin ): return self._unregister_additional_template_plugin(plugin.implementation) pluginLifecycleManager.add_callback("enabled", template_enabled) pluginLifecycleManager.add_callback("disabled", template_disabled) def _execute_preemptive_flask_caching(self, preemptive_cache): import time from werkzeug.test import EnvironBuilder # we clean up entries from our preemptive cache settings that haven't been # accessed longer than server.preemptiveCache.until days preemptive_cache_timeout = settings().getInt( ["server", "preemptiveCache", "until"] ) cutoff_timestamp = time.time() - preemptive_cache_timeout * 24 * 60 * 60 def filter_current_entries(entry): """Returns True for entries younger than the cutoff date""" return "_timestamp" in entry and entry["_timestamp"] > cutoff_timestamp def filter_http_entries(entry): """Returns True for entries targeting http or https.""" return ( "base_url" in entry and entry["base_url"] and ( entry["base_url"].startswith("http://") or entry["base_url"].startswith("https://") ) ) def filter_entries(entry): """Combined filter.""" filters = (filter_current_entries, filter_http_entries) return all([f(entry) for f in filters]) # filter out all old and non-http entries cache_data = preemptive_cache.clean_all_data( lambda root, entries: list(filter(filter_entries, entries)) ) if not cache_data: return def execute_caching(): logger = logging.getLogger(__name__ + ".preemptive_cache") for route in sorted(cache_data.keys(), key=lambda x: (x.count("/"), x)): entries = reversed( sorted(cache_data[route], key=lambda x: x.get("_count", 0)) ) for kwargs in entries: plugin = kwargs.get("plugin", None) if plugin: try: plugin_info = pluginManager.get_plugin_info( plugin, require_enabled=True ) if plugin_info is None: logger.info( "About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense".format( plugin ) ) continue implementation = plugin_info.implementation if implementation is None or not isinstance( implementation, octoprint.plugin.UiPlugin ): logger.info( "About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense".format( plugin ) ) continue if not implementation.get_ui_preemptive_caching_enabled(): logger.info( "About to preemptively cache plugin {} but it has disabled preemptive caching".format( plugin ) ) continue except Exception: logger.exception( "Error while trying to check if plugin {} has preemptive caching enabled, skipping entry" ) continue additional_request_data = kwargs.get("_additional_request_data", {}) kwargs = { k: v for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin" } kwargs.update(additional_request_data) try: start = time.monotonic() if plugin: logger.info( "Preemptively caching {} (ui {}) for {!r}".format( route, plugin, kwargs ) ) else: logger.info( "Preemptively caching {} (ui _default) for {!r}".format( route, kwargs ) ) headers = kwargs.get("headers", {}) headers["X-Force-View"] = plugin if plugin else "_default" headers["X-Preemptive-Recording"] = "yes" kwargs["headers"] = headers builder = EnvironBuilder(**kwargs) app(builder.get_environ(), lambda *a, **kw: None) logger.info(f"... done in {time.monotonic() - start:.2f}s") except Exception: logger.exception( "Error while trying to preemptively cache {} for {!r}".format( route, kwargs ) ) # asynchronous caching import threading cache_thread = threading.Thread( target=execute_caching, name="Preemptive Cache Worker" ) cache_thread.daemon = True cache_thread.start() def _register_template_plugins(self): template_plugins = pluginManager.get_implementations( octoprint.plugin.TemplatePlugin ) for plugin in template_plugins: try: self._register_additional_template_plugin(plugin) except Exception: self._logger.exception( "Error while trying to register templates of plugin {}, ignoring it".format( plugin._identifier ) ) def _register_additional_template_plugin(self, plugin): import octoprint.util.jinja folder = plugin.get_template_folder() if ( folder is not None and plugin.template_folder_key not in app.jinja_env.prefix_loader.mapping ): loader = octoprint.util.jinja.FilteredFileSystemLoader( [plugin.get_template_folder()], path_filter=lambda x: not octoprint.util.is_hidden_path(x), ) app.jinja_env.prefix_loader.mapping[plugin.template_folder_key] = loader def _unregister_additional_template_plugin(self, plugin): folder = plugin.get_template_folder() if ( folder is not None and plugin.template_folder_key in app.jinja_env.prefix_loader.mapping ): del app.jinja_env.prefix_loader.mapping[plugin.template_folder_key] def _setup_blueprints(self): # do not remove or the index view won't be found import octoprint.server.views # noqa: F401 from octoprint.server.api import api from octoprint.server.util.flask import make_api_error blueprints = [api] api_endpoints = ["/api"] registrators = [functools.partial(app.register_blueprint, api, url_prefix="/api")] # also register any blueprints defined in BlueprintPlugins ( blueprints_from_plugins, api_endpoints_from_plugins, registrators_from_plugins, ) = self._prepare_blueprint_plugins() blueprints += blueprints_from_plugins api_endpoints += api_endpoints_from_plugins registrators += registrators_from_plugins # and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves (blueprints_from_assets, registrators_from_assets) = self._prepare_asset_plugins() blueprints += blueprints_from_assets registrators += registrators_from_assets # make sure all before/after_request hook results are attached as well self._add_plugin_request_handlers_to_blueprints(*blueprints) # register everything with the system for registrator in registrators: registrator() @app.errorhandler(HTTPException) def _handle_api_error(ex): if any(map(lambda x: request.path.startswith(x), api_endpoints)): return make_api_error(ex.description, ex.code) else: return ex def _prepare_blueprint_plugins(self): def register_plugin_blueprint(plugin, blueprint, url_prefix): try: app.register_blueprint( blueprint, url_prefix=url_prefix, name_prefix="plugin" ) self._logger.debug( f"Registered API of plugin {plugin} under URL prefix {url_prefix}" ) except Exception: self._logger.exception( f"Error while registering blueprint of plugin {plugin}, ignoring it", extra={"plugin": plugin}, ) blueprints = [] api_endpoints = [] registrators = [] blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.BlueprintPlugin ) for plugin in blueprint_plugins: blueprint, prefix = self._prepare_blueprint_plugin(plugin) blueprints.append(blueprint) api_endpoints += map( lambda x: prefix + x, plugin.get_blueprint_api_prefixes() ) registrators.append( functools.partial( register_plugin_blueprint, plugin._identifier, blueprint, prefix ) ) return blueprints, api_endpoints, registrators def _prepare_asset_plugins(self): def register_asset_blueprint(plugin, blueprint, url_prefix): try: app.register_blueprint( blueprint, url_prefix=url_prefix, name_prefix="plugin" ) self._logger.debug( f"Registered assets of plugin {plugin} under URL prefix {url_prefix}" ) except Exception: self._logger.exception( f"Error while registering blueprint of plugin {plugin}, ignoring it", extra={"plugin": plugin}, ) blueprints = [] registrators = [] asset_plugins = octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.AssetPlugin ) for plugin in asset_plugins: if isinstance(plugin, octoprint.plugin.BlueprintPlugin): continue blueprint, prefix = self._prepare_asset_plugin(plugin) blueprints.append(blueprint) registrators.append( functools.partial( register_asset_blueprint, plugin._identifier, blueprint, prefix ) ) return blueprints, registrators def _prepare_blueprint_plugin(self, plugin): name = plugin._identifier blueprint = plugin.get_blueprint() if blueprint is None: return blueprint.before_request(corsRequestHandler) blueprint.before_request(loginFromApiKeyRequestHandler) blueprint.after_request(corsResponseHandler) if plugin.is_blueprint_csrf_protected(): self._logger.debug( f"CSRF Protection for Blueprint of plugin {name} is enabled" ) blueprint.before_request(csrfRequestHandler) else: self._logger.warning( f"CSRF Protection for Blueprint of plugin {name} is DISABLED" ) if plugin.is_blueprint_protected(): blueprint.before_request(requireLoginRequestHandler) url_prefix = f"/plugin/{name}" return blueprint, url_prefix def _prepare_asset_plugin(self, plugin): name = plugin._identifier url_prefix = f"/plugin/{name}" blueprint = Blueprint(name, name, static_folder=plugin.get_asset_folder()) blueprint.before_request(corsRequestHandler) blueprint.after_request(corsResponseHandler) return blueprint, url_prefix def _add_plugin_request_handlers_to_blueprints(self, *blueprints): before_hooks = octoprint.plugin.plugin_manager().get_hooks( "octoprint.server.api.before_request" ) after_hooks = octoprint.plugin.plugin_manager().get_hooks( "octoprint.server.api.after_request" ) for name, hook in before_hooks.items(): plugin = octoprint.plugin.plugin_manager().get_plugin(name) for blueprint in blueprints: try: result = hook(plugin=plugin) if isinstance(result, (list, tuple)): for h in result: blueprint.before_request(h) except Exception: self._logger.exception( "Error processing before_request hooks from plugin {}".format( plugin ), extra={"plugin": name}, ) for name, hook in after_hooks.items(): plugin = octoprint.plugin.plugin_manager().get_plugin(name) for blueprint in blueprints: try: result = hook(plugin=plugin) if isinstance(result, (list, tuple)): for h in result: blueprint.after_request(h) except Exception: self._logger.exception( "Error processing after_request hooks from plugin {}".format( plugin ), extra={"plugin": name}, ) def _setup_mimetypes(self): # Safety measures for Windows... apparently the mimetypes module takes its translation from the windows # registry, and if for some weird reason that gets borked the reported MIME types can be all over the place. # Since at least in Chrome that can cause hilarious issues with JS files (refusal to run them and thus a # borked UI) we make sure that .js always maps to the correct application/javascript, and also throw in a # .css -> text/css for good measure. # # See #3367 mimetypes.add_type("application/javascript", ".js") mimetypes.add_type("text/css", ".css") def _setup_assets(self): global app global assets global pluginManager from octoprint.server.util.webassets import MemoryManifest # noqa: F401 util.flask.fix_webassets_convert_item_to_flask_url() util.flask.fix_webassets_filtertool() base_folder = self._settings.getBaseFolder("generated") # clean the folder if self._settings.getBoolean(["devel", "webassets", "clean_on_startup"]): import errno import shutil for entry, recreate in ( ("webassets", True), # no longer used, but clean up just in case (".webassets-cache", False), (".webassets-manifest.json", False), ): path = os.path.join(base_folder, entry) # delete path if it exists if os.path.exists(path): try: self._logger.debug(f"Deleting {path}...") if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path) except Exception: self._logger.exception( f"Error while trying to delete {path}, " f"leaving it alone" ) continue # re-create path if necessary if recreate: self._logger.debug(f"Creating {path}...") error_text = ( f"Error while trying to re-create {path}, that might cause " f"errors with the webassets cache" ) try: os.makedirs(path) except OSError as e: if e.errno == errno.EACCES: # that might be caused by the user still having the folder open somewhere, let's try again after # waiting a bit import time for n in range(3): time.sleep(0.5) self._logger.debug( "Creating {path}: Retry #{retry} after {time}s".format( path=path, retry=n + 1, time=(n + 1) * 0.5 ) ) try: os.makedirs(path) break except Exception: if self._logger.isEnabledFor(logging.DEBUG): self._logger.exception( f"Ignored error while creating " f"directory {path}" ) pass else: # this will only get executed if we never did # successfully execute makedirs above self._logger.exception(error_text) continue else: # not an access error, so something we don't understand # went wrong -> log an error and stop self._logger.exception(error_text) continue except Exception: # not an OSError, so something we don't understand # went wrong -> log an error and stop self._logger.exception(error_text) continue self._logger.info(f"Reset webasset folder {path}...") AdjustedEnvironment = type(Environment)( Environment.__name__, (Environment,), {"resolver_class": util.flask.PluginAssetResolver}, ) class CustomDirectoryEnvironment(AdjustedEnvironment): @property def directory(self): return base_folder assets = CustomDirectoryEnvironment(app) assets.debug = not self._settings.getBoolean(["devel", "webassets", "bundle"]) # we should rarely if ever regenerate the webassets in production and can wait a # few seconds for regeneration in development, if it means we can get rid of # a whole monkey patch and in internal use of pickle with non-tamperproof files assets.cache = False assets.manifest = "memory" UpdaterType = type(util.flask.SettingsCheckUpdater)( util.flask.SettingsCheckUpdater.__name__, (util.flask.SettingsCheckUpdater,), {"updater": assets.updater}, ) assets.updater = UpdaterType preferred_stylesheet = self._settings.get(["devel", "stylesheet"]) dynamic_core_assets = util.flask.collect_core_assets() dynamic_plugin_assets = util.flask.collect_plugin_assets( preferred_stylesheet=preferred_stylesheet ) js_libs = [ "js/lib/babel-polyfill.min.js", "js/lib/jquery/jquery.min.js", "js/lib/modernizr.custom.js", "js/lib/lodash.min.js", "js/lib/sprintf.min.js", "js/lib/knockout.js", "js/lib/knockout.mapping-latest.js", "js/lib/babel.js", "js/lib/bootstrap/bootstrap.js", "js/lib/bootstrap/bootstrap-modalmanager.js", "js/lib/bootstrap/bootstrap-modal.js", "js/lib/bootstrap/bootstrap-slider.js", "js/lib/bootstrap/bootstrap-tabdrop.js", "js/lib/jquery/jquery-ui.js", "js/lib/jquery/jquery.flot.js", "js/lib/jquery/jquery.flot.time.js", "js/lib/jquery/jquery.flot.crosshair.js", "js/lib/jquery/jquery.flot.dashes.js", "js/lib/jquery/jquery.flot.resize.js", "js/lib/jquery/jquery.iframe-transport.js", "js/lib/jquery/jquery.fileupload.js", "js/lib/jquery/jquery.slimscroll.min.js", "js/lib/jquery/jquery.qrcode.min.js", "js/lib/jquery/jquery.bootstrap.wizard.js", "js/lib/pnotify/pnotify.core.min.js", "js/lib/pnotify/pnotify.buttons.min.js", "js/lib/pnotify/pnotify.callbacks.min.js", "js/lib/pnotify/pnotify.confirm.min.js", "js/lib/pnotify/pnotify.desktop.min.js", "js/lib/pnotify/pnotify.history.min.js", "js/lib/pnotify/pnotify.mobile.min.js", "js/lib/pnotify/pnotify.nonblock.min.js", "js/lib/pnotify/pnotify.reference.min.js", "js/lib/pnotify/pnotify.tooltip.min.js", "js/lib/pnotify/pnotify.maxheight.js", "js/lib/moment-with-locales.min.js", "js/lib/pusher.color.min.js", "js/lib/detectmobilebrowser.js", "js/lib/ua-parser.min.js", "js/lib/md5.min.js", "js/lib/bootstrap-slider-knockout-binding.js", "js/lib/loglevel.min.js", "js/lib/sockjs.min.js", "js/lib/hls.js", "js/lib/less.js", ] css_libs = [ "css/bootstrap.min.css", "css/bootstrap-modal.css", "css/bootstrap-slider.css", "css/bootstrap-tabdrop.css", "vendor/font-awesome-3.2.1/css/font-awesome.min.css", "vendor/fontawesome-6.1.1/css/all.min.css", "vendor/fontawesome-6.1.1/css/v4-shims.min.css", "vendor/fa5-power-transforms.min.css", "css/jquery.fileupload-ui.css", "css/pnotify.core.min.css", "css/pnotify.buttons.min.css", "css/pnotify.history.min.css", ] # a couple of custom filters from webassets.filter import register_filter from octoprint.server.util.webassets import ( GzipFile, JsDelimiterBundler, JsPluginBundle, LessImportRewrite, RJSMinExtended, SourceMapRemove, SourceMapRewrite, ) register_filter(LessImportRewrite) register_filter(SourceMapRewrite) register_filter(SourceMapRemove) register_filter(JsDelimiterBundler) register_filter(GzipFile) register_filter(RJSMinExtended) def all_assets_for_plugins(collection): """Gets all plugin assets for a dict of plugin->assets""" result = [] for assets in collection.values(): result += assets return result # -- JS -------------------------------------------------------------------------------------------------------- filters = ["sourcemap_remove"] if self._settings.getBoolean(["devel", "webassets", "minify"]): filters += ["rjsmin_extended"] filters += ["js_delimiter_bundler", "gzip"] js_filters = filters if self._settings.getBoolean(["devel", "webassets", "minify_plugins"]): js_plugin_filters = js_filters else: js_plugin_filters = [x for x in js_filters if x not in ("rjsmin_extended",)] def js_bundles_for_plugins(collection, filters=None): """Produces JsPluginBundle instances that output IIFE wrapped assets""" result = OrderedDict() for plugin, assets in collection.items(): if len(assets): result[plugin] = JsPluginBundle(plugin, *assets, filters=filters) return result js_core = ( dynamic_core_assets["js"] + all_assets_for_plugins(dynamic_plugin_assets["bundled"]["js"]) + ["js/app/dataupdater.js", "js/app/helpers.js", "js/app/main.js"] ) js_plugins = js_bundles_for_plugins( dynamic_plugin_assets["external"]["js"], filters="js_delimiter_bundler" ) clientjs_core = dynamic_core_assets["clientjs"] + all_assets_for_plugins( dynamic_plugin_assets["bundled"]["clientjs"] ) clientjs_plugins = js_bundles_for_plugins( dynamic_plugin_assets["external"]["clientjs"], filters="js_delimiter_bundler" ) js_libs_bundle = Bundle( *js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters) ) js_core_bundle = Bundle( *js_core, output="webassets/packed_core.js", filters=",".join(js_filters) ) if len(js_plugins) == 0: js_plugins_bundle = Bundle(*[]) else: js_plugins_bundle = Bundle( *js_plugins.values(), output="webassets/packed_plugins.js", filters=",".join(js_plugin_filters), ) js_app_bundle = Bundle( js_plugins_bundle, js_core_bundle, output="webassets/packed_app.js", filters=",".join(js_plugin_filters), ) js_client_core_bundle = Bundle( *clientjs_core, output="webassets/packed_client_core.js", filters=",".join(js_filters), ) if len(clientjs_plugins) == 0: js_client_plugins_bundle = Bundle(*[]) else: js_client_plugins_bundle = Bundle( *clientjs_plugins.values(), output="webassets/packed_client_plugins.js", filters=",".join(js_plugin_filters), ) js_client_bundle = Bundle( js_client_core_bundle, js_client_plugins_bundle, output="webassets/packed_client.js", filters=",".join(js_plugin_filters), ) # -- CSS ------------------------------------------------------------------------------------------------------- css_filters = ["cssrewrite", "gzip"] css_core = list(dynamic_core_assets["css"]) + all_assets_for_plugins( dynamic_plugin_assets["bundled"]["css"] ) css_plugins = list( all_assets_for_plugins(dynamic_plugin_assets["external"]["css"]) ) css_libs_bundle = Bundle( *css_libs, output="webassets/packed_libs.css", filters=",".join(css_filters) ) if len(css_core) == 0: css_core_bundle = Bundle(*[]) else: css_core_bundle = Bundle( *css_core, output="webassets/packed_core.css", filters=",".join(css_filters), ) if len(css_plugins) == 0: css_plugins_bundle = Bundle(*[]) else: css_plugins_bundle = Bundle( *css_plugins, output="webassets/packed_plugins.css", filters=",".join(css_filters), ) css_app_bundle = Bundle( css_core, css_plugins, output="webassets/packed_app.css", filters=",".join(css_filters), ) # -- LESS ------------------------------------------------------------------------------------------------------ less_filters = ["cssrewrite", "less_importrewrite", "gzip"] less_core = list(dynamic_core_assets["less"]) + all_assets_for_plugins( dynamic_plugin_assets["bundled"]["less"] ) less_plugins = all_assets_for_plugins(dynamic_plugin_assets["external"]["less"]) if len(less_core) == 0: less_core_bundle = Bundle(*[]) else: less_core_bundle = Bundle( *less_core, output="webassets/packed_core.less", filters=",".join(less_filters), ) if len(less_plugins) == 0: less_plugins_bundle = Bundle(*[]) else: less_plugins_bundle = Bundle( *less_plugins, output="webassets/packed_plugins.less", filters=",".join(less_filters), ) less_app_bundle = Bundle( less_core, less_plugins, output="webassets/packed_app.less", filters=",".join(less_filters), ) # -- asset registration ---------------------------------------------------------------------------------------- assets.register("js_libs", js_libs_bundle) assets.register("js_client_core", js_client_core_bundle) for plugin, bundle in clientjs_plugins.items(): # register our collected clientjs plugin bundles so that they are bound to the environment assets.register(f"js_client_plugin_{plugin}", bundle) assets.register("js_client_plugins", js_client_plugins_bundle) assets.register("js_client", js_client_bundle) assets.register("js_core", js_core_bundle) for plugin, bundle in js_plugins.items(): # register our collected plugin bundles so that they are bound to the environment assets.register(f"js_plugin_{plugin}", bundle) assets.register("js_plugins", js_plugins_bundle) assets.register("js_app", js_app_bundle) assets.register("css_libs", css_libs_bundle) assets.register("css_core", css_core_bundle) assets.register("css_plugins", css_plugins_bundle) assets.register("css_app", css_app_bundle) assets.register("less_core", less_core_bundle) assets.register("less_plugins", less_plugins_bundle) assets.register("less_app", less_app_bundle) def _setup_login_manager(self): global loginManager loginManager = LoginManager() # "strong" is incompatible to remember me, see maxcountryman/flask-login#156. It also causes issues with # clients toggling between IPv4 and IPv6 client addresses due to names being resolved one way or the other as # at least observed on a Win10 client targeting "localhost", resolved as both "127.0.0.1" and "::1" loginManager.session_protection = "basic" loginManager.user_loader(load_user) loginManager.unauthorized_handler(unauthorized_user) loginManager.anonymous_user = userManager.anonymous_user_factory loginManager.request_loader(load_user_from_request) loginManager.init_app(app, add_context_processor=False) def _start_intermediary_server(self): import socket import threading from http.server import BaseHTTPRequestHandler, HTTPServer host = self._host port = self._port class IntermediaryServerHandler(BaseHTTPRequestHandler): def __init__(self, rules=None, *args, **kwargs): if rules is None: rules = [] self.rules = rules BaseHTTPRequestHandler.__init__(self, *args, **kwargs) def do_GET(self): request_path = self.path if "?" in request_path: request_path = request_path[0 : request_path.find("?")] for rule in self.rules: path, data, content_type = rule if request_path == path: self.send_response(200) if content_type: self.send_header("Content-Type", content_type) self.end_headers() if isinstance(data, str): data = data.encode("utf-8") self.wfile.write(data) break else: self.send_response(404) self.wfile.write(b"Not found") base_path = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "static") ) rules = [ ( "/", [ "intermediary.html", ], "text/html", ), ("/favicon.ico", ["img", "tentacle-20x20.png"], "image/png"), ( "/intermediary.gif", bytes( base64.b64decode( "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" ) ), "image/gif", ), ] def contents(args): path = os.path.join(base_path, *args) if not os.path.isfile(path): return "" with open(path, "rb") as f: data = f.read() return data def process(rule): if len(rule) == 2: path, data = rule content_type = None else: path, data, content_type = rule if isinstance(data, (list, tuple)): data = contents(data) return path, data, content_type rules = list( map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules)) ) HTTPServerV4 = HTTPServer class HTTPServerV6(HTTPServer): address_family = socket.AF_INET6 class HTTPServerV6SingleStack(HTTPServerV6): def __init__(self, *args, **kwargs): HTTPServerV6.__init__(self, *args, **kwargs) # explicitly set V6ONLY flag - seems to be the default, but just to make sure... self.socket.setsockopt( octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 1 ) class HTTPServerV6DualStack(HTTPServerV6): def __init__(self, *args, **kwargs): HTTPServerV6.__init__(self, *args, **kwargs) # explicitly unset V6ONLY flag self.socket.setsockopt( octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0 ) if ":" in host: # v6 if host == "::" and not self._v6_only: ServerClass = HTTPServerV6DualStack else: ServerClass = HTTPServerV6SingleStack else: # v4 ServerClass = HTTPServerV4 if host == "::": if self._v6_only: self._logger.debug(f"Starting intermediary server on http://[::]:{port}") else: self._logger.debug( "Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}".format( port=port ) ) else: self._logger.debug( "Starting intermediary server on http://{}:{}".format( host if ":" not in host else "[" + host + "]", port ) ) self._intermediary_server = ServerClass( (host, port), lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs), bind_and_activate=False, ) # if possible, make sure our socket's port descriptor isn't handed over to subprocesses from octoprint.util.platform import set_close_exec try: set_close_exec(self._intermediary_server.fileno()) except Exception: self._logger.exception( "Error while attempting to set_close_exec on intermediary server socket" ) # then bind the server and have it serve our handler until stopped try: self._intermediary_server.server_bind() self._intermediary_server.server_activate() except Exception as exc: self._intermediary_server.server_close() if isinstance(exc, UnicodeDecodeError) and sys.platform == "win32": # we end up here if the hostname contains non-ASCII characters due to # https://bugs.python.org/issue26227 - tell the user they need # to either change their hostname or read up other options in # https://github.com/OctoPrint/OctoPrint/issues/3963 raise CannotStartServerException( "OctoPrint cannot start due to a Python bug " "(https://bugs.python.org/issue26227). Your " "computer's host name contains non-ASCII characters. " "Please either change your computer's host name to " "contain only ASCII characters, or take a look at " "https://github.com/OctoPrint/OctoPrint/issues/3963 for " "other options." ) else: raise def serve(): try: self._intermediary_server.serve_forever() except Exception: self._logger.exception("Error in intermediary server") thread = threading.Thread(target=serve) thread.daemon = True thread.start() self._logger.info("Intermediary server started") def _stop_intermediary_server(self): if self._intermediary_server is None: return self._logger.info("Shutting down intermediary server...") self._intermediary_server.shutdown() self._intermediary_server.server_close() self._logger.info("Intermediary server shut down") def _setup_plugin_permissions(self): global pluginManager from octoprint.access.permissions import PluginOctoPrintPermission key_whitelist = re.compile(r"[A-Za-z0-9_]*") def permission_key(plugin, definition): return "PLUGIN_{}_{}".format(plugin.upper(), definition["key"].upper()) def permission_name(plugin, definition): return "{}: {}".format(plugin, definition["name"]) def permission_role(plugin, role): return f"plugin_{plugin}_{role}" def process_regular_permission(plugin_info, definition): permissions = [] for key in definition.get("permissions", []): permission = octoprint.access.permissions.Permissions.find(key) if permission is None: # if there is still no permission found, postpone this - maybe it is a permission from # another plugin that hasn't been loaded yet return False permissions.append(permission) roles = definition.get("roles", []) description = definition.get("description", "") dangerous = definition.get("dangerous", False) default_groups = definition.get("default_groups", []) roles_and_permissions = [ permission_role(plugin_info.key, role) for role in roles ] + permissions key = permission_key(plugin_info.key, definition) permission = PluginOctoPrintPermission( permission_name(plugin_info.name, definition), description, *roles_and_permissions, plugin=plugin_info.key, dangerous=dangerous, default_groups=default_groups, ) setattr( octoprint.access.permissions.Permissions, key, PluginOctoPrintPermission( permission_name(plugin_info.name, definition), description, *roles_and_permissions, plugin=plugin_info.key, dangerous=dangerous, default_groups=default_groups, ), ) self._logger.info( "Added new permission from plugin {}: {} (needs: {!r})".format( plugin_info.key, key, ", ".join(map(repr, permission.needs)) ) ) return True postponed = [] hooks = pluginManager.get_hooks("octoprint.access.permissions") for name, factory in hooks.items(): try: if isinstance(factory, (tuple, list)): additional_permissions = list(factory) elif callable(factory): additional_permissions = factory() else: raise ValueError("factory must be either a callable, tuple or list") if not isinstance(additional_permissions, (tuple, list)): raise ValueError( "factory result must be either a tuple or a list of permission definition dicts" ) plugin_info = pluginManager.get_plugin_info(name) for p in additional_permissions: if not isinstance(p, dict): continue if "key" not in p or "name" not in p: continue if not key_whitelist.match(p["key"]): self._logger.warning( "Got permission with invalid key from plugin {}: {}".format( name, p["key"] ) ) continue if not process_regular_permission(plugin_info, p): postponed.append((plugin_info, p)) except Exception: self._logger.exception( f"Error while creating permission instance/s from {name}" ) # final resolution passes pass_number = 1 still_postponed = [] while len(postponed): start_length = len(postponed) self._logger.debug( "Plugin permission resolution pass #{}, " "{} unresolved permissions...".format(pass_number, start_length) ) for plugin_info, definition in postponed: if not process_regular_permission(plugin_info, definition): still_postponed.append((plugin_info, definition)) self._logger.debug( "... pass #{} done, {} permissions left to resolve".format( pass_number, len(still_postponed) ) ) if len(still_postponed) == start_length: # no change, looks like some stuff is unresolvable - let's bail for plugin_info, definition in still_postponed: self._logger.warning( "Unable to resolve permission from {}: {!r}".format( plugin_info.key, definition ) ) break postponed = still_postponed still_postponed = [] pass_number += 1 class LifecycleManager: def __init__(self, plugin_manager): self._plugin_manager = plugin_manager self._plugin_lifecycle_callbacks = defaultdict(list) self._logger = logging.getLogger(__name__) def wrap_plugin_event(lifecycle_event, new_handler): orig_handler = getattr(self._plugin_manager, "on_plugin_" + lifecycle_event) def handler(*args, **kwargs): if callable(orig_handler): orig_handler(*args, **kwargs) if callable(new_handler): new_handler(*args, **kwargs) return handler def on_plugin_event_factory(lifecycle_event): def on_plugin_event(name, plugin): self.on_plugin_event(lifecycle_event, name, plugin) return on_plugin_event for event in ("loaded", "unloaded", "enabled", "disabled"): wrap_plugin_event(event, on_plugin_event_factory(event)) def on_plugin_event(self, event, name, plugin): for lifecycle_callback in self._plugin_lifecycle_callbacks[event]: lifecycle_callback(name, plugin) def add_callback(self, events, callback): if isinstance(events, str): events = [events] for event in events: self._plugin_lifecycle_callbacks[event].append(callback) def remove_callback(self, callback, events=None): if events is None: for event in self._plugin_lifecycle_callbacks: if callback in self._plugin_lifecycle_callbacks[event]: self._plugin_lifecycle_callbacks[event].remove(callback) else: if isinstance(events, str): events = [events] for event in events: if callback in self._plugin_lifecycle_callbacks[event]: self._plugin_lifecycle_callbacks[event].remove(callback) class CannotStartServerException(Exception): pass
109,758
Python
.py
2,460
30.669919
173
0.554182
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,877
views.py
OctoPrint_OctoPrint/src/octoprint/server/views.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import base64 import datetime import logging import os import re from collections import defaultdict from flask import ( Response, abort, g, make_response, redirect, render_template, request, send_from_directory, url_for, ) from werkzeug.routing import BuildError import octoprint.plugin from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.filemanager import full_extension_tree, get_all_extensions from octoprint.server import ( # noqa: F401 BRANCH, DISPLAY_VERSION, LOCALES, NOT_MODIFIED, VERSION, app, debug, gettext, groupManager, pluginManager, preemptiveCache, userManager, ) from octoprint.server.util import ( has_permissions, require_fresh_login_with, require_login_with, validate_local_redirect, ) from octoprint.server.util.csrf import add_csrf_cookie from octoprint.server.util.flask import credentials_checked_recently from octoprint.settings import settings from octoprint.util import sv, to_bytes, to_unicode from octoprint.util.version import get_python_version_string from . import util _logger = logging.getLogger(__name__) _templates = {} _plugin_names = None _plugin_vars = None _valid_id_re = re.compile("[a-z_]+") _valid_div_re = re.compile("[a-zA-Z_-]+") def _preemptive_unless(base_url=None, additional_unless=None): if base_url is None: base_url = request.url_root disabled_for_root = ( not settings().getBoolean(["devel", "cache", "preemptive"]) or base_url in settings().get(["server", "preemptiveCache", "exceptions"]) or not (base_url.startswith("http://") or base_url.startswith("https://")) ) recording_disabled = request.headers.get("X-Preemptive-Recording", "no") == "yes" if callable(additional_unless): return recording_disabled or disabled_for_root or additional_unless() else: return recording_disabled or disabled_for_root def _preemptive_data( key, path=None, base_url=None, data=None, additional_request_data=None ): if path is None: path = request.path if base_url is None: base_url = request.url_root d = { "path": path, "base_url": base_url, "query_string": f"l10n={_locale_str(g.locale)}", } if key != "_default": d["plugin"] = key # add data if we have any if data is not None: try: if callable(data): data = data() if data: if "query_string" in data: data["query_string"] = "l10n={}&{}".format( _locale_str(g.locale), data["query_string"] ) d.update(data) except Exception: _logger.exception( f"Error collecting data for preemptive cache from plugin {key}" ) # add additional request data if we have any if callable(additional_request_data): try: ard = additional_request_data() if ard: d.update({"_additional_request_data": ard}) except Exception: _logger.exception( "Error retrieving additional data for preemptive cache from plugin {}".format( key ) ) return d def _cache_key(ui, url=None, locale=None, additional_key_data=None): if url is None: url = request.base_url if locale is None: locale = _locale_str(g.locale) k = f"ui:{ui}:{url}:{locale}" if callable(additional_key_data): try: ak = additional_key_data() if ak: # we have some additional key components, let's attach them if not isinstance(ak, (list, tuple)): ak = [ak] k = "{}:{}".format(k, ":".join(ak)) except Exception: _logger.exception( "Error while trying to retrieve additional cache key parts for ui {}".format( ui ) ) return k def _valid_status_for_cache(status_code): return 200 <= status_code < 400 def _add_additional_assets(hook_name): result = [] for name, hook in pluginManager.get_hooks(hook_name).items(): try: assets = hook() if isinstance(assets, (tuple, list)): result += assets except Exception: _logger.exception( f"Error fetching theming CSS to include from plugin {name}", extra={"plugin": name}, ) return result def _locale_str(locale): return str(locale) if locale else "en" @app.route("/login") @app.route("/login/") def login(): from flask_login import current_user default_redirect_url = url_for("index") redirect_url = request.args.get("redirect", default_redirect_url) configured_allowed_paths = settings().get(["server", "allowedLoginRedirectPaths"]) if configured_allowed_paths is None or not isinstance(configured_allowed_paths, list): configured_allowed_paths = [] configured_allowed_paths = list( filter( lambda x: isinstance(x, str), configured_allowed_paths, ) ) allowed_paths = [ url_for("index"), url_for("recovery"), url_for("reverse_proxy_test"), ] try: allowed_paths += [ url_for("plugin.appkeys.handle_auth_dialog", app_token="*"), ] except BuildError: pass # no appkeys plugin enabled, see #4763 allowed_paths += configured_allowed_paths if not validate_local_redirect(redirect_url, allowed_paths): _logger.warning( f"Got an invalid redirect URL with the login attempt, misconfiguration or attack attempt: {redirect_url}" ) redirect_url = default_redirect_url permissions = sorted( filter( lambda x: x is not None and isinstance(x, OctoPrintPermission), map( lambda x: getattr(Permissions, x.strip()), request.args.get("permissions", "").split(","), ), ), key=lambda x: x.get_name(), ) if not permissions: permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] user_id = request.args.get("user_id", "") reauthenticate = request.args.get("reauthenticate", "false").lower() == "true" if ( (not user_id or current_user.get_id() == user_id) and has_permissions(*permissions) and (not reauthenticate or credentials_checked_recently()) ): return redirect(redirect_url) render_kwargs = { "theming": [], "redirect_url": redirect_url, "permission_names": map(lambda x: x.get_name(), permissions), "user_id": user_id, "logged_in": not current_user.is_anonymous, "reauthenticate": reauthenticate, } try: additional_assets = _add_additional_assets("octoprint.theming.login") # backwards compatibility to forcelogin & loginui plugins which were replaced by this built-in dialog additional_assets += _add_additional_assets("octoprint.plugin.forcelogin.theming") additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming") render_kwargs.update({"theming": additional_assets}) except Exception: _logger.exception("Error processing theming CSS, ignoring") resp = make_response(render_template("login.jinja2", **render_kwargs)) return add_csrf_cookie(resp) @app.route("/recovery") @app.route("/recovery/") def recovery(): response = require_fresh_login_with(permissions=[Permissions.ADMIN]) if response: return response reauthentication_timeout = settings().getInt( ["accessControl", "defaultReauthenticationTimeout"] ) render_kwargs = {"theming": [], "reauthenticationTimeout": reauthentication_timeout} try: additional_assets = _add_additional_assets("octoprint.theming.recovery") render_kwargs.update({"theming": additional_assets}) except Exception: _logger.exception("Error processing theming CSS, ignoring") try: from octoprint.plugins.backup import MAX_UPLOAD_SIZE from octoprint.util import get_formatted_size render_kwargs.update( { "plugin_backup_max_upload_size": MAX_UPLOAD_SIZE, "plugin_backup_max_upload_size_str": get_formatted_size(MAX_UPLOAD_SIZE), } ) except Exception: _logger.exception("Error adding backup upload size info, ignoring") resp = make_response(render_template("recovery.jinja2", **render_kwargs)) return add_csrf_cookie(resp) @app.route("/cached.gif") def in_cache(): url = request.base_url.replace("/cached.gif", "/") path = request.path.replace("/cached.gif", "/") base_url = request.url_root # select view from plugins and fall back on default view if no plugin will handle it ui_plugins = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for plugin in ui_plugins: try: if plugin.will_handle_ui(request): ui = plugin._identifier key = _cache_key( plugin._identifier, url=url, additional_key_data=plugin.get_ui_additional_key_data_for_cache, ) unless = _preemptive_unless( url, additional_unless=plugin.get_ui_preemptive_caching_additional_unless, ) data = _preemptive_data( plugin._identifier, path=path, base_url=base_url, data=plugin.get_ui_data_for_preemptive_caching, additional_request_data=plugin.get_ui_additional_request_data_for_preemptive_caching, ) break except Exception: _logger.exception( f"Error while calling plugin {plugin._identifier}, skipping it", extra={"plugin": plugin._identifier}, ) else: ui = "_default" key = _cache_key("_default", url=url) unless = _preemptive_unless(url) data = _preemptive_data("_default", path=path, base_url=base_url) response = make_response( bytes( base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7") ) ) response.headers["Content-Type"] = "image/gif" if unless or not preemptiveCache.has_record(data, root=path): _logger.info( "Preemptive cache not active for path {}, ui {} and data {!r}, signaling as cached".format( path, ui, data ) ) return response elif util.flask.is_in_cache(key): _logger.info(f"Found path {path} in cache (key: {key}), signaling as cached") return response elif util.flask.is_cache_bypassed(key): _logger.info( "Path {} was bypassed from cache (key: {}), signaling as cached".format( path, key ) ) return response else: _logger.debug(f"Path {path} not yet cached (key: {key}), signaling as missing") return abort(404) @app.route("/reverse_proxy_test") @app.route("/reverse_proxy_test/") def reverse_proxy_test(): from octoprint.server.util.flask import get_reverse_proxy_info authenticated = request.args.get("authenticated", False) is not False if authenticated: response = require_fresh_login_with(permissions=[Permissions.ADMIN]) if response: return response kwargs = get_reverse_proxy_info().dict() try: return render_template( "reverse_proxy_test.jinja2", authenticated=authenticated, theming=[], **kwargs, ) except Exception: _logger.exception("Error rendering reverse proxy test page") return abort(500) @app.route("/") def index(): from octoprint.server import connectivityChecker, printer global _templates, _plugin_names, _plugin_vars preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"]) locale = _locale_str(g.locale) # helper to check if wizards are active def wizard_active(templates): return templates is not None and bool(templates["wizard"]["order"]) # we force a refresh if the client forces one and we are not printing or if we have wizards cached client_refresh = util.flask.cache_check_headers() request_refresh = "_refresh" in request.values printing = printer.is_printing() if client_refresh and printing: logging.getLogger(__name__).warning( "Client requested cache refresh via cache-control headers but we are printing. " "Not invalidating caches due to resource limitation. Append ?_refresh=true to " "the URL if you absolutely require a refresh now" ) client_refresh = client_refresh and not printing force_refresh = ( client_refresh or request_refresh or wizard_active(_templates.get(locale)) ) # if we need to refresh our template cache or it's not yet set, process it fetch_template_data(refresh=force_refresh) now = datetime.datetime.utcnow() enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"]) enable_loading_animation = settings().getBoolean(["devel", "showLoadingAnimation"]) enable_sd_support = settings().get(["feature", "sdSupport"]) enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"]) enable_temperature_graph = settings().get(["feature", "temperatureGraph"]) sockjs_connect_timeout = settings().getInt(["devel", "sockJsConnectTimeout"]) reauthentication_timeout = settings().getInt( ["accessControl", "defaultReauthenticationTimeout"] ) def default_template_filter(template_type, template_key): if template_type == "tab": return template_key != "timelapse" or enable_timelapse else: return True default_additional_etag = [ enable_timelapse, enable_loading_animation, enable_sd_support, enable_webcam, enable_temperature_graph, sockjs_connect_timeout, reauthentication_timeout, connectivityChecker.online, wizard_active(_templates.get(locale)), ] + sorted( "{}:{}".format(to_unicode(k, errors="replace"), to_unicode(v, errors="replace")) for k, v in _plugin_vars.items() ) def get_preemptively_cached_view( key, view, data=None, additional_request_data=None, additional_unless=None ): if (data is None and additional_request_data is None) or g.locale is None: return view d = _preemptive_data( key, data=data, additional_request_data=additional_request_data ) def unless(): return _preemptive_unless( base_url=request.url_root, additional_unless=additional_unless ) # finally decorate our view return util.flask.preemptively_cached( cache=preemptiveCache, data=d, unless=unless )(view) def get_cached_view( key, view, additional_key_data=None, additional_files=None, additional_etag=None, custom_files=None, custom_etag=None, custom_lastmodified=None, ): if additional_etag is None: additional_etag = [] def cache_key(): return _cache_key(key, additional_key_data=additional_key_data) def collect_files(): if callable(custom_files): try: files = custom_files() if files: return files except Exception: _logger.exception( "Error while trying to retrieve tracked files for plugin {}".format( key ) ) files = _get_all_templates() files += _get_all_assets() files += _get_all_translationfiles(_locale_str(g.locale), "messages") if callable(additional_files): try: af = additional_files() if af: files += af except Exception: _logger.exception( "Error while trying to retrieve additional tracked files for plugin {}".format( key ) ) return sorted(set(files)) def compute_lastmodified(files): if callable(custom_lastmodified): try: lastmodified = custom_lastmodified() if lastmodified: return lastmodified except Exception: _logger.exception( "Error while trying to retrieve custom LastModified value for plugin {}".format( key ) ) return _compute_date(files) def compute_etag(files, lastmodified, additional=None): if callable(custom_etag): try: etag = custom_etag() if etag: return etag except Exception: _logger.exception( "Error while trying to retrieve custom ETag value for plugin {}".format( key ) ) if lastmodified and not isinstance(lastmodified, str): from werkzeug.http import http_date lastmodified = http_date(lastmodified) if additional is None: additional = [] import hashlib hash = hashlib.sha1() def hash_update(value): hash.update(to_bytes(value, encoding="utf-8", errors="replace")) hash_update(octoprint.__version__) hash_update(get_python_version_string()) hash_update(",".join(sorted(files))) if lastmodified: hash_update(lastmodified) for add in additional: hash_update(add) return hash.hexdigest() current_files = collect_files() current_lastmodified = compute_lastmodified(current_files) current_etag = compute_etag( files=current_files, lastmodified=current_lastmodified, additional=[cache_key()] + additional_etag, ) def check_etag_and_lastmodified(): lastmodified_ok = util.flask.check_lastmodified(current_lastmodified) etag_ok = util.flask.check_etag(current_etag) return lastmodified_ok and etag_ok def validate_cache(cached): return force_refresh or (current_etag != cached.get_etag()[0]) decorated_view = view decorated_view = util.flask.lastmodified(lambda _: current_lastmodified)( decorated_view ) decorated_view = util.flask.etagged(lambda _: current_etag)(decorated_view) decorated_view = util.flask.cached( timeout=-1, refreshif=validate_cache, key=cache_key, unless_response=lambda response: util.flask.cache_check_response_headers( response ) or util.flask.cache_check_status_code(response, _valid_status_for_cache), )(decorated_view) decorated_view = util.flask.with_client_revalidation(decorated_view) decorated_view = util.flask.conditional( check_etag_and_lastmodified, NOT_MODIFIED )(decorated_view) return decorated_view def plugin_view(p): cached = get_cached_view( p._identifier, p.on_ui_render, additional_key_data=p.get_ui_additional_key_data_for_cache, additional_files=p.get_ui_additional_tracked_files, custom_files=p.get_ui_custom_tracked_files, custom_etag=p.get_ui_custom_etag, custom_lastmodified=p.get_ui_custom_lastmodified, additional_etag=p.get_ui_additional_etag(default_additional_etag), ) if preemptive_cache_enabled and p.get_ui_preemptive_caching_enabled(): view = get_preemptively_cached_view( p._identifier, cached, p.get_ui_data_for_preemptive_caching, p.get_ui_additional_request_data_for_preemptive_caching, p.get_ui_preemptive_caching_additional_unless, ) else: view = cached template_filter = p.get_ui_custom_template_filter(default_template_filter) if template_filter is not None and callable(template_filter): filtered_templates = _filter_templates(_templates[locale], template_filter) else: filtered_templates = _templates[locale] render_kwargs = _get_render_kwargs( filtered_templates, _plugin_names, _plugin_vars, now ) return view(now, request, render_kwargs) def default_view(): filtered_templates = _filter_templates( _templates[locale], default_template_filter ) wizard = wizard_active(filtered_templates) accesscontrol_active = userManager.has_been_customized() render_kwargs = _get_render_kwargs( filtered_templates, _plugin_names, _plugin_vars, now ) render_kwargs.update( { "enableWebcam": enable_webcam, "enableTemperatureGraph": enable_temperature_graph, "enableAccessControl": True, "accessControlActive": accesscontrol_active, "enableLoadingAnimation": enable_loading_animation, "enableSdSupport": enable_sd_support, "sockJsConnectTimeout": sockjs_connect_timeout * 1000, "reauthenticationTimeout": reauthentication_timeout, "wizard": wizard, "online": connectivityChecker.online, "now": now, } ) # no plugin took an interest, we'll use the default UI def make_default_ui(): r = make_response(render_template("index.jinja2", **render_kwargs)) if wizard: # if we have active wizard dialogs, set non caching headers r = util.flask.add_non_caching_response_headers(r) return r cached = get_cached_view( "_default", make_default_ui, additional_etag=default_additional_etag ) preemptively_cached = get_preemptively_cached_view("_default", cached, {}, {}) return preemptively_cached() default_permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] response = None forced_view = request.headers.get("X-Force-View", None) if forced_view: # we have view forced by the preemptive cache _logger.debug(f"Forcing rendering of view {forced_view}") if forced_view != "_default": plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True) if plugin is not None and isinstance( plugin.implementation, octoprint.plugin.UiPlugin ): permissions = plugin.implementation.get_ui_permissions() response = require_login_with(permissions=permissions) if not response: response = plugin_view(plugin.implementation) if _logger.isEnabledFor(logging.DEBUG) and isinstance( response, Response ): response.headers[ "X-Ui-Plugin" ] = plugin.implementation._identifier else: response = require_login_with(permissions=default_permissions) if not response: response = default_view() if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): response.headers["X-Ui-Plugin"] = "_default" else: # select view from plugins and fall back on default view if no plugin will handle it ui_plugins = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for plugin in ui_plugins: try: if plugin.will_handle_ui(request): # plugin claims responsibility, let it render the UI permissions = plugin.get_ui_permissions() response = require_login_with(permissions=permissions) if not response: response = plugin_view(plugin) if response is not None: if _logger.isEnabledFor(logging.DEBUG) and isinstance( response, Response ): response.headers["X-Ui-Plugin"] = plugin._identifier break else: _logger.warning( "UiPlugin {} returned an empty response".format( plugin._identifier ) ) except Exception: _logger.exception( "Error while calling plugin {}, skipping it".format( plugin._identifier ), extra={"plugin": plugin._identifier}, ) else: response = require_login_with(permissions=default_permissions) if not response: response = default_view() if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): response.headers["X-Ui-Plugin"] = "_default" if response is None: return abort(404) return add_csrf_cookie(response) def _get_render_kwargs(templates, plugin_names, plugin_vars, now): global _logger # ~~ a bunch of settings first_run = settings().getBoolean(["server", "firstRun"]) locales = {} for loc in LOCALES: try: key = _locale_str(loc) locales[key] = { "language": key, "display": loc.display_name, "english": loc.english_name, } except Exception: _logger.exception("Error while collecting available locales") permissions = [permission.as_dict() for permission in Permissions.all()] filetypes = list(sorted(full_extension_tree().keys())) extensions = list(map(lambda ext: f".{ext}", get_all_extensions())) # ~~ prepare full set of template vars for rendering render_kwargs = { "debug": debug, "firstRun": first_run, "version": {"number": VERSION, "display": DISPLAY_VERSION, "branch": BRANCH}, "python_version": get_python_version_string(), "templates": templates, "pluginNames": plugin_names, "locales": locales, "permissions": permissions, "supportedFiletypes": filetypes, "supportedExtensions": extensions, } render_kwargs.update(plugin_vars) return render_kwargs def fetch_template_data(refresh=False): global _templates, _plugin_names, _plugin_vars locale = _locale_str(g.locale) if ( not refresh and _templates.get(locale) is not None and _plugin_names is not None and _plugin_vars is not None ): return _templates[locale], _plugin_names, _plugin_vars first_run = settings().getBoolean(["server", "firstRun"]) ##~~ prepare templates templates = defaultdict(lambda: {"order": [], "entries": {}}) # rules for transforming template configs to template entries template_rules = { "navbar": { "div": lambda x: "navbar_plugin_" + x, "template": lambda x: x + "_navbar.jinja2", "to_entry": lambda data: data, }, "sidebar": { "div": lambda x: "sidebar_plugin_" + x, "template": lambda x: x + "_sidebar.jinja2", "to_entry": lambda data: (data["name"], data), }, "tab": { "div": lambda x: "tab_plugin_" + x, "template": lambda x: x + "_tab.jinja2", "to_entry": lambda data: (data["name"], data), }, "settings": { "div": lambda x: "settings_plugin_" + x, "template": lambda x: x + "_settings.jinja2", "to_entry": lambda data: (data["name"], data), }, "usersettings": { "div": lambda x: "usersettings_plugin_" + x, "template": lambda x: x + "_usersettings.jinja2", "to_entry": lambda data: (data["name"], data), }, "wizard": { "div": lambda x: "wizard_plugin_" + x, "template": lambda x: x + "_wizard.jinja2", "to_entry": lambda data: (data["name"], data), }, "webcam": { "div": lambda x: "webcam_plugin_" + x, "template": lambda x: x + "_webcam.jinja2", "to_entry": lambda data: (data["name"], data), }, "about": { "div": lambda x: "about_plugin_" + x, "template": lambda x: x + "_about.jinja2", "to_entry": lambda data: (data["name"], data), }, "generic": {"template": lambda x: x + ".jinja2", "to_entry": lambda data: data}, } # sorting orders def wizard_key_extractor(d, k): if d[1].get("_key", None) == "plugin_corewizard_acl": # Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and # that require to access APIs to function will run into errors since those APIs won't work before ACL # has been configured. See also #2140 return f"0:{to_unicode(d[0])}" elif d[1].get("mandatory", False): # Other mandatory steps come before the optional ones return f"1:{to_unicode(d[0])}" else: # Finally everything else return f"2:{to_unicode(d[0])}" template_sorting = { "navbar": {"add": "prepend", "key": None}, "sidebar": {"add": "append", "key": "name"}, "tab": {"add": "append", "key": "name"}, "settings": { "add": "custom_append", "key": "name", "custom_add_entries": lambda missing: { "section_plugins": (gettext("Plugins"), None) }, "custom_add_order": lambda missing: ["section_plugins"] + missing, }, "usersettings": {"add": "append", "key": "name"}, "wizard": {"add": "append", "key": "name", "key_extractor": wizard_key_extractor}, "webcam": {"add": "append", "key": "name"}, "about": {"add": "append", "key": "name"}, "generic": {"add": "append", "key": None}, } hooks = pluginManager.get_hooks("octoprint.ui.web.templatetypes") for name, hook in hooks.items(): try: result = hook(dict(template_sorting), dict(template_rules)) except Exception: _logger.exception( f"Error while retrieving custom template type " f"definitions from plugin {name}", extra={"plugin": name}, ) else: if not isinstance(result, list): continue for entry in result: if not isinstance(entry, tuple) or not len(entry) == 3: continue key, order, rule = entry # order defaults if "add" not in order: order["add"] = "prepend" if "key" not in order: order["key"] = "name" # rule defaults if "div" not in rule: # default div name: <hook plugin>_<template_key>_plugin_<plugin> div = f"{name}_{key}_plugin_" rule["div"] = lambda x: div + x if "template" not in rule: # default template name: <plugin>_plugin_<hook plugin>_<template key>.jinja2 template = f"_plugin_{name}_{key}.jinja2" rule["template"] = lambda x: x + template if "to_entry" not in rule: # default to_entry assumes existing "name" property to be used as label for 2-tuple entry data structure (<name>, <properties>) rule["to_entry"] = lambda data: (data["name"], data) template_rules["plugin_" + name + "_" + key] = rule template_sorting["plugin_" + name + "_" + key] = order template_types = list(template_rules.keys()) # navbar templates["navbar"]["entries"] = { "offlineindicator": { "template": "navbar/offlineindicator.jinja2", "_div": "navbar_offlineindicator", "custom_bindings": False, }, "settings": { "template": "navbar/settings.jinja2", "_div": "navbar_settings", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SETTINGS)", }, "systemmenu": { "template": "navbar/systemmenu.jinja2", "_div": "navbar_systemmenu", "classes": ["dropdown"], "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", "custom_bindings": False, }, "login": { "template": "navbar/login.jinja2", "_div": "navbar_login", "classes": ["dropdown"], "custom_bindings": False, }, } # sidebar templates["sidebar"]["entries"] = { "connection": ( gettext("Connection"), { "template": "sidebar/connection.jinja2", "_div": "connection", "icon": "signal", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.CONNECTION)", "template_header": "sidebar/connection_header.jinja2", }, ), "state": ( gettext("State"), { "template": "sidebar/state.jinja2", "_div": "state", "icon": "info-circle", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.STATUS)", }, ), "files": ( gettext("Files"), { "template": "sidebar/files.jinja2", "_div": "files", "icon": "list", "classes_content": ["overflow_visible"], "template_header": "sidebar/files_header.jinja2", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.FILES_LIST)", }, ), } # tabs templates["tab"]["entries"] = { "temperature": ( gettext("Temperature"), { "template": "tabs/temperature.jinja2", "_div": "temp", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)() && visible()", }, ), "control": ( gettext("Control"), { "template": "tabs/control.jinja2", "_div": "control", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.WEBCAM, access.permissions.CONTROL)", }, ), "terminal": ( gettext("Terminal"), { "template": "tabs/terminal.jinja2", "_div": "term", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.MONITOR_TERMINAL)", }, ), "timelapse": ( gettext("Timelapse"), { "template": "tabs/timelapse.jinja2", "_div": "timelapse", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.TIMELAPSE_LIST)", }, ), } # settings dialog templates["settings"]["entries"] = { "section_printer": (gettext("Printer"), None), "serial": ( gettext("Serial Connection"), { "template": "dialogs/settings/serialconnection.jinja2", "_div": "settings_serialConnection", "custom_bindings": False, }, ), "printerprofiles": ( gettext("Printer Profiles"), { "template": "dialogs/settings/printerprofiles.jinja2", "_div": "settings_printerProfiles", "custom_bindings": False, }, ), "temperatures": ( gettext("Temperatures"), { "template": "dialogs/settings/temperatures.jinja2", "_div": "settings_temperature", "custom_bindings": False, }, ), "terminalfilters": ( gettext("Terminal Filters"), { "template": "dialogs/settings/terminalfilters.jinja2", "_div": "settings_terminalFilters", "custom_bindings": False, }, ), "gcodescripts": ( gettext("GCODE Scripts"), { "template": "dialogs/settings/gcodescripts.jinja2", "_div": "settings_gcodeScripts", "custom_bindings": False, }, ), "section_features": (gettext("Features"), None), "features": ( gettext("Features"), { "template": "dialogs/settings/features.jinja2", "_div": "settings_features", "custom_bindings": False, }, ), "webcam": ( gettext("Webcam & Timelapse"), { "template": "dialogs/settings/webcam.jinja2", "_div": "settings_webcam", "custom_bindings": False, }, ), "api": ( gettext("API"), { "template": "dialogs/settings/api.jinja2", "_div": "settings_api", "custom_bindings": False, }, ), "section_octoprint": (gettext("OctoPrint"), None), "accesscontrol": ( gettext("Access Control"), { "template": "dialogs/settings/accesscontrol.jinja2", "_div": "settings_users", "custom_bindings": False, }, ), "folders": ( gettext("Folders"), { "template": "dialogs/settings/folders.jinja2", "_div": "settings_folders", "custom_bindings": False, }, ), "appearance": ( gettext("Appearance"), { "template": "dialogs/settings/appearance.jinja2", "_div": "settings_appearance", "custom_bindings": False, }, ), "server": ( gettext("Server"), { "template": "dialogs/settings/server.jinja2", "_div": "settings_server", "custom_bindings": False, }, ), } # user settings dialog templates["usersettings"]["entries"] = { "access": ( gettext("Access"), { "template": "dialogs/usersettings/access.jinja2", "_div": "usersettings_access", "custom_bindings": False, }, ), "interface": ( gettext("Interface"), { "template": "dialogs/usersettings/interface.jinja2", "_div": "usersettings_interface", "custom_bindings": False, }, ), } # wizard if first_run: def custom_insert_order(existing, missing): if "firstrunstart" in missing: missing.remove("firstrunstart") if "firstrunend" in missing: missing.remove("firstrunend") return ["firstrunstart"] + existing + missing + ["firstrunend"] template_sorting["wizard"].update( { "add": "custom_insert", "custom_insert_entries": lambda missing: {}, "custom_insert_order": custom_insert_order, } ) templates["wizard"]["entries"] = { "firstrunstart": ( gettext("Start"), { "template": "dialogs/wizard/firstrun_start.jinja2", "_div": "wizard_firstrun_start", }, ), "firstrunend": ( gettext("Finish"), { "template": "dialogs/wizard/firstrun_end.jinja2", "_div": "wizard_firstrun_end", }, ), } # about dialog templates["about"]["entries"] = { "about": ( "About OctoPrint", { "template": "dialogs/about/about.jinja2", "_div": "about_about", "custom_bindings": False, }, ), "license": ( "OctoPrint License", { "template": "dialogs/about/license.jinja2", "_div": "about_license", "custom_bindings": False, }, ), "thirdparty": ( "Third Party Licenses", { "template": "dialogs/about/thirdparty.jinja2", "_div": "about_thirdparty", "custom_bindings": False, }, ), "authors": ( "Authors", { "template": "dialogs/about/authors.jinja2", "_div": "about_authors", "custom_bindings": False, }, ), "supporters": ( "Supporters", { "template": "dialogs/about/supporters.jinja2", "_div": "about_sponsors", "custom_bindings": False, }, ), "systeminfo": ( "System Information", { "template": "dialogs/about/systeminfo.jinja2", "_div": "about_systeminfo", "custom_bindings": False, "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", }, ), } # extract data from template plugins template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin) plugin_vars = {} plugin_names = set() plugin_aliases = {} seen_wizards = settings().get(["server", "seenWizards"]) if not first_run else {} for implementation in template_plugins: name = implementation._identifier plugin_names.add(name) wizard_required = False wizard_ignored = False try: vars = implementation.get_template_vars() configs = implementation.get_template_configs() if isinstance(implementation, octoprint.plugin.WizardPlugin): wizard_required = implementation.is_wizard_required() wizard_ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored( seen_wizards, implementation ) except Exception: _logger.exception( "Error while retrieving template data for plugin {}, ignoring it".format( name ), extra={"plugin": name}, ) continue if not isinstance(vars, dict): vars = {} if not isinstance(configs, (list, tuple)): configs = [] for var_name, var_value in vars.items(): plugin_vars["plugin_" + name + "_" + var_name] = var_value try: includes = _process_template_configs( name, implementation, configs, template_rules ) except Exception: _logger.exception( "Error while processing template configs for plugin {}, ignoring it".format( name ), extra={"plugin": name}, ) if not wizard_required or wizard_ignored: includes["wizard"] = list() for t in template_types: plugin_aliases[t] = {} for include in includes[t]: if t == "navbar" or t == "generic": data = include else: data = include[1] key = data["_key"] if "replaces" in data: key = data["replaces"] plugin_aliases[t][data["_key"]] = data["replaces"] templates[t]["entries"][key] = include # ~~ order internal templates and plugins # make sure that # 1) we only have keys in our ordered list that we have entries for and # 2) we have all entries located somewhere within the order for t in template_types: default_order = ( settings().get( ["appearance", "components", "order", t], merged=True, config={} ) or [] ) configured_order = ( settings().get(["appearance", "components", "order", t], merged=True) or [] ) configured_disabled = ( settings().get(["appearance", "components", "disabled", t]) or [] ) # first create the ordered list of all component ids according to the configured order result = [] for x in configured_order: if x in plugin_aliases[t]: x = plugin_aliases[t][x] if ( x in templates[t]["entries"] and x not in configured_disabled and x not in result ): result.append(x) templates[t]["order"] = result # now append the entries from the default order that are not already in there templates[t]["order"] += [ x for x in default_order if x not in templates[t]["order"] and x in templates[t]["entries"] and x not in configured_disabled ] all_ordered = set(templates[t]["order"]) all_disabled = set(configured_disabled) # check if anything is missing, if not we are done here missing_in_order = ( set(templates[t]["entries"].keys()) .difference(all_ordered) .difference(all_disabled) ) if len(missing_in_order) == 0: continue # works with entries that are dicts and entries that are 2-tuples with the # entry data at index 1 def config_extractor(item, key, default_value=None): if isinstance(item, dict) and key in item: return item[key] if key in item else default_value elif ( isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1] ): return item[1][key] if key in item[1] else default_value return default_value # finally add anything that's not included in our order yet if template_sorting[t]["key"] is not None: # we'll use our config extractor as default key extractor extractor = config_extractor # if template type provides custom extractor, make sure its exceptions are handled if "key_extractor" in template_sorting[t] and callable( template_sorting[t]["key_extractor"] ): def create_safe_extractor(extractor): def f(x, k): try: return extractor(x, k) except Exception: _logger.exception( "Error while extracting sorting keys for template {}".format( t ) ) return None return f extractor = create_safe_extractor(template_sorting[t]["key_extractor"]) sort_key = template_sorting[t]["key"] def key_func(x): config = templates[t]["entries"][x] entry_order = config_extractor(config, "order", default_value=None) return ( entry_order is None, sv(entry_order), sv(extractor(config, sort_key)), ) sorted_missing = sorted(missing_in_order, key=key_func) else: def key_func(x): config = templates[t]["entries"][x] entry_order = config_extractor(config, "order", default_value=None) return entry_order is None, sv(entry_order) sorted_missing = sorted(missing_in_order, key=key_func) if template_sorting[t]["add"] == "prepend": templates[t]["order"] = sorted_missing + templates[t]["order"] elif template_sorting[t]["add"] == "append": templates[t]["order"] += sorted_missing elif ( template_sorting[t]["add"] == "custom_prepend" and "custom_add_entries" in template_sorting[t] and "custom_add_order" in template_sorting[t] ): templates[t]["entries"].update( template_sorting[t]["custom_add_entries"](sorted_missing) ) templates[t]["order"] = ( template_sorting[t]["custom_add_order"](sorted_missing) + templates[t]["order"] ) elif ( template_sorting[t]["add"] == "custom_append" and "custom_add_entries" in template_sorting[t] and "custom_add_order" in template_sorting[t] ): templates[t]["entries"].update( template_sorting[t]["custom_add_entries"](sorted_missing) ) templates[t]["order"] += template_sorting[t]["custom_add_order"]( sorted_missing ) elif ( template_sorting[t]["add"] == "custom_insert" and "custom_insert_entries" in template_sorting[t] and "custom_insert_order" in template_sorting[t] ): templates[t]["entries"].update( template_sorting[t]["custom_insert_entries"](sorted_missing) ) templates[t]["order"] = template_sorting[t]["custom_insert_order"]( templates[t]["order"], sorted_missing ) _templates[locale] = templates _plugin_names = plugin_names _plugin_vars = plugin_vars return templates, plugin_names, plugin_vars def _process_template_configs(name, implementation, configs, rules): from jinja2.exceptions import TemplateNotFound counters = defaultdict(lambda: 1) includes = defaultdict(list) for config in configs: if not isinstance(config, dict): continue if "type" not in config: continue template_type = config["type"] del config["type"] if template_type not in rules: continue rule = rules[template_type] data = _process_template_config( name, implementation, rule, config=config, counter=counters[template_type] ) if data is None: continue includes[template_type].append(rule["to_entry"](data)) counters[template_type] += 1 for template_type in rules: if len(includes[template_type]) == 0: # if no template of that type was added by the config, we'll try to use the default template name rule = rules[template_type] data = _process_template_config(name, implementation, rule) if data is not None: try: app.jinja_env.get_or_select_template(data["template"]) except TemplateNotFound: pass except Exception: _logger.exception( "Error in template {}, not going to include it".format( data["template"] ) ) else: includes[template_type].append(rule["to_entry"](data)) return includes def _process_template_config(name, implementation, rule, config=None, counter=1): if "mandatory" in rule: for mandatory in rule["mandatory"]: if mandatory not in config: return None if config is None: config = {} data = dict(config) if "suffix" not in data and counter > 1: data["suffix"] = "_%d" % counter if "div" in data: data["_div"] = data["div"] elif "div" in rule: data["_div"] = rule["div"](name) if "suffix" in data: data["_div"] = data["_div"] + data["suffix"] if not _valid_div_re.match(data["_div"]): _logger.warning( "Template config {} contains invalid div identifier {}, skipping it".format( name, data["_div"] ) ) return None if data.get("template"): data["template"] = implementation.template_folder_key + "/" + data["template"] else: data["template"] = ( implementation.template_folder_key + "/" + rule["template"](name) ) if data.get("template_header"): data["template_header"] = ( implementation.template_folder_key + "/" + data["template_header"] ) if "name" not in data: data["name"] = implementation._plugin_name if "custom_bindings" not in data or data["custom_bindings"]: data_bind = "allowBindings: true" if "data_bind" in data: data_bind = data_bind + ", " + data["data_bind"] data_bind = data_bind.replace('"', '\\"') data["data_bind"] = data_bind data["_key"] = "plugin_" + name if "suffix" in data: data["_key"] += data["suffix"] data["_plugin"] = name return data def _filter_templates(templates, template_filter): filtered_templates = {} for template_type, template_collection in templates.items(): filtered_entries = {} for template_key, template_entry in template_collection["entries"].items(): if template_filter(template_type, template_key): filtered_entries[template_key] = template_entry filtered_templates[template_type] = { "order": list( filter(lambda x: x in filtered_entries, template_collection["order"]) ), "entries": filtered_entries, } return filtered_templates @app.route("/robots.txt") def robotsTxt(): return send_from_directory(app.static_folder, "robots.txt") @app.route("/i18n/<string:locale>/<string:domain>.js") @util.flask.conditional(lambda: _check_etag_and_lastmodified_for_i18n(), NOT_MODIFIED) @util.flask.etagged( lambda _: _compute_etag_for_i18n( request.view_args["locale"], request.view_args["domain"] ) ) @util.flask.lastmodified( lambda _: _compute_date_for_i18n( request.view_args["locale"], request.view_args["domain"] ) ) def localeJs(locale, domain): messages = {} plural_expr = None if locale != "en": messages, plural_expr = _get_translations(locale, domain) catalog = { "messages": messages, "plural_expr": plural_expr, "locale": locale, "domain": domain, } from flask import Response return Response( render_template("i18n.js.jinja2", catalog=catalog), content_type="application/x-javascript; charset=utf-8", ) @app.route("/plugin_assets/<string:name>/<path:filename>") def plugin_assets(name, filename): return redirect(url_for("plugin." + name + ".static", filename=filename)) def _compute_etag_for_i18n(locale, domain, files=None, lastmodified=None): if files is None: files = _get_all_translationfiles(locale, domain) if lastmodified is None: lastmodified = _compute_date(files) if lastmodified and not isinstance(lastmodified, str): from werkzeug.http import http_date lastmodified = http_date(lastmodified) import hashlib hash = hashlib.sha1() def hash_update(value): hash.update(value.encode("utf-8")) hash_update(",".join(sorted(files))) if lastmodified: hash_update(lastmodified) return hash.hexdigest() def _compute_date_for_i18n(locale, domain): return _compute_date(_get_all_translationfiles(locale, domain)) def _compute_date(files): # Note, we do not expect everything in 'files' to exist. import stat from datetime import datetime from octoprint.util.tz import UTC_TZ max_timestamp = 0 for path in files: try: # try to stat file. If an exception is thrown, its because it does not exist. s = os.stat(path) if stat.S_ISREG(s.st_mode) and s.st_mtime > max_timestamp: # is a regular file and has a newer timestamp max_timestamp = s.st_mtime except Exception: # path does not exist. continue if max_timestamp: # we set the micros to 0 since microseconds are not speced for HTTP max_timestamp = ( datetime.fromtimestamp(max_timestamp) .replace(microsecond=0) .replace(tzinfo=UTC_TZ) ) return max_timestamp def _check_etag_and_lastmodified_for_i18n(): locale = request.view_args["locale"] domain = request.view_args["domain"] etag_ok = util.flask.check_etag( _compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]) ) lastmodified = _compute_date_for_i18n(locale, domain) lastmodified_ok = lastmodified is None or util.flask.check_lastmodified(lastmodified) return etag_ok and lastmodified_ok def _get_all_templates(): from octoprint.util.jinja import get_all_template_paths return get_all_template_paths(app.jinja_loader) def _get_all_assets(): from octoprint.util.jinja import get_all_asset_paths return get_all_asset_paths(app.jinja_env.assets_environment, verifyExist=False) def _get_all_translationfiles(locale, domain): from flask import current_app def get_po_path(basedir, locale, domain): return os.path.join(basedir, locale, "LC_MESSAGES", f"{domain}.po") po_files = [] user_base_path = os.path.join( settings().getBaseFolder("translations", check_writable=False) ) user_plugin_path = os.path.join(user_base_path, "_plugins") # plugin translations plugins = octoprint.plugin.plugin_manager().enabled_plugins for name, plugin in plugins.items(): dirs = [ os.path.join(user_plugin_path, name), os.path.join(plugin.location, "translations"), ] for dirname in dirs: po_files.append(get_po_path(dirname, locale, domain)) # core translations base_path = os.path.join(current_app.root_path, "translations") dirs = [user_base_path, base_path] for dirname in dirs: po_files.append(get_po_path(dirname, locale, domain)) return po_files def _get_translations(locale, domain): from babel.messages.pofile import read_po from octoprint.util import dict_merge messages = {} plural_expr = None def messages_from_po(path, locale, domain): messages = {} with open(path, encoding="utf-8") as f: catalog = read_po(f, locale=locale, domain=domain) for message in catalog: message_id = message.id if isinstance(message_id, (list, tuple)): message_id = message_id[0] if message.string: messages[message_id] = message.string return messages, catalog.plural_expr po_files = _get_all_translationfiles(locale, domain) for po_file in po_files: if not os.path.exists(po_file): continue po_messages, plural_expr = messages_from_po(po_file, locale, domain) if po_messages is not None: messages = dict_merge(messages, po_messages, in_place=True) return messages, plural_expr
62,405
Python
.py
1,554
28.686615
147
0.558849
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,878
users.py
OctoPrint_OctoPrint/src/octoprint/server/api/users.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import redirect, url_for from octoprint.server.api import api # NOTE: The redirects here should rather be 308 PERMANENT REDIRECT, however RFC7538 doesn't seem to be supported # by all browsers yet. So we stick to 307 TEMPORARY REDIRECT as defined in RFC7231 although it's definitely not a # temporary redirect we have here. @api.route("/users", methods=["GET"]) def deprecated_get_users(): return redirect(url_for("api.get_users"), code=307) @api.route("/users", methods=["POST"]) def addUser(): return redirect(url_for("api.add_user"), code=307) @api.route("/users/<username>", methods=["GET"]) def getUser(username): return redirect(url_for("api.get_user", username=username), code=307) @api.route("/users/<username>", methods=["PUT"]) def updateUser(username): return redirect(url_for("api.update_user", username=username), code=307) @api.route("/users/<username>", methods=["DELETE"]) def removeUser(username): return redirect(url_for("api.remove_user", username=username), code=307) @api.route("/users/<username>/password", methods=["PUT"]) def changePasswordForUser(username): return redirect(url_for("api.change_password_for_user", username=username), code=307) @api.route("/users/<username>/settings", methods=["GET"]) def getSettingsForUser(username): return redirect(url_for("api.get_settings_for_user", username=username), code=307) @api.route("/users/<username>/settings", methods=["PATCH"]) def changeSettingsForUser(username): return redirect(url_for("api.change_settings_for_user", username=username), code=307) @api.route("/users/<username>/apikey", methods=["DELETE"]) def deleteApikeyForUser(username): return redirect(url_for("api.delete_apikey_for_user", username=username), code=307) @api.route("/users/<username>/apikey", methods=["POST"]) def generateApikeyForUser(username): return redirect(url_for("api.generate_apikey_for_user", username=username), code=307)
2,151
Python
.py
37
55.432432
113
0.749402
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,879
slicing.py
OctoPrint_OctoPrint/src/octoprint/server/api/slicing.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import abort, jsonify, make_response, request, url_for from octoprint.access.permissions import Permissions from octoprint.server import slicingManager from octoprint.server.api import NO_CONTENT, api from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking from octoprint.settings import settings as s from octoprint.settings import valid_boolean_trues from octoprint.slicing import ( CouldNotDeleteProfile, SlicerNotConfigured, UnknownProfile, UnknownSlicer, ) _DATA_FORMAT_VERSION = "v2" def _lastmodified(configured): if configured: slicers = slicingManager.configured_slicers else: slicers = slicingManager.registered_slicers lms = [0] for slicer in slicers: lms.append(slicingManager.profiles_last_modified(slicer)) return max(lms) def _etag(configured, lm=None): if lm is None: lm = _lastmodified(configured) import hashlib hash = hashlib.sha1() def hash_update(value): value = value.encode("utf-8") hash.update(value) hash_update(str(lm)) if configured: slicers = slicingManager.configured_slicers else: slicers = slicingManager.registered_slicers default_slicer = s().get(["slicing", "defaultSlicer"]) for slicer in sorted(slicers): slicer_impl = slicingManager.get_slicer(slicer, require_configured=False) hash_update(slicer) hash_update(str(slicer_impl.is_slicer_configured())) hash_update(str(slicer == default_slicer)) hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format return hash.hexdigest() @api.route("/slicing", methods=["GET"]) @with_revalidation_checking( etag_factory=lambda lm=None: _etag( request.values.get("configured", "false") in valid_boolean_trues, lm=lm ), lastmodified_factory=lambda: _lastmodified( request.values.get("configured", "false") in valid_boolean_trues ), unless=lambda: request.values.get("force", "false") in valid_boolean_trues, ) @Permissions.SLICE.require(403) def slicingListAll(): from octoprint.filemanager import get_extensions default_slicer = s().get(["slicing", "defaultSlicer"]) if ( "configured" in request.values and request.values["configured"] in valid_boolean_trues ): slicers = slicingManager.configured_slicers else: slicers = slicingManager.registered_slicers result = {} for slicer in slicers: try: slicer_impl = slicingManager.get_slicer(slicer, require_configured=False) extensions = set() for source_file_type in slicer_impl.get_slicer_properties().get( "source_file_types", ["model"] ): extensions = extensions.union(get_extensions(source_file_type)) result[slicer] = { "key": slicer, "displayName": slicer_impl.get_slicer_properties().get("name", "n/a"), "sameDevice": slicer_impl.get_slicer_properties().get( "same_device", True ), "default": default_slicer == slicer, "configured": slicer_impl.is_slicer_configured(), "profiles": _getSlicingProfilesData(slicer), "extensions": { "source": list(extensions), "destination": slicer_impl.get_slicer_properties().get( "destination_extensions", ["gco", "gcode", "g"] ), }, } except (UnknownSlicer, SlicerNotConfigured): # this should never happen pass return jsonify(result) @api.route("/slicing/<string:slicer>/profiles", methods=["GET"]) @no_firstrun_access @Permissions.SLICE.require(403) def slicingListSlicerProfiles(slicer): configured = False if ( "configured" in request.values and request.values["configured"] in valid_boolean_trues ): configured = True try: return jsonify(_getSlicingProfilesData(slicer, require_configured=configured)) except (UnknownSlicer, SlicerNotConfigured): abort(404) @api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"]) @no_firstrun_access @Permissions.SLICE.require(403) def slicingGetSlicerProfile(slicer, name): try: profile = slicingManager.load_profile(slicer, name, require_configured=False) except UnknownSlicer: abort(404) except UnknownProfile: abort(404) result = _getSlicingProfileData(slicer, name, profile) result["data"] = profile.data return jsonify(result) @api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PUT"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def slicingAddSlicerProfile(slicer, name): json_data = request.get_json() data = {} display_name = None description = None if "data" in json_data: data = json_data["data"] if "displayName" in json_data: display_name = json_data["displayName"] if "description" in json_data: description = json_data["description"] try: profile = slicingManager.save_profile( slicer, name, data, allow_overwrite=True, display_name=display_name, description=description, ) except UnknownSlicer: abort(404, description="Unknown slicer") result = _getSlicingProfileData(slicer, name, profile) r = make_response(jsonify(result), 201) r.headers["Location"] = result["resource"] return r @api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PATCH"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def slicingPatchSlicerProfile(slicer, name): json_data = request.get_json() try: profile = slicingManager.load_profile(slicer, name, require_configured=False) except UnknownSlicer: return abort(404) except UnknownProfile: return abort(404) data = {} display_name = None description = None if "data" in json_data: data = json_data["data"] if "displayName" in json_data: display_name = json_data["displayName"] if "description" in json_data: description = json_data["description"] saved_profile = slicingManager.save_profile( slicer, name, profile, allow_overwrite=True, overrides=data, display_name=display_name, description=description, ) from octoprint.server.api import valid_boolean_trues if "default" in json_data and json_data["default"] in valid_boolean_trues: slicingManager.set_default_profile(slicer, name, require_exists=False) return jsonify(_getSlicingProfileData(slicer, name, saved_profile)) @api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def slicingDelSlicerProfile(slicer, name): try: slicingManager.delete_profile(slicer, name) except UnknownSlicer: abort(404) except CouldNotDeleteProfile as e: abort( 500, description="Could not delete profile for slicer: {cause}".format( cause=str(e.cause) ), ) return NO_CONTENT def _getSlicingProfilesData(slicer, require_configured=False): profiles = slicingManager.all_profiles(slicer, require_configured=require_configured) result = {} for name, profile in profiles.items(): result[name] = _getSlicingProfileData(slicer, name, profile) return result def _getSlicingProfileData(slicer, name, profile): defaultProfiles = s().get(["slicing", "defaultProfiles"]) result = { "key": name, "default": defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name, "resource": url_for( ".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True ), } if profile.display_name is not None: result["displayName"] = profile.display_name if profile.description is not None: result["description"] = profile.description return result
8,589
Python
.py
224
31.098214
103
0.669073
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,880
settings.py
OctoPrint_OctoPrint/src/octoprint/server/api/settings.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import re from flask import abort, jsonify, request from flask_login import current_user import octoprint.plugin import octoprint.util from octoprint.access.permissions import Permissions from octoprint.server import pluginManager, printer, userManager from octoprint.server.api import NO_CONTENT, api from octoprint.server.util.flask import ( credentials_checked_recently, no_firstrun_access, with_revalidation_checking, ) from octoprint.settings import settings, valid_boolean_trues from octoprint.timelapse import configure_timelapse from octoprint.webcams import ( get_default_webcam, get_snapshot_webcam, get_webcams_as_dicts, ) # ~~ settings FOLDER_TYPES = ("uploads", "timelapse", "watched") TIMELAPSE_BITRATE_PATTERN = re.compile(r"\d+[KMGTPEZY]?i?B?", flags=re.IGNORECASE) DEPRECATED_WEBCAM_KEYS = ( "streamUrl", "streamRatio", "streamTimeout", "streamWebrtcIceServers", "snapshotUrl", "snapshotTimeout", "snapshotSslValidation", "cacheBuster", "flipH", "flipV", "rotate90", ) def _lastmodified(): return settings().last_modified def _etag(lm=None): if lm is None: lm = _lastmodified() connection_options = printer.__class__.get_connection_options() plugins = sorted(octoprint.plugin.plugin_manager().enabled_plugins) plugin_settings = _get_plugin_settings() from collections import OrderedDict sorted_plugin_settings = OrderedDict() for key in sorted(plugin_settings.keys()): sorted_plugin_settings[key] = plugin_settings.get(key, {}) if current_user is not None and not current_user.is_anonymous: roles = sorted(current_user.permissions, key=lambda x: x.key) else: roles = [] import hashlib hash = hashlib.sha1() def hash_update(value): value = value.encode("utf-8") hash.update(value) # last modified timestamp hash_update(str(lm)) # effective config from config.yaml + overlays hash_update(repr(settings().effective)) # might duplicate settings().effective, but plugins might also inject additional keys into the settings # output that are not stored in config.yaml hash_update(repr(sorted_plugin_settings)) # connection options are also part of the settings hash_update(repr(connection_options)) # if the list of plugins changes, the settings structure changes too hash_update(repr(plugins)) # and likewise if the role of the user changes hash_update(repr(roles)) # of if the user reauthenticates hash_update(repr(credentials_checked_recently())) return hash.hexdigest() @api.route("/settings", methods=["GET"]) @with_revalidation_checking( etag_factory=_etag, lastmodified_factory=_lastmodified, unless=lambda: request.values.get("force", "false") in valid_boolean_trues or settings().getBoolean(["server", "firstRun"]) or not userManager.has_been_customized(), ) def getSettings(): if not Permissions.SETTINGS_READ.can() and not ( settings().getBoolean(["server", "firstRun"]) or not userManager.has_been_customized() ): abort(403) s = settings() connectionOptions = printer.__class__.get_connection_options() # NOTE: Remember to adjust the docs of the data model on the Settings API if anything # is changed, added or removed here data = { "api": { "key": ( s.get(["api", "key"]) if Permissions.ADMIN.can() and credentials_checked_recently() else None ), "allowCrossOrigin": s.get(["api", "allowCrossOrigin"]), }, "appearance": { "name": s.get(["appearance", "name"]), "color": s.get(["appearance", "color"]), "colorTransparent": s.getBoolean(["appearance", "colorTransparent"]), "colorIcon": s.getBoolean(["appearance", "colorIcon"]), "defaultLanguage": s.get(["appearance", "defaultLanguage"]), "showFahrenheitAlso": s.getBoolean(["appearance", "showFahrenheitAlso"]), "fuzzyTimes": s.getBoolean(["appearance", "fuzzyTimes"]), "closeModalsWithClick": s.getBoolean(["appearance", "closeModalsWithClick"]), "showInternalFilename": s.getBoolean(["appearance", "showInternalFilename"]), }, "feature": { "temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]), "sdSupport": s.getBoolean(["feature", "sdSupport"]), "keyboardControl": s.getBoolean(["feature", "keyboardControl"]), "pollWatched": s.getBoolean(["feature", "pollWatched"]), "modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]), "rememberFileFolder": s.getBoolean(["feature", "rememberFileFolder"]), "printStartConfirmation": s.getBoolean(["feature", "printStartConfirmation"]), "printCancelConfirmation": s.getBoolean( ["feature", "printCancelConfirmation"] ), "uploadOverwriteConfirmation": s.getBoolean( ["feature", "uploadOverwriteConfirmation"] ), "g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]), "autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]), "enableDragDropUpload": s.getBoolean(["feature", "enableDragDropUpload"]), }, "gcodeAnalysis": { "runAt": s.get(["gcodeAnalysis", "runAt"]), "bedZ": s.getFloat(["gcodeAnalysis", "bedZ"]), }, "serial": { "port": connectionOptions["portPreference"], "baudrate": connectionOptions["baudratePreference"], "exclusive": s.getBoolean(["serial", "exclusive"]), "lowLatency": s.getBoolean(["serial", "lowLatency"]), "portOptions": connectionOptions["ports"], "baudrateOptions": connectionOptions["baudrates"], "autoconnect": s.getBoolean(["serial", "autoconnect"]), "timeoutConnection": s.getFloat(["serial", "timeout", "connection"]), "timeoutDetectionFirst": s.getFloat(["serial", "timeout", "detectionFirst"]), "timeoutDetectionConsecutive": s.getFloat( ["serial", "timeout", "detectionConsecutive"] ), "timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]), "timeoutCommunicationBusy": s.getFloat( ["serial", "timeout", "communicationBusy"] ), "timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]), "timeoutTemperatureTargetSet": s.getFloat( ["serial", "timeout", "temperatureTargetSet"] ), "timeoutTemperatureAutoreport": s.getFloat( ["serial", "timeout", "temperatureAutoreport"] ), "timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]), "timeoutSdStatusAutoreport": s.getFloat( ["serial", "timeout", "sdStatusAutoreport"] ), "timeoutPosAutoreport": s.getFloat(["serial", "timeout", "posAutoreport"]), "timeoutBaudrateDetectionPause": s.getFloat( ["serial", "timeout", "baudrateDetectionPause"] ), "timeoutPositionLogWait": s.getFloat( ["serial", "timeout", "positionLogWait"] ), "log": s.getBoolean(["serial", "log"]), "additionalPorts": s.get(["serial", "additionalPorts"]), "additionalBaudrates": s.get(["serial", "additionalBaudrates"]), "blacklistedPorts": s.get(["serial", "blacklistedPorts"]), "blacklistedBaudrates": s.get(["serial", "blacklistedBaudrates"]), "longRunningCommands": s.get(["serial", "longRunningCommands"]), "checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]), "blockedCommands": s.get(["serial", "blockedCommands"]), "ignoredCommands": s.get(["serial", "ignoredCommands"]), "pausingCommands": s.get(["serial", "pausingCommands"]), "sdCancelCommand": s.get(["serial", "sdCancelCommand"]), "emergencyCommands": s.get(["serial", "emergencyCommands"]), "helloCommand": s.get(["serial", "helloCommand"]), "ignoreErrorsFromFirmware": s.getBoolean( ["serial", "ignoreErrorsFromFirmware"] ), "disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]), "triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]), "logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]), "logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]), "abortHeatupOnCancel": s.getBoolean(["serial", "abortHeatupOnCancel"]), "supportResendsWithoutOk": s.get(["serial", "supportResendsWithoutOk"]), "waitForStart": s.getBoolean(["serial", "waitForStartOnConnect"]), "waitToLoadSdFileList": s.getBoolean(["serial", "waitToLoadSdFileList"]), "alwaysSendChecksum": s.getBoolean(["serial", "alwaysSendChecksum"]), "neverSendChecksum": s.getBoolean(["serial", "neverSendChecksum"]), "sendChecksumWithUnknownCommands": s.getBoolean( ["serial", "sendChecksumWithUnknownCommands"] ), "unknownCommandsNeedAck": s.getBoolean(["serial", "unknownCommandsNeedAck"]), "sdRelativePath": s.getBoolean(["serial", "sdRelativePath"]), "sdAlwaysAvailable": s.getBoolean(["serial", "sdAlwaysAvailable"]), "sdLowerCase": s.getBoolean(["serial", "sdLowerCase"]), "swallowOkAfterResend": s.getBoolean(["serial", "swallowOkAfterResend"]), "repetierTargetTemp": s.getBoolean(["serial", "repetierTargetTemp"]), "externalHeatupDetection": s.getBoolean( ["serial", "externalHeatupDetection"] ), "ignoreIdenticalResends": s.getBoolean(["serial", "ignoreIdenticalResends"]), "firmwareDetection": s.getBoolean(["serial", "firmwareDetection"]), "blockWhileDwelling": s.getBoolean(["serial", "blockWhileDwelling"]), "useParityWorkaround": s.get(["serial", "useParityWorkaround"]), "sanityCheckTools": s.getBoolean(["serial", "sanityCheckTools"]), "notifySuppressedCommands": s.get(["serial", "notifySuppressedCommands"]), "sendM112OnError": s.getBoolean(["serial", "sendM112OnError"]), "disableSdPrintingDetection": s.getBoolean( ["serial", "disableSdPrintingDetection"] ), "ackMax": s.getInt(["serial", "ackMax"]), "maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]), "maxTimeoutsPrinting": s.getInt( ["serial", "maxCommunicationTimeouts", "printing"] ), "maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"]), "capAutoreportTemp": s.getBoolean( ["serial", "capabilities", "autoreport_temp"] ), "capAutoreportSdStatus": s.getBoolean( ["serial", "capabilities", "autoreport_sdstatus"] ), "capAutoreportPos": s.getBoolean( ["serial", "capabilities", "autoreport_pos"] ), "capBusyProtocol": s.getBoolean(["serial", "capabilities", "busy_protocol"]), "capEmergencyParser": s.getBoolean( ["serial", "capabilities", "emergency_parser"] ), "capExtendedM20": s.getBoolean(["serial", "capabilities", "extended_m20"]), "capLfnWrite": s.getBoolean(["serial", "capabilities", "lfn_write"]), "resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]), "resendRatioStart": s.getInt(["serial", "resendRatioStart"]), "ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]), "encoding": s.get(["serial", "encoding"]), "enableShutdownActionCommand": s.get( ["serial", "enableShutdownActionCommand"] ), }, "folder": { "uploads": s.getBaseFolder("uploads"), "timelapse": s.getBaseFolder("timelapse"), "watched": s.getBaseFolder("watched"), }, "temperature": { "profiles": s.get(["temperature", "profiles"]), "cutoff": s.getInt(["temperature", "cutoff"]), "sendAutomatically": s.getBoolean(["temperature", "sendAutomatically"]), "sendAutomaticallyAfter": s.getInt( ["temperature", "sendAutomaticallyAfter"], min=0, max=30 ), }, "system": { "actions": s.get(["system", "actions"]), "events": s.get(["system", "events"]), }, "terminalFilters": s.get(["terminalFilters"]), "scripts": { "gcode": { "afterPrinterConnected": None, "beforePrinterDisconnected": None, "beforePrintStarted": None, "afterPrintCancelled": None, "afterPrintDone": None, "beforePrintPaused": None, "afterPrintResumed": None, "beforeToolChange": None, "afterToolChange": None, "snippets": {}, } }, "server": { "commands": { "systemShutdownCommand": s.get( ["server", "commands", "systemShutdownCommand"] ), "systemRestartCommand": s.get( ["server", "commands", "systemRestartCommand"] ), "serverRestartCommand": s.get( ["server", "commands", "serverRestartCommand"] ), }, "diskspace": { "warning": s.getInt(["server", "diskspace", "warning"]), "critical": s.getInt(["server", "diskspace", "critical"]), }, "onlineCheck": { "enabled": s.getBoolean(["server", "onlineCheck", "enabled"]), "interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60), "host": s.get(["server", "onlineCheck", "host"]), "port": s.getInt(["server", "onlineCheck", "port"]), "name": s.get(["server", "onlineCheck", "name"]), }, "pluginBlacklist": { "enabled": s.getBoolean(["server", "pluginBlacklist", "enabled"]), "url": s.get(["server", "pluginBlacklist", "url"]), "ttl": int(s.getInt(["server", "pluginBlacklist", "ttl"]) / 60), }, "allowFraming": s.getBoolean(["server", "allowFraming"]), }, "devel": {"pluginTimings": s.getBoolean(["devel", "pluginTimings"])}, "slicing": {"defaultSlicer": s.get(["slicing", "defaultSlicer"])}, } gcode_scripts = s.listScripts("gcode") if gcode_scripts: data["scripts"] = {"gcode": {}} for name in gcode_scripts: data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True) plugin_settings = _get_plugin_settings() if len(plugin_settings): data["plugins"] = plugin_settings if Permissions.WEBCAM.can() or ( settings().getBoolean(["server", "firstRun"]) and not userManager.has_been_customized() ): webcamsDict = get_webcams_as_dicts() data["webcam"] = { "webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]), "timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]), "ffmpegPath": s.get(["webcam", "ffmpeg"]), "ffmpegCommandline": s.get(["webcam", "ffmpegCommandline"]), "bitrate": s.get(["webcam", "bitrate"]), "ffmpegThreads": s.get(["webcam", "ffmpegThreads"]), "ffmpegVideoCodec": s.get(["webcam", "ffmpegVideoCodec"]), "watermark": s.getBoolean(["webcam", "watermark"]), # webcams & defaults "webcams": webcamsDict, "defaultWebcam": None, "snapshotWebcam": None, } for key in DEPRECATED_WEBCAM_KEYS: data["webcam"][key] = None defaultWebcam = get_default_webcam() if defaultWebcam: data["webcam"].update( { "flipH": defaultWebcam.config.flipH, "flipV": defaultWebcam.config.flipV, "rotate90": defaultWebcam.config.rotate90, "defaultWebcam": defaultWebcam.config.name, } ) compatWebcam = defaultWebcam.config.compat if defaultWebcam is not None else None if compatWebcam: data["webcam"].update( { "streamUrl": compatWebcam.stream, "streamRatio": compatWebcam.streamRatio, "streamTimeout": compatWebcam.streamTimeout, "streamWebrtcIceServers": compatWebcam.streamWebrtcIceServers, "snapshotUrl": compatWebcam.snapshot, "snapshotTimeout": compatWebcam.snapshotTimeout, "snapshotSslValidation": compatWebcam.snapshotSslValidation, "cacheBuster": compatWebcam.cacheBuster, } ) snapshotWebcam = get_snapshot_webcam() if snapshotWebcam: data["webcam"].update( { "snapshotWebcam": snapshotWebcam.config.name, } ) else: data["webcam"] = {} if Permissions.ADMIN.can(): data["accessControl"] = { "autologinLocal": s.getBoolean(["accessControl", "autologinLocal"]), "autologinHeadsupAcknowledged": s.getBoolean( ["accessControl", "autologinHeadsupAcknowledged"] ), } return jsonify(data) def _get_plugin_settings(): logger = logging.getLogger(__name__) data = {} def process_plugin_result(name, result): if result: try: jsonify(test=result) except Exception: logger.exception( "Error while jsonifying settings from plugin {}, please contact the plugin author about this".format( name ) ) raise else: if "__enabled" in result: del result["__enabled"] data[name] = result for plugin in octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.SettingsPlugin ): try: result = plugin.on_settings_load() process_plugin_result(plugin._identifier, result) except Exception: logger.exception( "Could not load settings for plugin {name} ({version})".format( version=plugin._plugin_version, name=plugin._plugin_name ), extra={"plugin": plugin._identifier}, ) return data @api.route("/settings", methods=["POST"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def setSettings(): data = request.get_json() if not isinstance(data, dict): abort(400, description="Malformed JSON body in request") response = _saveSettings(data) if response: return response return getSettings() @api.route("/settings/apikey", methods=["POST"]) @no_firstrun_access @Permissions.ADMIN.require(403) def generateApiKey(): apikey = settings().generateApiKey() return jsonify(apikey=apikey) @api.route("/settings/apikey", methods=["DELETE"]) @no_firstrun_access @Permissions.ADMIN.require(403) def deleteApiKey(): settings().deleteApiKey() return NO_CONTENT @api.route("/settings/templates", methods=["GET"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def fetchTemplateData(): from octoprint.server.views import fetch_template_data refresh = request.values.get("refresh", "false") in valid_boolean_trues templates, _, _ = fetch_template_data(refresh=refresh) result = {} for tt in templates: result[tt] = [] for key in templates[tt]["order"]: entry = templates[tt]["entries"].get(key) if not entry: continue if isinstance(entry, dict): name = key else: name, entry = entry data = {"id": key, "name": name} if entry and "_plugin" in entry: plugin = pluginManager.get_plugin_info( entry["_plugin"], require_enabled=False ) data["plugin_id"] = plugin.key data["plugin_name"] = plugin.name result[tt].append(data) return jsonify(order=result) def _saveSettings(data): logger = logging.getLogger(__name__) s = settings() # NOTE: Remember to adjust the docs of the data model on the Settings API if anything # is changed, added or removed here if "folder" in data: try: folders = data["folder"] future = {} for folder in FOLDER_TYPES: future[folder] = s.getBaseFolder(folder) if folder in folders: future[folder] = folders[folder] for folder in folders: if folder not in FOLDER_TYPES: continue for other_folder in FOLDER_TYPES: if folder == other_folder: continue if future[folder] == future[other_folder]: # duplicate detected, raise raise ValueError( "Duplicate folder path for {} and {}".format( folder, other_folder ) ) s.setBaseFolder(folder, future[folder]) except Exception: logger.exception("Something went wrong while saving a folder path") abort(400, description="At least one of the configured folders is invalid") if "api" in data: if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"]) if "accessControl" in data: if "autologinHeadsupAcknowledged" in data["accessControl"]: s.setBoolean( ["accessControl", "autologinHeadsupAcknowledged"], data["accessControl"]["autologinHeadsupAcknowledged"], ) if "appearance" in data: if "name" in data["appearance"]: s.set(["appearance", "name"], data["appearance"]["name"]) if "color" in data["appearance"]: s.set(["appearance", "color"], data["appearance"]["color"]) if "colorTransparent" in data["appearance"]: s.setBoolean( ["appearance", "colorTransparent"], data["appearance"]["colorTransparent"] ) if "colorIcon" in data["appearance"]: s.setBoolean(["appearance", "colorIcon"], data["appearance"]["colorIcon"]) if "defaultLanguage" in data["appearance"]: s.set( ["appearance", "defaultLanguage"], data["appearance"]["defaultLanguage"] ) if "showFahrenheitAlso" in data["appearance"]: s.setBoolean( ["appearance", "showFahrenheitAlso"], data["appearance"]["showFahrenheitAlso"], ) if "fuzzyTimes" in data["appearance"]: s.setBoolean(["appearance", "fuzzyTimes"], data["appearance"]["fuzzyTimes"]) if "closeModalsWithClick" in data["appearance"]: s.setBoolean( ["appearance", "closeModalsWithClick"], data["appearance"]["closeModalsWithClick"], ) if "showInternalFilename" in data["appearance"]: s.setBoolean( ["appearance", "showInternalFilename"], data["appearance"]["showInternalFilename"], ) if "printer" in data: if "defaultExtrusionLength" in data["printer"]: s.setInt( ["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"], ) if "webcam" in data: for key in DEPRECATED_WEBCAM_KEYS: if key in data["webcam"]: logger.warning( f"Setting webcam.{key} via the API is no longer supported, please use the individual settings of the default webcam instead." ) if "webcamEnabled" in data["webcam"]: s.setBoolean(["webcam", "webcamEnabled"], data["webcam"]["webcamEnabled"]) if "timelapseEnabled" in data["webcam"]: s.setBoolean( ["webcam", "timelapseEnabled"], data["webcam"]["timelapseEnabled"] ) if "snapshotTimeout" in data["webcam"]: s.setInt(["webcam", "snapshotTimeout"], data["webcam"]["snapshotTimeout"]) if "snapshotSslValidation" in data["webcam"]: s.setBoolean( ["webcam", "snapshotSslValidation"], data["webcam"]["snapshotSslValidation"], ) if "ffmpegPath" in data["webcam"]: s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"]) if "ffmpegCommandline" in data["webcam"]: commandline = data["webcam"]["ffmpegCommandline"] if not all( map(lambda x: "{" + x + "}" in commandline, ("ffmpeg", "input", "output")) ): abort( 400, description="Invalid webcam.ffmpegCommandline setting, lacks mandatory {ffmpeg}, {input} or {output}", ) try: commandline.format( ffmpeg="ffmpeg", fps="fps", bitrate="bitrate", threads="threads", input="input", output="output", videocodec="videocodec", containerformat="containerformat", filters="filters", ) except Exception: # some invalid data we'll refuse to set logger.exception("Invalid webcam.ffmpegCommandline setting") abort(400, description="Invalid webcam.ffmpegCommandline setting") else: s.set(["webcam", "ffmpegCommandline"], commandline) if "bitrate" in data["webcam"] and data["webcam"]["bitrate"]: bitrate = str(data["webcam"]["bitrate"]) if not TIMELAPSE_BITRATE_PATTERN.match(bitrate): abort( 400, description="Invalid webcam.bitrate setting, needs to be a valid ffmpeg bitrate", ) s.set(["webcam", "bitrate"], bitrate) if "ffmpegThreads" in data["webcam"]: s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"]) if "ffmpegVideoCodec" in data["webcam"] and data["webcam"][ "ffmpegVideoCodec" ] in ("mpeg2video", "libx264"): s.set(["webcam", "ffmpegVideoCodec"], data["webcam"]["ffmpegVideoCodec"]) if "watermark" in data["webcam"]: s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"]) if "defaultWebcam" in data["webcam"]: s.set(["webcam", "defaultWebcam"], data["webcam"]["defaultWebcam"]) if "snapshotWebcam" in data["webcam"]: s.set(["webcam", "snapshotWebcam"], data["webcam"]["snapshotWebcam"]) # timelapse needs to be reconfigured now since it depends on the current snapshot webcam configure_timelapse() if "feature" in data: if "temperatureGraph" in data["feature"]: s.setBoolean( ["feature", "temperatureGraph"], data["feature"]["temperatureGraph"] ) if "sdSupport" in data["feature"]: s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"]) if "keyboardControl" in data["feature"]: s.setBoolean( ["feature", "keyboardControl"], data["feature"]["keyboardControl"] ) if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"]) if "modelSizeDetection" in data["feature"]: s.setBoolean( ["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"] ) if "rememberFileFolder" in data["feature"]: s.setBoolean( ["feature", "rememberFileFolder"], data["feature"]["rememberFileFolder"], ) if "printStartConfirmation" in data["feature"]: s.setBoolean( ["feature", "printStartConfirmation"], data["feature"]["printStartConfirmation"], ) if "printCancelConfirmation" in data["feature"]: s.setBoolean( ["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"], ) if "uploadOverwriteConfirmation" in data["feature"]: s.setBoolean( ["feature", "uploadOverwriteConfirmation"], data["feature"]["uploadOverwriteConfirmation"], ) if "g90InfluencesExtruder" in data["feature"]: s.setBoolean( ["feature", "g90InfluencesExtruder"], data["feature"]["g90InfluencesExtruder"], ) if "autoUppercaseBlacklist" in data["feature"] and isinstance( data["feature"]["autoUppercaseBlacklist"], (list, tuple) ): s.set( ["feature", "autoUppercaseBlacklist"], data["feature"]["autoUppercaseBlacklist"], ) if "enableDragDropUpload" in data["feature"]: s.setBoolean( ["feature", "enableDragDropUpload"], data["feature"]["enableDragDropUpload"], ) if "gcodeAnalysis" in data: if "runAt" in data["gcodeAnalysis"]: s.set(["gcodeAnalysis", "runAt"], data["gcodeAnalysis"]["runAt"]) if "bedZ" in data["gcodeAnalysis"]: s.setFloat(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"]) if "serial" in data: if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) if "port" in data["serial"]: s.set(["serial", "port"], data["serial"]["port"]) if "baudrate" in data["serial"]: s.setInt(["serial", "baudrate"], data["serial"]["baudrate"]) if "exclusive" in data["serial"]: s.setBoolean(["serial", "exclusive"], data["serial"]["exclusive"]) if "lowLatency" in data["serial"]: s.setBoolean(["serial", "lowLatency"], data["serial"]["lowLatency"]) if "timeoutConnection" in data["serial"]: s.setFloat( ["serial", "timeout", "connection"], data["serial"]["timeoutConnection"], min=1.0, ) if "timeoutDetectionFirst" in data["serial"]: s.setFloat( ["serial", "timeout", "detectionFirst"], data["serial"]["timeoutDetectionFirst"], min=1.0, ) if "timeoutDetectionConsecutive" in data["serial"]: s.setFloat( ["serial", "timeout", "detectionConsecutive"], data["serial"]["timeoutDetectionConsecutive"], min=1.0, ) if "timeoutCommunication" in data["serial"]: s.setFloat( ["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"], min=1.0, ) if "timeoutCommunicationBusy" in data["serial"]: s.setFloat( ["serial", "timeout", "communicationBusy"], data["serial"]["timeoutCommunicationBusy"], min=1.0, ) if "timeoutTemperature" in data["serial"]: s.setFloat( ["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"], min=1.0, ) if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat( ["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"], min=1.0, ) if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat( ["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"], min=0.0, ) if "timeoutSdStatus" in data["serial"]: s.setFloat( ["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"], min=1.0, ) if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat( ["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"], min=0.0, ) if "timeoutPosAutoreport" in data["serial"]: s.setFloat( ["serial", "timeout", "posAutoreport"], data["serial"]["timeoutPosAutoreport"], min=0.0, ) if "timeoutBaudrateDetectionPause" in data["serial"]: s.setFloat( ["serial", "timeout", "baudrateDetectionPause"], data["serial"]["timeoutBaudrateDetectionPause"], min=0.0, ) if "timeoutPositionLogWait" in data["serial"]: s.setFloat( ["serial", "timeout", "positionLogWait"], data["serial"]["timeoutPositionLogWait"], min=1.0, ) if "additionalPorts" in data["serial"] and isinstance( data["serial"]["additionalPorts"], (list, tuple) ): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"]) if "additionalBaudrates" in data["serial"] and isinstance( data["serial"]["additionalBaudrates"], (list, tuple) ): s.set( ["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"] ) if "blacklistedPorts" in data["serial"] and isinstance( data["serial"]["blacklistedPorts"], (list, tuple) ): s.set(["serial", "blacklistedPorts"], data["serial"]["blacklistedPorts"]) if "blacklistedBaudrates" in data["serial"] and isinstance( data["serial"]["blacklistedBaudrates"], (list, tuple) ): s.set( ["serial", "blacklistedBaudrates"], data["serial"]["blacklistedBaudrates"] ) if "longRunningCommands" in data["serial"] and isinstance( data["serial"]["longRunningCommands"], (list, tuple) ): s.set( ["serial", "longRunningCommands"], data["serial"]["longRunningCommands"] ) if "checksumRequiringCommands" in data["serial"] and isinstance( data["serial"]["checksumRequiringCommands"], (list, tuple) ): s.set( ["serial", "checksumRequiringCommands"], data["serial"]["checksumRequiringCommands"], ) if "blockedCommands" in data["serial"] and isinstance( data["serial"]["blockedCommands"], (list, tuple) ): s.set(["serial", "blockedCommands"], data["serial"]["blockedCommands"]) if "ignoredCommands" in data["serial"] and isinstance( data["serial"]["ignoredCommands"], (list, tuple) ): s.set(["serial", "ignoredCommands"], data["serial"]["ignoredCommands"]) if "pausingCommands" in data["serial"] and isinstance( data["serial"]["pausingCommands"], (list, tuple) ): s.set(["serial", "pausingCommands"], data["serial"]["pausingCommands"]) if "sdCancelCommand" in data["serial"]: s.set(["serial", "sdCancelCommand"], data["serial"]["sdCancelCommand"]) if "emergencyCommands" in data["serial"] and isinstance( data["serial"]["emergencyCommands"], (list, tuple) ): s.set(["serial", "emergencyCommands"], data["serial"]["emergencyCommands"]) if "helloCommand" in data["serial"]: s.set(["serial", "helloCommand"], data["serial"]["helloCommand"]) if "ignoreErrorsFromFirmware" in data["serial"]: s.setBoolean( ["serial", "ignoreErrorsFromFirmware"], data["serial"]["ignoreErrorsFromFirmware"], ) if "disconnectOnErrors" in data["serial"]: s.setBoolean( ["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"] ) if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"]) if "supportResendsWithoutOk" in data["serial"]: value = data["serial"]["supportResendsWithoutOk"] if value in ("always", "detect", "never"): s.set(["serial", "supportResendsWithoutOk"], value) if "waitForStart" in data["serial"]: s.setBoolean( ["serial", "waitForStartOnConnect"], data["serial"]["waitForStart"] ) if "waitToLoadSdFileList" in data["serial"]: s.setBoolean( ["serial", "waitToLoadSdFileList"], data["serial"]["waitToLoadSdFileList"], ) if "alwaysSendChecksum" in data["serial"]: s.setBoolean( ["serial", "alwaysSendChecksum"], data["serial"]["alwaysSendChecksum"] ) if "neverSendChecksum" in data["serial"]: s.setBoolean( ["serial", "neverSendChecksum"], data["serial"]["neverSendChecksum"] ) if "sendChecksumWithUnknownCommands" in data["serial"]: s.setBoolean( ["serial", "sendChecksumWithUnknownCommands"], data["serial"]["sendChecksumWithUnknownCommands"], ) if "unknownCommandsNeedAck" in data["serial"]: s.setBoolean( ["serial", "unknownCommandsNeedAck"], data["serial"]["unknownCommandsNeedAck"], ) if "sdRelativePath" in data["serial"]: s.setBoolean(["serial", "sdRelativePath"], data["serial"]["sdRelativePath"]) if "sdAlwaysAvailable" in data["serial"]: s.setBoolean( ["serial", "sdAlwaysAvailable"], data["serial"]["sdAlwaysAvailable"] ) if "sdLowerCase" in data["serial"]: s.setBoolean(["serial", "sdLowerCase"], data["serial"]["sdLowerCase"]) if "swallowOkAfterResend" in data["serial"]: s.setBoolean( ["serial", "swallowOkAfterResend"], data["serial"]["swallowOkAfterResend"] ) if "repetierTargetTemp" in data["serial"]: s.setBoolean( ["serial", "repetierTargetTemp"], data["serial"]["repetierTargetTemp"] ) if "externalHeatupDetection" in data["serial"]: s.setBoolean( ["serial", "externalHeatupDetection"], data["serial"]["externalHeatupDetection"], ) if "ignoreIdenticalResends" in data["serial"]: s.setBoolean( ["serial", "ignoreIdenticalResends"], data["serial"]["ignoreIdenticalResends"], ) if "firmwareDetection" in data["serial"]: s.setBoolean( ["serial", "firmwareDetection"], data["serial"]["firmwareDetection"] ) if "blockWhileDwelling" in data["serial"]: s.setBoolean( ["serial", "blockWhileDwelling"], data["serial"]["blockWhileDwelling"] ) if "useParityWorkaround" in data["serial"]: value = data["serial"]["useParityWorkaround"] if value in ("always", "detect", "never"): s.set(["serial", "useParityWorkaround"], value) if "sanityCheckTools" in data["serial"]: s.setBoolean( ["serial", "sanityCheckTools"], data["serial"]["sanityCheckTools"] ) if "notifySuppressedCommands" in data["serial"]: value = data["serial"]["notifySuppressedCommands"] if value in ("info", "warn", "never"): s.set(["serial", "notifySuppressedCommands"], value) if "sendM112OnError" in data["serial"]: s.setBoolean(["serial", "sendM112OnError"], data["serial"]["sendM112OnError"]) if "disableSdPrintingDetection" in data["serial"]: s.setBoolean( ["serial", "disableSdPrintingDetection"], data["serial"]["disableSdPrintingDetection"], ) if "ackMax" in data["serial"]: s.setInt(["serial", "ackMax"], data["serial"]["ackMax"]) if "logPositionOnPause" in data["serial"]: s.setBoolean( ["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"] ) if "logPositionOnCancel" in data["serial"]: s.setBoolean( ["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"] ) if "abortHeatupOnCancel" in data["serial"]: s.setBoolean( ["serial", "abortHeatupOnCancel"], data["serial"]["abortHeatupOnCancel"] ) if "maxTimeoutsIdle" in data["serial"]: s.setInt( ["serial", "maxCommunicationTimeouts", "idle"], data["serial"]["maxTimeoutsIdle"], ) if "maxTimeoutsPrinting" in data["serial"]: s.setInt( ["serial", "maxCommunicationTimeouts", "printing"], data["serial"]["maxTimeoutsPrinting"], ) if "maxTimeoutsLong" in data["serial"]: s.setInt( ["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"], ) if "capAutoreportTemp" in data["serial"]: s.setBoolean( ["serial", "capabilities", "autoreport_temp"], data["serial"]["capAutoreportTemp"], ) if "capAutoreportSdStatus" in data["serial"]: s.setBoolean( ["serial", "capabilities", "autoreport_sdstatus"], data["serial"]["capAutoreportSdStatus"], ) if "capAutoreportPos" in data["serial"]: s.setBoolean( ["serial", "capabilities", "autoreport_pos"], data["serial"]["capAutoreportPos"], ) if "capBusyProtocol" in data["serial"]: s.setBoolean( ["serial", "capabilities", "busy_protocol"], data["serial"]["capBusyProtocol"], ) if "capEmergencyParser" in data["serial"]: s.setBoolean( ["serial", "capabilities", "emergency_parser"], data["serial"]["capEmergencyParser"], ) if "capExtendedM20" in data["serial"]: s.setBoolean( ["serial", "capabilities", "extended_m20"], data["serial"]["capExtendedM20"], ), if "capLfnWrite" in data["serial"]: s.setBoolean( ["serial", "capabilities", "lfn_write"], data["serial"]["capLfnWrite"], ) if "resendRatioThreshold" in data["serial"]: s.setInt( ["serial", "resendRatioThreshold"], data["serial"]["resendRatioThreshold"] ) if "resendRatioStart" in data["serial"]: s.setInt(["serial", "resendRatioStart"], data["serial"]["resendRatioStart"]) if "ignoreEmptyPorts" in data["serial"]: s.setBoolean( ["serial", "ignoreEmptyPorts"], data["serial"]["ignoreEmptyPorts"] ) if "encoding" in data["serial"]: s.set(["serial", "encoding"], data["serial"]["encoding"]) if "enableShutdownActionCommand" in data["serial"]: s.setBoolean( ["serial", "enableShutdownActionCommand"], data["serial"]["enableShutdownActionCommand"], ) oldLog = s.getBoolean(["serial", "log"]) if "log" in data["serial"]: s.setBoolean(["serial", "log"], data["serial"]["log"]) if oldLog and not s.getBoolean(["serial", "log"]): # disable debug logging to serial.log logging.getLogger("SERIAL").debug("Disabling serial logging") logging.getLogger("SERIAL").setLevel(logging.CRITICAL) elif not oldLog and s.getBoolean(["serial", "log"]): # enable debug logging to serial.log logging.getLogger("SERIAL").setLevel(logging.DEBUG) logging.getLogger("SERIAL").debug("Enabling serial logging") if "temperature" in data: if "profiles" in data["temperature"]: result = [] for profile in data["temperature"]["profiles"]: try: profile["bed"] = int(profile["bed"]) profile["extruder"] = int(profile["extruder"]) except ValueError: pass result.append(profile) s.set(["temperature", "profiles"], result) if "cutoff" in data["temperature"]: try: cutoff = int(data["temperature"]["cutoff"]) if cutoff > 1: s.setInt(["temperature", "cutoff"], cutoff) except ValueError: pass if "sendAutomatically" in data["temperature"]: s.setBoolean( ["temperature", "sendAutomatically"], data["temperature"]["sendAutomatically"], ) if "sendAutomaticallyAfter" in data["temperature"]: s.setInt( ["temperature", "sendAutomaticallyAfter"], data["temperature"]["sendAutomaticallyAfter"], min=0, max=30, ) if "terminalFilters" in data: s.set(["terminalFilters"], data["terminalFilters"]) if "system" in data: if "actions" in data["system"]: s.set(["system", "actions"], data["system"]["actions"]) if "events" in data["system"]: s.set(["system", "events"], data["system"]["events"]) if "scripts" in data: if "gcode" in data["scripts"] and isinstance(data["scripts"]["gcode"], dict): for name, script in data["scripts"]["gcode"].items(): if name == "snippets": continue if not isinstance(script, str): continue s.saveScript( "gcode", name, script.replace("\r\n", "\n").replace("\r", "\n") ) if "server" in data: if "commands" in data["server"]: if "systemShutdownCommand" in data["server"]["commands"]: s.set( ["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"], ) if "systemRestartCommand" in data["server"]["commands"]: s.set( ["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"], ) if "serverRestartCommand" in data["server"]["commands"]: s.set( ["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"], ) if "diskspace" in data["server"]: if "warning" in data["server"]["diskspace"]: s.setInt( ["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"], ) if "critical" in data["server"]["diskspace"]: s.setInt( ["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"], ) if "onlineCheck" in data["server"]: if "enabled" in data["server"]["onlineCheck"]: s.setBoolean( ["server", "onlineCheck", "enabled"], data["server"]["onlineCheck"]["enabled"], ) if "interval" in data["server"]["onlineCheck"]: try: interval = int(data["server"]["onlineCheck"]["interval"]) s.setInt(["server", "onlineCheck", "interval"], interval * 60) except ValueError: pass if "host" in data["server"]["onlineCheck"]: s.set( ["server", "onlineCheck", "host"], data["server"]["onlineCheck"]["host"], ) if "port" in data["server"]["onlineCheck"]: s.setInt( ["server", "onlineCheck", "port"], data["server"]["onlineCheck"]["port"], ) if "name" in data["server"]["onlineCheck"]: s.set( ["server", "onlineCheck", "name"], data["server"]["onlineCheck"]["name"], ) if "pluginBlacklist" in data["server"]: if "enabled" in data["server"]["pluginBlacklist"]: s.setBoolean( ["server", "pluginBlacklist", "enabled"], data["server"]["pluginBlacklist"]["enabled"], ) if "url" in data["server"]["pluginBlacklist"]: s.set( ["server", "pluginBlacklist", "url"], data["server"]["pluginBlacklist"]["url"], ) if "ttl" in data["server"]["pluginBlacklist"]: try: ttl = int(data["server"]["pluginBlacklist"]["ttl"]) s.setInt(["server", "pluginBlacklist", "ttl"], ttl * 60) except ValueError: pass if "allowFraming" in data["server"]: s.setBoolean(["server", "allowFraming"], data["server"]["allowFraming"]) if "devel" in data: oldLog = s.getBoolean(["devel", "pluginTimings"]) if "pluginTimings" in data["devel"]: s.setBoolean(["devel", "pluginTimings"], data["devel"]["pluginTimings"]) if oldLog and not s.getBoolean(["devel", "pluginTimings"]): # disable plugin timing logging to plugintimings.log logging.getLogger("PLUGIN_TIMINGS").debug("Disabling plugin timings logging") logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.INFO) elif not oldLog and s.getBoolean(["devel", "pluginTimings"]): # enable plugin timing logging to plugintimings.log logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.DEBUG) logging.getLogger("PLUGIN_TIMINGS").debug("Enabling plugin timings logging") if "slicing" in data: if "defaultSlicer" in data["slicing"]: s.set(["slicing", "defaultSlicer"], data["slicing"]["defaultSlicer"]) if "plugins" in data: for plugin in octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.SettingsPlugin ): plugin_id = plugin._identifier if plugin_id in data["plugins"]: try: plugin.on_settings_save(data["plugins"][plugin_id]) except TypeError: logger.warning( "Could not save settings for plugin {name} ({version}). It may have called super(...)".format( name=plugin._plugin_name, version=plugin._plugin_version ) ) logger.warning( "in a way which has issues due to OctoPrint's dynamic reloading after plugin operations." ) logger.warning( "Please contact the plugin's author and ask to update the plugin to use a direct call like" ) logger.warning( "octoprint.plugin.SettingsPlugin.on_settings_save(self, data) instead.", exc_info=True, ) except Exception: logger.exception( "Could not save settings for plugin {name} ({version})".format( version=plugin._plugin_version, name=plugin._plugin_name ), extra={"plugin": plugin._identifier}, ) s.save(trigger_event=True)
54,130
Python
.py
1,169
33.47562
145
0.554087
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,881
access.py
OctoPrint_OctoPrint/src/octoprint/server/api/access.py
__author__ = "Marc Hannappel <salandora@gmail.com>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import abort, jsonify, request from flask_login import current_user import octoprint.access.groups as groups import octoprint.access.users as users from octoprint.access.permissions import Permissions from octoprint.server import SUCCESS, groupManager, userManager from octoprint.server.api import api, valid_boolean_trues from octoprint.server.util.flask import ( ensure_credentials_checked_recently, no_firstrun_access, require_credentials_checked_recently, ) # ~~ permission api @api.route("/access/permissions", methods=["GET"]) def get_permissions(): return jsonify(permissions=[permission.as_dict() for permission in Permissions.all()]) # ~~ group api @api.route("/access/groups", methods=["GET"]) @no_firstrun_access @Permissions.ADMIN.require(403) def get_groups(): return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups))) @api.route("/access/groups", methods=["POST"]) @no_firstrun_access @require_credentials_checked_recently @Permissions.ADMIN.require(403) def add_group(): data = request.get_json() if "key" not in data: abort(400, description="key is missing") if "name" not in data: abort(400, description="name is missing") if "permissions" not in data: abort(400, description="permissions are missing") key = data["key"] name = data["name"] description = data.get("description", "") permissions = data["permissions"] subgroups = data["subgroups"] default = data.get("default", False) try: groupManager.add_group( key, name, description=description, permissions=permissions, subgroups=subgroups, default=default, ) except groups.GroupAlreadyExists: abort(409) return get_groups() @api.route("/access/groups/<key>", methods=["GET"]) @no_firstrun_access @Permissions.ADMIN.require(403) def get_group(key): group = groupManager.find_group(key) if group is not None: return jsonify(group) else: abort(404) @api.route("/access/groups/<key>", methods=["PUT"]) @no_firstrun_access @require_credentials_checked_recently @Permissions.ADMIN.require(403) def update_group(key): data = request.get_json() try: kwargs = {} if "permissions" in data: kwargs["permissions"] = data["permissions"] if "subgroups" in data: kwargs["subgroups"] = data["subgroups"] if "default" in data: kwargs["default"] = data["default"] in valid_boolean_trues if "description" in data: kwargs["description"] = data["description"] groupManager.update_group(key, **kwargs) return get_groups() except groups.GroupCantBeChanged: abort(403) except groups.UnknownGroup: abort(404) @api.route("/access/groups/<key>", methods=["DELETE"]) @no_firstrun_access @require_credentials_checked_recently @Permissions.ADMIN.require(403) def remove_group(key): try: groupManager.remove_group(key) return get_groups() except groups.UnknownGroup: abort(404) except groups.GroupUnremovable: abort(403) # ~~ user api @api.route("/access/users", methods=["GET"]) @no_firstrun_access @Permissions.ADMIN.require(403) def get_users(): return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users()))) @api.route("/access/users", methods=["POST"]) @no_firstrun_access @require_credentials_checked_recently @Permissions.ADMIN.require(403) def add_user(): data = request.get_json() if "name" not in data: abort(400, description="name is missing") if "password" not in data: abort(400, description="password is missing") if "active" not in data: abort(400, description="active is missing") name = data["name"] password = data["password"] active = data["active"] in valid_boolean_trues groups = data.get("groups", None) permissions = data.get("permissions", None) try: userManager.add_user(name, password, active, permissions, groups) except users.UserAlreadyExists: abort(409) except users.InvalidUsername: abort(400, "Username invalid") return get_users() @api.route("/access/users/<username>", methods=["GET"]) @no_firstrun_access def get_user(username): if ( current_user is not None and not current_user.is_anonymous and ( current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN) ) ): user = userManager.find_user(username) if user is not None: return jsonify(user) else: abort(404) else: abort(403) @api.route("/access/users/<username>", methods=["PUT"]) @no_firstrun_access @require_credentials_checked_recently @Permissions.ADMIN.require(403) def update_user(username): user = userManager.find_user(username) if user is not None: data = request.get_json() # change groups if "groups" in data: groups = data["groups"] userManager.change_user_groups(username, groups) # change permissions if "permissions" in data: permissions = data["permissions"] userManager.change_user_permissions(username, permissions) # change activation if "active" in data: userManager.change_user_activation( username, data["active"] in valid_boolean_trues ) return get_users() else: abort(404) @api.route("/access/users/<username>", methods=["DELETE"]) @no_firstrun_access @require_credentials_checked_recently @Permissions.ADMIN.require(403) def remove_user(username): if not userManager.enabled: return jsonify(SUCCESS) if current_user.get_name() == username: abort(400, description="You cannot delete yourself") try: userManager.remove_user(username) return get_users() except users.UnknownUser: abort(404) @api.route("/access/users/<username>/password", methods=["PUT"]) @no_firstrun_access def change_password_for_user(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.has_permission(Permissions.ADMIN) ) ): data = request.get_json() if "password" not in data or not data["password"]: abort(400, description="new password is missing") if current_user.get_name() == username: if "current" not in data or not data["current"]: abort(400, description="current password is missing") if not userManager.check_password(username, data["current"]): abort(403, description="Invalid current password") elif current_user.has_permission(Permissions.ADMIN): ensure_credentials_checked_recently() else: # this should never happen abort(403, description="You are not allowed to change this user's password") try: userManager.change_user_password(username, data["password"]) except users.UnknownUser: abort(404) return jsonify(SUCCESS) else: abort(403) @api.route("/access/users/<username>/settings", methods=["GET"]) @no_firstrun_access def get_settings_for_user(username): if ( current_user is None or current_user.is_anonymous or ( current_user.get_name() != username and not current_user.has_permission(Permissions.ADMIN) ) ): abort(403) try: return jsonify(userManager.get_all_user_settings(username)) except users.UnknownUser: abort(404) @api.route("/access/users/<username>/settings", methods=["PATCH"]) @no_firstrun_access def change_settings_for_user(username): if ( current_user is None or current_user.is_anonymous or ( current_user.get_name() != username and not current_user.has_permission(Permissions.ADMIN) ) ): abort(403) if current_user.get_name() != username: # this must be an admin, so we need to ensure credentials were checked ensure_credentials_checked_recently() data = request.get_json() try: userManager.change_user_settings(username, data) return jsonify(SUCCESS) except users.UnknownUser: abort(404) @api.route("/access/users/<username>/apikey", methods=["DELETE"]) @no_firstrun_access def delete_apikey_for_user(username): if ( current_user is not None and not current_user.is_anonymous and ( current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN) ) ): if current_user.get_name() != username: # this must be an admin, so we need to ensure credentials were checked ensure_credentials_checked_recently() try: userManager.delete_api_key(username) except users.UnknownUser: abort(404) return jsonify(SUCCESS) else: abort(403) @api.route("/access/users/<username>/apikey", methods=["POST"]) @no_firstrun_access def generate_apikey_for_user(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.has_permission(Permissions.ADMIN) ) ): if current_user.get_name() != username: # this must be an admin, so we need to ensure credentials were checked ensure_credentials_checked_recently() try: apikey = userManager.generate_api_key(username) except users.UnknownUser: abort(404) return jsonify({"apikey": apikey}) else: abort(403) def _to_external_permissions(*permissions): return list(map(lambda p: p.get_name(), permissions)) def _to_external_groups(*groups): return list(map(lambda g: g.get_name(), groups))
10,638
Python
.py
302
28.364238
103
0.657828
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,882
printer_profiles.py
OctoPrint_OctoPrint/src/octoprint/server/api/printer_profiles.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import copy from flask import abort, jsonify, request, url_for from octoprint.access.permissions import Permissions from octoprint.printer.profile import CouldNotOverwriteError, InvalidProfileError from octoprint.server import printerProfileManager from octoprint.server.api import NO_CONTENT, api, valid_boolean_trues from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking from octoprint.util import dict_merge def _lastmodified(): return printerProfileManager.last_modified def _etag(lm=None): if lm is None: lm = _lastmodified() import hashlib hash = hashlib.sha1() def hash_update(value): value = value.encode("utf-8") hash.update(value) hash_update(str(lm)) hash_update(repr(printerProfileManager.get_default())) hash_update(repr(printerProfileManager.get_current())) return hash.hexdigest() @api.route("/printerprofiles", methods=["GET"]) @with_revalidation_checking( etag_factory=_etag, lastmodified_factory=_lastmodified, unless=lambda: request.values.get("force", "false") in valid_boolean_trues, ) @no_firstrun_access @Permissions.CONNECTION.require(403) def printerProfilesList(): all_profiles = printerProfileManager.get_all() return jsonify({"profiles": _convert_profiles(all_profiles)}) @api.route("/printerprofiles", methods=["POST"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def printerProfilesAdd(): json_data = request.get_json() # Werkzeug should return 400 if invalid JSON if "profile" not in json_data: abort(400, description="profile is missing") base_profile = printerProfileManager.get_default() if "basedOn" in json_data and isinstance(json_data["basedOn"], str): other_profile = printerProfileManager.get(json_data["basedOn"]) if other_profile is not None: base_profile = other_profile if "id" in base_profile: del base_profile["id"] if "name" in base_profile: del base_profile["name"] if "default" in base_profile: del base_profile["default"] new_profile = json_data["profile"] make_default = False if "default" in new_profile: make_default = True del new_profile["default"] profile = dict_merge(base_profile, new_profile) if "id" not in profile: abort(400, description="profile.id is missing") if "name" not in profile: abort(400, description="profile.name is missing") try: saved_profile = printerProfileManager.save( profile, allow_overwrite=False, make_default=make_default, trigger_event=True ) except InvalidProfileError: abort(400, description="profile is invalid") except CouldNotOverwriteError: abort(400, description="Profile already exists and overwriting was not allowed") except Exception as e: abort(500, description="Could not save profile: %s" % str(e)) else: return jsonify({"profile": _convert_profile(saved_profile)}) @api.route("/printerprofiles/<string:identifier>", methods=["GET"]) @no_firstrun_access @Permissions.CONNECTION.require(403) def printerProfilesGet(identifier): profile = printerProfileManager.get(identifier) if profile is None: abort(404) else: return jsonify(_convert_profile(profile)) @api.route("/printerprofiles/<string:identifier>", methods=["DELETE"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def printerProfilesDelete(identifier): current_profile = printerProfileManager.get_current() if current_profile and current_profile["id"] == identifier: abort(409, description="Cannot delete currently selected profile") default_profile = printerProfileManager.get_default() if default_profile and default_profile["id"] == identifier: abort(409, description="Cannot delete default profile") printerProfileManager.remove(identifier, trigger_event=True) return NO_CONTENT @api.route("/printerprofiles/<string:identifier>", methods=["PATCH"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def printerProfilesUpdate(identifier): json_data = request.get_json() if "profile" not in json_data: abort(400, description="profile missing") profile = printerProfileManager.get(identifier) if profile is None: profile = printerProfileManager.get_default() new_profile = json_data["profile"] merged_profile = dict_merge(profile, new_profile) make_default = False if "default" in merged_profile: make_default = True del new_profile["default"] merged_profile["id"] = identifier try: saved_profile = printerProfileManager.save( merged_profile, allow_overwrite=True, make_default=make_default, trigger_event=True, ) except InvalidProfileError: abort(400, description="profile is invalid") except CouldNotOverwriteError: abort(400, description="Profile already exists and overwriting was not allowed") except Exception as e: abort(500, description="Could not save profile: %s" % str(e)) else: return jsonify({"profile": _convert_profile(saved_profile)}) def _convert_profiles(profiles): result = {} for identifier, profile in profiles.items(): result[identifier] = _convert_profile(profile) return result def _convert_profile(profile): default = printerProfileManager.get_default()["id"] current = printerProfileManager.get_current_or_default()["id"] converted = copy.deepcopy(profile) converted["resource"] = url_for( ".printerProfilesGet", identifier=profile["id"], _external=True ) converted["default"] = profile["id"] == default converted["current"] = profile["id"] == current return converted
6,112
Python
.py
144
36.833333
103
0.716745
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,883
languages.py
OctoPrint_OctoPrint/src/octoprint/server/api/languages.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os import zipfile from collections import defaultdict from flask import abort, jsonify, request from flask_babel import Locale from octoprint.access.permissions import Permissions from octoprint.plugin import plugin_manager from octoprint.server.api import api from octoprint.server.util.flask import no_firstrun_access from octoprint.settings import settings from octoprint.util import yaml @api.route("/languages", methods=["GET"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def getInstalledLanguagePacks(): translation_folder = settings().getBaseFolder("translations", check_writable=False) if not os.path.exists(translation_folder): return jsonify(language_packs={"_core": []}) core_packs = [] plugin_packs = defaultdict( lambda: {"identifier": None, "display": None, "languages": []} ) for entry in os.scandir(translation_folder): if not entry.is_dir(): continue def load_meta(path, locale): meta = {} meta_path = os.path.join(path, "meta.yaml") if os.path.isfile(meta_path): try: meta = yaml.load_from_file(path=meta_path) except Exception: logging.getLogger(__name__).exception("Could not load %s", meta_path) pass else: import datetime if "last_update" in meta and isinstance( meta["last_update"], datetime.datetime ): meta["last_update"] = ( meta["last_update"] - datetime.datetime(1970, 1, 1) ).total_seconds() loc = Locale.parse(locale) meta["locale"] = str(loc) meta["locale_display"] = loc.display_name meta["locale_english"] = loc.english_name return meta if entry.name == "_plugins": for plugin_entry in os.scandir(entry.path): if not plugin_entry.is_dir(): continue if plugin_entry.name not in plugin_manager().plugins: continue plugin_info = plugin_manager().plugins[plugin_entry.name] plugin_packs[plugin_entry.name]["identifier"] = plugin_entry.name plugin_packs[plugin_entry.name]["display"] = plugin_info.name for language_entry in os.scandir(plugin_entry.path): try: plugin_packs[plugin_entry.name]["languages"].append( load_meta(language_entry.path, language_entry.name) ) except Exception: logging.getLogger(__name__).exception( "Error while parsing metadata for language pack {} from {} for plugin {}".format( language_entry.name, language_entry.path, plugin_entry.name, ) ) continue else: try: core_packs.append(load_meta(entry.path, entry.name)) except ValueError: logging.getLogger(__name__).exception( "Core language pack {} doesn't appear to actually be one".format( entry.name ) ) except Exception: logging.getLogger(__name__).exception( "Error while parsing metadata for core language pack {} from {}".format( entry.name, entry.path ) ) result = { "_core": {"identifier": "_core", "display": "Core", "languages": core_packs} } result.update(plugin_packs) return jsonify(language_packs=result) @api.route("/languages", methods=["POST"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def uploadLanguagePack(): input_name = "file" input_upload_path = ( input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) ) input_upload_name = ( input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) ) if input_upload_path not in request.values or input_upload_name not in request.values: abort(400, description="No file included") upload_name = request.values[input_upload_name] upload_path = request.values[input_upload_path] exts = list( filter( lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar") ) ) if not len(exts): abort( 400, description="File doesn't have a valid extension for a language pack archive", ) target_path = settings().getBaseFolder("translations") if not zipfile.is_zipfile(upload_path): abort(400, description="No zip file included") if not _validate_and_install_language_pack(upload_path, target_path): abort(400, description="Invalid language pack archive") return getInstalledLanguagePacks() @api.route("/languages/<string:locale>/<string:pack>", methods=["DELETE"]) @no_firstrun_access @Permissions.SETTINGS.require(403) def deleteInstalledLanguagePack(locale, pack): if pack == "_core": target_path = os.path.join(settings().getBaseFolder("translations"), locale) else: target_path = os.path.join( settings().getBaseFolder("translations"), "_plugins", pack, locale ) if os.path.isdir(target_path): import shutil shutil.rmtree(target_path) return getInstalledLanguagePacks() def _validate_and_install_language_pack(path, target): import tempfile if not zipfile.is_zipfile(path): return False something_installed = False with tempfile.TemporaryDirectory() as temp_dir: with zipfile.ZipFile(path, mode="r") as zip: # protect against path traversal if any( map( lambda x: not os.path.abspath(os.path.join(temp_dir, x)).startswith( temp_dir + os.path.sep ), zip.namelist(), ) ): return False zip.extractall(temp_dir) something_installed = ( _validate_and_install_translations(temp_dir, target) or something_installed ) if os.path.exists(os.path.join(temp_dir, "_plugins")): something_installed = ( _validate_and_install_plugin_language_pack( os.path.join(temp_dir, "_plugins"), os.path.join(target, "_plugins") ) or something_installed ) return something_installed def _validate_and_install_plugin_language_pack(path, target): something_installed = False for entry in os.scandir(path): if not entry.is_dir(): continue something_installed = ( _validate_and_install_translations( entry.path, os.path.join(target, entry.name) ) or something_installed ) return something_installed def _validate_and_install_translations(path, target): import shutil from babel.core import Locale something_installed = False for entry in os.scandir(path): if not entry.is_dir(): continue try: loc = Locale.parse(entry.name) except Exception: continue if not os.path.isfile(os.path.join(entry.path, "meta.yaml")): continue if not os.path.isdir(os.path.join(entry.path, "LC_MESSAGES")): continue if not os.path.isfile(os.path.join(entry.path, "LC_MESSAGES", "messages.mo")): continue # looks like a valid translation folder incl. metadata, let's move it if not os.path.exists(target): os.makedirs(target) shutil.move(entry.path, os.path.join(target, str(loc))) something_installed = True return something_installed class InvalidLanguagePack(Exception): pass
8,539
Python
.py
205
30.278049
109
0.583404
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,884
timelapse.py
OctoPrint_OctoPrint/src/octoprint/server/api/timelapse.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os import threading from urllib.parse import quote as urlquote from flask import abort, jsonify, request, url_for import octoprint.timelapse import octoprint.util as util from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT, admin_permission, printer from octoprint.server.api import api from octoprint.server.util.flask import ( get_json_command_from_request, no_firstrun_access, redirect_to_tornado, with_revalidation_checking, ) from octoprint.settings import settings, valid_boolean_trues _DATA_FORMAT_VERSION = "v2" # ~~ timelapse handling _timelapse_cache_finished = [] _timelapse_cache_finished_lastmodified = None _timelapse_cache_unrendered = [] _timelapse_cache_unrendered_lastmodified = None _timelapse_cache_mutex = threading.RLock() def _config_for_timelapse(timelapse): if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse): return { "type": "zchange", "postRoll": timelapse.post_roll, "fps": timelapse.fps, "retractionZHop": timelapse.retraction_zhop, "minDelay": timelapse.min_delay, } elif timelapse is not None and isinstance( timelapse, octoprint.timelapse.TimedTimelapse ): return { "type": "timed", "postRoll": timelapse.post_roll, "fps": timelapse.fps, "interval": timelapse.interval, } else: return {"type": "off"} def _lastmodified(unrendered): lm_finished = octoprint.timelapse.last_modified_finished() if unrendered: lm_unrendered = octoprint.timelapse.last_modified_unrendered() if lm_finished is None or lm_unrendered is None: return None return max(lm_finished, lm_unrendered) return lm_finished def _etag(unrendered, lm=None): if lm is None: lm = _lastmodified(unrendered) timelapse = octoprint.timelapse.current config = _config_for_timelapse(timelapse) import hashlib hash = hashlib.sha1() def hash_update(value): value = value.encode("utf-8") hash.update(value) hash_update(str(lm)) hash_update(repr(config)) hash_update(repr(_DATA_FORMAT_VERSION)) return hash.hexdigest() @api.route("/timelapse", methods=["GET"]) @with_revalidation_checking( etag_factory=lambda lm=None: _etag( request.values.get("unrendered", "false") in valid_boolean_trues, lm=lm ), lastmodified_factory=lambda: _lastmodified( request.values.get("unrendered", "false") in valid_boolean_trues ), unless=lambda: request.values.get("force", "false") in valid_boolean_trues, ) @no_firstrun_access @Permissions.TIMELAPSE_LIST.require(403) def getTimelapseData(): timelapse = octoprint.timelapse.current config = _config_for_timelapse(timelapse) force = request.values.get("force", "false") in valid_boolean_trues unrendered = request.values.get("unrendered", "false") in valid_boolean_trues global _timelapse_cache_finished_lastmodified, _timelapse_cache_finished, _timelapse_cache_unrendered_lastmodified, _timelapse_cache_unrendered with _timelapse_cache_mutex: current_lastmodified_finished = octoprint.timelapse.last_modified_finished() current_lastmodified_unrendered = octoprint.timelapse.last_modified_unrendered() if ( not force and _timelapse_cache_finished_lastmodified == current_lastmodified_finished ): files = _timelapse_cache_finished else: files = octoprint.timelapse.get_finished_timelapses() _timelapse_cache_finished = files _timelapse_cache_finished_lastmodified = current_lastmodified_finished unrendered_files = [] if unrendered: if ( not force and _timelapse_cache_unrendered_lastmodified == current_lastmodified_unrendered ): unrendered_files = _timelapse_cache_unrendered else: unrendered_files = octoprint.timelapse.get_unrendered_timelapses() _timelapse_cache_unrendered = unrendered_files _timelapse_cache_unrendered_lastmodified = current_lastmodified_unrendered finished_list = [] for f in files: output = dict(f) output["url"] = url_for("index") + "downloads/timelapse/" + urlquote(f["name"]) if output["thumbnail"] is not None: output["thumbnail"] = ( url_for("index") + "downloads/timelapse/" + urlquote(f["thumbnail"]) ) else: output.pop("thumbnail", None) finished_list.append(output) result = { "config": config, "enabled": settings().getBoolean(["webcam", "timelapseEnabled"]), "files": finished_list, } if unrendered: result.update(unrendered=unrendered_files) return jsonify(result) @api.route("/timelapse/<filename>", methods=["GET"]) @no_firstrun_access @Permissions.TIMELAPSE_DOWNLOAD.require(403) def downloadTimelapse(filename): return redirect_to_tornado( request, url_for("index") + "downloads/timelapse/" + urlquote(filename) ) @api.route("/timelapse/<filename>", methods=["DELETE"]) @no_firstrun_access @Permissions.TIMELAPSE_DELETE.require(403) def deleteTimelapse(filename): timelapse_folder = settings().getBaseFolder("timelapse") full_path = os.path.realpath(os.path.join(timelapse_folder, filename)) thumb_path = octoprint.timelapse.create_thumbnail_path(full_path) if ( octoprint.timelapse.valid_timelapse(full_path) and full_path.startswith(os.path.realpath(timelapse_folder)) and os.path.exists(full_path) and not util.is_hidden_path(full_path) ): try: os.remove(full_path) except Exception as ex: logging.getLogger(__file__).exception( f"Error deleting timelapse file {full_path}" ) abort(500, description=f"Unexpected error: {ex}") if ( octoprint.timelapse.valid_timelapse_thumbnail(thumb_path) and thumb_path.startswith(os.path.realpath(timelapse_folder)) and os.path.exists(thumb_path) and not util.is_hidden_path(thumb_path) ): try: os.remove(thumb_path) except Exception as ex: # Do not treat this as an error, log and ignore logging.getLogger(__file__).warning( f"Unable to delete thumbnail {thumb_path} ({ex})" ) return getTimelapseData() @api.route("/timelapse/unrendered/<name>", methods=["DELETE"]) @no_firstrun_access @Permissions.TIMELAPSE_MANAGE_UNRENDERED.require(403) def deleteUnrenderedTimelapse(name): octoprint.timelapse.delete_unrendered_timelapse(name) return NO_CONTENT @api.route("/timelapse/unrendered/<name>", methods=["POST"]) @no_firstrun_access @Permissions.TIMELAPSE_MANAGE_UNRENDERED.require(403) def processUnrenderedTimelapseCommand(name): # valid file commands, dict mapping command name to mandatory parameters valid_commands = {"render": []} command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response if command == "render": if printer.is_printing() or printer.is_paused(): abort( 409, description="Printer is currently printing, cannot render timelapse" ) octoprint.timelapse.render_unrendered_timelapse(name) return NO_CONTENT @api.route("/timelapse", methods=["POST"]) @no_firstrun_access @Permissions.TIMELAPSE_ADMIN.require(403) def setTimelapseConfig(): data = request.get_json(silent=True) if data is None: data = request.values if "type" in data: config = {"type": data["type"], "postRoll": 0, "fps": 25, "options": {}} if "postRoll" in data: try: postRoll = int(data["postRoll"]) except ValueError: abort(400, description="postRoll is invalid") else: if postRoll >= 0: config["postRoll"] = postRoll else: abort(400, description="postRoll is invalid") if "fps" in data: try: fps = int(data["fps"]) except ValueError: abort(400, description="fps is invalid") else: if fps > 0: config["fps"] = fps else: abort(400, description="fps is invalid") if "interval" in data: try: interval = int(data["interval"]) except ValueError: abort(400, description="interval is invalid") else: if interval > 0: config["options"]["interval"] = interval else: abort(400, description="interval is invalid") if "retractionZHop" in data: try: retractionZHop = float(data["retractionZHop"]) except ValueError: abort(400, description="retractionZHop is invalid") else: if retractionZHop >= 0: config["options"]["retractionZHop"] = retractionZHop else: abort(400, description="retractionZHop is invalid") if "minDelay" in data: try: minDelay = float(data["minDelay"]) except ValueError: abort(400, description="minDelay is invalid") else: if minDelay > 0: config["options"]["minDelay"] = minDelay else: abort(400, description="minDelay is invalid") if ( admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues ): octoprint.timelapse.configure_timelapse(config, True) else: octoprint.timelapse.configure_timelapse(config) return getTimelapseData()
10,499
Python
.py
261
31.321839
147
0.63773
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,885
__init__.py
OctoPrint_OctoPrint/src/octoprint/server/api/__init__.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import datetime import logging from flask import ( Blueprint, Response, abort, current_app, g, jsonify, make_response, request, session, ) from flask_login import current_user, login_user, logout_user from werkzeug.exceptions import HTTPException import octoprint.access.users import octoprint.plugin import octoprint.server import octoprint.util.net as util_net from octoprint.access import auth_log from octoprint.access.permissions import Permissions from octoprint.events import Events, eventManager from octoprint.server import NO_CONTENT from octoprint.server.util import ( LoginMechanism, corsRequestHandler, corsResponseHandler, csrfRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, noCachingExceptGetResponseHandler, ) from octoprint.server.util.flask import ( get_json_command_from_request, limit, no_firstrun_access, passive_login, session_signature, to_api_credentials_seen, ) from octoprint.settings import settings as s from octoprint.settings import valid_boolean_trues from octoprint.vendor.flask_principal import Identity, identity_changed # ~~ init api blueprint, including sub modules api = Blueprint("api", __name__) from . import access as api_access # noqa: F401,E402 from . import connection as api_connection # noqa: F401,E402 from . import files as api_files # noqa: F401,E402 from . import job as api_job # noqa: F401,E402 from . import languages as api_languages # noqa: F401,E402 from . import printer as api_printer # noqa: F401,E402 from . import printer_profiles as api_printer_profiles # noqa: F401,E402 from . import settings as api_settings # noqa: F401,E402 from . import slicing as api_slicing # noqa: F401,E402 from . import system as api_system # noqa: F401,E402 from . import timelapse as api_timelapse # noqa: F401,E402 from . import users as api_users # noqa: F401,E402 VERSION = "0.1" api.after_request(noCachingExceptGetResponseHandler) api.before_request(corsRequestHandler) api.before_request(loginFromAuthorizationHeaderRequestHandler) api.before_request(loginFromApiKeyRequestHandler) api.before_request(csrfRequestHandler) api.after_request(corsResponseHandler) # ~~ data from plugins @api.route("/plugin/<string:name>", methods=["GET"]) def pluginData(name): api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations( lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin ) if not api_plugins: abort(404) if len(api_plugins) > 1: abort(500, description="More than one api provider registered, can't proceed") try: api_plugin = api_plugins[0] if api_plugin.is_api_adminonly() and not current_user.is_admin: abort(403) response = api_plugin.on_api_get(request) if response is not None: message = ( "Rewriting response from {} to use abort(msg, code) - please " "consider upgrading the implementation accordingly".format(name) ) if ( isinstance(response, Response) and response.mimetype == "text/html" and response.status_code >= 300 ): # this actually looks like an error response logging.getLogger(__name__).info(message) abort(response.status_code, description=response.data) elif ( isinstance(response, tuple) and len(response) == 2 and isinstance(response[0], (str, bytes)) and response[1] >= 300 ): # this actually looks like an error response logging.getLogger(__name__).info(message) abort(response[1], response[0]) return response return NO_CONTENT except HTTPException: raise except Exception: logging.getLogger(__name__).exception( f"Error calling SimpleApiPlugin {name}", extra={"plugin": name} ) return abort(500) # ~~ commands for plugins @api.route("/plugin/<string:name>", methods=["POST"]) @no_firstrun_access def pluginCommand(name): api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations( lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin ) if not api_plugins: abort(400) if len(api_plugins) > 1: abort(500, description="More than one api provider registered, can't proceed") api_plugin = api_plugins[0] try: valid_commands = api_plugin.get_api_commands() if valid_commands is None: abort(405) if api_plugin.is_api_adminonly() and not Permissions.ADMIN.can(): abort(403) command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response response = api_plugin.on_api_command(command, data) if response is not None: return response return NO_CONTENT except HTTPException: raise except Exception: logging.getLogger(__name__).exception( f"Error while executing SimpleApiPlugin {name}", extra={"plugin": name}, ) return abort(500) # ~~ first run setup @api.route("/setup/wizard", methods=["GET"]) def wizardState(): if ( not s().getBoolean(["server", "firstRun"]) and octoprint.server.userManager.has_been_customized() and not Permissions.ADMIN.can() ): abort(403) seen_wizards = s().get(["server", "seenWizards"]) result = {} wizard_plugins = octoprint.server.pluginManager.get_implementations( octoprint.plugin.WizardPlugin ) for implementation in wizard_plugins: name = implementation._identifier try: required = implementation.is_wizard_required() details = implementation.get_wizard_details() version = implementation.get_wizard_version() ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored( seen_wizards, implementation ) except Exception: logging.getLogger(__name__).exception( "There was an error fetching wizard " "details for {}, ignoring".format(name), extra={"plugin": name}, ) else: result[name] = { "required": required, "details": details, "version": version, "ignored": ignored, } return jsonify(result) @api.route("/setup/wizard", methods=["POST"]) def wizardFinish(): if ( not s().getBoolean(["server", "firstRun"]) and octoprint.server.userManager.has_been_customized() and not Permissions.ADMIN.can() ): abort(403) data = {} try: data = request.get_json() except Exception: abort(400) if data is None: abort(400) if "handled" not in data: abort(400) handled = data["handled"] if s().getBoolean(["server", "firstRun"]): s().setBoolean(["server", "firstRun"], False) seen_wizards = dict(s().get(["server", "seenWizards"])) wizard_plugins = octoprint.server.pluginManager.get_implementations( octoprint.plugin.WizardPlugin ) for implementation in wizard_plugins: name = implementation._identifier try: implementation.on_wizard_finish(name in handled) if name in handled: seen_wizards[name] = implementation.get_wizard_version() except Exception: logging.getLogger(__name__).exception( "There was an error finishing the " "wizard for {}, ignoring".format(name), extra={"plugin": name}, ) s().set(["server", "seenWizards"], seen_wizards) s().save() return NO_CONTENT # ~~ system state @api.route("/version", methods=["GET"]) @Permissions.STATUS.require(403) def apiVersion(): return jsonify( server=octoprint.server.VERSION, api=VERSION, text=f"OctoPrint {octoprint.server.DISPLAY_VERSION}", ) @api.route("/server", methods=["GET"]) @Permissions.STATUS.require(403) def serverStatus(): return jsonify(version=octoprint.server.VERSION, safemode=octoprint.server.safe_mode) # ~~ Login/user handling @api.route("/login", methods=["POST"]) @limit( "3/minute;5/10 minutes;10/hour", deduct_when=lambda response: response.status_code == 403, error_message="You have made too many failed login attempts. Please try again later.", ) def login(): data = request.get_json(silent=True) if not data: data = request.values if "user" in data and "pass" in data: username = data["user"] password = data["pass"] remote_addr = request.remote_addr if "remember" in data and data["remember"] in valid_boolean_trues: remember = True else: remember = False if "usersession.id" in session: _logout(current_user) user = octoprint.server.userManager.find_user(username) if user is not None: if octoprint.server.userManager.check_password(username, password): if not user.is_active: auth_log( f"Failed login attempt for user {username} from {remote_addr}, user is deactivated" ) abort(403) user = octoprint.server.userManager.login_user(user) session["usersession.id"] = user.session session["usersession.signature"] = session_signature( username, user.session ) g.user = user login_user(user, remember=remember) identity_changed.send( current_app._get_current_object(), identity=Identity(user.get_id()) ) session["login_mechanism"] = LoginMechanism.PASSWORD session["credentials_seen"] = datetime.datetime.now().timestamp() logging.getLogger(__name__).info( "Actively logging in user {} from {}".format( user.get_id(), remote_addr ) ) response = user.as_dict() response["_is_external_client"] = s().getBoolean( ["server", "ipCheck", "enabled"] ) and not util_net.is_lan_address( remote_addr, additional_private=s().get(["server", "ipCheck", "trustedSubnets"]), ) response["_login_mechanism"] = session["login_mechanism"] response["_credentials_seen"] = to_api_credentials_seen( session["credentials_seen"] ) r = make_response(jsonify(response)) r.delete_cookie("active_logout") eventManager().fire( Events.USER_LOGGED_IN, payload={"username": user.get_id()} ) auth_log(f"Logging in user {username} from {remote_addr} via credentials") return r else: auth_log( f"Failed login attempt for user {username} from {remote_addr}, wrong password" ) else: auth_log( f"Failed login attempt for user {username} from {remote_addr}, user is unknown" ) abort(403) elif "passive" in data: return passive_login() abort(400, description="Neither user and pass attributes nor passive flag present") @api.route("/logout", methods=["POST"]) def logout(): username = None if current_user: username = current_user.get_id() # logout from user manager... _logout(current_user) # ... and from flask login (and principal) logout_user() # ... and send an active logout session cookie r = make_response(jsonify(octoprint.server.userManager.anonymous_user_factory())) r.set_cookie("active_logout", "true") if username: eventManager().fire(Events.USER_LOGGED_OUT, payload={"username": username}) auth_log(f"Logging out user {username} from {request.remote_addr}") return r def _logout(user): if "usersession.id" in session: del session["usersession.id"] if "login_mechanism" in session: del session["login_mechanism"] octoprint.server.userManager.logout_user(user) @api.route("/currentuser", methods=["GET"]) def get_current_user(): return jsonify( name=current_user.get_name(), permissions=[permission.key for permission in current_user.effective_permissions], groups=[group.key for group in current_user.groups], ) # ~~ Test utils @api.route("/util/test", methods=["POST"]) @no_firstrun_access @Permissions.ADMIN.require(403) def utilTest(): valid_commands = { "path": ["path"], "url": ["url"], "server": ["host", "port"], "resolution": ["name"], "address": [], } command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response if command == "path": return _test_path(data) elif command == "url": return _test_url(data) elif command == "server": return _test_server(data) elif command == "resolution": return _test_resolution(data) elif command == "address": return _test_address(data) def _test_path(data): import os from octoprint.util.paths import normalize path = normalize(data["path"], real=False) if not path: return jsonify( path=path, exists=False, typeok=False, broken_symlink=False, access=False, result=False, ) unreal_path = path path = os.path.realpath(path) check_type = None check_access = [] if "check_type" in data and data["check_type"] in ("file", "dir"): check_type = data["check_type"] if "check_access" in data: request_check_access = data["check_access"] if not isinstance(request_check_access, list): request_check_access = list(request_check_access) check_access = [ check for check in request_check_access if check in ("r", "w", "x") ] allow_create_dir = data.get("allow_create_dir", False) and check_type == "dir" check_writable_dir = data.get("check_writable_dir", False) and check_type == "dir" if check_writable_dir and "w" not in check_access: check_access.append("w") # check if path exists exists = os.path.exists(path) if not exists: if os.path.islink(unreal_path): # broken symlink, see #2644 logging.getLogger(__name__).error( "{} is a broken symlink pointing at non existing {}".format( unreal_path, path ) ) return jsonify( path=unreal_path, exists=False, typeok=False, broken_symlink=True, access=False, result=False, ) elif check_type == "dir" and allow_create_dir: try: os.makedirs(path) except Exception: logging.getLogger(__name__).exception( f"Error while trying to create {path}" ) return jsonify( path=path, exists=False, typeok=False, broken_symlink=False, access=False, result=False, ) else: exists = True # check path type type_mapping = {"file": os.path.isfile, "dir": os.path.isdir} if check_type: typeok = type_mapping[check_type](path) else: typeok = exists # check if path allows requested access access_mapping = {"r": os.R_OK, "w": os.W_OK, "x": os.X_OK} if check_access: mode = 0 for a in map(lambda x: access_mapping[x], check_access): mode |= a access = os.access(path, mode) else: access = exists if check_writable_dir and check_type == "dir": try: test_path = os.path.join(path, ".testballoon.txt") with open(test_path, "wb") as f: f.write(b"Test") os.remove(test_path) except Exception: logging.getLogger(__name__).exception( f"Error while testing if {path} is really writable" ) return jsonify( path=path, exists=exists, typeok=typeok, broken_symlink=False, access=False, result=False, ) return jsonify( path=path, exists=exists, typeok=typeok, broken_symlink=False, access=access, result=exists and typeok and access, ) def _test_url(data): import requests from octoprint import util as util class StatusCodeRange: def __init__(self, start=None, end=None): self.start = start self.end = end def __contains__(self, item): if not isinstance(item, int): return False if self.start and self.end: return self.start <= item < self.end elif self.start: return self.start <= item elif self.end: return item < self.end else: return False def as_dict(self): return {"start": self.start, "end": self.end} status_ranges = { "informational": StatusCodeRange(start=100, end=200), "success": StatusCodeRange(start=200, end=300), "redirection": StatusCodeRange(start=300, end=400), "client_error": StatusCodeRange(start=400, end=500), "server_error": StatusCodeRange(start=500, end=600), "normal": StatusCodeRange(end=400), "error": StatusCodeRange(start=400, end=600), "any": StatusCodeRange(start=100), "timeout": StatusCodeRange(start=0, end=1), } url = data["url"] method = data.get("method", "HEAD") timeout = 3.0 valid_ssl = True check_status = [status_ranges["normal"]] content_type_whitelist = None content_type_blacklist = None if "timeout" in data: try: timeout = float(data["timeout"]) except Exception: abort(400, description="timeout is invalid") if "validSsl" in data: valid_ssl = data["validSsl"] in valid_boolean_trues if "status" in data: request_status = data["status"] if not isinstance(request_status, list): request_status = [request_status] check_status = [] for rs in request_status: if isinstance(rs, int): check_status.append([rs]) else: if rs in status_ranges: check_status.append(status_ranges[rs]) else: code = requests.codes[rs] if code is not None: check_status.append([code]) if "content_type_whitelist" in data: if not isinstance(data["content_type_whitelist"], (list, tuple)): abort(400, description="content_type_whitelist must be a list of mime types") content_type_whitelist = list( map(util.parse_mime_type, data["content_type_whitelist"]) ) if "content_type_blacklist" in data: if not isinstance(data["content_type_whitelist"], (list, tuple)): abort(400, description="content_type_blacklist must be a list of mime types") content_type_blacklist = list( map(util.parse_mime_type, data["content_type_blacklist"]) ) response_result = None outcome = True status = 0 try: with requests.request( method=method, url=url, timeout=timeout, verify=valid_ssl, stream=True ) as response: status = response.status_code outcome = outcome and any(map(lambda x: status in x, check_status)) content_type = response.headers.get("content-type") response_result = { "headers": dict(response.headers), "content_type": content_type, } if not content_type and data.get("content_type_guess") in valid_boolean_trues: content = response.content content_type = util.guess_mime_type(bytearray(content)) if not content_type: content_type = "application/octet-stream" response_result = {"assumed_content_type": content_type} parsed_content_type = util.parse_mime_type(content_type) in_whitelist = content_type_whitelist is None or any( map( lambda x: util.mime_type_matches(parsed_content_type, x), content_type_whitelist, ) ) in_blacklist = content_type_blacklist is not None and any( map( lambda x: util.mime_type_matches(parsed_content_type, x), content_type_blacklist, ) ) if not in_whitelist or in_blacklist: # we don't support this content type response.close() outcome = False elif "response" in data and ( data["response"] in valid_boolean_trues or data["response"] in ("json", "bytes") ): if data["response"] == "json": content = response.json() else: import base64 content = base64.standard_b64encode(response.content) response_result["content"] = content except Exception: logging.getLogger(__name__).exception( f"Error while running a test {method} request on {url}" ) outcome = False result = {"url": url, "status": status, "result": outcome} if response_result: result["response"] = response_result return jsonify(**result) def _test_server(data): host = data["host"] try: port = int(data["port"]) except Exception: abort(400, description="Invalid value for port") timeout = 3.05 if "timeout" in data: try: timeout = float(data["timeout"]) except Exception: abort(400, description="Invalid value for timeout") protocol = data.get("protocol", "tcp") if protocol not in ("tcp", "udp"): abort(400, description="Invalid value for protocol") from octoprint.util import server_reachable reachable = server_reachable(host, port, timeout=timeout, proto=protocol) result = {"host": host, "port": port, "protocol": protocol, "result": reachable} return jsonify(**result) def _test_resolution(data): name = data["name"] from octoprint.util.net import resolve_host resolvable = len(resolve_host(name)) > 0 result = {"name": name, "result": resolvable} return jsonify(**result) def _test_address(data): import netaddr from octoprint.util.net import get_lan_ranges, sanitize_address remote_addr = data.get("address") if not remote_addr: remote_addr = request.remote_addr remote_addr = sanitize_address(remote_addr) ip = netaddr.IPAddress(remote_addr) lan_subnets = get_lan_ranges() detected_subnet = None for subnet in lan_subnets: if ip in subnet: detected_subnet = subnet break result = { "is_lan_address": detected_subnet is not None, "address": remote_addr, } if detected_subnet is not None: result["subnet"] = str(detected_subnet) return jsonify(**result)
24,684
Python
.py
645
28.64031
107
0.598367
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,886
printer.py
OctoPrint_OctoPrint/src/octoprint/server/api/printer.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import re from flask import Response, abort, jsonify, request from octoprint.access.permissions import Permissions from octoprint.printer import UnknownScript from octoprint.server import NO_CONTENT, printer, printerProfileManager from octoprint.server.api import api from octoprint.server.util.flask import get_json_command_from_request, no_firstrun_access from octoprint.settings import settings, valid_boolean_trues # ~~ Printer @api.route("/printer", methods=["GET"]) @Permissions.STATUS.require(403) def printerState(): if not printer.is_operational(): abort(409, description="Printer is not operational") # process excludes excludes = [] if "exclude" in request.values: excludeStr = request.values["exclude"] if len(excludeStr.strip()) > 0: excludes = list( filter( lambda x: x in ["temperature", "sd", "state"], map(lambda x: x.strip(), excludeStr.split(",")), ) ) result = {} # add temperature information if "temperature" not in excludes: processor = lambda x: x heated_bed = printerProfileManager.get_current_or_default()["heatedBed"] heated_chamber = printerProfileManager.get_current_or_default()["heatedChamber"] if not heated_bed and not heated_chamber: processor = _keep_tools elif not heated_bed: processor = _delete_bed elif not heated_chamber: processor = _delete_chamber result.update({"temperature": _get_temperature_data(processor)}) # add sd information if "sd" not in excludes and settings().getBoolean(["feature", "sdSupport"]): result.update({"sd": {"ready": printer.is_sd_ready()}}) # add state information if "state" not in excludes: state = printer.get_current_data()["state"] result.update({"state": state}) return jsonify(result) # ~~ Tool @api.route("/printer/tool", methods=["POST"]) @no_firstrun_access @Permissions.CONTROL.require(403) def printerToolCommand(): if not printer.is_operational(): abort(409, description="Printer is not operational") valid_commands = { "select": ["tool"], "target": ["targets"], "offset": ["offsets"], "extrude": ["amount"], "flowrate": ["factor"], } command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response validation_regex = re.compile(r"tool\d+") tags = {"source:api", "api:printer.tool"} ##~~ tool selection if command == "select": tool = data["tool"] if not isinstance(tool, str) or re.match(validation_regex, tool) is None: abort(400, description="tool is invalid") printer.change_tool(tool, tags=tags) ##~~ temperature elif command == "target": targets = data["targets"] # make sure the targets are valid and the values are numbers validated_values = {} for tool, value in targets.items(): if re.match(validation_regex, tool) is None: abort(400, description="targets contains invalid tool") if not isinstance(value, (int, float)): abort(400, description="targets contains invalid value") validated_values[tool] = value # perform the actual temperature commands for tool in validated_values.keys(): printer.set_temperature(tool, validated_values[tool], tags=tags) ##~~ temperature offset elif command == "offset": offsets = data["offsets"] # make sure the targets are valid, the values are numbers and in the range [-50, 50] validated_values = {} for tool, value in offsets.items(): if re.match(validation_regex, tool) is None: abort(400, description="offsets contains invalid tool") if not isinstance(value, (int, float)) or not -50 <= value <= 50: abort(400, description="offsets contains invalid value") validated_values[tool] = value # set the offsets printer.set_temperature_offset(validated_values) ##~~ extrusion elif command == "extrude": if printer.is_printing(): # do not extrude when a print job is running abort(409, description="Printer is currently printing") amount = data["amount"] speed = data.get("speed", None) if not isinstance(amount, (int, float)): abort(400, description="amount is invalid") printer.extrude(amount, speed=speed, tags=tags) elif command == "flowrate": factor = data["factor"] if not isinstance(factor, (int, float)): abort(400, description="factor is invalid") try: printer.flow_rate(factor, tags=tags) except ValueError: abort(400, description="factor is invalid") return NO_CONTENT @api.route("/printer/tool", methods=["GET"]) @no_firstrun_access @Permissions.STATUS.require(403) def printerToolState(): if not printer.is_operational(): abort(409, description="Printer is not operational") return jsonify(_get_temperature_data(_keep_tools)) ##~~ Heated bed @api.route("/printer/bed", methods=["POST"]) @no_firstrun_access @Permissions.CONTROL.require(403) def printerBedCommand(): if not printer.is_operational(): abort(409, description="Printer is not operational") if not printerProfileManager.get_current_or_default()["heatedBed"]: abort(409, description="Printer does not have a heated bed") valid_commands = {"target": ["target"], "offset": ["offset"]} command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response tags = {"source:api", "api:printer.bed"} ##~~ temperature if command == "target": target = data["target"] # make sure the target is a number if not isinstance(target, (int, float)): abort(400, description="target is invalid") # perform the actual temperature command printer.set_temperature("bed", target, tags=tags) ##~~ temperature offset elif command == "offset": offset = data["offset"] # make sure the offset is valid if not isinstance(offset, (int, float)) or not -50 <= offset <= 50: abort(400, description="offset is invalid") # set the offsets printer.set_temperature_offset({"bed": offset}) return NO_CONTENT @api.route("/printer/bed", methods=["GET"]) @no_firstrun_access @Permissions.STATUS.require(403) def printerBedState(): if not printer.is_operational(): abort(409, description="Printer is not operational") if not printerProfileManager.get_current_or_default()["heatedBed"]: abort(409, description="Printer does not have a heated bed") data = _get_temperature_data(_keep_bed) if isinstance(data, Response): return data else: return jsonify(data) ##~~ Heated chamber @api.route("/printer/chamber", methods=["POST"]) @no_firstrun_access @Permissions.CONTROL.require(403) def printerChamberCommand(): if not printer.is_operational(): abort(409, description="Printer is not operational") if not printerProfileManager.get_current_or_default()["heatedChamber"]: abort(409, description="Printer does not have a heated chamber") valid_commands = {"target": ["target"], "offset": ["offset"]} command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response tags = {"source:api", "api:printer.chamber"} ##~~ temperature if command == "target": target = data["target"] # make sure the target is a number if not isinstance(target, (int, float)): abort(400, description="target is invalid") # perform the actual temperature command printer.set_temperature("chamber", target, tags=tags) ##~~ temperature offset elif command == "offset": offset = data["offset"] # make sure the offset is valid if not isinstance(offset, (int, float)) or not -50 <= offset <= 50: abort(400, description="offset is invalid") # set the offsets printer.set_temperature_offset({"chamber": offset}) return NO_CONTENT @api.route("/printer/chamber", methods=["GET"]) @no_firstrun_access @Permissions.STATUS.require(403) def printerChamberState(): if not printer.is_operational(): abort(409, description="Printer is not operational") if not printerProfileManager.get_current_or_default()["heatedChamber"]: abort(409, description="Printer does not have a heated chamber") data = _get_temperature_data(_keep_chamber) if isinstance(data, Response): return data else: return jsonify(data) ##~~ Print head @api.route("/printer/printhead", methods=["POST"]) @no_firstrun_access @Permissions.CONTROL.require(403) def printerPrintheadCommand(): valid_commands = {"jog": [], "home": ["axes"], "feedrate": ["factor"]} command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response if not printer.is_operational() or (printer.is_printing() and command != "feedrate"): # do not jog when a print job is running or we don't have a connection abort(409, description="Printer is not operational or currently printing") tags = {"source:api", "api:printer.printhead"} valid_axes = ["x", "y", "z"] ##~~ jog command if command == "jog": # validate all jog instructions, make sure that the values are numbers validated_values = {} for axis in valid_axes: if axis in data: value = data[axis] if not isinstance(value, (int, float)): abort(400, description="axis value is invalid") validated_values[axis] = value absolute = "absolute" in data and data["absolute"] in valid_boolean_trues speed = data.get("speed", None) # execute the jog commands printer.jog(validated_values, relative=not absolute, speed=speed, tags=tags) ##~~ home command elif command == "home": validated_values = [] axes = data["axes"] for axis in axes: if axis not in valid_axes: abort(400, description="axis is invalid") validated_values.append(axis) # execute the home command printer.home(validated_values, tags=tags) elif command == "feedrate": factor = data["factor"] if not isinstance(factor, (int, float)): abort(400, description="factor is invalid") try: printer.feed_rate(factor, tags=tags) except ValueError: abort(400, description="factor is invalid") return NO_CONTENT ##~~ SD Card @api.route("/printer/sd", methods=["POST"]) @no_firstrun_access @Permissions.CONTROL.require(403) def printerSdCommand(): if not settings().getBoolean(["feature", "sdSupport"]): abort(404, description="SD support is disabled") if not printer.is_operational() or printer.is_printing() or printer.is_paused(): abort(409, description="Printer is not operational or currently busy") valid_commands = {"init": [], "refresh": [], "release": []} command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response tags = {"source:api", "api:printer.sd"} if command == "init": printer.init_sd_card(tags=tags) elif command == "refresh": printer.refresh_sd_files(tags=tags) elif command == "release": printer.release_sd_card(tags=tags) return NO_CONTENT @api.route("/printer/sd", methods=["GET"]) @no_firstrun_access @Permissions.STATUS.require(403) def printerSdState(): if not settings().getBoolean(["feature", "sdSupport"]): abort(404, description="SD support is disabled") return jsonify(ready=printer.is_sd_ready()) ##~~ Commands @api.route("/printer/command", methods=["POST"]) @no_firstrun_access @Permissions.CONTROL.require(403) def printerCommand(): if not printer.is_operational(): abort(409, description="Printer is not operational") data = request.get_json() if "command" in data and "commands" in data: abort(400, description="'command' and 'commands' are mutually exclusive") elif ("command" in data or "commands" in data) and "script" in data: abort(400, description="'command'/'commands' and 'script' are mutually exclusive") elif not ("command" in data or "commands" in data or "script" in data): abort(400, description="Need one of 'command', 'commands' or 'script'") parameters = {} if "parameters" in data: parameters = data["parameters"] tags = {"source:api", "api:printer.command"} if "command" in data or "commands" in data: if "command" in data: commands = [data["command"]] else: if not isinstance(data["commands"], (list, tuple)): abort(400, description="commands is invalid") commands = data["commands"] commandsToSend = [] for command in commands: commandToSend = command if len(parameters) > 0: commandToSend = command % parameters commandsToSend.append(commandToSend) printer.commands(commandsToSend, tags=tags) elif "script" in data: script_name = data["script"] context = {"parameters": parameters} if "context" in data: context["context"] = data["context"] try: printer.script(script_name, context=context, tags=tags) except UnknownScript: abort(404, description="Unknown script") return NO_CONTENT @api.route("/printer/command/custom", methods=["GET"]) @no_firstrun_access @Permissions.CONTROL.require(403) def getCustomControls(): customControls = settings().get(["controls"]) return jsonify(controls=customControls) def _get_temperature_data(preprocessor): if not printer.is_operational(): abort(409, description="Printer is not operational") tempData = printer.get_current_temperatures() if "history" in request.values and request.values["history"] in valid_boolean_trues: history = printer.get_temperature_history() limit = 300 if "limit" in request.values and str(request.values["limit"]).isnumeric(): limit = int(request.values["limit"]) limit = min(limit, len(history)) tempData.update( {"history": list(map(lambda x: preprocessor(x), history[-limit:]))} ) return preprocessor(tempData) @api.route("/printer/error", methods=["GET"]) @no_firstrun_access @Permissions.STATUS.require(403) def getLastPrinterError(): error_info = printer.error_info if error_info is None: return jsonify(error="", reason="") if not Permissions.MONITOR_TERMINAL.can() and "logs" in error_info: del error_info["logs"] return jsonify(**error_info) def _keep_tools(x): return _delete_from_data(x, lambda k: not k.startswith("tool") and k != "history") def _keep_bed(x): return _delete_from_data(x, lambda k: k != "bed" and k != "history") def _delete_bed(x): return _delete_from_data(x, lambda k: k == "bed") def _keep_chamber(x): return _delete_from_data(x, lambda k: k != "chamber" and k != "history") def _delete_chamber(x): return _delete_from_data(x, lambda k: k == "chamber") def _delete_from_data(x, key_matcher): data = dict(x) # must make list of keys first to avoid # RuntimeError: dictionary changed size during iteration for k in list(data.keys()): if key_matcher(k): del data[k] return data
16,387
Python
.py
380
35.823684
103
0.653034
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,887
system.py
OctoPrint_OctoPrint/src/octoprint/server/api/system.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import collections import logging import re import threading import psutil from flask import abort, jsonify, request, url_for from flask_babel import gettext from octoprint.access.permissions import Permissions from octoprint.logging import prefix_multilines from octoprint.plugin import plugin_manager from octoprint.server import NO_CONTENT from octoprint.server.api import api from octoprint.server.util.flask import no_firstrun_access from octoprint.settings import settings as s from octoprint.systemcommands import system_command_manager from octoprint.util.commandline import CommandlineCaller @api.route("/system/usage", methods=["GET"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def readUsageForFolders(): return jsonify(usage=_usageForFolders()) @api.route("/system/info", methods=["GET"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def getSystemInfo(): from octoprint.cli.systeminfo import get_systeminfo from octoprint.server import ( connectivityChecker, environmentDetector, printer, safe_mode, ) from octoprint.util import dict_flatten systeminfo = get_systeminfo( environmentDetector, connectivityChecker, s(), { "browser.user_agent": request.headers.get("User-Agent"), "octoprint.safe_mode": safe_mode is not None, "systeminfo.generator": "systemapi", }, ) if printer and printer.is_operational(): firmware_info = printer.firmware_info if firmware_info: systeminfo.update( dict_flatten({"firmware": firmware_info["name"]}, prefix="printer") ) return jsonify(systeminfo=systeminfo) @api.route("/system/startup", methods=["GET"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def getStartupInformation(): from octoprint.server import safe_mode from octoprint.settings import settings result = {} if safe_mode is not None: result["safe_mode"] = safe_mode flagged_basefolders = settings().flagged_basefolders if flagged_basefolders: result["flagged_basefolders"] = flagged_basefolders return jsonify(startup=result) def _usageForFolders(): data = {} for folder_name in s().get(["folder"]).keys(): path = s().getBaseFolder(folder_name, check_writable=False) if path is not None: usage = psutil.disk_usage(path) data[folder_name] = {"free": usage.free, "total": usage.total} return data @api.route("/system", methods=["POST"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def performSystemAction(): logging.getLogger(__name__).warning( f"Deprecated API call to /api/system made by {request.remote_addr}, should be migrated to use /system/commands/custom/<action>" ) data = request.get_json(silent=True) if data is None: data = request.values if "action" not in data: abort(400, description="action is missing") return executeSystemCommand("custom", data["action"]) @api.route("/system/commands", methods=["GET"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def retrieveSystemCommands(): return jsonify( core=_to_client_specs(_get_core_command_specs()), plugin=_to_client_specs(_get_plugin_command_specs()), custom=_to_client_specs(_get_custom_command_specs()), ) @api.route("/system/commands/<string:source>", methods=["GET"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def retrieveSystemCommandsForSource(source): if source == "core": specs = _get_core_command_specs() elif source == "custom": specs = _get_custom_command_specs() elif source == "plugin": specs = _get_plugin_command_specs() else: abort(404) return jsonify(_to_client_specs(specs)) @api.route("/system/commands/<string:source>/<string:command>", methods=["POST"]) @no_firstrun_access @Permissions.SYSTEM.require(403) def executeSystemCommand(source, command): logger = logging.getLogger(__name__) if command == "divider": abort(400, description="Dividers cannot be executed") command_spec = _get_command_spec(source, command) if not command_spec: abort(404) if "command" not in command_spec: abort( 500, description="Command does not define a command to execute, can't proceed" ) do_async = command_spec.get("async", False) do_ignore = command_spec.get("ignore", False) debug = command_spec.get("debug", False) if logger.isEnabledFor(logging.DEBUG) or debug: logger.info( "Performing command for {}:{}: {}".format( source, command, command_spec["command"] ) ) else: logger.info(f"Performing command for {source}:{command}") try: if "before" in command_spec and callable(command_spec["before"]): command_spec["before"]() except Exception as e: if not do_ignore: error = f'Command "before" for {source}:{command} failed: {e}' logger.warning(error) abort(500, description=error) try: def execute(): # we run this with shell=True since we have to trust whatever # our admin configured as command and since we want to allow # shell-alike handling here... return_code, stdout_lines, stderr_lines = CommandlineCaller().call( command_spec["command"], shell=True ) if not do_ignore and return_code != 0: stdout = "\n".join(stdout_lines) stderr = "\n".join(stderr_lines) error = f"Command for {source}:{command} failed with return code {return_code}:\n\nSTDOUT:\n{stdout}\n\nSTDERR:\n{stderr}" logger.warning(prefix_multilines(error, prefix="! ")) if not do_async: raise CommandFailed(error) if do_async: thread = threading.Thread(target=execute) thread.daemon = True thread.start() else: try: execute() except CommandFailed as exc: abort(500, exc.error) except Exception as e: if not do_ignore: error = f"Command for {source}:{command} failed: {e}" logger.warning(error) abort(500, error) return NO_CONTENT def _to_client_specs(specs): result = list() for spec in specs.values(): if "action" not in spec or "source" not in spec: continue copied = { k: v for k, v in spec.items() if k in ("source", "action", "name", "confirm") } copied["resource"] = url_for( ".executeSystemCommand", source=spec["source"], command=spec["action"], _external=True, ) result.append(copied) return result def _get_command_spec(source, action): if source == "core": return _get_core_command_spec(action) elif source == "custom": return _get_custom_command_spec(action) elif source == "plugin": return _get_plugin_command_spec(action) else: return None def _get_core_command_specs(): def enable_safe_mode(): s().set(["server", "startOnceInSafeMode"], True) s().save() commands = collections.OrderedDict( shutdown={ "command": system_command_manager().get_system_shutdown_command(), "name": gettext("Shutdown system"), "confirm": gettext( "<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)." ), }, reboot={ "command": system_command_manager().get_system_restart_command(), "name": gettext("Reboot system"), "confirm": gettext( "<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)." ), }, restart={ "command": system_command_manager().get_server_restart_command(), "name": gettext("Restart OctoPrint"), "confirm": gettext( "<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)." ), }, restart_safe={ "command": system_command_manager().get_server_restart_command(), "name": gettext("Restart OctoPrint in safe mode"), "confirm": gettext( "<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)." ), "before": enable_safe_mode, }, ) available_commands = collections.OrderedDict() for action, spec in commands.items(): if not spec["command"]: continue spec.update({"action": action, "source": "core", "async": True, "debug": True}) available_commands[action] = spec return available_commands def _get_core_command_spec(action): available_actions = _get_core_command_specs() if action not in available_actions: logging.getLogger(__name__).warning( "Command for core action {} is not configured, you need to configure the command before it can be used".format( action ) ) return None return available_actions[action] _plugin_action_regex = re.compile(r"[a-z0-9_-]+") def _get_plugin_command_specs(plugin=None): specs = collections.OrderedDict() hooks = plugin_manager().get_hooks("octoprint.system.additional_commands") if plugin is not None: if plugin in hooks: hooks = {plugin: hooks[plugin]} else: hooks = {} for name, hook in hooks.items(): try: plugin_specs = hook() for spec in plugin_specs: action = spec.get("action") if ( not action or action == "divider" or not _plugin_action_regex.match(action) ): continue action = name.lower() + ":" + action copied = dict(spec) copied["source"] = "plugin" copied["action"] = action specs[action] = copied except Exception: logging.getLogger(__name__).exception( f"Error while fetching additional actions from plugin {name}", extra={"plugin": name}, ) return specs def _get_plugin_command_spec(action): plugin = action.split(":", 1)[0] available_actions = _get_plugin_command_specs(plugin=plugin) return available_actions.get(action) def _get_custom_command_specs(): specs = collections.OrderedDict() dividers = 0 for spec in s().get(["system", "actions"]): if "action" not in spec: continue copied = dict(spec) copied["source"] = "custom" action = spec["action"] if action == "divider": dividers += 1 action = f"divider_{dividers}" specs[action] = copied return specs def _get_custom_command_spec(action): available_actions = _get_custom_command_specs() return available_actions.get(action) class CommandFailed(Exception): def __init__(self, error): self.error = error
12,357
Python
.py
303
32.39604
289
0.633344
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,888
job.py
OctoPrint_OctoPrint/src/octoprint/server/api/job.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import abort, jsonify, request from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT, current_user, printer from octoprint.server.api import api from octoprint.server.util.flask import get_json_command_from_request, no_firstrun_access @api.route("/job", methods=["POST"]) @no_firstrun_access def controlJob(): if not printer.is_operational(): abort(409, description="Printer is not operational") valid_commands = {"start": [], "restart": [], "pause": [], "cancel": []} command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response activePrintjob = printer.is_printing() or printer.is_paused() tags = {"source:api", "api:job"} user = current_user.get_name() with Permissions.PRINT.require(403): if command == "start": if activePrintjob: abort( 409, description="Printer already has an active print job, did you mean 'restart'?", ) printer.start_print(tags=tags, user=user) elif command == "restart": if not printer.is_paused(): abort( 409, description="Printer does not have an active print job or is not paused", ) printer.start_print(tags=tags, user=user) elif command == "pause": if not activePrintjob: abort( 409, description="Printer is neither printing nor paused, 'pause' command cannot be performed", ) action = data.get("action", "toggle") if action == "toggle": printer.toggle_pause_print(tags=tags, user=user) elif action == "pause": printer.pause_print(tags=tags, user=user) elif action == "resume": printer.resume_print(tags=tags, user=user) else: abort(400, description="Unknown action") elif command == "cancel": if not activePrintjob: abort( 409, description="Printer is neither printing nor paused, 'cancel' command cannot be performed", ) printer.cancel_print(tags=tags, user=user) return NO_CONTENT @api.route("/job", methods=["GET"]) @Permissions.STATUS.require(403) def jobState(): currentData = printer.get_current_data() response = { "job": currentData["job"], "progress": currentData["progress"], "state": currentData["state"]["text"], } if currentData["state"]["error"]: response["error"] = currentData["state"]["error"] return jsonify(**response)
3,065
Python
.py
70
33.542857
111
0.600671
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,889
connection.py
OctoPrint_OctoPrint/src/octoprint/server/api/connection.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import abort, jsonify, request from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT, printer, printerProfileManager from octoprint.server.api import api from octoprint.server.util.flask import get_json_command_from_request, no_firstrun_access from octoprint.settings import settings @api.route("/connection", methods=["GET"]) @Permissions.STATUS.require(403) def connectionState(): state, port, baudrate, printer_profile = printer.get_current_connection() current = { "state": state, "port": port, "baudrate": baudrate, "printerProfile": printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default", } return jsonify({"current": current, "options": _get_options()}) @api.route("/connection", methods=["POST"]) @no_firstrun_access @Permissions.CONNECTION.require(403) def connectionCommand(): valid_commands = {"connect": [], "disconnect": [], "fake_ack": []} command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response if command == "connect": connection_options = printer.__class__.get_connection_options() port = None baudrate = None printerProfile = None if "port" in data: port = data["port"] if port not in connection_options["ports"] and port != "AUTO": abort(400, description="port is invalid") if "baudrate" in data: baudrate = data["baudrate"] if baudrate not in connection_options["baudrates"] and baudrate != 0: abort(400, description="baudrate is invalid") if "printerProfile" in data: printerProfile = data["printerProfile"] if not printerProfileManager.exists(printerProfile): abort(400, description="printerProfile is invalid") if "save" in data and data["save"]: settings().set(["serial", "port"], port) settings().setInt(["serial", "baudrate"], baudrate) printerProfileManager.set_default(printerProfile) if "autoconnect" in data: settings().setBoolean(["serial", "autoconnect"], data["autoconnect"]) settings().save() printer.connect(port=port, baudrate=baudrate, profile=printerProfile) elif command == "disconnect": printer.disconnect() elif command == "fake_ack": printer.fake_ack() return NO_CONTENT def _get_options(): connection_options = printer.__class__.get_connection_options() profile_options = printerProfileManager.get_all() default_profile = printerProfileManager.get_default() options = { "ports": connection_options["ports"], "baudrates": connection_options["baudrates"], "printerProfiles": [ { "id": printer_profile["id"], "name": printer_profile["name"] if "name" in printer_profile else printer_profile["id"], } for printer_profile in profile_options.values() if "id" in printer_profile ], "portPreference": connection_options["portPreference"], "baudratePreference": connection_options["baudratePreference"], "printerProfilePreference": default_profile["id"] if "id" in default_profile else None, } return options
3,734
Python
.py
84
36.345238
103
0.650702
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,890
files.py
OctoPrint_OctoPrint/src/octoprint/server/api/files.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import hashlib import logging import os import threading from urllib.parse import quote as urlquote import psutil from flask import abort, jsonify, make_response, request, url_for import octoprint.filemanager import octoprint.filemanager.storage import octoprint.filemanager.util import octoprint.slicing from octoprint.access.permissions import Permissions from octoprint.events import Events from octoprint.filemanager.destinations import FileDestinations from octoprint.filemanager.storage import StorageError from octoprint.server import ( NO_CONTENT, current_user, eventManager, fileManager, printer, slicingManager, ) from octoprint.server.api import api from octoprint.server.util.flask import ( get_json_command_from_request, no_firstrun_access, with_revalidation_checking, ) from octoprint.settings import settings, valid_boolean_trues from octoprint.util import sv, time_this # ~~ GCODE file handling _file_cache = {} _file_cache_mutex = threading.RLock() _DATA_FORMAT_VERSION = "v2" def _clear_file_cache(): with _file_cache_mutex: _file_cache.clear() def _create_lastmodified(path, recursive): path = path[len("/api/files") :] if path.startswith("/"): path = path[1:] if path == "": # all storages involved lms = [0] for storage in fileManager.registered_storages: try: lms.append(fileManager.last_modified(storage, recursive=recursive)) except Exception: logging.getLogger(__name__).exception( "There was an error retrieving the last modified data from storage {}".format( storage ) ) lms.append(None) if any(filter(lambda x: x is None, lms)): # we return None if ANY of the involved storages returned None return None # if we reach this point, we return the maximum of all dates return max(lms) else: if "/" in path: storage, path_in_storage = path.split("/", 1) else: storage = path path_in_storage = None try: return fileManager.last_modified( storage, path=path_in_storage, recursive=recursive ) except Exception: logging.getLogger(__name__).exception( "There was an error retrieving the last modified data from storage {} and path {}".format( storage, path_in_storage ) ) return None def _create_etag(path, filter, recursive, lm=None): if lm is None: lm = _create_lastmodified(path, recursive) if lm is None: return None hash = hashlib.sha1() def hash_update(value): value = value.encode("utf-8") hash.update(value) hash_update(str(lm)) hash_update(str(filter)) hash_update(str(recursive)) path = path[len("/api/files") :] if path.startswith("/"): path = path[1:] if "/" in path: storage, _ = path.split("/", 1) else: storage = path if path == "" or storage == FileDestinations.SDCARD: # include sd data in etag hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: sv(x["name"])))) hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format return hash.hexdigest() @api.route("/files", methods=["GET"]) @Permissions.FILES_LIST.require(403) @with_revalidation_checking( etag_factory=lambda lm=None: _create_etag( request.path, request.values.get("filter", False), request.values.get("recursive", False), lm=lm, ), lastmodified_factory=lambda: _create_lastmodified( request.path, request.values.get("recursive", False) ), unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False), ) def readGcodeFiles(): filter = request.values.get("filter", False) recursive = request.values.get("recursive", "false") in valid_boolean_trues force = request.values.get("force", "false") in valid_boolean_trues files = _getFileList( FileDestinations.LOCAL, filter=filter, recursive=recursive, allow_from_cache=not force, ) files.extend(_getFileList(FileDestinations.SDCARD, allow_from_cache=not force)) usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False)) return jsonify(files=files, free=usage.free, total=usage.total) @api.route("/files/test", methods=["POST"]) @Permissions.FILES_LIST.require(403) def runFilesTest(): valid_commands = { "sanitize": ["storage", "path", "filename"], "exists": ["storage", "path", "filename"], } command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response def sanitize(storage, path, filename): sanitized_path = fileManager.sanitize_path(storage, path) sanitized_name = fileManager.sanitize_name(storage, filename) joined = fileManager.join_path(storage, sanitized_path, sanitized_name) return sanitized_path, sanitized_name, joined if command == "sanitize": _, _, sanitized = sanitize(data["storage"], data["path"], data["filename"]) return jsonify(sanitized=sanitized) elif command == "exists": storage = data["storage"] path = data["path"] filename = data["filename"] sanitized_path, _, sanitized = sanitize(storage, path, filename) exists = _getFileDetails(storage, sanitized) if exists: suggestion = filename name, ext = os.path.splitext(filename) counter = 0 while fileManager.file_exists( storage, fileManager.join_path( storage, sanitized_path, fileManager.sanitize_name(storage, suggestion), ), ): counter += 1 suggestion = f"{name}_{counter}{ext}" return jsonify( exists=True, suggestion=suggestion, size=exists.get("size"), date=exists.get("date"), ) else: return jsonify(exists=False) @api.route("/files/<string:origin>", methods=["GET"]) @Permissions.FILES_LIST.require(403) @with_revalidation_checking( etag_factory=lambda lm=None: _create_etag( request.path, request.values.get("filter", False), request.values.get("recursive", False), lm=lm, ), lastmodified_factory=lambda: _create_lastmodified( request.path, request.values.get("recursive", False) ), unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False), ) def readGcodeFilesForOrigin(origin): if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) filter = request.values.get("filter", False) recursive = request.values.get("recursive", "false") in valid_boolean_trues force = request.values.get("force", "false") in valid_boolean_trues files = _getFileList( origin, filter=filter, recursive=recursive, allow_from_cache=not force ) if origin == FileDestinations.LOCAL: usage = psutil.disk_usage( settings().getBaseFolder("uploads", check_writable=False) ) return jsonify(files=files, free=usage.free, total=usage.total) else: return jsonify(files=files) @api.route("/files/<string:target>/<path:filename>", methods=["GET"]) @Permissions.FILES_LIST.require(403) @with_revalidation_checking( etag_factory=lambda lm=None: _create_etag( request.path, request.values.get("filter", False), request.values.get("recursive", False), lm=lm, ), lastmodified_factory=lambda: _create_lastmodified( request.path, request.values.get("recursive", False) ), unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False), ) def readGcodeFile(target, filename): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) if not _validate(target, filename): abort(404) recursive = False if "recursive" in request.values: recursive = request.values["recursive"] in valid_boolean_trues file = _getFileDetails(target, filename, recursive=recursive) if not file: abort(404) return jsonify(file) def _getFileDetails(origin, path, recursive=True): parent, path = os.path.split(path) files = _getFileList(origin, path=parent, recursive=recursive, level=1) for f in files: if f["name"] == path: return f else: return None @time_this( logtarget=__name__ + ".timings", message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms", incl_func_args=True, log_enter=True, message_enter="Entering {func}({func_args},{func_kwargs})...", ) def _getFileList( origin, path=None, filter=None, recursive=False, level=0, allow_from_cache=True ): if origin == FileDestinations.SDCARD: sdFileList = printer.get_sd_files(refresh=not allow_from_cache) files = [] if sdFileList is not None: for f in sdFileList: type_path = octoprint.filemanager.get_file_type(f["name"]) if not type_path: # only supported extensions continue else: file_type = type_path[0] file = { "type": file_type, "typePath": type_path, "name": f["name"], "display": f["display"] if f["display"] else f["name"], "path": f["name"], "origin": FileDestinations.SDCARD, "refs": { "resource": url_for( ".readGcodeFile", target=FileDestinations.SDCARD, filename=f["name"], _external=True, ) }, } if f["size"] is not None: file.update({"size": f["size"]}) if f["date"] is not None: file.update({"date": f["date"]}) files.append(file) else: # PERF: Only retrieve the extension tree once extension_tree = octoprint.filemanager.full_extension_tree() filter_func = None if filter: filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type( entry, type=filter, tree=extension_tree ) with _file_cache_mutex: cache_key = f"{origin}:{path}:{recursive}:{filter}" files, lastmodified = _file_cache.get(cache_key, ([], None)) # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422 if ( not allow_from_cache or lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=True) ): files = list( fileManager.list_files( origin, path=path, filter=filter_func, recursive=recursive, level=level, force_refresh=not allow_from_cache, )[origin].values() ) lastmodified = fileManager.last_modified( origin, path=path, recursive=True ) _file_cache[cache_key] = (files, lastmodified) def analyse_recursively(files, path=None): if path is None: path = "" result = [] for file_or_folder in files: # make a shallow copy in order to not accidentally modify the cached data file_or_folder = dict(file_or_folder) file_or_folder["origin"] = FileDestinations.LOCAL if file_or_folder["type"] == "folder": if "children" in file_or_folder: children = analyse_recursively( file_or_folder["children"].values(), path + file_or_folder["name"] + "/", ) latest_print = None success = 0 failure = 0 for child in children: if ( "prints" not in child or "last" not in child["prints"] or "date" not in child["prints"]["last"] ): continue success += child["prints"].get("success", 0) failure += child["prints"].get("failure", 0) if ( latest_print is None or child["prints"]["last"]["date"] > latest_print["date"] ): latest_print = child["prints"]["last"] file_or_folder["children"] = children file_or_folder["prints"] = { "success": success, "failure": failure, } if latest_print: file_or_folder["prints"]["last"] = latest_print file_or_folder["refs"] = { "resource": url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=path + file_or_folder["name"], _external=True, ) } else: if ( "analysis" in file_or_folder and octoprint.filemanager.valid_file_type( file_or_folder["name"], type="gcode", tree=extension_tree ) ): file_or_folder["gcodeAnalysis"] = file_or_folder["analysis"] del file_or_folder["analysis"] if ( "history" in file_or_folder and octoprint.filemanager.valid_file_type( file_or_folder["name"], type="gcode", tree=extension_tree ) ): # convert print log history = file_or_folder["history"] del file_or_folder["history"] success = 0 failure = 0 last = None for entry in history: success += 1 if "success" in entry and entry["success"] else 0 failure += ( 1 if "success" in entry and not entry["success"] else 0 ) if not last or ( "timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"] ): last = entry if last: prints = { "success": success, "failure": failure, "last": { "success": last["success"], "date": last["timestamp"], }, } if "printTime" in last: prints["last"]["printTime"] = last["printTime"] file_or_folder["prints"] = prints file_or_folder["refs"] = { "resource": url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=file_or_folder["path"], _external=True, ), "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + urlquote(file_or_folder["path"]), } result.append(file_or_folder) return result files = analyse_recursively(files) return files def _verifyFileExists(origin, filename): if origin == FileDestinations.SDCARD: return filename in (x["name"] for x in printer.get_sd_files()) else: return fileManager.file_exists(origin, filename) def _verifyFolderExists(origin, foldername): if origin == FileDestinations.SDCARD: return False else: return fileManager.folder_exists(origin, foldername) def _isBusy(target, path): currentOrigin, currentPath = _getCurrentFile() if ( currentPath is not None and currentOrigin == target and fileManager.file_in_path(FileDestinations.LOCAL, path, currentPath) and (printer.is_printing() or printer.is_paused()) ): return True return any( target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1]) for x in fileManager.get_busy_files() ) @api.route("/files/<string:target>", methods=["POST"]) @no_firstrun_access @Permissions.FILES_UPLOAD.require(403) def uploadGcodeFile(target): input_name = "file" input_upload_name = ( input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) ) input_upload_path = ( input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) ) if input_upload_name in request.values and input_upload_path in request.values: if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) upload = octoprint.filemanager.util.DiskFileWrapper( request.values[input_upload_name], request.values[input_upload_path] ) # Store any additional user data the caller may have passed. userdata = None if "userdata" in request.values: import json try: userdata = json.loads(request.values["userdata"]) except Exception: abort(400, description="userdata contains invalid JSON") # check preconditions for SD upload if target == FileDestinations.SDCARD and not settings().getBoolean( ["feature", "sdSupport"] ): abort(404) sd = target == FileDestinations.SDCARD if sd: # validate that all preconditions for SD upload are met before attempting it if not ( printer.is_operational() and not (printer.is_printing() or printer.is_paused()) ): abort( 409, description="Can not upload to SD card, printer is either not operational or already busy", ) if not printer.is_sd_ready(): abort(409, description="Can not upload to SD card, not yet initialized") # evaluate select and print parameter and if set check permissions & preconditions # and adjust as necessary # # we do NOT abort(409) here since this would be a backwards incompatible behaviour change # on the API, but instead return the actually effective select and print flags in the response # # note that this behaviour might change in a future API version select_request = ( "select" in request.values and request.values["select"] in valid_boolean_trues and Permissions.FILES_SELECT.can() ) print_request = ( "print" in request.values and request.values["print"] in valid_boolean_trues and Permissions.PRINT.can() ) to_select = select_request to_print = print_request if (to_select or to_print) and not ( printer.is_operational() and not (printer.is_printing() or printer.is_paused()) ): # can't select or print files if not operational or ready to_select = to_print = False # determine future filename of file to be uploaded, abort if it can't be uploaded try: # FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet canonPath, canonFilename = fileManager.canonicalize( FileDestinations.LOCAL, upload.filename ) if request.values.get("path"): canonPath = request.values.get("path") if request.values.get("filename"): canonFilename = request.values.get("filename") futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath) futureFilename = fileManager.sanitize_name( FileDestinations.LOCAL, canonFilename ) except Exception: canonFilename = None futurePath = None futureFilename = None if futureFilename is None: abort(400, description="Can not upload file, invalid file name") # prohibit overwriting currently selected file while it's being printed futureFullPath = fileManager.join_path( FileDestinations.LOCAL, futurePath, futureFilename ) futureFullPathInStorage = fileManager.path_in_storage( FileDestinations.LOCAL, futureFullPath ) if not printer.can_modify_file(futureFullPathInStorage, sd): abort( 409, description="Trying to overwrite file that is currently being printed", ) if ( fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage) and request.values.get("noOverwrite") in valid_boolean_trues ): abort(409, description="File already exists and noOverwrite was set") if ( fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage) and not Permissions.FILES_DELETE.can() ): abort( 403, description="File already exists, cannot overwrite due to a lack of permissions", ) reselect = printer.is_current_file(futureFullPathInStorage, sd) user = current_user.get_name() def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls to_select. """ if ( destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode") ): return filename, printer.add_sd_file( filename, absFilename, on_success=selectAndOrPrint, tags={"source:api", "api:files.sd"}, ) else: selectAndOrPrint(filename, absFilename, destination) return filename def selectAndOrPrint(filename, absFilename, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either to_select or to_print are True, or if the exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type(added_file, "gcode") and ( to_select or to_print or reselect ): printer.select_file( absFilename, destination == FileDestinations.SDCARD, to_print, user, ) try: added_file = fileManager.add_file( FileDestinations.LOCAL, futureFullPathInStorage, upload, allow_overwrite=True, display=canonFilename, ) except (OSError, StorageError) as e: _abortWithException(e) else: filename = fileProcessingFinished( added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target, ) done = not sd if userdata is not None: # upload included userdata, add this now to the metadata fileManager.set_additional_metadata( FileDestinations.LOCAL, added_file, "userdata", userdata ) sdFilename = None if isinstance(filename, tuple): filename, sdFilename = filename payload = { "name": futureFilename, "path": filename, "target": target, "select": select_request, "print": print_request, "effective_select": to_select, "effective_print": to_print, } if userdata is not None: payload["userdata"] = userdata eventManager.fire(Events.UPLOAD, payload) files = {} location = url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True, ) files.update( { FileDestinations.LOCAL: { "name": futureFilename, "path": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + urlquote(filename), }, } } ) if sd and sdFilename: location = url_for( ".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True, ) files.update( { FileDestinations.SDCARD: { "name": sdFilename, "path": sdFilename, "origin": FileDestinations.SDCARD, "refs": {"resource": location}, } } ) r = make_response( jsonify( files=files, done=done, effectiveSelect=to_select, effectivePrint=to_print, ), 201, ) r.headers["Location"] = location return r elif "foldername" in request.values: foldername = request.values["foldername"] if target not in [FileDestinations.LOCAL]: abort(400, description="target is invalid") canonPath, canonName = fileManager.canonicalize(target, foldername) futurePath = fileManager.sanitize_path(target, canonPath) futureName = fileManager.sanitize_name(target, canonName) if not futureName or not futurePath: abort(400, description="folder name is empty") if "path" in request.values and request.values["path"]: futurePath = fileManager.sanitize_path( FileDestinations.LOCAL, request.values["path"] ) futureFullPath = fileManager.join_path(target, futurePath, futureName) if octoprint.filemanager.valid_file_type(futureName): abort(409, description="Can't create folder, please try another name") try: added_folder = fileManager.add_folder( target, futureFullPath, display=canonName ) except (OSError, StorageError) as e: _abortWithException(e) location = url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=added_folder, _external=True, ) folder = { "name": futureName, "path": added_folder, "origin": target, "refs": {"resource": location}, } r = make_response(jsonify(folder=folder, done=True), 201) r.headers["Location"] = location return r else: abort(400, description="No file to upload and no folder to create") @api.route("/files/<string:target>/<path:filename>", methods=["POST"]) @no_firstrun_access def gcodeFileCommand(filename, target): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) if not _validate(target, filename): abort(404) # valid file commands, dict mapping command name to mandatory parameters valid_commands = { "select": [], "unselect": [], "slice": [], "analyse": [], "copy": ["destination"], "move": ["destination"], } command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response user = current_user.get_name() if command == "select": with Permissions.FILES_SELECT.require(403): if not _verifyFileExists(target, filename): abort(404) # selects/loads a file if not octoprint.filemanager.valid_file_type(filename, type="machinecode"): abort( 415, description="Cannot select file for printing, not a machinecode file", ) if not printer.is_ready(): abort( 409, description="Printer is already printing, cannot select a new file", ) printAfterLoading = False if "print" in data and data["print"] in valid_boolean_trues: with Permissions.PRINT.require(403): if not printer.is_operational(): abort( 409, description="Printer is not operational, cannot directly start printing", ) printAfterLoading = True sd = False if target == FileDestinations.SDCARD: filenameToSelect = filename sd = True else: filenameToSelect = fileManager.path_on_disk(target, filename) printer.select_file(filenameToSelect, sd, printAfterLoading, user) elif command == "unselect": with Permissions.FILES_SELECT.require(403): if not printer.is_ready(): return make_response( "Printer is already printing, cannot unselect current file", 409 ) _, currentFilename = _getCurrentFile() if currentFilename is None: return make_response( "Cannot unselect current file when there is no file selected", 409 ) if filename != currentFilename and filename != "current": return make_response( "Only the currently selected file can be unselected", 400 ) printer.unselect_file() elif command == "slice": with Permissions.SLICE.require(403): if not _verifyFileExists(target, filename): abort(404) try: if "slicer" in data: slicer = data["slicer"] del data["slicer"] slicer_instance = slicingManager.get_slicer(slicer) elif "cura" in slicingManager.registered_slicers: slicer = "cura" slicer_instance = slicingManager.get_slicer("cura") else: abort(415, description="Cannot slice file, no slicer available") except octoprint.slicing.UnknownSlicer: abort(404) if not any( [ octoprint.filemanager.valid_file_type(filename, type=source_file_type) for source_file_type in slicer_instance.get_slicer_properties().get( "source_file_types", ["model"] ) ] ): abort(415, description="Cannot slice file, not a model file") cores = psutil.cpu_count() if ( slicer_instance.get_slicer_properties().get("same_device", True) and (printer.is_printing() or printer.is_paused()) and (cores is None or cores < 2) ): # slicer runs on same device as OctoPrint, slicing while printing is hence disabled abort( 409, description="Cannot slice on this slicer while printing on single core systems or systems of unknown core count due to performance reasons", ) if "destination" in data and data["destination"]: destination = data["destination"] del data["destination"] elif "gcode" in data and data["gcode"]: destination = data["gcode"] del data["gcode"] else: import os name, _ = os.path.splitext(filename) destination = ( name + "." + slicer_instance.get_slicer_properties().get( "destination_extensions", ["gco", "gcode", "g"] )[0] ) full_path = destination if "path" in data and data["path"]: full_path = fileManager.join_path(target, data["path"], destination) else: path, _ = fileManager.split_path(target, filename) if path: full_path = fileManager.join_path(target, path, destination) canon_path, canon_name = fileManager.canonicalize(target, full_path) sanitized_name = fileManager.sanitize_name(target, canon_name) if canon_path: full_path = fileManager.join_path(target, canon_path, sanitized_name) else: full_path = sanitized_name # prohibit overwriting the file that is currently being printed currentOrigin, currentFilename = _getCurrentFile() if ( currentFilename == full_path and currentOrigin == target and (printer.is_printing() or printer.is_paused()) ): abort( 409, description="Trying to slice into file that is currently being printed", ) if "profile" in data and data["profile"]: profile = data["profile"] del data["profile"] else: profile = None if "printerProfile" in data and data["printerProfile"]: printerProfile = data["printerProfile"] del data["printerProfile"] else: printerProfile = None if ( "position" in data and data["position"] and isinstance(data["position"], dict) and "x" in data["position"] and "y" in data["position"] ): position = data["position"] del data["position"] else: position = None select_after_slicing = False if "select" in data and data["select"] in valid_boolean_trues: if not printer.is_operational(): abort( 409, description="Printer is not operational, cannot directly select for printing", ) select_after_slicing = True print_after_slicing = False if "print" in data and data["print"] in valid_boolean_trues: if not printer.is_operational(): abort( 409, description="Printer is not operational, cannot directly start printing", ) select_after_slicing = print_after_slicing = True override_keys = [ k for k in data if k.startswith("profile.") and data[k] is not None ] overrides = {} for key in override_keys: overrides[key[len("profile.") :]] = data[key] def slicing_done(target, path, select_after_slicing, print_after_slicing): if select_after_slicing or print_after_slicing: sd = False if target == FileDestinations.SDCARD: filenameToSelect = path sd = True else: filenameToSelect = fileManager.path_on_disk(target, path) printer.select_file(filenameToSelect, sd, print_after_slicing, user) try: fileManager.slice( slicer, target, filename, target, full_path, profile=profile, printer_profile_id=printerProfile, position=position, overrides=overrides, display=canon_name, callback=slicing_done, callback_args=( target, full_path, select_after_slicing, print_after_slicing, ), ) except octoprint.slicing.UnknownProfile: abort(404, description="Unknown profile") location = url_for( ".readGcodeFile", target=target, filename=full_path, _external=True, ) result = { "name": destination, "path": full_path, "display": canon_name, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + target + "/" + urlquote(full_path), }, } r = make_response(jsonify(result), 202) r.headers["Location"] = location return r elif command == "analyse": with Permissions.FILES_UPLOAD.require(403): if not _verifyFileExists(target, filename): abort(404) printer_profile = None if "printerProfile" in data and data["printerProfile"]: printer_profile = data["printerProfile"] if not fileManager.analyse( target, filename, printer_profile_id=printer_profile ): abort(400, description="No analysis possible") elif command == "copy" or command == "move": with Permissions.FILES_UPLOAD.require(403): # Copy and move are only possible on local storage if target not in [FileDestinations.LOCAL]: abort(400, description=f"Unsupported target for {command}") if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): abort(404) path, name = fileManager.split_path(target, filename) destination = data["destination"] dst_path, dst_name = fileManager.split_path(target, destination) sanitized_destination = fileManager.join_path( target, dst_path, fileManager.sanitize_name(target, dst_name) ) # Check for exception thrown by _verifyFolderExists, if outside the root directory try: if ( _verifyFolderExists(target, destination) and sanitized_destination != filename ): # destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed # to move filename to this folder under the same name destination = fileManager.join_path(target, destination, name) if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): abort(409, description="File or folder does already exist") except Exception: abort( 409, description="Exception thrown by storage, bad folder/file name?" ) is_file = fileManager.file_exists(target, filename) is_folder = fileManager.folder_exists(target, filename) if not (is_file or is_folder): abort(400, description=f"Neither file nor folder, can't {command}") try: if command == "copy": # destination already there? error... if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): abort(409, description="File or folder does already exist") if is_file: fileManager.copy_file(target, filename, destination) else: fileManager.copy_folder(target, filename, destination) elif command == "move": with Permissions.FILES_DELETE.require(403): if _isBusy(target, filename): abort( 409, description="Trying to move a file or folder that is currently in use", ) # destination already there AND not ourselves (= display rename)? error... if ( _verifyFileExists(target, destination) or _verifyFolderExists(target, destination) ) and sanitized_destination != filename: abort(409, description="File or folder does already exist") # deselect the file if it's currently selected currentOrigin, currentFilename = _getCurrentFile() if currentFilename is not None and filename == currentFilename: printer.unselect_file() if is_file: fileManager.move_file(target, filename, destination) else: fileManager.move_folder(target, filename, destination) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE: abort( 415, description=f"Could not {command} {filename} to {destination}, invalid type", ) else: abort( 500, description=f"Could not {command} {filename} to {destination}", ) location = url_for( ".readGcodeFile", target=target, filename=destination, _external=True, ) result = { "name": name, "path": destination, "origin": FileDestinations.LOCAL, "refs": {"resource": location}, } if is_file: result["refs"]["download"] = ( url_for("index", _external=True) + "downloads/files/" + target + "/" + urlquote(destination) ) r = make_response(jsonify(result), 201) r.headers["Location"] = location return r return NO_CONTENT @api.route("/files/<string:target>/<path:filename>", methods=["DELETE"]) @no_firstrun_access @Permissions.FILES_DELETE.require(403) def deleteGcodeFile(filename, target): if not _validate(target, filename): abort(404) if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): abort(404) if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) if _verifyFileExists(target, filename): if _isBusy(target, filename): abort(409, description="Trying to delete a file that is currently in use") # deselect the file if it's currently selected currentOrigin, currentPath = _getCurrentFile() if ( currentPath is not None and currentOrigin == target and filename == currentPath ): printer.unselect_file() # delete it if target == FileDestinations.SDCARD: printer.delete_sd_file(filename, tags={"source:api", "api:files.sd"}) else: try: fileManager.remove_file(target, filename) except (OSError, StorageError) as e: _abortWithException(e) elif _verifyFolderExists(target, filename): if _isBusy(target, filename): abort( 409, description="Trying to delete a folder that contains a file that is currently in use", ) # deselect the file if it's currently selected currentOrigin, currentPath = _getCurrentFile() if ( currentPath is not None and currentOrigin == target and fileManager.file_in_path(target, filename, currentPath) ): printer.unselect_file() # delete it try: fileManager.remove_folder(target, filename, recursive=True) except (OSError, StorageError) as e: _abortWithException(e) return NO_CONTENT def _abortWithException(error): if type(error) is StorageError: logging.getLogger(__name__).error(f"{error}: {error.code}", exc_info=error.cause) if error.code == StorageError.INVALID_DIRECTORY: abort(400, description="Could not create folder, invalid directory") elif error.code == StorageError.INVALID_FILE: abort(415, description="Could not upload file, invalid type") elif error.code == StorageError.INVALID_SOURCE: abort(404, description="Source path does not exist, invalid source") elif error.code == StorageError.INVALID_DESTINATION: abort(400, description="Destination is invalid") elif error.code == StorageError.DOES_NOT_EXIST: abort(404, description="Does not exit") elif error.code == StorageError.ALREADY_EXISTS: abort(409, description="File or folder already exists") elif error.code == StorageError.SOURCE_EQUALS_DESTINATION: abort(400, description="Source and destination are the same folder") elif error.code == StorageError.NOT_EMPTY: abort(409, description="Folder is not empty") elif error.code == StorageError.UNKNOWN: abort(500, description=str(error.cause).split(":")[0]) else: abort(500, description=error) else: logging.getLogger(__name__).exception(error) abort(500, description=str(error).split(":")[0]) def _getCurrentFile(): currentJob = printer.get_current_job() if ( currentJob is not None and "file" in currentJob and "path" in currentJob["file"] and "origin" in currentJob["file"] ): return currentJob["file"]["origin"], currentJob["file"]["path"] else: return None, None def _validate(target, filename): if target == FileDestinations.SDCARD: # we make no assumptions about the shape of valid SDCard file names return True else: return filename == "/".join( map(lambda x: fileManager.sanitize_name(target, x), filename.split("/")) ) class WerkzeugFileWrapper(octoprint.filemanager.util.AbstractFileWrapper): """ A wrapper around a Werkzeug ``FileStorage`` object. Arguments: file_obj (werkzeug.datastructures.FileStorage): The Werkzeug ``FileStorage`` instance to wrap. .. seealso:: `werkzeug.datastructures.FileStorage <http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.FileStorage>`_ The documentation of Werkzeug's ``FileStorage`` class. """ def __init__(self, file_obj): octoprint.filemanager.util.AbstractFileWrapper.__init__(self, file_obj.filename) self.file_obj = file_obj def save(self, path): """ Delegates to ``werkzeug.datastructures.FileStorage.save`` """ self.file_obj.save(path) def stream(self): """ Returns ``werkzeug.datastructures.FileStorage.stream`` """ return self.file_obj.stream
51,270
Python
.py
1,199
28.774812
160
0.54171
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,891
watchdog.py
OctoPrint_OctoPrint/src/octoprint/server/util/watchdog.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os import shutil import threading import time import watchdog.events import octoprint.filemanager import octoprint.filemanager.util import octoprint.util class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): """ Takes care of automatically "uploading" files that get added to the watched folder. """ def __init__(self, file_manager, printer): watchdog.events.PatternMatchingEventHandler.__init__( self, patterns=list( map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions()) ), ) self._logger = logging.getLogger(__name__) self._file_manager = file_manager self._printer = printer self._watched_folder = None def initial_scan(self, folder): def _recursive_scandir(path): """Recursively yield DirEntry objects for given directory.""" for entry in os.scandir(path): if entry.is_dir(follow_symlinks=False): yield from _recursive_scandir(entry.path) else: yield entry def run_scan(): self._logger.info("Running initial scan on watched folder...") self._watched_folder = folder for entry in _recursive_scandir(folder): path = entry.path if not self._valid_path(path): continue self._logger.info(f"Found {path}, trying to add it") self._upload(path) self._logger.info("... initial scan done.") thread = threading.Thread(target=run_scan) thread.daemon = True thread.start() def on_created(self, event): self._start_check(event.src_path) def on_moved(self, event): # for move/rename we are only interested in the dest_path self._start_check(event.dest_path) def _start_check(self, path): if not self._valid_path(path): return thread = threading.Thread(target=self._repeatedly_check, args=(path,)) thread.daemon = True thread.start() def _upload(self, path): # noinspection PyBroadException try: file_wrapper = octoprint.filemanager.util.DiskFileWrapper( os.path.basename(path), path ) relative_path = os.path.relpath(path, self._watched_folder) # determine future filename of file to be uploaded, abort if it can't be uploaded try: futurePath, futureFilename = self._file_manager.sanitize( octoprint.filemanager.FileDestinations.LOCAL, relative_path ) except Exception: self._logger.exception("Could not wrap %s", path) futurePath = None futureFilename = None if futureFilename is None or ( len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename) ): return # prohibit overwriting currently selected file while it's being printed futureFullPath = self._file_manager.join_path( octoprint.filemanager.FileDestinations.LOCAL, futurePath, futureFilename ) futureFullPathInStorage = self._file_manager.path_in_storage( octoprint.filemanager.FileDestinations.LOCAL, futureFullPath ) if not self._printer.can_modify_file(futureFullPathInStorage, False): return reselect = self._printer.is_current_file(futureFullPathInStorage, False) added_file = self._file_manager.add_file( octoprint.filemanager.FileDestinations.LOCAL, relative_path, file_wrapper, allow_overwrite=True, ) if os.path.exists(path): try: os.remove(path) except Exception: pass if reselect: self._printer.select_file( self._file_manager.path_on_disk( octoprint.filemanager.FileDestinations.LOCAL, added_file ), False, ) except Exception: self._logger.exception( "There was an error while processing the file {} in the watched folder".format( path ) ) finally: if os.path.exists(path): # file is still there - that should only happen if something went wrong, so mark it as failed # noinspection PyBroadException try: shutil.move(path, f"{path}.failed") except Exception: # something went really wrong here.... but we can't do anything about it, so just log it self._logger.exception( "There was an error while trying to mark {} as failed in the watched folder".format( path ) ) def _repeatedly_check(self, path, interval=1, stable=5): try: last_size = os.stat(path).st_size except Exception: return countdown = stable while True: try: new_size = os.stat(path).st_size except Exception: return if new_size == last_size: self._logger.debug( "File at {} is no longer growing, counting down: {}".format( path, countdown ) ) countdown -= 1 if countdown <= 0: break else: self._logger.debug( "File at {} is still growing (last: {}, new: {}), waiting...".format( path, last_size, new_size ) ) countdown = stable last_size = new_size time.sleep(interval) self._logger.debug(f"File at {path} is stable, moving it") self._upload(path) def _valid_path(self, path): _, ext = os.path.splitext(path) return ( octoprint.filemanager.valid_file_type(path) and not octoprint.util.is_hidden_path(path) and ext != "failed" )
6,843
Python
.py
165
28.078788
109
0.550971
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,892
flask.py
OctoPrint_OctoPrint/src/octoprint/server/util/flask.py
from flask import make_response __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import functools import hashlib import hmac import logging import os import threading import time from datetime import datetime, timedelta, timezone from typing import Any, Dict, List, Union import flask import flask.json import flask.json.provider import flask.sessions import flask.templating import flask_assets import flask_login import netaddr import tornado.web import webassets.updater import webassets.utils from cachelib import BaseCache from flask import current_app from flask_login import COOKIE_NAME as REMEMBER_COOKIE_NAME from flask_login.utils import decode_cookie, encode_cookie from pydantic import BaseModel from werkzeug.local import LocalProxy from werkzeug.utils import cached_property import octoprint.access.users import octoprint.plugin import octoprint.server import octoprint.vendor.flask_principal as flask_principal from octoprint.access import auth_log from octoprint.events import Events, eventManager from octoprint.settings import settings from octoprint.util import DefaultOrderedDict, deprecated, yaml from octoprint.util.json import JsonEncoding from octoprint.util.net import is_lan_address from octoprint.util.tz import UTC_TZ, is_timezone_aware # ~~ monkey patching def enable_additional_translations(default_locale="en", additional_folders=None): import os import flask_babel from babel import Locale, support if additional_folders is None: additional_folders = [] logger = logging.getLogger(__name__) def fixed_list_translations(self): """Returns a list of all the locales translations exist for. The list returned will be filled with actual locale objects and not just strings. """ def list_translations(dirname): if not os.path.isdir(dirname): return [] result = [] for entry in os.scandir(dirname): locale_dir = os.path.join(entry.path, "LC_MESSAGES") if not os.path.isdir(locale_dir): continue if any(filter(lambda x: x.name.endswith(".mo"), os.scandir(locale_dir))): result.append(Locale.parse(entry.name)) return result dirs = additional_folders + [os.path.join(self.app.root_path, "translations")] # translations from plugins plugins = octoprint.plugin.plugin_manager().enabled_plugins for plugin in plugins.values(): plugin_translation_dir = os.path.join(plugin.location, "translations") if not os.path.isdir(plugin_translation_dir): continue dirs.append(plugin_translation_dir) result = {Locale.parse(default_locale)} for dir in dirs: result.update(list_translations(dir)) return list(result) def fixed_get_translations(): """Returns the correct gettext translations that should be used for this request. This will never fail and return a dummy translation object if used outside of the request or if a translation cannot be found. """ if flask.g is None: return None translations = getattr(flask.g, "babel_translations", None) if translations is None: locale = flask_babel.get_locale() translations = support.Translations() if str(locale) != default_locale: # plugin translations plugins = octoprint.plugin.plugin_manager().enabled_plugins for name, plugin in plugins.items(): dirs = list( map( lambda x: os.path.join(x, "_plugins", name), additional_folders, ) ) + [os.path.join(plugin.location, "translations")] for dirname in dirs: if not os.path.isdir(dirname): continue try: plugin_translations = support.Translations.load( dirname, [locale] ) except Exception: logger.exception( f"Error while trying to load translations " f"for plugin {name}" ) else: if isinstance(plugin_translations, support.Translations): translations = translations.merge(plugin_translations) logger.debug( f"Using translation plugin folder {dirname} from " f"plugin {name} for locale {locale}" ) break else: logger.debug( f"No translations for locale {locale} " f"from plugin {name}" ) # core translations dirs = additional_folders + [ os.path.join(flask.current_app.root_path, "translations") ] for dirname in dirs: core_translations = support.Translations.load(dirname, [locale]) if isinstance(core_translations, support.Translations): logger.debug( f"Using translation core folder {dirname} " f"for locale {locale}" ) break else: logger.debug(f"No translations for locale {locale} in core folders") translations = translations.merge(core_translations) flask.g.babel_translations = translations return translations flask_babel.Babel.list_translations = fixed_list_translations flask_babel.get_translations = fixed_get_translations def fix_webassets_filtertool(): from webassets.merge import FilterTool, MemoryHunk, log error_logger = logging.getLogger(__name__ + ".fix_webassets_filtertool") def fixed_wrap_cache(self, key, func): """Return cache value ``key``, or run ``func``.""" if self.cache: if not self.no_cache_read: log.debug("Checking cache for key %s", key) content = self.cache.get(key) if content not in (False, None): log.debug("Using cached result for %s", key) return MemoryHunk(content) try: content = func().getvalue() if self.cache: try: log.debug( "Storing result in cache with key %s", key, ) self.cache.set(key, content) except Exception: error_logger.exception( "Got an exception while trying to save file to cache, not caching" ) return MemoryHunk(content) except Exception: error_logger.exception( "Got an exception while trying to apply filter, ignoring file" ) return MemoryHunk("") FilterTool._wrap_cache = fixed_wrap_cache def fix_webassets_convert_item_to_flask_url(): import flask_assets def fixed_convert_item_to_flask_url(self, ctx, item, filepath=None): from flask import url_for directory, rel_path, endpoint = self.split_prefix(ctx, item) if filepath is not None: filename = filepath[len(directory) + 1 :] else: filename = rel_path flask_ctx = None if not flask.has_request_context(): # fixed, was _request_ctx.top flask_ctx = ctx.environment._app.test_request_context() flask_ctx.push() try: url = url_for(endpoint, filename=filename) # In some cases, url will be an absolute url with a scheme and hostname. # (for example, when using werkzeug's host matching). # In general, url_for() will return a http url. During assets build, we # we don't know yet if the assets will be served over http, https or both. # Let's use // instead. url_for takes a _scheme argument, but only together # with external=True, which we do not want to force every time. Further, # this _scheme argument is not able to render // - it always forces a colon. if url and url.startswith("http:"): url = url[5:] return url finally: if flask_ctx: flask_ctx.pop() flask_assets.FlaskResolver.convert_item_to_flask_url = fixed_convert_item_to_flask_url # ~~ WSGI environment wrapper for reverse proxying class ReverseProxiedEnvironment: @staticmethod def to_header_candidates(values): if values is None: return [] if not isinstance(values, (list, tuple)): values = [values] to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_") return list(map(to_wsgi_format, values)) @staticmethod def valid_ip(address): import netaddr try: netaddr.IPAddress(address) return True except Exception: return False def __init__( self, header_prefix=None, header_scheme=None, header_host=None, header_server=None, header_port=None, prefix=None, scheme=None, host=None, server=None, port=None, ): # sensible defaults if header_prefix is None: header_prefix = ["x-script-name", "x-forwarded-prefix"] if header_scheme is None: header_scheme = ["x-forwarded-proto", "x-scheme"] if header_host is None: header_host = ["x-forwarded-host"] if header_server is None: header_server = ["x-forwarded-server"] if header_port is None: header_port = ["x-forwarded-port"] # header candidates self._headers_prefix = self.to_header_candidates(header_prefix) self._headers_scheme = self.to_header_candidates(header_scheme) self._headers_host = self.to_header_candidates(header_host) self._headers_server = self.to_header_candidates(header_server) self._headers_port = self.to_header_candidates(header_port) # fallback prefix & scheme & host from config self._fallback_prefix = prefix self._fallback_scheme = scheme self._fallback_host = host self._fallback_server = server self._fallback_port = port def __call__(self, environ): def retrieve_header(header_type): candidates = getattr(self, "_headers_" + header_type, []) fallback = getattr(self, "_fallback_" + header_type, None) for candidate in candidates: value = environ.get(candidate, None) if value is not None: return value else: return fallback def host_to_server_and_port(host, scheme): if host is None: return None, None default_port = "443" if scheme == "https" else "80" host = host.strip() if ":" in host: # we might have an ipv6 address here, or a port, or both if host[0] == "[": # that looks like an ipv6 address with port, e.g. [fec1::1]:80 address_end = host.find("]") if address_end == -1: # no ], that looks like a seriously broken address return None, None # extract server ip, skip enclosing [ and ] server = host[1:address_end] tail = host[address_end + 1 :] # now check if there's also a port if len(tail) and tail[0] == ":": # port included as well port = tail[1:] else: # no port, use default one port = default_port elif self.__class__.valid_ip(host): # ipv6 address without port server = host port = default_port else: # ipv4 address with port server, port = host.rsplit(":", 1) else: server = host port = default_port return server, port # determine prefix prefix = retrieve_header("prefix") if prefix is not None: environ["SCRIPT_NAME"] = prefix path_info = environ["PATH_INFO"] if path_info.startswith(prefix): environ["PATH_INFO"] = path_info[len(prefix) :] # determine scheme scheme = retrieve_header("scheme") if scheme is not None and "," in scheme: # Scheme might be something like "https,https" if doubly-reverse-proxied # without stripping original scheme header first, make sure to only use # the first entry in such a case. See #1391. scheme, _ = map(lambda x: x.strip(), scheme.split(",", 1)) if scheme is not None: environ["wsgi.url_scheme"] = scheme # determine host url_scheme = environ["wsgi.url_scheme"] host = retrieve_header("host") if host is not None: # if we have a host, we take server_name and server_port from it server, port = host_to_server_and_port(host, url_scheme) environ["HTTP_HOST"] = host environ["SERVER_NAME"] = server environ["SERVER_PORT"] = port elif environ.get("HTTP_HOST", None) is not None: # if we have a Host header, we use that and make sure our server name and port properties match it host = environ["HTTP_HOST"] server, port = host_to_server_and_port(host, url_scheme) environ["SERVER_NAME"] = server environ["SERVER_PORT"] = port else: # else we take a look at the server and port headers and if we have # something there we derive the host from it # determine server - should usually not be used server = retrieve_header("server") if server is not None: environ["SERVER_NAME"] = server # determine port - should usually not be used port = retrieve_header("port") if port is not None: environ["SERVER_PORT"] = port # reconstruct host header if ( url_scheme == "http" and environ["SERVER_PORT"] == "80" or url_scheme == "https" and environ["SERVER_PORT"] == "443" ): # default port for scheme, can be skipped environ["HTTP_HOST"] = environ["SERVER_NAME"] else: server_name_component = environ["SERVER_NAME"] if ":" in server_name_component and self.__class__.valid_ip( server_name_component ): # this is an ipv6 address, we need to wrap that in [ and ] before appending the port server_name_component = "[" + server_name_component + "]" environ["HTTP_HOST"] = ( server_name_component + ":" + environ["SERVER_PORT"] ) # call wrapped app with rewritten environment return environ # ~~ request and response versions def encode_remember_me_cookie(value): from octoprint.server import userManager name = value.split("|")[0] try: remember_key = userManager.signature_key_for_user( name, current_app.config["SECRET_KEY"] ) timestamp = datetime.utcnow().timestamp() return encode_cookie(f"{name}|{timestamp}", key=remember_key) except Exception: pass return "" def decode_remember_me_cookie(value): from octoprint.server import userManager parts = value.split("|") if len(parts) == 3: name, created, _ = parts try: # valid signature? signature_key = userManager.signature_key_for_user( name, current_app.config["SECRET_KEY"] ) cookie = decode_cookie(value, key=signature_key) if cookie: # still valid? if ( datetime.fromtimestamp(float(created)) + timedelta(seconds=current_app.config["REMEMBER_COOKIE_DURATION"]) > datetime.utcnow() ): return encode_cookie(name) except Exception: pass raise ValueError("Invalid remember me cookie") def get_cookie_suffix(request): """ Request specific suffix for set and read cookies We need this because cookies are not port-specific and we don't want to overwrite our session and other cookies from one OctoPrint instance on our machine with those of another one who happens to listen on the same address albeit a different port or script root. """ result = "_P" + request.server_port if request.script_root: return result + "_R" + request.script_root.replace("/", "|") return result class OctoPrintFlaskRequest(flask.Request): environment_wrapper = staticmethod(lambda x: x) def __init__(self, environ, *args, **kwargs): # apply environment wrapper to provided WSGI environment flask.Request.__init__(self, self.environment_wrapper(environ), *args, **kwargs) @cached_property def cookies(self): # strip cookie_suffix from all cookies in the request, return result cookies = flask.Request.cookies.__get__(self) result = {} desuffixed = {} for key, value in cookies.items(): def process_value(k, v): if k == current_app.config.get( "REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME ): return decode_remember_me_cookie(v) return v try: if key.endswith(self.cookie_suffix): key = key[: -len(self.cookie_suffix)] desuffixed[key] = process_value(key, value) else: result[key] = process_value(key, value) except ValueError: # ignore broken cookies pass result.update(desuffixed) return result @cached_property def server_name(self): """Short cut to the request's server name header""" return self.environ.get("SERVER_NAME") @cached_property def server_port(self): """Short cut to the request's server port header""" return self.environ.get("SERVER_PORT") @cached_property def cookie_suffix(self): return get_cookie_suffix(self) class OctoPrintFlaskResponse(flask.Response): def set_cookie(self, key, value="", *args, **kwargs): # restrict cookie path to script root kwargs["path"] = flask.request.script_root + kwargs.get("path", "/") # set same-site header samesite = settings().get(["server", "cookies", "samesite"]) if samesite is not None: samesite = samesite.lower() if samesite == "none": # Must be string "None" samesite = "None" if samesite not in ("None", "strict", "lax"): # If NoneType, the cookie is not set samesite = None kwargs["samesite"] = samesite # set secure if necessary kwargs["secure"] = flask.request.environ.get( "wsgi.url_scheme" ) == "https" or settings().getBoolean(["server", "cookies", "secure"]) # tie account properties to remember me cookie (e.g. current password hash) if key == current_app.config.get("REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME): value = encode_remember_me_cookie(value) # add request specific cookie suffix to name flask.Response.set_cookie( self, key + flask.request.cookie_suffix, value=value, *args, **kwargs ) def delete_cookie(self, key, path="/", domain=None): flask.Response.delete_cookie(self, key, path=path, domain=domain) # we also still might have a cookie left over from before we started prefixing, delete that manually # without any pre processing (no path prefix, no key suffix) flask.Response.set_cookie( self, key, expires=0, max_age=0, path=path, domain=domain ) class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface): def should_set_cookie(self, app, session): return flask.request.endpoint != "static" def save_session(self, app, session, response): if flask.g.get("login_via_apikey", False): return return super().save_session(app, session, response) # ~~ jinja environment class PrefixAwareJinjaEnvironment(flask.templating.Environment): def __init__(self, *args, **kwargs): flask.templating.Environment.__init__(self, *args, **kwargs) self.prefix_loader = None self._cached_templates = {} def join_path(self, template, parent): if parent and "/" in parent: prefix, _ = parent.split("/", 1) if template in self._templates_for_prefix(prefix) and not template.startswith( prefix + "/" ): return prefix + "/" + template return template def _templates_for_prefix(self, prefix): if prefix in self._cached_templates: return self._cached_templates[prefix] templates = [] if prefix in self.prefix_loader.mapping: templates = self.prefix_loader.mapping[prefix].list_templates() self._cached_templates[prefix] = templates return templates # ~~ passive login helper _cached_local_networks = None def _local_networks(): global _cached_local_networks if _cached_local_networks is None: logger = logging.getLogger(__name__) local_networks = netaddr.IPSet([]) for entry in settings().get(["accessControl", "localNetworks"]): try: network = netaddr.IPNetwork(entry) except Exception: logger.warning( "Invalid network definition configured in localNetworks: {}".format( entry ) ) continue local_networks.add(network) logger.debug(f"Added network {network} to localNetworks") if network.version == 4: network_v6 = network.ipv6() local_networks.add(network_v6) logger.debug( "Also added v6 representation of v4 network {} = {} to localNetworks".format( network, network_v6 ) ) _cached_local_networks = local_networks return _cached_local_networks def passive_login(): logger = logging.getLogger(__name__) user = flask_login.current_user remote_address = flask.request.remote_addr ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"]) ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"]) if isinstance(user, LocalProxy): # noinspection PyProtectedMember user = user._get_current_object() def login(u): # login known user if not u.is_anonymous: if not flask.g.identity or not flask.g.identity.id: # the user was just now found login_mechanism = octoprint.server.util.LoginMechanism.to_log( flask.session.get("login_mechanism", "unknown") ) auth_log( f"Logging in user {u.get_id()} from {remote_address} via {login_mechanism}" ) u = octoprint.server.userManager.login_user(u) flask_login.login_user(u) flask_principal.identity_changed.send( flask.current_app._get_current_object(), identity=flask_principal.Identity(u.get_id()), ) if hasattr(u, "session"): flask.session["usersession.id"] = u.session flask.session["usersession.signature"] = session_signature( u.get_id(), u.session ) flask.g.user = u eventManager().fire(Events.USER_LOGGED_IN, payload={"username": u.get_id()}) return u def determine_user(u): if not u.is_anonymous and u.is_active: # known active user logger.info(f"Passively logging in user {u.get_id()} from {remote_address}") elif ( settings().getBoolean(["accessControl", "autologinLocal"]) and settings().get(["accessControl", "autologinAs"]) is not None and settings().get(["accessControl", "localNetworks"]) is not None and "active_logout" not in flask.request.cookies and remote_address ): # attempt local autologin autologin_as = settings().get(["accessControl", "autologinAs"]) local_networks = _local_networks() logger.debug( "Checking if remote address {} is in localNetworks ({!r})".format( remote_address, local_networks ) ) try: if netaddr.IPAddress(remote_address) in local_networks: autologin_user = octoprint.server.userManager.find_user(autologin_as) if autologin_user is not None and autologin_user.is_active: logger.info( f"Logging in user {autologin_as} from {remote_address} via autologin" ) flask.session[ "login_mechanism" ] = octoprint.server.util.LoginMechanism.AUTOLOGIN flask.session["credentials_seen"] = False return autologin_user except Exception: logger.exception( "Could not autologin user {} from {} for networks {}".format( autologin_as, remote_address, local_networks ) ) if not u.is_active: # inactive user, switch to anonymous u = octoprint.server.userManager.anonymous_user_factory() return u user = login(determine_user(user)) response = user.as_dict() response["_is_external_client"] = ip_check_enabled and not is_lan_address( remote_address, additional_private=ip_check_trusted ) if flask.session.get("login_mechanism") is not None: response["_login_mechanism"] = flask.session.get("login_mechanism") response["_credentials_seen"] = to_api_credentials_seen( flask.session.get("credentials_seen", False) ) return flask.jsonify(response) def to_api_credentials_seen(credentials_seen): if not credentials_seen: return False return ( datetime.fromtimestamp(credentials_seen, tz=timezone.utc) .replace(microsecond=0) .isoformat() ) # ~~ rate limiting helper def limit(*args, **kwargs): if octoprint.server.limiter: return octoprint.server.limiter.limit(*args, **kwargs) else: def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): return f(*args, **kwargs) return decorated_function return decorator # ~~ cache decorator for cacheable views class LessSimpleCache(BaseCache): """ Slightly improved version of :class:`SimpleCache`. Setting ``default_timeout`` or ``timeout`` to ``-1`` will have no timeout be applied at all. """ def __init__(self, threshold=500, default_timeout=300): BaseCache.__init__(self, default_timeout=default_timeout) self._mutex = threading.RLock() self._cache = {} self._bypassed = set() self.clear = self._cache.clear self._threshold = threshold def _prune(self): if self.over_threshold(): now = time.time() for idx, (key, (expires, _)) in enumerate(self._cache.items()): if expires is not None and expires <= now or idx % 3 == 0: with self._mutex: self._cache.pop(key, None) def get(self, key): import pickle now = time.time() with self._mutex: expires, value = self._cache.get(key, (0, None)) if expires is None or expires > now: return pickle.loads(value) def set(self, key, value, timeout=None): import pickle with self._mutex: self._prune() self._cache[key] = ( self.calculate_timeout(timeout=timeout), pickle.dumps(value, pickle.HIGHEST_PROTOCOL), ) if key in self._bypassed: self._bypassed.remove(key) def add(self, key, value, timeout=None): with self._mutex: self.set(key, value, timeout=None) self._cache.setdefault(key, self._cache[key]) def delete(self, key): with self._mutex: self._cache.pop(key, None) def calculate_timeout(self, timeout=None): if timeout is None: timeout = self.default_timeout if timeout == -1: return None return time.time() + timeout def over_threshold(self): if self._threshold is None: return False with self._mutex: return len(self._cache) > self._threshold def __getitem__(self, key): return self.get(key) def __setitem__(self, key, value): return self.set(key, value) def __delitem__(self, key): return self.delete(key) def __contains__(self, key): with self._mutex: return key in self._cache def set_bypassed(self, key): with self._mutex: self._bypassed.add(key) def is_bypassed(self, key): with self._mutex: return key in self._bypassed _cache = LessSimpleCache() def cached( timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=None, refreshif=None, unless_response=None, ): def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): logger = logging.getLogger(__name__) cache_key = key() def f_with_duration(*args, **kwargs): start_time = time.time() try: return f(*args, **kwargs) finally: elapsed = time.time() - start_time logger.debug( "Needed {elapsed:.2f}s to render {path} (key: {key})".format( elapsed=elapsed, path=flask.request.path, key=cache_key ) ) # bypass the cache if "unless" condition is true if callable(unless) and unless(): logger.debug( "Cache for {path} bypassed, calling wrapped function".format( path=flask.request.path ) ) _cache.set_bypassed(cache_key) return f_with_duration(*args, **kwargs) # also bypass the cache if it's disabled completely if not settings().getBoolean(["devel", "cache", "enabled"]): logger.debug( "Cache for {path} disabled, calling wrapped function".format( path=flask.request.path ) ) _cache.set_bypassed(cache_key) return f_with_duration(*args, **kwargs) rv = _cache.get(cache_key) # only take the value from the cache if we are not required to refresh it from the wrapped function if rv is not None and (not callable(refreshif) or not refreshif(rv)): logger.debug( "Serving entry for {path} from cache (key: {key})".format( path=flask.request.path, key=cache_key ) ) if "X-From-Cache" not in rv.headers: rv.headers["X-From-Cache"] = "true" return rv # get value from wrapped function logger.debug( "No cache entry or refreshing cache for {path} (key: {key}), calling wrapped function".format( path=flask.request.path, key=cache_key ) ) rv = f_with_duration(*args, **kwargs) # do not store if the "unless_response" condition is true if callable(unless_response) and unless_response(rv): logger.debug( "Not caching result for {path} (key: {key}), bypassed".format( path=flask.request.path, key=cache_key ) ) _cache.set_bypassed(cache_key) return rv # store it in the cache _cache.set(cache_key, rv, timeout=timeout) return rv return decorated_function return decorator def is_in_cache(key=lambda: "view:%s" % flask.request.path): if callable(key): key = key() return key in _cache def is_cache_bypassed(key=lambda: "view:%s" % flask.request.path): if callable(key): key = key() return _cache.is_bypassed(key) def cache_check_headers(): return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma def cache_check_response_headers(response): if not isinstance(response, flask.Response): return False headers = response.headers if "Cache-Control" in headers and ( "no-cache" in headers["Cache-Control"] or "no-store" in headers["Cache-Control"] ): return True if "Pragma" in headers and "no-cache" in headers["Pragma"]: return True if "Expires" in headers and headers["Expires"] in ("0", "-1"): return True return False def cache_check_status_code(response, valid): if not isinstance(response, flask.Response): return False if callable(valid): return not valid(response.status_code) else: return response.status_code not in valid class PreemptiveCache: def __init__(self, cachefile): self.cachefile = cachefile self.environment = None self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__) self._lock = threading.RLock() def record(self, data, unless=None, root=None): if callable(unless) and unless(): return entry_data = data if callable(entry_data): entry_data = entry_data() if entry_data is not None: if root is None: from flask import request root = request.path self.add_data(root, entry_data) def has_record(self, data, root=None): if callable(data): data = data() if data is None: return False if root is None: from flask import request root = request.path all_data = self.get_data(root) for existing in all_data: if self._compare_data(data, existing): return True return False def clean_all_data(self, cleanup_function): assert callable(cleanup_function) with self._lock: all_data = self.get_all_data() for root, entries in list(all_data.items()): old_count = len(entries) entries = cleanup_function(root, entries) if not entries: del all_data[root] self._logger.debug(f"Removed root {root} from preemptive cache") elif len(entries) < old_count: all_data[root] = entries self._logger.debug( "Removed {} entries from preemptive cache for root {}".format( old_count - len(entries), root ) ) self.set_all_data(all_data) return all_data def get_all_data(self): cache_data = None with self._lock: try: cache_data = yaml.load_from_file(path=self.cachefile) except OSError as e: import errno if e.errno != errno.ENOENT: raise except Exception: self._logger.exception(f"Error while reading {self.cachefile}") if cache_data is None: cache_data = {} if not self._validate_data(cache_data): self._logger.warning("Preemptive cache data was invalid, ignoring it") cache_data = {} return cache_data def get_data(self, root): cache_data = self.get_all_data() return cache_data.get(root, list()) def set_all_data(self, data): from octoprint.util import atomic_write with self._lock: try: with atomic_write(self.cachefile, "wt", max_permissions=0o666) as handle: yaml.save_to_file(data, file=handle, pretty=True) except Exception: self._logger.exception(f"Error while writing {self.cachefile}") def set_data(self, root, data): with self._lock: all_data = self.get_all_data() all_data[root] = data self.set_all_data(all_data) def add_data(self, root, data): def split_matched_and_unmatched(entry, entries): matched = [] unmatched = [] for e in entries: if self._compare_data(e, entry): matched.append(e) else: unmatched.append(e) return matched, unmatched with self._lock: cache_data = self.get_all_data() if root not in cache_data: cache_data[root] = [] existing, other = split_matched_and_unmatched(data, cache_data[root]) def get_newest(entries): result = None for entry in entries: if "_timestamp" in entry and ( result is None or ( "_timestamp" in result and result["_timestamp"] < entry["_timestamp"] ) ): result = entry return result to_persist = get_newest(existing) if not to_persist: import copy to_persist = copy.deepcopy(data) to_persist["_timestamp"] = time.time() to_persist["_count"] = 1 self._logger.info(f"Adding entry for {root} and {to_persist!r}") else: to_persist["_timestamp"] = time.time() to_persist["_count"] = to_persist.get("_count", 0) + 1 self._logger.debug( f"Updating timestamp and counter for {root} and {data!r}" ) self.set_data(root, [to_persist] + other) def _compare_data(self, a, b): from octoprint.util import dict_filter def strip_ignored(d): return dict_filter(d, lambda k, v: not k.startswith("_")) return set(strip_ignored(a).items()) == set(strip_ignored(b).items()) def _validate_data(self, data): if not isinstance(data, dict): return False for entries in data.values(): if not isinstance(entries, list): return False for entry in entries: if not self._validate_entry(entry): return False return True def _validate_entry(self, entry): return isinstance(entry, dict) and "_timestamp" in entry and "_count" in entry def preemptively_cached(cache, data, unless=None): def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): try: cache.record(data, unless=unless) except Exception: logging.getLogger(__name__).exception( f"Error while recording preemptive cache entry: {data!r}" ) return f(*args, **kwargs) return decorated_function return decorator def etagged(etag): def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): rv = f(*args, **kwargs) if isinstance(rv, flask.Response): try: result = etag if callable(result): result = result(rv) if result: rv.set_etag(result) except Exception: logging.getLogger(__name__).exception( "Error while calculating the etag value for response {!r}".format( rv ) ) return rv return decorated_function return decorator def lastmodified(date): def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): rv = f(*args, **kwargs) if "Last-Modified" not in rv.headers: try: result = date if callable(result): result = result(rv) if not isinstance(result, str): from werkzeug.http import http_date result = http_date(result) if result: rv.headers["Last-Modified"] = result except Exception: logging.getLogger(__name__).exception( "Error while calculating the lastmodified value for response {!r}".format( rv ) ) return rv return decorated_function return decorator def conditional(condition, met): def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): try: if callable(condition) and condition(): # condition has been met, return met-response rv = met if callable(met): rv = met() return rv except Exception: logging.getLogger(__name__).exception( "Error while evaluating conditional {!r} or met {!r}".format( condition, met ) ) # condition hasn't been met, call decorated function return f(*args, **kwargs) return decorated_function return decorator def with_client_revalidation(f): @functools.wraps(f) def decorated_function(*args, **kwargs): r = f(*args, **kwargs) if isinstance(r, flask.Response): r = add_revalidation_response_headers(r) return r return decorated_function def with_revalidation_checking( etag_factory=None, lastmodified_factory=None, condition=None, unless=None ): if etag_factory is None: def etag_factory(lm=None): return None if lastmodified_factory is None: def lastmodified_factory(): return None if condition is None: def condition(lm=None, etag=None): if lm is None: lm = lastmodified_factory() if etag is None: etag = etag_factory(lm=lm) if flask.request.if_none_match and flask.request.if_modified_since: # use both return check_lastmodified(lm) and check_etag(etag) elif flask.request.if_none_match: # use only ETag return check_etag(etag) elif flask.request.if_modified_since: # use only Last-Modified return check_lastmodified(lm) else: # assume stale cache return False if unless is None: def unless(): return False def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): from octoprint.server import NOT_MODIFIED lm = lastmodified_factory() etag = etag_factory(lm) if condition(lm, etag) and not unless(): return NOT_MODIFIED # generate response response = f(*args, **kwargs) # set etag header if not already set if etag and response.get_etag()[0] is None: response.set_etag(etag) # set last modified header if not already set if lm and response.headers.get("Last-Modified", None) is None: if not isinstance(lm, str): from werkzeug.http import http_date lm = http_date(lm) response.headers["Last-Modified"] = lm response = add_no_max_age_response_headers(response) return response return decorated_function return decorator def check_etag(etag): if etag is None: return False return ( flask.request.method in ("GET", "HEAD") and flask.request.if_none_match is not None and etag in flask.request.if_none_match ) def check_lastmodified(lastmodified: Union[int, float, datetime]) -> bool: """Compares the provided lastmodified value with the value of the If-Modified-Since header. If ``lastmodified`` is an int or float, it's assumed to be a Unix timestamp and converted to a timezone aware datetime instance in UTC. If ``lastmodified`` is a datetime instance, it needs to be timezone aware or the result will always be ``False``. Args: lastmodified (Union[int, float, datetime]): The last modified value to compare against Raises: ValueError: If anything but an int, float or datetime instance is passed Returns: bool: true if the values indicate that the document is still up to date """ if lastmodified is None: return False if isinstance(lastmodified, (int, float)): # max(86400, lastmodified) is workaround for https://bugs.python.org/issue29097, # present in CPython 3.6.x up to 3.7.1. # # I think it's fair to say that we'll never encounter lastmodified values older than # 1970-01-02 so this is a safe workaround. # # Timestamps are defined as seconds since epoch aka 1970/01/01 00:00:00Z, so we # use UTC as timezone here. lastmodified = datetime.fromtimestamp( max(86400, lastmodified), tz=UTC_TZ ).replace(microsecond=0) if not isinstance(lastmodified, datetime): raise ValueError( "lastmodified must be a datetime or float or int instance but, got {} instead".format( lastmodified.__class__ ) ) if not is_timezone_aware(lastmodified): # datetime object is not timezone aware, we can't check lastmodified with that logger = logging.getLogger(__name__) logger.warning( "lastmodified is not timezone aware, cannot check against If-Modified-Since. In the future this will become an error!", stack_info=logger.isEnabledFor(logging.DEBUG), ) return False return ( flask.request.method in ("GET", "HEAD") and flask.request.if_modified_since is not None and lastmodified <= flask.request.if_modified_since ) def add_revalidation_response_headers(response): import werkzeug.http cache_control = werkzeug.http.parse_dict_header( response.headers.get("Cache-Control", "") ) if "no-cache" not in cache_control: cache_control["no-cache"] = None if "must-revalidate" not in cache_control: cache_control["must-revalidate"] = None response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control) return response def add_non_caching_response_headers(response): import werkzeug.http cache_control = werkzeug.http.parse_dict_header( response.headers.get("Cache-Control", "") ) if "no-store" not in cache_control: cache_control["no-store"] = None if "no-cache" not in cache_control: cache_control["no-cache"] = None if "must-revalidate" not in cache_control: cache_control["must-revalidate"] = None if "post-check" not in cache_control or cache_control["post-check"] != "0": cache_control["post-check"] = "0" if "pre-check" not in cache_control or cache_control["pre-check"] != "0": cache_control["pre-check"] = "0" if "max-age" not in cache_control or cache_control["max-age"] != "0": cache_control["max-age"] = "0" response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control) response.headers["Pragma"] = "no-cache" response.headers["Expires"] = "-1" return response def add_no_max_age_response_headers(response): import werkzeug.http cache_control = werkzeug.http.parse_dict_header( response.headers.get("Cache-Control", "") ) if "max-age" not in cache_control or cache_control["max-age"] != "0": cache_control["max-age"] = "0" response.headers["Cache-Control"] = werkzeug.http.dump_header(cache_control) return response # ~~ access validators for use with tornado def permission_validator(request, permission): """ Validates that the given request is made by an authorized user, identified either by API key or existing Flask session. Must be executed in an existing Flask request context! :param request: The Flask request object :param request: The required permission """ user = get_flask_user_from_request(request) if not user.has_permission(permission): raise tornado.web.HTTPError(403) def permission_and_fresh_credentials_validator(request, permission): """ Validates that the given request is made by an authorized user, identified either by API key or existing Flask session, and that the credentials have been checked recently if it's a Flask session. Must be executed in an existing Flask request context! :param request: The Flask request object :param request: The required permission """ permission_validator(request, permission) ensure_credentials_checked_recently() @deprecated( "admin_validator is deprecated, please use new permission_validator", since="" ) def admin_validator(request): from octoprint.access.permissions import Permissions return permission_validator(request, Permissions.ADMIN) @deprecated("user_validator is deprecated, please use new permission_validator", since="") def user_validator(request): return True def get_flask_user_from_request(request): """ Retrieves the current flask user from the request context. Uses API key if available, otherwise the current user session if available. :param request: flask request from which to retrieve the current user :return: the user (might be an anonymous user) """ import flask_login import octoprint.server.util user = None apikey = octoprint.server.util.get_api_key(request) if apikey is not None: # user from api key? user = octoprint.server.util.get_user_for_apikey(apikey) if user is None: # user still None -> current session user user = flask_login.current_user if user is None: # user still None -> anonymous from octoprint.server import userManager user = userManager.anonymous_user_factory() return user def redirect_to_tornado(request, target, code=302): """ Redirects from flask to tornado, flask request context must exist. :param request: :param target: :param code: :return: """ import flask requestUrl = request.url appBaseUrl = requestUrl[: requestUrl.find(flask.url_for("index") + "api")] redirectUrl = appBaseUrl + target if "?" in requestUrl: fragment = requestUrl[requestUrl.rfind("?") :] redirectUrl += fragment return flask.redirect(redirectUrl, code=code) def restricted_access(func): """ This combines :py:func:`no_firstrun_access` and ``login_required``. """ @functools.wraps(func) def decorated_view(*args, **kwargs): return no_firstrun_access(flask_login.login_required(func))(*args, **kwargs) return decorated_view def no_firstrun_access(func): """ If you decorate a view with this, it will ensure that first setup has been done for OctoPrint's Access Control. If OctoPrint's Access Control has not been setup yet (indicated by the userManager not reporting that its user database has been customized from default), the decorator will cause a HTTP 403 status code to be returned by the decorated resource. """ @functools.wraps(func) def decorated_view(*args, **kwargs): # if OctoPrint hasn't been set up yet, abort if settings().getBoolean(["server", "firstRun"]) and ( octoprint.server.userManager is None or not octoprint.server.userManager.has_been_customized() ): flask.abort(403) return func(*args, **kwargs) return decorated_view def firstrun_only_access(func): """ If you decorate a view with this, it will ensure that first setup has _not_ been done for OctoPrint's Access Control. Otherwise it will cause a HTTP 403 status code to be returned by the decorated resource. """ @functools.wraps(func) def decorated_view(*args, **kwargs): # if OctoPrint has been set up yet, abort if settings().getBoolean(["server", "firstRun"]) and ( octoprint.server.userManager is None or not octoprint.server.userManager.has_been_customized() ): return func(*args, **kwargs) else: flask.abort(403) return decorated_view def credentials_checked_recently(): minutes = settings().getInt(["accessControl", "defaultReauthenticationTimeout"]) if not minutes: return True login_mechanism = flask.session.get("login_mechanism") if not octoprint.server.util.LoginMechanism.reauthentication_enabled(login_mechanism): return True credentials_seen = flask.session.get("credentials_seen") now = datetime.now() try: if credentials_seen and datetime.fromtimestamp( credentials_seen ) > now - timedelta(minutes=minutes): # credentials seen less than the set minutes ago, proceed return True except Exception: logging.getLogger(__name__).exception("Error while checking for seen credentials") pass return False def ensure_credentials_checked_recently(): if not credentials_checked_recently(): flask.abort(403, description="Please reauthenticate with your credentials") def require_credentials_checked_recently(func): """ If you decorate a view with this, it will ensure that only users who entered their password recently in this login session are allowed to proceed. Otherwise it will cause a HTTP 403 status code to be returned by the decorated resource. """ @functools.wraps(func) def decorated_view(*args, **kwargs): ensure_credentials_checked_recently() return func(*args, **kwargs) return decorated_view @deprecated( "get_remote_address is no longer required and deprecated, you can just use flask.request.remote_addr instead", since="1.10.0", ) def get_remote_address(request): return request.remote_addr def get_json_command_from_request(request, valid_commands): data = request.get_json() if "command" not in data or data["command"] not in valid_commands: flask.abort(400, description="command is invalid") command = data["command"] if any(map(lambda x: x not in data, valid_commands[command])): flask.abort(400, description="Mandatory parameters missing") return command, data, None def make_text_response(message, status): """ Helper to generate basic text responses. Response will have the provided message as body, the provided status code, and a content type of "text/plain". Args: message: The message in the response body status: The HTTP status code Returns: """ return make_response(message, status, {"Content-Type": "text/plain"}) def make_api_error(message, status): """ Helper to generate API error responses in JSON format. Turns something like ``make_api_error("Not Found", 404)`` into a JSON response with body ``{"error": "Not Found"}``. Args: message: The error message to put into the response status: The HTTP status code Returns: a flask response to return to the client """ return make_response(flask.jsonify(error=message), status) ##~~ Flask-Assets resolver with plugin asset support class PluginAssetResolver(flask_assets.FlaskResolver): def split_prefix(self, ctx, item): app = ctx.environment._app if item.startswith("plugin/"): try: prefix, plugin, name = item.split("/", 2) blueprint = prefix + "." + plugin directory = flask_assets.get_static_folder(app.blueprints[blueprint]) item = name endpoint = blueprint + ".static" return directory, item, endpoint except (ValueError, KeyError): pass return flask_assets.FlaskResolver.split_prefix(self, ctx, item) def resolve_output_to_path(self, ctx, target, bundle): import os return os.path.normpath(os.path.join(ctx.environment.directory, target)) ##~~ Webassets updater that takes changes in the configuration into account class SettingsCheckUpdater(webassets.updater.BaseUpdater): updater = "always" def __init__(self): self._delegate = webassets.updater.get_updater(self.__class__.updater) def needs_rebuild(self, bundle, ctx): return self._delegate.needs_rebuild(bundle, ctx) or self.changed_settings(ctx) def changed_settings(self, ctx): if not ctx.cache: return False cache_key = ("octo", "settings") current_hash = settings().effective_hash cached_hash = ctx.cache.get(cache_key) # This may seem counter-intuitive, but if no cache entry is found # then we actually return "no update needed". This is because # otherwise if no cache / a dummy cache is used, then we would be # rebuilding every single time. if cached_hash is not None: return cached_hash != current_hash return False def build_done(self, bundle, ctx): self._delegate.build_done(bundle, ctx) if not ctx.cache: return cache_key = ("octo", "settings") ctx.cache.set(cache_key, settings().effective_hash) ##~~ core assets collector def collect_core_assets(preferred_stylesheet="css"): assets = {"js": [], "clientjs": [], "css": [], "less": []} assets["js"] = [ "js/app/bindings/allowbindings.js", "js/app/bindings/contextmenu.js", "js/app/bindings/gettext.js", "js/app/bindings/invisible.js", "js/app/bindings/popover.js", "js/app/bindings/qrcode.js", "js/app/bindings/slimscrolledforeach.js", "js/app/bindings/toggle.js", "js/app/bindings/togglecontent.js", "js/app/bindings/valuewithinit.js", "js/app/viewmodels/access.js", "js/app/viewmodels/appearance.js", "js/app/viewmodels/connection.js", "js/app/viewmodels/control.js", "js/app/viewmodels/files.js", "js/app/viewmodels/firstrun_wizard.js", "js/app/viewmodels/loginstate.js", "js/app/viewmodels/loginui.js", "js/app/viewmodels/navigation.js", "js/app/viewmodels/printerstate.js", "js/app/viewmodels/printerprofiles.js", "js/app/viewmodels/settings.js", "js/app/viewmodels/slicing.js", "js/app/viewmodels/system.js", "js/app/viewmodels/temperature.js", "js/app/viewmodels/terminal.js", "js/app/viewmodels/timelapse.js", "js/app/viewmodels/uistate.js", "js/app/viewmodels/users.js", "js/app/viewmodels/usersettings.js", "js/app/viewmodels/wizard.js", "js/app/viewmodels/about.js", ] assets["clientjs"] = [ "js/app/client/base.js", "js/app/client/socket.js", "js/app/client/access.js", "js/app/client/browser.js", "js/app/client/connection.js", "js/app/client/control.js", "js/app/client/files.js", "js/app/client/job.js", "js/app/client/languages.js", "js/app/client/printer.js", "js/app/client/printerprofiles.js", "js/app/client/settings.js", "js/app/client/slicing.js", "js/app/client/system.js", "js/app/client/timelapse.js", "js/app/client/users.js", "js/app/client/util.js", "js/app/client/wizard.js", ] if preferred_stylesheet == "less": assets["less"].append("less/octoprint.less") elif preferred_stylesheet == "css": assets["css"].append("css/octoprint.css") return assets ##~~ plugin assets collector def collect_plugin_assets(preferred_stylesheet="css"): logger = logging.getLogger(__name__ + ".collect_plugin_assets") supported_stylesheets = ("css", "less") assets = { "bundled": { "js": DefaultOrderedDict(list), "clientjs": DefaultOrderedDict(list), "css": DefaultOrderedDict(list), "less": DefaultOrderedDict(list), }, "external": { "js": DefaultOrderedDict(list), "clientjs": DefaultOrderedDict(list), "css": DefaultOrderedDict(list), "less": DefaultOrderedDict(list), }, } asset_plugins = octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.AssetPlugin ) for implementation in asset_plugins: name = implementation._identifier is_bundled = implementation._plugin_info.bundled asset_key = "bundled" if is_bundled else "external" try: all_assets = implementation.get_assets() basefolder = implementation.get_asset_folder() except Exception: logger.exception( "Got an error while trying to collect assets from {}, ignoring assets from the plugin".format( name ), extra={"plugin": name}, ) continue def asset_exists(category, asset): exists = os.path.exists(os.path.join(basefolder, asset)) if not exists: logger.warning( "Plugin {} is referring to non existing {} asset {}".format( name, category, asset ) ) return exists if "js" in all_assets: for asset in all_assets["js"]: if not asset_exists("js", asset): continue assets[asset_key]["js"][name].append(f"plugin/{name}/{asset}") if "clientjs" in all_assets: for asset in all_assets["clientjs"]: if not asset_exists("clientjs", asset): continue assets[asset_key]["clientjs"][name].append(f"plugin/{name}/{asset}") if preferred_stylesheet in all_assets: for asset in all_assets[preferred_stylesheet]: if not asset_exists(preferred_stylesheet, asset): continue assets[asset_key][preferred_stylesheet][name].append( f"plugin/{name}/{asset}" ) else: for stylesheet in supported_stylesheets: if stylesheet not in all_assets: continue for asset in all_assets[stylesheet]: if not asset_exists(stylesheet, asset): continue assets[asset_key][stylesheet][name].append(f"plugin/{name}/{asset}") break return assets ##~~ JSON encoding class OctoPrintJsonProvider(flask.json.provider.DefaultJSONProvider): @staticmethod def default(object_): try: return JsonEncoding.encode(object_) except TypeError: return flask.json.provider.DefaultJSONProvider.default(object_) def dumps(self, obj: Any, **kwargs: Any) -> str: kwargs.setdefault("allow_nan", False) return super().dumps(obj, **kwargs) ##~~ Session signing def session_signature(user, session): from octoprint.server import userManager key = userManager.signature_key_for_user(user, current_app.config["SECRET_KEY"]) return hmac.new( key.encode("utf-8"), session.encode("utf-8"), hashlib.sha512 ).hexdigest() def validate_session_signature(sig, user, session): user_sig = session_signature(user, session) return len(user_sig) == len(sig) and hmac.compare_digest(sig, user_sig) ##~~ Reverse proxy info class ReverseProxyInfo(BaseModel): client_ip: str server_protocol: str server_name: str server_port: int server_path: str cookie_suffix: str trusted_proxies: List[str] = [] headers: Dict[str, str] = {} def get_reverse_proxy_info(): headers = {} for header in sorted( ( "X-Forwarded-For", "X-Forwarded-Protocol", "X-Scheme", "X-Forwarded-Host", "X-Forwarded-Port", "X-Forwarded-Server", "Host", "X-Script-Name", ) ): if header in flask.request.headers: headers[header] = flask.request.headers[header] trusted_downstreams = settings().get(["server", "reverseProxy", "trustedDownstream"]) if not trusted_downstreams: trusted_downstreams = [] return ReverseProxyInfo( client_ip=flask.request.remote_addr, server_protocol=flask.request.environ.get("wsgi.url_scheme"), server_name=flask.request.environ.get("SERVER_NAME"), server_port=int(flask.request.environ.get("SERVER_PORT")), server_path=flask.request.script_root if flask.request.script_root else "/", cookie_suffix=get_cookie_suffix(flask.request), trusted_proxies=trusted_downstreams, headers=headers, )
68,419
Python
.py
1,615
31.16904
131
0.589068
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,893
tornado.py
OctoPrint_OctoPrint/src/octoprint/server/util/tornado.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import asyncio import logging import mimetypes import os import re import sys from urllib.parse import urlparse import tornado import tornado.escape import tornado.gen import tornado.http1connection import tornado.httpclient import tornado.httpserver import tornado.httputil import tornado.iostream import tornado.netutil import tornado.tcpserver import tornado.util import tornado.web from tornado.concurrent import dummy_executor from tornado.ioloop import IOLoop from zipstream.ng import ZIP_DEFLATED, ZipStream import octoprint.util import octoprint.util.net def fix_json_encode(): """ This makes tornado.escape.json_encode use octoprint.util.JsonEncoding.encode as fallback in order to allow serialization of globally registered types like frozendict and others. """ import json from octoprint.util.json import JsonEncoding def fixed_json_encode(value): return json.dumps(value, default=JsonEncoding.encode, allow_nan=False).replace( "</", "<\\/" ) import tornado.escape tornado.escape.json_encode = fixed_json_encode def enable_per_message_deflate_extension(): """ This configures tornado.websocket.WebSocketHandler.get_compression_options to support the permessage-deflate extension to the websocket protocol, minimizing data bandwidth if clients support the extension as well """ def get_compression_options(self): return {"compression_level": 1, "mem_level": 1} tornado.websocket.WebSocketHandler.get_compression_options = get_compression_options def fix_websocket_check_origin(): """ This fixes tornado.websocket.WebSocketHandler.check_origin to do the same origin check against the Host header case-insensitively, as defined in RFC6454, Section 4, item 5. """ scheme_translation = {"wss": "https", "ws": "http"} def patched_check_origin(self, origin): def get_check_tuple(urlstring): parsed = urlparse(urlstring) scheme = scheme_translation.get(parsed.scheme, parsed.scheme) return ( scheme, parsed.hostname, ( parsed.port if parsed.port else 80 if scheme == "http" else 443 if scheme == "https" else None ), ) return get_check_tuple(origin) == get_check_tuple(self.request.full_url()) import tornado.websocket tornado.websocket.WebSocketHandler.check_origin = patched_check_origin def fix_tornado_xheader_handling(): """ This fixes tornado.httpserver._HTTPRequestContext._apply_xheaders to only use "X-Forwarded-For" header for rewriting the ``remote_ip`` field, utilizing the set of trusted downstreams, instead of blindly trusting ``X-Real-Ip``, and to also fetch the scheme from "X-Forwarded-Proto" if available. """ def patched_apply_xheaders(self, headers: "tornado.httputil.HTTPHeaders") -> None: """Rewrite the ``remote_ip`` and ``protocol`` fields.""" # other than the default implementation, we only use "X-Forwarded-For" here, not "X-Real-Ip" ip = octoprint.util.net.get_http_client_ip( self.remote_ip, headers.get("X-Forwarded-For"), self.trusted_downstream ) if tornado.netutil.is_valid_ip(ip): self.remote_ip = ip # also fetch scheme from "X-Forwarded-Proto" if available proto_header = headers.get("X-Scheme", headers.get("X-Forwarded-Proto")) if proto_header: # use only the last proto entry if there is more than one proto_header = proto_header.split(",")[-1].strip() if proto_header in ("http", "https"): self.protocol = proto_header import tornado.httpserver tornado.httpserver._HTTPRequestContext._apply_xheaders = patched_apply_xheaders # ~~ More sensible logging class RequestlessExceptionLoggingMixin(tornado.web.RequestHandler): LOG_REQUEST = False def log_exception(self, typ, value, tb, *args, **kwargs): if isinstance(value, tornado.web.HTTPError): if value.log_message: format = "%d %s: " + value.log_message args = [value.status_code, self._request_summary()] + list(value.args) tornado.web.gen_log.warning(format, *args) else: if self.LOG_REQUEST: tornado.web.app_log.error( "Uncaught exception %s\n%r", self._request_summary(), self.request, exc_info=(typ, value, tb), ) else: tornado.web.app_log.error( "Uncaught exception %s", self._request_summary(), exc_info=(typ, value, tb), ) # ~~ CORS support class CorsSupportMixin(tornado.web.RequestHandler): """ `tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ mixin that makes sure to set CORS headers similarly to the Flask backed API endpoints. """ ENABLE_CORS = False def set_default_headers(self): origin = self.request.headers.get("Origin") if self.request.method != "OPTIONS" and origin and self.ENABLE_CORS: self.set_header("Access-Control-Allow-Origin", origin) @tornado.gen.coroutine def options(self, *args, **kwargs): if self.ENABLE_CORS: origin = self.request.headers.get("Origin") method = self.request.headers.get("Access-Control-Request-Method") # Allow the origin which made the XHR self.set_header("Access-Control-Allow-Origin", origin) # Allow the actual method self.set_header("Access-Control-Allow-Methods", method) # Allow for 10 seconds self.set_header("Access-Control-Max-Age", "10") # 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key) custom_headers = self.request.headers.get("Access-Control-Request-Headers") if custom_headers is not None: self.set_header("Access-Control-Allow-Headers", custom_headers) self.set_status(204) self.finish() # ~~ WSGI middleware @tornado.web.stream_request_body class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupportMixin): """ A ``RequestHandler`` similar to ``tornado.web.FallbackHandler`` which fetches any files contained in the request bodies of content type ``multipart``, stores them in temporary files and supplies the ``fallback`` with the file's ``name``, ``content_type``, ``path`` and ``size`` instead via a rewritten body. Basically similar to what the nginx upload module does. Basic request body example: .. code-block:: none ------WebKitFormBoundarypYiSUx63abAmhT5C Content-Disposition: form-data; name="file"; filename="test.gcode" Content-Type: application/octet-stream ... ------WebKitFormBoundarypYiSUx63abAmhT5C Content-Disposition: form-data; name="apikey" my_funny_apikey ------WebKitFormBoundarypYiSUx63abAmhT5C Content-Disposition: form-data; name="select" true ------WebKitFormBoundarypYiSUx63abAmhT5C-- That would get turned into: .. code-block:: none ------WebKitFormBoundarypYiSUx63abAmhT5C Content-Disposition: form-data; name="apikey" my_funny_apikey ------WebKitFormBoundarypYiSUx63abAmhT5C Content-Disposition: form-data; name="select" true ------WebKitFormBoundarypYiSUx63abAmhT5C Content-Disposition: form-data; name="file.path" Content-Type: text/plain; charset=utf-8 /tmp/tmpzupkro ------WebKitFormBoundarypYiSUx63abAmhT5C Content-Disposition: form-data; name="file.name" Content-Type: text/plain; charset=utf-8 test.gcode ------WebKitFormBoundarypYiSUx63abAmhT5C Content-Disposition: form-data; name="file.content_type" Content-Type: text/plain; charset=utf-8 application/octet-stream ------WebKitFormBoundarypYiSUx63abAmhT5C Content-Disposition: form-data; name="file.size" Content-Type: text/plain; charset=utf-8 349182 ------WebKitFormBoundarypYiSUx63abAmhT5C-- The underlying application can then access the contained files via their respective paths and just move them where necessary. """ BODY_METHODS = ("POST", "PATCH", "PUT") """ The request methods that may contain a request body. """ def initialize( self, fallback, file_prefix="tmp", file_suffix="", path=None, suffixes=None ): if not suffixes: suffixes = {} self._fallback = fallback self._file_prefix = file_prefix self._file_suffix = file_suffix self._path = path self._suffixes = {key: key for key in ("name", "path", "content_type", "size")} for suffix_type, suffix in suffixes.items(): if suffix_type in self._suffixes and suffix is not None: self._suffixes[suffix_type] = suffix # multipart boundary self._multipart_boundary = None # Parts, files and values will be stored here self._parts = {} self._files = [] # Part currently being processed self._current_part = None # content type of request body self._content_type = None # bytes left to read according to content_length of request body self._bytes_left = 0 # buffer needed for identifying form data parts self._buffer = b"" # buffer for new body self._new_body = b"" # logger self._logger = logging.getLogger(__name__) def prepare(self): """ Prepares the processing of the request. If it's a request that may contain a request body (as defined in :attr:`UploadStorageFallbackHandler.BODY_METHODS`) prepares the multipart parsing if content type fits. If it's a body-less request, just calls the ``fallback`` with an empty body and finishes the request. """ if self.request.method in UploadStorageFallbackHandler.BODY_METHODS: self._bytes_left = self.request.headers.get("Content-Length", 0) self._content_type = self.request.headers.get("Content-Type", None) # request might contain a body if self.is_multipart(): if not self._bytes_left: # we don't support requests without a content-length raise tornado.web.HTTPError( 411, log_message="No Content-Length supplied" ) # extract the multipart boundary fields = self._content_type.split(";") for field in fields: k, sep, v = field.strip().partition("=") if k == "boundary" and v: if v.startswith('"') and v.endswith('"'): self._multipart_boundary = tornado.escape.utf8(v[1:-1]) else: self._multipart_boundary = tornado.escape.utf8(v) break else: # RFC2046 section 5.1 (as referred to from RFC 7578) defines the boundary # parameter as mandatory for multipart requests: # # The only mandatory global parameter for the "multipart" media type is # the boundary parameter, which consists of 1 to 70 characters [...] # # So no boundary? 400 Bad Request raise tornado.web.HTTPError( 400, log_message="No multipart boundary supplied" ) else: self._fallback(self.request, b"") self._finished = True self.on_finish() def data_received(self, chunk): """ Called by Tornado on receiving a chunk of the request body. If request is a multipart request, takes care of processing the multipart data structure via :func:`_process_multipart_data`. If not, just adds the chunk to internal in-memory buffer. :param chunk: chunk of data received from Tornado """ data = self._buffer + chunk if self.is_multipart(): self._process_multipart_data(data) else: self._buffer = data def is_multipart(self): """Checks whether this request is a ``multipart`` request""" return self._content_type is not None and self._content_type.startswith( "multipart" ) def _process_multipart_data(self, data): """ Processes the given data, parsing it for multipart definitions and calling the appropriate methods. :param data: the data to process as a string """ # check for boundary delimiter = b"--%s" % self._multipart_boundary delimiter_loc = data.find(delimiter) delimiter_len = len(delimiter) end_of_header = -1 if delimiter_loc != -1: # found the delimiter in the currently available data delimiter_data_end = 0 if delimiter_loc == 0 else delimiter_loc - 2 data, self._buffer = data[0:delimiter_data_end], data[delimiter_loc:] end_of_header = self._buffer.find(b"\r\n\r\n") else: # make sure any boundary (with single or double ==) contained at the end of chunk does not get # truncated by this processing round => save it to the buffer for next round endlen = len(self._multipart_boundary) + 4 data, self._buffer = data[0:-endlen], data[-endlen:] # stream data to part handler if data and self._current_part: self._on_part_data(self._current_part, data) if end_of_header >= 0: self._on_part_header(self._buffer[delimiter_len + 2 : end_of_header]) self._buffer = self._buffer[end_of_header + 4 :] if delimiter_loc != -1 and self._buffer.strip() == delimiter + b"--": # we saw the last boundary and are at the end of our request if self._current_part: self._on_part_finish(self._current_part) self._current_part = None self._buffer = b"" self._on_request_body_finish() def _on_part_header(self, header): """ Called for a new multipart header, takes care of parsing the header and calling :func:`_on_part` with the relevant data, setting the current part in the process. :param header: header to parse """ # close any open parts if self._current_part: self._on_part_finish(self._current_part) self._current_part = None header_check = header.find(self._multipart_boundary) if header_check != -1: self._logger.warning( "Header still contained multipart boundary, stripping it..." ) header = header[header_check:] # convert to dict try: header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8")) except UnicodeDecodeError: try: header = tornado.httputil.HTTPHeaders.parse(header.decode("iso-8859-1")) except Exception: # looks like we couldn't decode something here neither as UTF-8 nor ISO-8859-1 self._logger.warning( "Could not decode multipart headers in request, should be either UTF-8 or ISO-8859-1" ) self.send_error(400) return disp_header = header.get("Content-Disposition", "") disposition, disp_params = _parse_header(disp_header, strip_quotes=False) if disposition != "form-data": self._logger.warning( "Got a multipart header without form-data content disposition, ignoring that one" ) return if not disp_params.get("name"): self._logger.warning("Got a multipart header without name, ignoring that one") return filename = disp_params.get("filename*", None) # RFC 5987 header present? if filename is not None: try: filename = _extended_header_value(filename) except Exception: # parse error, this is not RFC 5987 compliant after all self._logger.warning( "extended filename* value {!r} is not RFC 5987 compliant".format( filename ) ) self.send_error(400) return else: # no filename* header, just strip quotes from filename header then and be done filename = _strip_value_quotes(disp_params.get("filename", None)) self._current_part = self._on_part_start( _strip_value_quotes(disp_params["name"]), header.get("Content-Type", None), filename=filename, ) def _on_part_start(self, name, content_type, filename=None): """ Called for new parts in the multipart stream. If ``filename`` is given creates new ``file`` part (which leads to storage of the data as temporary file on disk), if not creates a new ``data`` part (which stores incoming data in memory). Structure of ``file`` parts: * ``name``: name of the part * ``filename``: filename associated with the part * ``path``: path to the temporary file storing the file's data * ``content_type``: content type of the part * ``file``: file handle for the temporary file (mode "wb", not deleted on close, will be deleted however after handling of the request has finished in :func:`_handle_method`) Structure of ``data`` parts: * ``name``: name of the part * ``content_type``: content type of the part * ``data``: bytes of the part (initialized to an empty string) :param name: name of the part :param content_type: content type of the part :param filename: filename associated with the part. :return: dict describing the new part """ if filename is not None: # this is a file import tempfile handle = tempfile.NamedTemporaryFile( mode="wb", prefix=self._file_prefix, suffix=self._file_suffix, dir=self._path, delete=False, ) return { "name": tornado.escape.utf8(name), "filename": tornado.escape.utf8(filename), "path": tornado.escape.utf8(handle.name), "content_type": tornado.escape.utf8(content_type), "file": handle, } else: return { "name": tornado.escape.utf8(name), "content_type": tornado.escape.utf8(content_type), "data": b"", } def _on_part_data(self, part, data): """ Called when new bytes are received for the given ``part``, takes care of writing them to their storage. :param part: part for which data was received :param data: data chunk which was received """ if "file" in part: part["file"].write(data) else: part["data"] += data def _on_part_finish(self, part): """ Called when a part gets closed, takes care of storing the finished part in the internal parts storage and for ``file`` parts closing the temporary file and storing the part in the internal files storage. :param part: part which was closed """ name = part["name"] self._parts[name] = part if "file" in part: self._files.append(part["path"]) part["file"].close() del part["file"] def _on_request_body_finish(self): """ Called when the request body has been read completely. Takes care of creating the replacement body out of the logged parts, turning ``file`` parts into new ``data`` parts. """ self._new_body = b"" for name, part in self._parts.items(): if "filename" in part: # add form fields for filename, path, size and content_type for all files contained in the request if "path" not in part: continue parameters = { "name": part["filename"], "path": part["path"], "size": str(os.stat(part["path"]).st_size), } if "content_type" in part: parameters["content_type"] = part["content_type"] fields = { self._suffixes[key]: value for (key, value) in parameters.items() } for n, p in fields.items(): if n is None or p is None: continue key = name + b"." + octoprint.util.to_bytes(n) self._new_body += b"--%s\r\n" % self._multipart_boundary self._new_body += ( b'Content-Disposition: form-data; name="%s"\r\n' % key ) self._new_body += b"Content-Type: text/plain; charset=utf-8\r\n" self._new_body += b"\r\n" self._new_body += octoprint.util.to_bytes(p) + b"\r\n" elif "data" in part: self._new_body += b"--%s\r\n" % self._multipart_boundary value = part["data"] self._new_body += b'Content-Disposition: form-data; name="%s"\r\n' % name if "content_type" in part and part["content_type"] is not None: self._new_body += b"Content-Type: %s\r\n" % part["content_type"] self._new_body += b"\r\n" self._new_body += value + b"\r\n" self._new_body += b"--%s--\r\n" % self._multipart_boundary async def _handle_method(self, *args, **kwargs): """ Takes care of defining the new request body if necessary and forwarding the current request and changed body to the ``fallback``. """ # determine which body to supply body = b"" if self.is_multipart(): # make sure we really processed all data in the buffer while len(self._buffer): self._process_multipart_data(self._buffer) # use rewritten body body = self._new_body elif self.request.method in UploadStorageFallbackHandler.BODY_METHODS: # directly use data from buffer body = self._buffer self.request.headers["Content-Length"] = len(body) try: # call the configured fallback with request and body to use result = self._fallback(self.request, body) if result is not None: await result finally: self._finished = True self.on_finish() def on_finish(self): self._cleanup_files() def _cleanup_files(self): """ Removes all temporary files created by this handler. """ for f in self._files: octoprint.util.silent_remove(f) # make all http methods trigger _handle_method get = _handle_method post = _handle_method put = _handle_method patch = _handle_method delete = _handle_method head = _handle_method options = _handle_method def _parse_header(line, strip_quotes=True): parts = tornado.httputil._parseparam(";" + line) key = next(parts) pdict = {} for p in parts: i = p.find("=") if i >= 0: name = p[:i].strip().lower() value = p[i + 1 :].strip() if strip_quotes: value = _strip_value_quotes(value) pdict[name] = value return key, pdict def _strip_value_quotes(value): if not value: return value if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] value = value.replace("\\\\", "\\").replace('\\"', '"') return value def _extended_header_value(value): if not value: return value if value.lower().startswith("iso-8859-1'") or value.lower().startswith("utf-8'"): # RFC 5987 section 3.2 from urllib.parse import unquote encoding, _, value = value.split("'", 2) return unquote(value, encoding=encoding) else: # no encoding provided, strip potentially present quotes and call it a day return octoprint.util.to_unicode(_strip_value_quotes(value), encoding="utf-8") class WsgiInputContainer: """ A WSGI container for use with Tornado that allows supplying the request body to be used for ``wsgi.input`` in the generated WSGI environment upon call. A ``RequestHandler`` can thus provide the WSGI application with a stream for the request body, or a modified body. Example usage: .. code-block:: python wsgi_app = octoprint.server.util.WsgiInputContainer(octoprint_app) application = tornado.web.Application([ (r".*", UploadStorageFallbackHandler, dict(fallback=wsgi_app), ]) The implementation logic is basically the same as ``tornado.wsgi.WSGIContainer`` but the ``__call__`` and ``environ`` methods have been adjusted to allow for an optionally supplied ``body`` argument which is then used for ``wsgi.input``. Additionally, some headers can be added or removed from the response by supplying ``forced_headers`` and ``removed_headers`` arguments. ``forced_headers`` will be added to the response, ``removed_headers`` will be removed. """ def __init__( self, wsgi_application, executor=None, headers=None, forced_headers=None, removed_headers=None, ): self.wsgi_application = wsgi_application self.executor = dummy_executor if executor is None else executor if headers is None: headers = {} if forced_headers is None: forced_headers = {} if removed_headers is None: removed_headers = [] self.headers = headers self.forced_headers = forced_headers self.removed_headers = removed_headers def __call__(self, request, body=None): future = tornado.concurrent.Future() IOLoop.current().spawn_callback( self.handle_request, request, body=body, future=future ) return future async def handle_request(self, request, body=None, future=None): """ Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado ``HTTPServerRequest``. :param request: the ``tornado.httpserver.HTTPServerRequest`` to derive the WSGI environment from :param body: an optional body to use as ``wsgi.input`` instead of ``request.body``, can be a string or a stream :param future: a future to complete after the request has been handled """ data = {} response = [] def start_response(status, response_headers, exc_info=None): data["status"] = status data["headers"] = response_headers return response.append try: loop = IOLoop.current() app_response = await loop.run_in_executor( self.executor, self.wsgi_application, self.environ(request, body), start_response, ) try: app_response_iter = iter(app_response) def next_chunk(): try: return next(app_response_iter) except StopIteration: return None while True: chunk = await loop.run_in_executor(self.executor, next_chunk) if chunk is None: break response.append(chunk) finally: if hasattr(app_response, "close"): app_response.close() body = b"".join(response) if not data: raise Exception("WSGI app did not call start_response") status_code_str, reason = data["status"].split(" ", 1) status_code = int(status_code_str) headers = data["headers"] header_set = {k.lower() for (k, v) in headers} body = tornado.escape.utf8(body) if status_code != 304: if "content-length" not in header_set: headers.append(("Content-Length", str(len(body)))) if "content-type" not in header_set: headers.append(("Content-Type", "text/html; charset=UTF-8")) header_set = {k.lower() for (k, v) in headers} for header, value in self.headers.items(): if header.lower() not in header_set: headers.append((header, value)) for header, value in self.forced_headers.items(): headers.append((header, value)) headers = [ (header, value) for header, value in headers if header.lower() not in self.removed_headers ] start_line = tornado.httputil.ResponseStartLine( "HTTP/1.1", status_code, reason ) header_obj = tornado.httputil.HTTPHeaders() for key, value in headers: header_obj.add(key, value) assert request.connection is not None request.connection.write_headers(start_line, header_obj, chunk=body) request.connection.finish() self._log(status_code, request) except Exception: logging.getLogger(__name__).exception("Exception in WSGI application") finally: if future is not None: future.set_result(None) @staticmethod def environ(request, body=None): """ Converts a ``tornado.httputil.HTTPServerRequest`` to a WSGI environment. An optional ``body`` to be used for populating ``wsgi.input`` can be supplied (either a string or a stream). If not supplied, ``request.body`` will be wrapped into a ``io.BytesIO`` stream and used instead. :param request: the ``tornado.httpserver.HTTPServerRequest`` to derive the WSGI environment from :param body: an optional body to use as ``wsgi.input`` instead of ``request.body``, can be a string or a stream """ import io from tornado.wsgi import to_wsgi_str # determine the request_body to supply as wsgi.input if body is not None: if isinstance(body, (bytes, str)): request_body = io.BytesIO(tornado.escape.utf8(body)) else: request_body = body else: request_body = io.BytesIO(tornado.escape.utf8(request.body)) hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: host = request.host port = 443 if request.protocol == "https" else 80 environ = { "REQUEST_METHOD": request.method, "SCRIPT_NAME": "", "PATH_INFO": to_wsgi_str( tornado.escape.url_unescape(request.path, encoding=None, plus=False) ), "QUERY_STRING": request.query, "REMOTE_ADDR": request.remote_ip, "SERVER_NAME": host, "SERVER_PORT": str(port), "SERVER_PROTOCOL": request.version, "wsgi.version": (1, 0), "wsgi.url_scheme": request.protocol, "wsgi.input": request_body, "wsgi.errors": sys.stderr, "wsgi.multithread": False, "wsgi.multiprocess": True, "wsgi.run_once": False, } if "Content-Type" in request.headers: environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") if "Content-Length" in request.headers: environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") # remove transfer encoding header if chunked, otherwise flask wsgi entrypoint makes input empty if ( "Transfer-Encoding" in request.headers and request.headers.get("Transfer-Encoding") == "chunked" ): request.headers.pop("Transfer-Encoding") for key, value in request.headers.items(): environ["HTTP_" + key.replace("-", "_").upper()] = value return environ def _log(self, status_code, request): access_log = logging.getLogger("tornado.access") if status_code < 400: log_method = access_log.info elif status_code < 500: log_method = access_log.warning else: log_method = access_log.error request_time = 1000 * request.request_time() summary = request.method + " " + request.uri + " (" + request.remote_ip + ")" log_method("%d %s %.2fms", status_code, summary, request_time) # ~~ customized HTTP1Connection implementation class CustomHTTPServer(tornado.httpserver.HTTPServer): """ Custom implementation of ``tornado.httpserver.HTTPServer`` that allows defining max body sizes depending on path and method. The implementation is mostly taken from ``tornado.httpserver.HTTPServer``, the only difference is the creation of a ``CustomHTTP1ConnectionParameters`` instance instead of ``tornado.http1connection.HTTP1ConnectionParameters`` which is supplied with the two new constructor arguments ``max_body_sizes`` and ``max_default_body_size`` and the creation of a ``CustomHTTP1ServerConnection`` instead of a ``tornado.http1connection.HTTP1ServerConnection`` upon connection by a client. ``max_body_sizes`` is expected to be an iterable containing tuples of the form (method, path regex, maximum body size), with method and path regex having to match in order for maximum body size to take affect. ``default_max_body_size`` is the default maximum body size to apply if no specific one from ``max_body_sizes`` matches. """ def __init__(self, *args, **kwargs): pass 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 = { "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, self.trusted_downstream ) conn = CustomHTTP1ServerConnection(stream, self.conn_params, context) self._connections.add(conn) conn.start_serving(self) class CustomHTTP1ServerConnection(tornado.http1connection.HTTP1ServerConnection): """ A custom implementation of ``tornado.http1connection.HTTP1ServerConnection`` which utilizes a ``CustomHTTP1Connection`` instead of a ``tornado.http1connection.HTTP1Connection`` in ``_server_request_loop``. The implementation logic is otherwise the same as ``tornado.http1connection.HTTP1ServerConnection``. """ async def _server_request_loop(self, delegate): try: while True: conn = CustomHTTP1Connection( self.stream, False, self.params, self.context ) request_delegate = delegate.start_request(self, conn) try: ret = await conn.read_response(request_delegate) except ( tornado.iostream.StreamClosedError, tornado.iostream.UnsatisfiableReadError, asyncio.CancelledError, ): return except tornado.http1connection._QuietException: # This exception was already logged. conn.close() return except Exception: tornado.http1connection.gen_log.error( "Uncaught exception", exc_info=True ) conn.close() return if not ret: return await asyncio.sleep(0) finally: delegate.on_close(self) class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection): """ A custom implementation of ``tornado.http1connection.HTTP1Connection`` which upon checking the ``Content-Length`` of the request against the configured maximum utilizes ``max_body_sizes`` and ``default_max_body_size`` as a fallback. """ def __init__(self, stream, is_client, params=None, context=None): if params is None: params = CustomHTTP1ConnectionParameters() tornado.http1connection.HTTP1Connection.__init__( self, stream, is_client, params=params, context=context ) import re self._max_body_sizes = list( map( lambda x: (x[0], re.compile(x[1]), x[2]), self.params.max_body_sizes or [], ) ) self._default_max_body_size = ( self.params.default_max_body_size or self.stream.max_buffer_size ) def _read_body(self, code, headers, delegate): """ Basically the same as ``tornado.http1connection.HTTP1Connection._read_body``, but determines the maximum content length individually for the request (utilizing ``._get_max_content_length``). If the individual max content length is 0 or smaller no content length is checked. If the content length of the current request exceeds the individual max content length, the request processing is aborted and an ``HTTPInputError`` is raised. """ 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 # use them but if they differ it's an error. pieces = re.split(r",\s*", headers["Content-Length"]) if any(i != pieces[0] for i in pieces): raise tornado.httputil.HTTPInputError( "Multiple unequal Content-Lengths: %r" % headers["Content-Length"] ) headers["Content-Length"] = pieces[0] 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") else: content_length = None if code == 204: # This response code is not allowed to have a non-empty body, # and has an implicit length of zero instead of read-until-close. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 if "Transfer-Encoding" in headers or content_length not in (None, 0): raise tornado.httputil.HTTPInputError( "Response with code %d should not have body" % code ) content_length = 0 if content_length is not None: return self._read_fixed_body(content_length, delegate) if headers.get("Transfer-Encoding") == "chunked": return self._read_chunked_body(delegate) if self.is_client: return self._read_body_until_close(delegate) return None def _get_max_content_length(self, method, path): """ Gets the max content length for the given method and path. Checks whether method and path match against any of the specific maximum content lengths supplied in ``max_body_sizes`` and returns that as the maximum content length if available, otherwise returns ``default_max_body_size``. :param method: method of the request to match against :param path: path of the request to match against :return: determine maximum content length to apply to this request, max return 0 for unlimited allowed content length """ for m, p, s in self._max_body_sizes: if method == m and p.match(path): return s return self._default_max_body_size class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionParameters): """ An implementation of ``tornado.http1connection.HTTP1ConnectionParameters`` that adds two new parameters ``max_body_sizes`` and ``default_max_body_size``. For a description of these please see the documentation of ``CustomHTTPServer`` above. """ def __init__(self, *args, **kwargs): 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 class LargeResponseHandler( RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.StaticFileHandler ): """ Customized `tornado.web.StaticFileHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#tornado.web.StaticFileHandler>`_ that allows delivery of the requested resource as attachment and access and request path validation through optional callbacks. Note that access validation takes place before path validation. Arguments: path (str): The system path from which to serve files (this will be forwarded to the ``initialize`` method of :class:``~tornado.web.StaticFileHandler``) default_filename (str): The default filename to serve if none is explicitly specified and the request references a subdirectory of the served path (this will be forwarded to the ``initialize`` method of :class:``~tornado.web.StaticFileHandler`` as the ``default_filename`` keyword parameter). Defaults to ``None``. as_attachment (bool): Whether to serve requested files with ``Content-Disposition: attachment`` header (``True``) or not. Defaults to ``False``. allow_client_caching (bool): Whether to allow the client to cache (by not setting any ``Cache-Control`` or ``Expires`` headers on the response) or not. access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will be called with ``self.request`` as parameter which contains the full tornado request object. Should raise a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed. Defaults to ``None`` and hence no access validation being performed. path_validation (function): Callback to call in the ``get`` method to validate the requested path. Will be called with the requested path as parameter. Should raise a ``tornado.web.HTTPError`` (e.g. an 404) if the requested path does not pass validation in which case the request will not be further processed. Defaults to ``None`` and hence no path validation being performed. etag_generator (function): Callback to call for generating the value of the ETag response header. Will be called with the response handler as parameter. May return ``None`` to prevent the ETag response header from being set. If not provided the last modified time of the file in question will be used as returned by ``get_content_version``. name_generator (function): Callback to call for generating the value of the attachment file name header. Will be called with the requested path as parameter. mime_type_guesser (function): Callback to guess the mime type to use for the content type encoding of the response. Will be called with the requested path on disk as parameter. is_pre_compressed (bool): if the file is expected to be pre-compressed, i.e, if there is a file in the same directory with the same name, but with '.gz' appended and gzip-encoded """ def initialize( self, path, default_filename=None, as_attachment=False, allow_client_caching=True, access_validation=None, path_validation=None, etag_generator=None, name_generator=None, mime_type_guesser=None, is_pre_compressed=False, stream_body=False, ): tornado.web.StaticFileHandler.initialize( self, os.path.abspath(path), default_filename ) self._as_attachment = as_attachment self._allow_client_caching = allow_client_caching self._access_validation = access_validation self._path_validation = path_validation self._etag_generator = etag_generator self._name_generator = name_generator self._mime_type_guesser = mime_type_guesser self._is_pre_compressed = is_pre_compressed self._stream_body = stream_body def should_use_precompressed(self): return self._is_pre_compressed and "gzip" in self.request.headers.get( "Accept-Encoding", "" ) def get(self, path, include_body=True): if self._access_validation is not None: self._access_validation(self.request) if self._path_validation is not None: self._path_validation(path) if "cookie" in self.request.arguments: self.set_cookie(self.request.arguments["cookie"][0], "true", path="/") if self.should_use_precompressed(): if os.path.exists(os.path.join(self.root, path + ".gz")): self.set_header("Content-Encoding", "gzip") path = path + ".gz" else: logging.getLogger(__name__).warning( "Precompressed assets expected but {}.gz does not exist " "in {}, using plain file instead.".format(path, self.root) ) if self._stream_body: return self.streamed_get(path, include_body=include_body) else: return tornado.web.StaticFileHandler.get( self, path, include_body=include_body ) @tornado.gen.coroutine def streamed_get(self, path, include_body=True): """ Version of StaticFileHandler.get that doesn't support ranges or ETag but streams the content. Helpful for files that might still change while being transmitted (e.g. log files) """ # Set up our path instance variables. self.path = self.parse_url_path(path) del path # make sure we don't refer to path instead of self.path again absolute_path = self.get_absolute_path(self.root, self.path) self.absolute_path = self.validate_absolute_path(self.root, absolute_path) if self.absolute_path is None: return content_type = self.get_content_type() if content_type: self.set_header("Content-Type", content_type) self.set_extra_headers(self.path) if include_body: content = self.get_content(self.absolute_path) if isinstance(content, bytes): content = [content] for chunk in content: try: self.write(chunk) yield self.flush() except tornado.iostream.StreamClosedError: return else: assert self.request.method == "HEAD" def set_extra_headers(self, path): if self._as_attachment: filename = None if callable(self._name_generator): filename = self._name_generator(path) if filename is None: filename = os.path.basename(path) filename = tornado.escape.url_escape(filename, plus=False) self.set_header( "Content-Disposition", "attachment; filename=\"{}\"; filename*=UTF-8''{}".format( filename, filename ), ) if not self._allow_client_caching: self.set_header("Cache-Control", "max-age=0, must-revalidate, private") self.set_header("Expires", "-1") self.set_header("X-Original-Content-Length", str(self.get_content_size())) @property def original_absolute_path(self): """The path of the uncompressed file corresponding to the compressed file""" if self._is_pre_compressed: return self.absolute_path.rstrip(".gz") return self.absolute_path def compute_etag(self): if self._etag_generator is not None: etag = self._etag_generator(self) else: etag = str(self.get_content_version(self.absolute_path)) if not etag.endswith('"'): etag = f'"{etag}"' return etag # noinspection PyAttributeOutsideInit def get_content_type(self): if self._mime_type_guesser is not None: type = self._mime_type_guesser(self.original_absolute_path) if type is not None: return type correct_absolute_path = None try: # reset self.absolute_path temporarily if self.should_use_precompressed(): correct_absolute_path = self.absolute_path self.absolute_path = self.original_absolute_path return tornado.web.StaticFileHandler.get_content_type(self) finally: # restore self.absolute_path if self.should_use_precompressed() and correct_absolute_path is not None: self.absolute_path = correct_absolute_path @classmethod def get_content_version(cls, abspath): import os import stat return os.stat(abspath)[stat.ST_MTIME] ##~~ URL Forward Handler for forwarding requests to a preconfigured static URL class UrlProxyHandler( RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.RequestHandler ): """ `tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment and access validation through an optional callback. This will use `tornado.httpclient.AsyncHTTPClient <http://tornado.readthedocs.org/en/branch4.0/httpclient.html#tornado.httpclient.AsyncHTTPClient>`_ for making the request to the configured endpoint and return the body of the client response with the status code from the client response and the following headers: * ``Date``, ``Cache-Control``, ``Expires``, ``ETag``, ``Server``, ``Content-Type`` and ``Location`` will be copied over. * If ``as_attachment`` is set to True, ``Content-Disposition`` will be set to ``attachment``. If ``basename`` is set including the attachment's ``filename`` attribute will be set to the base name followed by the extension guessed based on the MIME type from the ``Content-Type`` header of the response. If no extension can be guessed no ``filename`` attribute will be set. Arguments: url (str): URL to forward any requests to. A 404 response will be returned if this is not set. Defaults to ``None``. as_attachment (bool): Whether to serve files with ``Content-Disposition: attachment`` header (``True``) or not. Defaults to ``False``. basename (str): base name of file names to return as part of the attachment header, see above. Defaults to ``None``. access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will be called with ``self.request`` as parameter which contains the full tornado request object. Should raise a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed. Defaults to ``None`` and hence no access validation being performed. """ def initialize( self, url=None, as_attachment=False, basename=None, access_validation=None ): tornado.web.RequestHandler.initialize(self) self._url = url self._as_attachment = as_attachment self._basename = basename self._access_validation = access_validation @tornado.gen.coroutine def get(self, *args, **kwargs): if self._access_validation is not None: self._access_validation(self.request) if self._url is None: raise tornado.web.HTTPError(404) client = tornado.httpclient.AsyncHTTPClient() r = tornado.httpclient.HTTPRequest( url=self._url, method=self.request.method, body=self.request.body, headers=self.request.headers, follow_redirects=False, allow_nonstandard_methods=True, ) try: return client.fetch(r, self.handle_response) except tornado.web.HTTPError as e: if hasattr(e, "response") and e.response: self.handle_response(e.response) else: raise tornado.web.HTTPError(500) def handle_response(self, response): if response.error and not isinstance(response.error, tornado.web.HTTPError): raise tornado.web.HTTPError(500) filename = None self.set_status(response.code) for name in ( "Date", "Cache-Control", "Server", "Content-Type", "Location", "Expires", "ETag", ): value = response.headers.get(name) if value: self.set_header(name, value) if name == "Content-Type": filename = self.get_filename(value) if self._as_attachment: if filename is not None: self.set_header( "Content-Disposition", "attachment; filename=%s" % filename ) else: self.set_header("Content-Disposition", "attachment") if response.body: self.write(response.body) self.finish() def get_filename(self, content_type): if not self._basename: return None typeValue = list(x.strip() for x in content_type.split(";")) if len(typeValue) == 0: return None extension = mimetypes.guess_extension(typeValue[0]) if not extension: return None return f"{self._basename}{extension}" class StaticDataHandler( RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.RequestHandler ): """ `tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that returns static ``data`` of a configured ``content_type``. Arguments: data (str): The data with which to respond content_type (str): The content type with which to respond. Defaults to ``text/plain`` """ def initialize(self, data="", content_type="text/plain"): self.data = data self.content_type = content_type def get(self, *args, **kwargs): self.set_status(200) self.set_header("Content-Type", self.content_type) self.write(self.data) self.flush() self.finish() class GeneratingDataHandler( RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.RequestHandler ): """ A `RequestHandler` that generates data from a generator function and returns it to the client. Arguments: generator (function): A generator function that returns the data to be written to the client. The function will be called without any parameters. content_type (str): The content type with which to respond. Defaults to `text/plain` as_attachment (bool | str): Whether to serve files with `Content-Disposition: attachment` header (`True`) or not. Defaults to `False`. If a string is given it will be used as the filename of the attachment. access_validation (function): Callback to call in the `get` method to validate access to the resource. Will be called with `self.request` as parameter which contains the full tornado request object. Should raise a `tornado.web.HTTPError` if access is not allowed in which case the request will not be further processed. Defaults to `None` and hence no access validation being performed. """ def initialize( self, generator=None, content_type="text/plain", as_attachment=False, access_validation=None, ): super().initialize() self._generator = generator self._content_type = content_type self._as_attachment = as_attachment self._access_validation = access_validation @tornado.gen.coroutine def get(self, *args, **kwargs): if self._access_validation is not None: self._access_validation(self.request) self.set_status(200) self.set_header("Content-Type", self._content_type) self.set_content_disposition() for data in self._generator(): self.write(data) yield self.flush() self.finish() def set_content_disposition(self): if self._as_attachment: if isinstance(self._as_attachment, str): self.set_header( "Content-Disposition", f"attachment; filename={self._as_attachment}" ) else: self.set_header("Content-Disposition", "attachment") class WebcamSnapshotHandler(GeneratingDataHandler): """ `GeneratingDataHandler` that returns a snapshot from the configured webcam. Arguments: as_attachment (bool | str): Whether to serve files with `Content-Disposition: attachment` header (`True`) or not. Defaults to `False`. If a string is given it will be used as the filename of the attachment. access_validation (function): Callback to call in the `get` method to validate access to the resource. Will be called with `self.request` as parameter which contains the full tornado request object. Should raise a `tornado.web.HTTPError` if access is not allowed in which case the request will not be further processed. Defaults to `None` and hence no access validation being performed. """ def initialize(self, as_attachment=False, access_validation=None): super().initialize( content_type="image/jpeg", as_attachment=as_attachment, access_validation=access_validation, ) @tornado.gen.coroutine def get(self, *args, **kwargs): if self._access_validation is not None: self._access_validation(self.request) import functools from octoprint.webcams import get_snapshot_webcam webcam = get_snapshot_webcam() if not webcam: raise tornado.web.HTTPError(404) generator = functools.partial( webcam.providerPlugin.take_webcam_snapshot, webcam.config.name ) self.set_status(200) self.set_header("Content-Type", self._content_type) self.set_content_disposition() for data in generator(): self.write(data) yield self.flush() self.finish() class DeprecatedEndpointHandler(CorsSupportMixin, tornado.web.RequestHandler): """ `tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that redirects to another ``url`` and logs a deprecation warning. Arguments: url (str): URL to which to redirect """ def initialize(self, url): self._url = url self._logger = logging.getLogger(__name__) def _handle_method(self, *args, **kwargs): to_url = self._url.format(*args) self._logger.info( f"Redirecting deprecated endpoint {self.request.path} to {to_url}" ) self.redirect(to_url, permanent=True) # make all http methods trigger _handle_method get = _handle_method post = _handle_method put = _handle_method patch = _handle_method delete = _handle_method head = _handle_method options = _handle_method class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): def initialize( self, files=None, as_attachment=True, attachment_name=None, access_validation=None, compress=False, ): if files is None: files = [] if as_attachment and not attachment_name: raise ValueError("attachment name must be set if as_attachment is True") self._files = files self._as_attachment = as_attachment self._attachment_name = attachment_name self._access_validator = access_validation self._compress = compress def get(self, *args, **kwargs): if self._access_validator is not None: self._access_validator(self.request) return self.stream_zip(self._files) def get_attachment_name(self): return self._attachment_name def normalize_files(self, files): result = [] for f in files: if isinstance(f, str): result.append({"path": f}) elif isinstance(f, dict) and ("path" in f or "iter" in f or "content" in f): result.append(f) return result @tornado.gen.coroutine def stream_zip(self, files): self.set_header("Content-Type", "application/zip") if self._as_attachment: self.set_header( "Content-Disposition", f'attachment; filename="{self.get_attachment_name()}"', ) z = ZipStream(sized=True) if self._compress: try: z = ZipStream(compress_type=ZIP_DEFLATED) except RuntimeError: # no zlib support pass for f in self.normalize_files(files): name = f.get("name") path = f.get("path") data = f.get("iter") or f.get("content") if path: z.add_path(path, arcname=name) elif data and name: z.add(data, arcname=name) if z.sized: self.set_header("Content-Length", len(z)) self.set_header("Last-Modified", z.last_modified) for chunk in z: try: self.write(chunk) yield self.flush() except tornado.iostream.StreamClosedError: return class DynamicZipBundleHandler(StaticZipBundleHandler): # noinspection PyMethodOverriding def initialize( self, path_validation=None, path_processor=None, as_attachment=True, attachment_name=None, access_validation=None, compress=False, ): if as_attachment and not attachment_name: raise ValueError("attachment name must be set if as_attachment is True") self._path_validator = path_validation self._path_processor = path_processor self._as_attachment = as_attachment self._attachment_name = attachment_name self._access_validator = access_validation self._compress = compress def get(self, *args, **kwargs): if self._access_validator is not None: self._access_validator(self.request) files = list( map(octoprint.util.to_unicode, self.request.query_arguments.get("files", [])) ) return self._get_files_zip(files) def post(self, *args, **kwargs): if self._access_validator is not None: self._access_validator(self.request) import json content_type = self.request.headers.get("Content-Type", "") try: if "application/json" in content_type: data = json.loads(self.request.body) else: data = self.request.body_arguments except Exception: raise tornado.web.HTTPError(400) return self._get_files_zip( list(map(octoprint.util.to_unicode, data.get("files", []))) ) def _get_files_zip(self, files): files = self.normalize_files(files) if not files: raise tornado.web.HTTPError(400) for f in files: if "path" in f: if callable(self._path_processor): path = self._path_processor(f["path"]) if isinstance(path, tuple): f["name"], f["path"] = path else: f["path"] = path self._path_validator(f["path"]) return self.stream_zip(files) class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): # noinspection PyMethodOverriding def initialize(self, access_validation=None): self._access_validator = access_validation @tornado.gen.coroutine def get(self, *args, **kwargs): if self._access_validator is not None: self._access_validator(self.request) from octoprint.cli.systeminfo import ( get_systeminfo, get_systeminfo_bundle, get_systeminfo_bundle_name, ) from octoprint.server import ( connectivityChecker, environmentDetector, pluginManager, printer, safe_mode, ) from octoprint.settings import settings systeminfo = get_systeminfo( environmentDetector, connectivityChecker, settings(), { "browser.user_agent": self.request.headers.get("User-Agent"), "octoprint.safe_mode": safe_mode is not None, "systeminfo.generator": "zipapi", }, ) z = get_systeminfo_bundle( systeminfo, settings().getBaseFolder("logs"), printer=printer, plugin_manager=pluginManager, ) self.set_header("Content-Type", "application/zip") self.set_header( "Content-Disposition", f'attachment; filename="{get_systeminfo_bundle_name()}"', ) if z.sized: self.set_header("Content-Length", len(z)) self.set_header("Last-Modified", z.last_modified) for chunk in z: try: self.write(chunk) yield self.flush() except tornado.iostream.StreamClosedError: return def get_attachment_name(self): import time return "octoprint-systeminfo-{}.zip".format(time.strftime("%Y%m%d%H%M%S")) class GlobalHeaderTransform(tornado.web.OutputTransform): HEADERS = {} FORCED_HEADERS = {} REMOVED_HEADERS = [] @classmethod def for_headers(cls, name, headers=None, forced_headers=None, removed_headers=None): if headers is None: headers = {} if forced_headers is None: forced_headers = {} if removed_headers is None: removed_headers = [] return type( name, (GlobalHeaderTransform,), { "HEADERS": headers, "FORCED_HEADERS": forced_headers, "REMOVED_HEADERS": removed_headers, }, ) def __init__(self, request): tornado.web.OutputTransform.__init__(self, request) def transform_first_chunk(self, status_code, headers, chunk, finishing): for header, value in self.HEADERS.items(): if header not in headers: headers[header] = value for header, value in self.FORCED_HEADERS.items(): headers[header] = value for header in self.REMOVED_HEADERS: del headers[header] return status_code, headers, chunk # ~~ Factory method for creating Flask access validation wrappers from the Tornado request context def access_validation_factory(app, validator, *args): """ Creates an access validation wrapper using the supplied validator. :param validator: the access validator to use inside the validation wrapper :return: an access validator taking a request as parameter and performing the request validation """ # noinspection PyProtectedMember def f(request): """ Creates a custom wsgi and Flask request context in order to be able to process user information stored in the current session. :param request: The Tornado request for which to create the environment and context """ import flask from werkzeug.exceptions import HTTPException wsgi_environ = WsgiInputContainer.environ(request) with app.request_context(wsgi_environ): session = app.session_interface.open_session(app, flask.request) user_id = session.get("_user_id") user = None # Yes, using protected methods is ugly. But these used to be publicly available in former versions # of flask-login, there are no replacements, and seeing them renamed & hidden in a minor version release # without any mention in the changelog means the public API ain't strictly stable either, so we might # as well make our life easier here and just use them... if user_id is not None and app.login_manager._user_callback is not None: user = app.login_manager._user_callback(user_id) app.login_manager._update_request_context_with_user(user) try: validator(flask.request, *args) except HTTPException as e: raise tornado.web.HTTPError(e.code) return f def path_validation_factory(path_filter, status_code=404): """ Creates a request path validation wrapper returning the defined status code if the supplied path_filter returns False. :param path_filter: the path filter to use on the requested path, should return False for requests that should be responded with the provided error code. :return: a request path validator taking a request path as parameter and performing the request validation """ def f(path): if not path_filter(path): raise tornado.web.HTTPError(status_code) return f def validation_chain(*validators): def f(request): for validator in validators: validator(request) return f
73,484
Python
.py
1,574
35.79479
152
0.614777
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,894
csrf.py
OctoPrint_OctoPrint/src/octoprint/server/util/csrf.py
"""CSRF double cookie implementation""" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" import flask from octoprint.server.util.flask import OctoPrintFlaskResponse exempt_views = set() def _get_view_location(view): if isinstance(view, str): return view else: return f"{view.__module__}.{view.__name__}" def add_exempt_view(view): exempt_views.add(_get_view_location(view)) def is_exempt(view): if not view: return False return _get_view_location(view) in exempt_views def generate_csrf_token(): import hashlib import os from itsdangerous import URLSafeTimedSerializer value = hashlib.sha1(os.urandom(64)).hexdigest() secret = flask.current_app.config["SECRET_KEY"] s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token") return s.dumps(value) def validate_csrf_tokens(cookie, header): import hmac from itsdangerous import URLSafeTimedSerializer if cookie is None or header is None: return False secret = flask.current_app.config["SECRET_KEY"] s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token") try: # TODO: set max age for values, once we have a REST based heartbeat # that takes care of regular cookie refresh value_cookie = s.loads(cookie) value_header = s.loads(header) return hmac.compare_digest(value_cookie, value_header) except Exception: return False def add_csrf_cookie(response): if not isinstance(response, OctoPrintFlaskResponse): response = flask.make_response(response) token = generate_csrf_token() response.set_cookie("csrf_token", token, httponly=False) return response def validate_csrf_request(request): if request.method in ["GET", "HEAD", "OPTIONS"]: # Irrelevant method for CSRF, bypass return session = getattr(flask, "session", {}) if len(session) == 0 or session.get("login_mechanism") == "apikey": # empty session, not a browser context return if is_exempt(request.endpoint): # marked as exempt, bypass return cookie = request.cookies.get("csrf_token", None) header = request.headers.get("X-CSRF-Token", None) if not validate_csrf_tokens(cookie, header): flask.abort(400, "CSRF validation failed") def csrf_exempt(view): add_exempt_view(view) return view
2,552
Python
.py
64
34.09375
103
0.702526
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,895
__init__.py
OctoPrint_OctoPrint/src/octoprint/server/util/__init__.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import base64 import datetime import logging import sys PY3 = sys.version_info >= (3, 0) # should now always be True, kept for plugins import flask as _flask import flask_login import octoprint.server import octoprint.timelapse import octoprint.vendor.flask_principal as flask_principal from octoprint.plugin import plugin_manager from octoprint.settings import settings from octoprint.util import deprecated, to_unicode from . import flask, sockjs, tornado, watchdog # noqa: F401 class LoginMechanism: PASSWORD = "password" REMEMBER_ME = "remember_me" AUTOLOGIN = "autologin" APIKEY = "apikey" AUTHHEADER = "authheader" REMOTE_USER = "remote_user" _REAUTHENTICATION_ENABLED = (PASSWORD, REMEMBER_ME, AUTOLOGIN) @classmethod def reauthentication_enabled(cls, login_mechanism): return login_mechanism in cls._REAUTHENTICATION_ENABLED @classmethod def to_log(cls, login_mechanism): if login_mechanism == cls.PASSWORD: return "credentials" elif login_mechanism == cls.REMEMBER_ME: return "Remember Me cookie" elif login_mechanism == cls.AUTOLOGIN: return "autologin" elif login_mechanism == cls.APIKEY: return "API Key" elif login_mechanism == cls.AUTHHEADER: return "Basic Authorization header" elif login_mechanism == cls.REMOTE_USER: return "Remote User header" return "unknown method" @deprecated( "API keys are no longer needed for anonymous access and thus this is now obsolete" ) def enforceApiKeyRequestHandler(): pass apiKeyRequestHandler = deprecated( "apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler" )(enforceApiKeyRequestHandler) def loginFromApiKeyRequestHandler(): """ ``before_request`` handler for blueprints which creates a login session for the provided api key (if available) App session keys are handled as anonymous keys here and ignored. TODO 1.11.0: Do we still need this with load_user_from_request in place? """ try: if loginUserFromApiKey(): _flask.g.login_via_apikey = True except InvalidApiKeyException: _flask.abort(403, "Invalid API key") def loginFromAuthorizationHeaderRequestHandler(): """ ``before_request`` handler for creating login sessions based on the Authorization header. TODO 1.11.0: Do we still need this with load_user_from_request in place? """ try: if loginUserFromAuthorizationHeader(): _flask.g.login_via_header = True except InvalidApiKeyException: _flask.abort(403, "Invalid credentials in Basic Authorization header") class InvalidApiKeyException(Exception): pass def loginUserFromApiKey(): apikey = get_api_key(_flask.request) if not apikey: return False user = get_user_for_apikey(apikey) if user is None: # invalid API key = no API key raise InvalidApiKeyException("Invalid API key") return _loginHelper(user, login_mechanism=LoginMechanism.APIKEY) def loginUserFromAuthorizationHeader(): authorization_header = get_authorization_header(_flask.request) user = get_user_for_authorization_header(authorization_header) return _loginHelper(user, login_mechanism=LoginMechanism.AUTHHEADER) def _loginHelper(user, login_mechanism=None): if ( user is not None and user.is_active 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()), ) if login_mechanism: _flask.session["login_mechanism"] = login_mechanism _flask.session["credentials_seen"] = False return True return False def requireLoginRequestHandler(): if _flask.request.endpoint.endswith(".static"): return if not octoprint.server.userManager.has_been_customized(): return user = flask_login.current_user if user is None or user.is_anonymous or not user.is_active: _flask.abort(403) def corsRequestHandler(): """ ``before_request`` handler for blueprints which sets CORS headers for OPTIONS requests if enabled """ if _flask.request.method == "OPTIONS" and settings().getBoolean( ["api", "allowCrossOrigin"] ): # reply to OPTIONS request for CORS headers return optionsAllowOrigin(_flask.request) def corsResponseHandler(resp): """ ``after_request`` handler for blueprints for which CORS is supported. Sets ``Access-Control-Allow-Origin`` headers for ``Origin`` request header on response. """ # Allow crossdomain allowCrossOrigin = settings().getBoolean(["api", "allowCrossOrigin"]) if ( _flask.request.method != "OPTIONS" and "Origin" in _flask.request.headers and allowCrossOrigin ): resp.headers["Access-Control-Allow-Origin"] = _flask.request.headers["Origin"] return resp def csrfRequestHandler(): """ ``before_request`` handler for blueprints which checks for CRFS double token on relevant requests & methods. """ from octoprint.server.util.csrf import validate_csrf_request if settings().getBoolean(["devel", "enableCsrfProtection"]): validate_csrf_request(_flask.request) def csrfResponseHandler(resp): """ ``after_request`` handler for updating the CSRF cookie on each response. """ from octoprint.server.util.csrf import add_csrf_cookie return add_csrf_cookie(resp) def noCachingResponseHandler(resp): """ ``after_request`` handler for blueprints which shall set no caching headers on their responses. Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly to prevent all client side caching from taking place. """ return flask.add_non_caching_response_headers(resp) def noCachingExceptGetResponseHandler(resp): """ ``after_request`` handler for blueprints which shall set no caching headers on their responses to any requests that are not sent with method ``GET``. See :func:`noCachingResponseHandler`. """ if _flask.request.method == "GET": return flask.add_no_max_age_response_headers(resp) else: return flask.add_non_caching_response_headers(resp) def optionsAllowOrigin(request): """ Shortcut for request handling for CORS OPTIONS requests to set CORS headers. """ resp = _flask.current_app.make_default_options_response() # Allow the origin which made the XHR resp.headers["Access-Control-Allow-Origin"] = request.headers["Origin"] # Allow the actual method resp.headers["Access-Control-Allow-Methods"] = request.headers[ "Access-Control-Request-Method" ] # Allow for 10 seconds resp.headers["Access-Control-Max-Age"] = "10" # 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key) customRequestHeaders = request.headers.get("Access-Control-Request-Headers", None) if customRequestHeaders is not None: # If present => allow them all resp.headers["Access-Control-Allow-Headers"] = customRequestHeaders return resp def get_user_for_apikey(apikey): if apikey is not None: if apikey == settings().get(["api", "key"]): # master key was used return octoprint.server.userManager.api_user_factory() user = octoprint.server.userManager.find_user(apikey=apikey) if user is not None: # user key was used return user apikey_hooks = plugin_manager().get_hooks("octoprint.accesscontrol.keyvalidator") for name, hook in apikey_hooks.items(): try: user = hook(apikey) if user is not None: return user except Exception: logging.getLogger(__name__).exception( "Error running api key validator " "for plugin {} and key {}".format(name, apikey), extra={"plugin": name}, ) return None def get_user_for_remote_user_header(request): if not settings().getBoolean(["accessControl", "trustRemoteUser"]): return None header = request.headers.get(settings().get(["accessControl", "remoteUserHeader"])) if header is None: return None user = octoprint.server.userManager.findUser(userid=header) if user is None and settings().getBoolean(["accessControl", "addRemoteUsers"]): octoprint.server.userManager.add_user( header, settings().generateApiKey(), active=True ) user = octoprint.server.userManager.findUser(userid=header) if user: _flask.session["login_mechanism"] = LoginMechanism.REMOTE_USER _flask.session["credentials_seen"] = datetime.datetime.now().timestamp() return user def get_user_for_authorization_header(header): if not settings().getBoolean(["accessControl", "trustBasicAuthentication"]): return None if header is None: return None if not header.startswith("Basic "): # we currently only support Basic Authentication return None header = header.replace("Basic ", "", 1) try: header = to_unicode(base64.b64decode(header)) except TypeError: return None name, password = header.split(":", 1) if not octoprint.server.userManager.enabled: return None user = octoprint.server.userManager.find_user(userid=name) if settings().getBoolean( ["accessControl", "checkBasicAuthenticationPassword"] ) and not octoprint.server.userManager.check_password(name, password): # password check enabled and password don't match return None if user: _flask.session["login_mechanism"] = LoginMechanism.AUTHHEADER _flask.session["credentials_seen"] = datetime.datetime.now().timestamp() return user def get_api_key(request): # Check Flask GET/POST arguments if hasattr(request, "values") and "apikey" in request.values: return request.values["apikey"] # Check Tornado GET/POST arguments if ( hasattr(request, "arguments") and "apikey" in request.arguments and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0 ): return request.arguments["apikey"] # Check Tornado and Flask headers if "X-Api-Key" in request.headers: return request.headers.get("X-Api-Key") # Check Tornado and Flask headers if "Authorization" in request.headers: header = request.headers.get("Authorization") if header.startswith("Bearer "): token = header.replace("Bearer ", "", 1) return token return None def get_authorization_header(request): # Tornado and Flask headers return request.headers.get("Authorization") def get_plugin_hash(): from octoprint.plugin import plugin_manager plugin_signature = lambda impl: f"{impl._identifier}:{impl._plugin_version}" template_plugins = list( map( plugin_signature, plugin_manager().get_implementations(octoprint.plugin.TemplatePlugin), ) ) asset_plugins = list( map( plugin_signature, plugin_manager().get_implementations(octoprint.plugin.AssetPlugin), ) ) ui_plugins = sorted(set(template_plugins + asset_plugins)) import hashlib plugin_hash = hashlib.sha1() plugin_hash.update(",".join(ui_plugins).encode("utf-8")) return plugin_hash.hexdigest() def has_permissions(*permissions): """ Determines if the current user (either from the session, api key or authorization header) has all of the requested permissions. Args: *permissions: list of all permissions required to pass the check Returns: True if the user has all permissions, False otherwise """ logged_in = False try: if loginUserFromApiKey(): logged_in = True except InvalidApiKeyException: pass # ignored if not logged_in: loginUserFromAuthorizationHeader() flask.passive_login() return all(map(lambda p: p.can(), permissions)) def require_fresh_login_with(permissions=None, user_id=None): """ Requires a login with fresh credentials. Args: permissions: list of all permissions required to pass the check user_id: required user to pass the check Returns: a flask redirect response to return if a login is required, or None """ from octoprint.server import current_user, userManager from octoprint.server.util.flask import credentials_checked_recently response = require_login_with(permissions=permissions, user_id=user_id) if response is not None: return response login_kwargs = { "redirect": _flask.request.script_root + _flask.request.full_path, "reauthenticate": "true", "user_id": current_user.get_id(), } if ( _flask.request.headers.get("X-Preemptive-Recording", "no") == "no" and userManager.has_been_customized() ): if not credentials_checked_recently(): return _flask.redirect(_flask.url_for("login", **login_kwargs)) return None def require_login_with(permissions=None, user_id=None): """ Requires a login with the given permissions and/or user id. Args: permissions: list of all permissions required to pass the check user_id: required user to pass the check Returns: a flask redirect response to return if a login is required, or None """ from octoprint.server import current_user, userManager login_kwargs = {"redirect": _flask.request.script_root + _flask.request.full_path} if ( _flask.request.headers.get("X-Preemptive-Recording", "no") == "no" and userManager.has_been_customized() ): requires_login = False if permissions is not None and not has_permissions(*permissions): requires_login = True login_kwargs["permissions"] = ",".join([x.key for x in permissions]) if user_id is not None and current_user.get_id() != user_id: requires_login = True login_kwargs["user_id"] = user_id if requires_login: return _flask.redirect(_flask.url_for("login", **login_kwargs)) return None def require_login(*permissions): """ Returns a redirect response to the login view if the permission requirements are not met. Args: *permissions: a list of permissions required to pass the check Returns: a flask redirect response to return if a login is required, or None """ from octoprint.server import userManager if not permissions: return None if ( _flask.request.headers.get("X-Preemptive-Recording", "no") == "no" and userManager.has_been_customized() ): if not has_permissions(*permissions): return _flask.redirect( _flask.url_for( "login", redirect=_flask.request.script_root + _flask.request.full_path, permissions=",".join([x.key for x in permissions]), ) ) return None def validate_local_redirect(url, allowed_paths): """Validates the given local redirect URL against the given allowed paths. An `url` is valid for a local redirect if it has neither scheme nor netloc defined, and its path is one of the given allowed paths. Args: url (str): URL to validate allowed_paths (List[str]): List of allowed paths, only paths contained or prefixed (if allowed path ends with "*") will be considered valid. Returns: bool: Whether the `url` passed validation or not. """ from urllib.parse import urlparse parsed = urlparse(url) return ( parsed.scheme == "" and parsed.netloc == "" and any( map( lambda x: ( parsed.path.startswith(x[:-1]) if x.endswith("*") else parsed.path == x ), allowed_paths, ) ) )
16,719
Python
.py
411
33.399027
115
0.674189
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,896
sockjs.py
OctoPrint_OctoPrint/src/octoprint/server/util/sockjs.py
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import re import threading import time import wrapt import octoprint.access.users import octoprint.events import octoprint.plugin import octoprint.printer import octoprint.server import octoprint.timelapse import octoprint.vendor.sockjs.tornado import octoprint.vendor.sockjs.tornado.proto import octoprint.vendor.sockjs.tornado.session import octoprint.vendor.sockjs.tornado.util from octoprint.access.groups import GroupChangeListener from octoprint.access.permissions import Permissions from octoprint.access.users import LoginStatusListener, SessionUser from octoprint.events import Events from octoprint.settings import settings from octoprint.util import RepeatedTimer from octoprint.util.json import dumps as json_dumps from octoprint.util.version import get_python_version_string class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session): def __init__(self, conn, server, session_id, expiry=None): octoprint.vendor.sockjs.tornado.session.Session.__init__( self, conn, server, session_id, expiry=expiry ) def set_handler(self, handler, start_heartbeat=True): if getattr(handler, "__orig_send_pack", None) is None: orig_send_pack = handler.send_pack mutex = threading.RLock() def send_pack(*args, **kwargs): with mutex: return orig_send_pack(*args, **kwargs) handler.send_pack = send_pack handler.__orig_send_pack = orig_send_pack return octoprint.vendor.sockjs.tornado.session.Session.set_handler( self, handler, start_heartbeat=start_heartbeat ) def remove_handler(self, handler): result = octoprint.vendor.sockjs.tornado.session.Session.remove_handler( self, handler ) if getattr(handler, "__orig_send_pack", None) is not None: handler.send_pack = handler.__orig_send_pack delattr(handler, "__orig_send_pack") return result class JsonEncodingSessionWrapper(wrapt.ObjectProxy): def send_message(self, msg, stats=True, binary=False): self.send_jsonified( json_dumps(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg)), stats, ) class PrinterStateConnection( octoprint.vendor.sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback, LoginStatusListener, GroupChangeListener, ): _event_permissions = { Events.USER_LOGGED_IN: [Permissions.ADMIN], Events.USER_LOGGED_OUT: [Permissions.ADMIN], "*": [], } _event_payload_processors = { Events.CLIENT_OPENED: [ lambda user, payload: ( payload if user.has_permission(Permissions.ADMIN) else {} ) ], Events.CLIENT_AUTHED: [ lambda user, payload: ( payload if user.has_permission(Permissions.ADMIN) else {} ) ], "*": [], } # TODO: Permissions should be overridable from plugins, this special case stuff here is a hack _emit_permissions = { "connected": [], "reauthRequired": [], "plugin": lambda payload: ( [] if payload.get("plugin") in ("backup", "softwareupdate") and settings().getBoolean(["server", "firstRun"]) else [Permissions.STATUS] ), "*": [Permissions.STATUS], } _unauthed_backlog_max = 100 def __init__( self, printer, fileManager, analysisQueue, userManager, groupManager, eventManager, pluginManager, connectivityChecker, session, ): if isinstance(session, octoprint.vendor.sockjs.tornado.session.Session): session = JsonEncodingSessionWrapper(session) octoprint.vendor.sockjs.tornado.SockJSConnection.__init__(self, session) self._logger = logging.getLogger(__name__) self._temperatureBacklog = [] self._temperatureBacklogMutex = threading.Lock() self._logBacklog = [] self._logBacklogMutex = threading.Lock() self._messageBacklog = [] self._messageBacklogMutex = threading.Lock() self._unauthed_backlog = [] self._unauthed_backlog_mutex = threading.RLock() self._printer = printer self._fileManager = fileManager self._analysisQueue = analysisQueue self._userManager = userManager self._groupManager = groupManager self._eventManager = eventManager self._pluginManager = pluginManager self._connectivityChecker = connectivityChecker self._remoteAddress = None self._user = self._userManager.anonymous_user_factory() self._throttle_factor = 1 self._last_current = 0 self._base_rate_limit = 0.5 self._held_back_current = None self._held_back_mutex = threading.RLock() self._register_hooks = self._pluginManager.get_hooks( "octoprint.server.sockjs.register" ) self._authed_hooks = self._pluginManager.get_hooks( "octoprint.server.sockjs.authed" ) self._emit_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.emit") self._registered = False self._authed = False self._initial_data_sent = False self._subscriptions_active = False self._subscriptions = {"state": False, "plugins": [], "events": []} self._keep_alive = RepeatedTimer( 60, self._keep_alive_callback, condition=lambda: self._authed ) @staticmethod def _get_remote_address(info): from octoprint.util.net import get_http_client_ip trusted_proxies = settings().get(["server", "reverseProxy", "trustedUpstream"]) if not isinstance(trusted_proxies, list): trusted_proxies = ["127.0.0.1"] return get_http_client_ip( info.ip, info.headers.get("X-Forwarded-For"), trusted_proxies ) def _keep_alive_callback(self): if not self._authed: return if not isinstance(self._user, SessionUser): return self._user.touch() def __str__(self): if self._remoteAddress: return f"{self!r} connected to {self._remoteAddress}" else: return f"Unconnected {self!r}" def on_open(self, info): self._pluginManager.register_message_receiver(self.on_plugin_message) self._remoteAddress = self._get_remote_address(info) self._logger.info("New connection from client: %s" % self._remoteAddress) self._userManager.register_login_status_listener(self) self._groupManager.register_listener(self) plugin_signature = lambda impl: "{}:{}".format( impl._identifier, impl._plugin_version ) template_plugins = list( map( plugin_signature, self._pluginManager.get_implementations(octoprint.plugin.TemplatePlugin), ) ) asset_plugins = list( map( plugin_signature, self._pluginManager.get_implementations(octoprint.plugin.AssetPlugin), ) ) ui_plugins = sorted(set(template_plugins + asset_plugins)) import hashlib plugin_hash = hashlib.md5() plugin_hash.update(",".join(ui_plugins).encode("utf-8")) config_hash = settings().config_hash # connected => update the API key, might be necessary if the client was left open while the server restarted self._emit( "connected", { "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION, "branch": octoprint.server.BRANCH, "python_version": get_python_version_string(), "plugin_hash": plugin_hash.hexdigest(), "config_hash": config_hash, "debug": octoprint.server.debug, "safe_mode": octoprint.server.safe_mode, "online": self._connectivityChecker.online, "permissions": [permission.as_dict() for permission in Permissions.all()], }, ) self._eventManager.fire( Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress} ) self._register() def on_close(self): self._user = self._userManager.anonymous_user_factory() self._groupManager.unregister_listener(self) self._userManager.unregister_login_status_listener(self) self._unregister() self._eventManager.fire( Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress} ) self._logger.info("Client connection closed: %s" % self._remoteAddress) self._on_logout() self._remoteAddress = None self._pluginManager.unregister_message_receiver(self.on_plugin_message) def on_message(self, message): try: import json message = json.loads(message) except Exception: self._logger.warning( "Invalid JSON received from client {}, ignoring: {!r}".format( self._remoteAddress, message ) ) return if "auth" in message: try: parts = message["auth"].split(":") if not len(parts) == 2: raise ValueError() except ValueError: self._logger.warning( "Got invalid auth message from client {}, ignoring: {!r}".format( self._remoteAddress, message["auth"] ) ) else: user_id, user_session = parts if self._userManager.validate_user_session(user_id, user_session): user = self._userManager.find_user( userid=user_id, session=user_session ) self._on_login(user) else: self._logger.warning( f"Unknown user/session combo: {user_id}:{user_session}" ) self._on_logout() self._sendReauthRequired("stale") self._register() elif "throttle" in message: try: throttle = int(message["throttle"]) if throttle < 1: raise ValueError() except ValueError: self._logger.warning( "Got invalid throttle factor from client {}, ignoring: {!r}".format( self._remoteAddress, message["throttle"] ) ) else: self._throttle_factor = throttle self._logger.debug( "Set throttle factor for client {} to {}".format( self._remoteAddress, self._throttle_factor ) ) elif "subscribe" in message: if not self._subscriptions_active: self._subscriptions_active = True self._logger.debug("Client makes use of subscriptions") def list_or_boolean(value): if isinstance(value, list): return value elif isinstance(value, bool): return [] if not value else None else: raise ValueError("value must be a list or boolean") def regex_or_boolean(value): if isinstance(value, str): try: return re.compile(value) except Exception: raise ValueError("value must be a valid regex") elif isinstance(value, bool): return value else: raise ValueError("value must be a string or boolean") try: subscribe = message["subscribe"] state = subscribe.get("state", False) if isinstance(state, bool): if state: state = {"logs": True, "messages": False} elif isinstance(state, dict): logs = regex_or_boolean(state.get("logs", False)) messages = regex_or_boolean(state.get("messages", False)) state = { "logs": logs, "messages": messages, } plugins = list_or_boolean(subscribe.get("plugins", [])) events = list_or_boolean(subscribe.get("events", [])) except ValueError as e: self._logger.warning( "Got invalid subscription message from client {}, ignoring: {!r} ({}) ".format( self._remoteAddress, message["subscribe"], str(e) ) ) else: old_state = self._subscriptions["state"] self._subscriptions["state"] = state self._subscriptions["plugins"] = plugins self._subscriptions["events"] = events if state and state != old_state: # state is requested and was changed from previous state # we should send a history message to send the update data self._printer.send_initial_callback(self) elif old_state and not state: # we no longer should send state updates self._initial_data_sent = False def on_printer_send_current_data(self, data): if not self._user.has_permission(Permissions.STATUS): return if self._subscriptions_active and not self._subscriptions["state"]: return if not self._initial_data_sent: self._logger.debug("Initial data not yet send, dropping current message") return # make sure we rate limit the updates according to our throttle factor with self._held_back_mutex: if self._held_back_current is not None: self._held_back_current.cancel() self._held_back_current = None now = time.time() delta = ( self._last_current + self._base_rate_limit * self._throttle_factor - now ) if delta > 0: self._held_back_current = threading.Timer( delta, lambda: self.on_printer_send_current_data(data) ) self._held_back_current.start() return self._last_current = now # add current temperature, log and message backlogs to sent data with self._temperatureBacklogMutex: temperatures = self._temperatureBacklog self._temperatureBacklog = [] with self._logBacklogMutex: logs = self._filter_logs(self._logBacklog) self._logBacklog = [] with self._messageBacklogMutex: messages = self._filter_messages(self._messageBacklog) self._messageBacklog = [] busy_files = [ {"origin": v[0], "path": v[1]} for v in self._fileManager.get_busy_files() ] if ( "job" in data and data["job"] is not None and "file" in data["job"] and "path" in data["job"]["file"] and "origin" in data["job"]["file"] and data["job"]["file"]["path"] is not None and data["job"]["file"]["origin"] is not None and (self._printer.is_printing() or self._printer.is_paused()) ): busy_files.append( { "origin": data["job"]["file"]["origin"], "path": data["job"]["file"]["path"], } ) data.update( { "serverTime": time.time(), "temps": temperatures, "busyFiles": busy_files, "markings": list(self._printer.get_markings()), } ) if self._user.has_permission(Permissions.MONITOR_TERMINAL): data.update( { "logs": self._filter_logs(logs), "messages": messages, } ) self._emit("current", payload=data) def on_printer_send_initial_data(self, data): self._initial_data_sent = True if self._subscriptions_active and not self._subscriptions["state"]: self._logger.debug("Not subscribed to state, dropping history") return data_to_send = dict(data) data_to_send["serverTime"] = time.time() if self._user.has_permission(Permissions.MONITOR_TERMINAL): data_to_send["logs"] = self._filter_logs(data_to_send.get("logs", [])) data_to_send["messages"] = self._filter_messages( data_to_send.get("messages", []) ) self._emit("history", payload=data_to_send) def _filter_state_subscription(self, sub, values): if not self._subscriptions_active or self._subscriptions["state"][sub] is True: return values if self._subscriptions["state"][sub] is False: return [] return [line for line in values if self._subscriptions["state"][sub].search(line)] def _filter_logs(self, logs): return self._filter_state_subscription("logs", logs) def _filter_messages(self, messages): return self._filter_state_subscription("messages", messages) def sendEvent(self, type, payload=None): permissions = self._event_permissions.get(type, self._event_permissions["*"]) permissions = [x(self._user) if callable(x) else x for x in permissions] if not self._user or not all( map(lambda p: self._user.has_permission(p), permissions) ): return processors = self._event_payload_processors.get( type, self._event_payload_processors["*"] ) for processor in processors: payload = processor(self._user, payload) self._emit("event", payload={"type": type, "payload": payload}) def sendTimelapseConfig(self, timelapseConfig): self._emit("timelapse", payload=timelapseConfig) def sendSlicingProgress( self, slicer, source_location, source_path, dest_location, dest_path, progress ): self._emit( "slicingProgress", payload={ "slicer": slicer, "source_location": source_location, "source_path": source_path, "dest_location": dest_location, "dest_path": dest_path, "progress": progress, }, ) def sendRenderProgress(self, progress): self._emit("renderProgress", {"progress": progress}) def on_plugin_message(self, plugin, data, permissions=None): if ( self._subscriptions_active and self._subscriptions["plugins"] is not None and plugin not in self._subscriptions["plugins"] ): return self._emit( "plugin", payload={"plugin": plugin, "data": data}, permissions=permissions ) def on_printer_add_log(self, data): with self._logBacklogMutex: self._logBacklog.append(data) def on_printer_add_message(self, data): with self._messageBacklogMutex: self._messageBacklog.append(data) def on_printer_add_temperature(self, data): with self._temperatureBacklogMutex: self._temperatureBacklog.append(data) def on_user_logged_out(self, user, stale=False): if ( user.get_id() == self._user.get_id() and hasattr(user, "session") and hasattr(self._user, "session") and user.session == self._user.session ): self._logger.info(f"User {user.get_id()} logged out, logging out on socket") self._on_logout() if stale: self._sendReauthRequired("stale") else: self._sendReauthRequired("logout") def on_user_modified(self, user): if user.get_id() == self._user.get_id(): self._sendReauthRequired("modified") def on_user_removed(self, userid): if self._user.get_id() == userid: self._logger.info(f"User {userid} deleted, logging out on socket") self._on_logout() self._sendReauthRequired("removed") def on_group_permissions_changed(self, group, added=None, removed=None): if self._user.is_anonymous and group == self._groupManager.guest_group: self._sendReauthRequired("modified") def on_group_subgroups_changed(self, group, added=None, removed=None): if self._user.is_anonymous and group == self._groupManager.guest_group: self._sendReauthRequired("modified") def _onEvent(self, event, payload): if ( self._subscriptions_active and self._subscriptions["events"] is not None and event not in self._subscriptions["events"] ): return self.sendEvent(event, payload) def _register(self): """Register this socket with the system if STATUS permission is available.""" proceed = True for name, hook in self._register_hooks.items(): try: proceed = proceed and hook(self, self._user) except Exception: self._logger.exception( f"Error processing register hook handler for plugin {name}", extra={"plugin": name}, ) if not proceed: return if self._registered: return if not self._user.has_permission(Permissions.STATUS): return # printer self._printer.register_callback(self) self._printer.send_initial_callback(self) # files self._fileManager.register_slicingprogress_callback(self) # events for event in octoprint.events.all_events(): self._eventManager.subscribe(event, self._onEvent) # timelapse octoprint.timelapse.register_callback(self) octoprint.timelapse.notify_callback(self, timelapse=octoprint.timelapse.current) if octoprint.timelapse.current_render_job is not None: # This is a horrible hack for now to allow displaying a notification that a render job is still # active in the backend on a fresh connect of a client. This needs to be substituted with a proper # job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints # start and so on. # # For now this is the easiest way though to at least inform the user that a timelapse is still ongoing. # # TODO remove when central job management becomes available and takes care of this for us self.sendEvent( Events.MOVIE_RENDERING, payload=octoprint.timelapse.current_render_job ) self._registered = True def _unregister(self): """Unregister this socket from the system""" self._printer.unregister_callback(self) self._fileManager.unregister_slicingprogress_callback(self) octoprint.timelapse.unregister_callback(self) for event in octoprint.events.all_events(): self._eventManager.unsubscribe(event, self._onEvent) def _reregister(self): """Unregister and register again""" self._unregister() self._register() def _sendReauthRequired(self, reason): self._emit("reauthRequired", payload={"reason": reason}) def _emit(self, type, payload=None, permissions=None): proceed = True for name, hook in self._emit_hooks.items(): try: proceed = proceed and hook(self, self._user, type, payload) except Exception: self._logger.exception( f"Error processing emit hook handler from plugin {name}", extra={"plugin": name}, ) if not proceed: return if permissions is None: permissions = self._emit_permissions.get(type, self._emit_permissions["*"]) permissions = ( permissions(payload) if callable(permissions) else [x for x in permissions] ) if not self._user or not all( map(lambda p: self._user.has_permission(p), permissions) ): if not self._authed: with self._unauthed_backlog_mutex: if len(self._unauthed_backlog) < self._unauthed_backlog_max: self._unauthed_backlog.append((type, payload)) self._logger.debug( "Socket message held back until permissions cleared, added to backlog: {}".format( type ) ) else: self._logger.debug( "Socket message held back, but backlog full. Throwing message away: {}".format( type ) ) return self._do_emit(type, payload) def _do_emit(self, type, payload): try: self.send({type: payload}) except Exception as e: if self._logger.isEnabledFor(logging.DEBUG): self._logger.exception( f"Could not send message to client {self._remoteAddress}" ) else: self._logger.warning( "Could not send message to client {}: {}".format( self._remoteAddress, e ) ) def _on_login(self, user): self._user = user self._logger.info( "User {} logged in on the socket from client {}".format( user.get_name(), self._remoteAddress ) ) self._authed = True self._keep_alive.start() for name, hook in self._authed_hooks.items(): try: hook(self, self._user) except Exception: self._logger.exception( f"Error processing authed hook handler for plugin {name}", extra={"plugin": name}, ) # if we have a backlog from being unauthed, process that now with self._unauthed_backlog_mutex: backlog = self._unauthed_backlog self._unauthed_backlog = [] if len(backlog): self._logger.debug( "Sending {} messages on the socket that were held back".format( len(backlog) ) ) for message, payload in backlog: self._do_emit(message, payload) # trigger ClientAuthed event octoprint.events.eventManager().fire( octoprint.events.Events.CLIENT_AUTHED, payload={"username": user.get_name(), "remoteAddress": self._remoteAddress}, ) def _on_logout(self): self._user = self._userManager.anonymous_user_factory() self._authed = False for name, hook in self._authed_hooks.items(): try: hook(self, self._user) except Exception: self._logger.exception( f"Error processing authed hook handler for plugin {name}", extra={"plugin": name}, )
28,411
Python
.py
663
30.458522
116
0.569882
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,897
webassets.py
OctoPrint_OctoPrint/src/octoprint/server/util/webassets.py
__author__ = "Gina Häußge <gina@octoprint.org>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import gzip import logging import os import re import threading from urllib import parse as urlparse import webassets.filter.cssrewrite.urlpath as urlpath from webassets.bundle import Bundle from webassets.filter import Filter from webassets.filter.cssrewrite.base import PatternRewriter from webassets.filter.rjsmin import rjsmin from webassets.merge import BaseHunk, MemoryHunk from webassets.version import Manifest def replace_url(source_url, output_url, url): # If path is an absolute one, keep it parsed = urlparse.urlparse(url) if not parsed.scheme and not parsed.path.startswith("/"): abs_source_url = urlparse.urljoin(source_url, url) # relpath() will not detect this case if urlparse.urlparse(abs_source_url).scheme: return abs_source_url # rewritten url: relative path from new location (output) # to location of referenced file (source + current url) url = urlpath.relpath(output_url, abs_source_url) return url class UrlRewriter(PatternRewriter): def input(self, _in, out, **kw): source, source_path, output, output_path = ( kw["source"], kw["source_path"], kw["output"], kw["output_path"], ) self.source_path = source_path self.output_path = output_path self.source_url = self.ctx.resolver.resolve_source_to_url( self.ctx, source_path, source ) self.output_url = self.ctx.resolver.resolve_output_to_url(self.ctx, output) return super().input(_in, out, **kw) def replace_url(self, url): return replace_url(self.source_url, self.output_url, url) class LessImportRewrite(UrlRewriter): name = "less_importrewrite" patterns = {"import_rewrite": re.compile(r"(@import(\s+\(.*\))?\s+)\"(.*)\";")} def import_rewrite(self, m): import_with_options = m.group(1) import_url = self.replace_url(m.group(3)) return f'{import_with_options}"{import_url}";' class SourceMapRewrite(UrlRewriter): name = "sourcemap_urlrewrite" patterns = {"url_rewrite": re.compile(r"(//#\s+sourceMappingURL=)(.*)")} def url_rewrite(self, m): mapping = m.group(1) source_url = self.replace_url(m.group(2)) return f"{mapping}{source_url}" class SourceMapRemove(PatternRewriter): name = "sourcemap_remove" patterns = {"sourcemap_remove": re.compile(r"(//#\s+sourceMappingURL=)(.*)")} def sourcemap_remove(self, m): return "" class JsDelimiterBundler(Filter): name = "js_delimiter_bundler" options = {} def input(self, _in, out, **kwargs): source = kwargs.get("source", "n/a") out.write("// source: " + source + "\n") out.write(_in.read()) out.write("\n;\n") class RJSMinExtended(Filter): name = "rjsmin_extended" options = { "keep_bang_comments": "RJSMIN_KEEP_BANG_COMMENTS", } def input(self, _in, out, **kw): source = kw["source"] if source.endswith(".min.js"): # out.write("// source is already minified, not minifying again\n") out.write(_in.read()) else: keep = self.keep_bang_comments or False out.write(rjsmin.jsmin(_in.read(), keep_bang_comments=keep)) class GzipFile(Filter): name = "gzip" options = {} def output(self, _in, out, **kwargs): data = _in.read() out.write(data) # webassets requires us to output a "str", but we can't do that since gzip # provides binary outputs. # # We work around that by outputting the gzipped file to another path output_path = kwargs.get("output_path", None) if output_path: gzipped_output_path = output_path + ".gz" try: with gzip.open(gzipped_output_path, "wb", 9) as f: f.write(data.encode("utf8")) except Exception: logging.getLogger(__name__).exception( "Error writing gzipped " "output of {} to {}".format(output_path, gzipped_output_path) ) try: os.remove(gzipped_output_path) except Exception: logging.getLogger(__name__).exception( "Error removing broken " ".gz from {}".format(gzipped_output_path) ) class ChainedHunk(BaseHunk): def __init__(self, *hunks): self._hunks = hunks def mtime(self): pass def data(self): result = "" for hunk in self._hunks: if isinstance(hunk, tuple) and len(hunk) == 2: hunk, f = hunk else: f = lambda x: x result += f(hunk.data()) return result _PLUGIN_BUNDLE_WRAPPER_PREFIX = """// JS assets for plugin {plugin} (function () {{ try {{ """ _PLUGIN_BUNDLE_WRAPPER_SUFFIX = """ }} catch (error) {{ log.error("Error in JS assets for plugin {plugin}:", `${{exc.message}}\n${{exc.stack || exc}}`); }} }})(); """ class JsPluginBundle(Bundle): def __init__(self, plugin, *args, **kwargs): Bundle.__init__(self, *args, **kwargs) self.plugin = plugin def _merge_and_apply( self, ctx, output, force, parent_debug=None, parent_filters=None, extra_filters=None, disable_cache=None, ): hunk = Bundle._merge_and_apply( self, ctx, output, force, parent_debug=parent_debug, parent_filters=parent_filters, extra_filters=extra_filters, disable_cache=disable_cache, ) return ChainedHunk( MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_PREFIX.format(plugin=self.plugin)), (hunk, lambda x: x.replace("\n", "\n ")), MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_SUFFIX.format(plugin=self.plugin)), ) class MemoryManifest(Manifest): id = "memory" def __init__(self, *args, **kwargs): self.manifest = {} self._lock = threading.RLock() def remember(self, bundle, ctx, version): with self._lock: self.manifest[bundle.output] = version def query(self, bundle, ctx): with self._lock: return self.manifest.get(bundle.output, None)
6,697
Python
.py
176
29.590909
104
0.600031
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,898
net.py
OctoPrint_OctoPrint/src/octoprint/util/net.py
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os import socket import sys import netaddr import netifaces import requests import werkzeug.http from werkzeug.utils import secure_filename _cached_check_v6 = None def check_v6(): global _cached_check_v6 def f(): if not socket.has_ipv6: return False try: socket.socket(socket.AF_INET6, socket.SOCK_STREAM) except Exception: # "[Errno 97] Address family not supported by protocol" or anything else really... return False return True if _cached_check_v6 is None: _cached_check_v6 = f() return _cached_check_v6 HAS_V6 = check_v6() if hasattr(socket, "IPPROTO_IPV6") and hasattr(socket, "IPV6_V6ONLY"): # Dual stack support, hooray! IPPROTO_IPV6 = socket.IPPROTO_IPV6 IPV6_V6ONLY = socket.IPV6_V6ONLY else: if sys.platform == "win32": # Python on Windows lacks IPPROTO_IPV6, but supports the socket options just fine, let's redefine it IPPROTO_IPV6 = 41 IPV6_V6ONLY = 27 else: # Whatever we are running on here, we don't want to use V6 on here due to lack of dual stack support HAS_V6 = False def get_netmask(address): # netifaces2 - see #5005 netmask = address.get("mask") if netmask: return netmask # netifaces netmask = address.get("netmask") if netmask: return netmask raise ValueError(f"No netmask found in address: {address!r}") def get_lan_ranges(additional_private=None): logger = logging.getLogger(__name__) if additional_private is None or not isinstance(additional_private, (list, tuple)): additional_private = [] def to_ipnetwork(address): prefix = get_netmask(address) if "/" in prefix: # v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64" _, prefix = prefix.split("/") addr = strip_interface_tag(address["addr"]) return netaddr.IPNetwork(f"{addr}/{prefix}") subnets = [] for interface in netifaces.interfaces(): addrs = netifaces.ifaddresses(interface) for v4 in addrs.get(socket.AF_INET, ()): try: subnets.append(to_ipnetwork(v4)) except Exception: if logger.isEnabledFor(logging.DEBUG): logger.exception( "Error while trying to add v4 network to local subnets: {!r}".format( v4 ) ) if HAS_V6: for v6 in addrs.get(socket.AF_INET6, ()): try: subnets.append(to_ipnetwork(v6)) except Exception: if logger.isEnabledFor(logging.DEBUG): logger.exception( "Error while trying to add v6 network to local subnets: {!r}".format( v6 ) ) for additional in additional_private: try: subnets.append(netaddr.IPNetwork(additional)) except Exception: if logger.isEnabledFor(logging.DEBUG): logger.exception( "Error while trying to add additional private network to local subnets: {}".format( additional ) ) subnets += list(netaddr.ip.IPV4_PRIVATE) + [ netaddr.ip.IPV4_LOOPBACK, netaddr.ip.IPV4_LINK_LOCAL, ] if HAS_V6: subnets += list(netaddr.ip.IPV6_PRIVATE) + [ netaddr.IPNetwork(netaddr.ip.IPV6_LOOPBACK), netaddr.ip.IPV6_LINK_LOCAL, ] return subnets def is_lan_address(address, additional_private=None): if not address: # no address is LAN address return True try: address = sanitize_address(address) ip = netaddr.IPAddress(address) subnets = get_lan_ranges(additional_private=additional_private) if any(map(lambda subnet: ip in subnet, subnets)): return True return False except Exception: # we are extra careful here since an unhandled exception in this method will effectively nuke the whole UI logging.getLogger(__name__).exception( "Error while trying to determine whether {} is a local address".format( address ) ) return True def sanitize_address(address): address = unmap_v4_as_v6(address) address = strip_interface_tag(address) return address def strip_interface_tag(address): if "%" in address: # interface comment, e.g. "fe80::457f:bbee:d579:1063%wlan0" address = address[: address.find("%")] return address def unmap_v4_as_v6(address): if address.lower().startswith("::ffff:") and "." in address: # ipv6 mapped ipv4 address, unmap address = address[len("::ffff:") :] return address def interface_addresses(family=None, interfaces=None, ignored=None): """ Retrieves all of the host's network interface addresses. """ import netifaces if not family: family = netifaces.AF_INET if interfaces is None: interfaces = netifaces.interfaces() if ignored is not None: interfaces = [i for i in interfaces if i not in ignored] for interface in interfaces: try: ifaddresses = netifaces.ifaddresses(interface) except Exception: continue if family in ifaddresses: for ifaddress in ifaddresses[family]: address = netaddr.IPAddress(ifaddress["addr"]) if not address.is_link_local() and not address.is_loopback(): yield ifaddress["addr"] def address_for_client( host, port, timeout=3.05, addresses=None, interfaces=None, ignored=None ): """ Determines the address of the network interface on this host needed to connect to the indicated client host and port. """ if addresses is None: addresses = interface_addresses(interfaces=interfaces, ignored=ignored) for address in addresses: try: if server_reachable(host, port, timeout=timeout, proto="udp", source=address): return address except Exception: continue def server_reachable(host, port, timeout=3.05, proto="tcp", source=None): """ Checks if a server is reachable Args: host (str): host to check against port (int): port to check against timeout (float): timeout for check proto (str): ``tcp`` or ``udp`` source (str): optional, socket used for check will be bound against this address if provided Returns: boolean: True if a connection to the server could be opened, False otherwise """ import socket if proto not in ("tcp", "udp"): raise ValueError("proto must be either 'tcp' or 'udp'") if HAS_V6: families = [socket.AF_INET6, socket.AF_INET] else: families = [socket.AF_INET] for family in families: try: sock = socket.socket( family, socket.SOCK_DGRAM if proto == "udp" else socket.SOCK_STREAM ) sock.settimeout(timeout) if source is not None: sock.bind((source, 0)) sock.connect((host, port)) return True except Exception: pass return False def resolve_host(host): import socket from octoprint.util import to_unicode try: return [to_unicode(x[4][0]) for x in socket.getaddrinfo(host, 80)] except Exception: return [] def download_file(url, folder, max_length=None, connect_timeout=3.05, read_timeout=7): with requests.get(url, stream=True, timeout=(connect_timeout, read_timeout)) as r: r.raise_for_status() filename = None if "Content-Disposition" in r.headers.keys(): _, options = werkzeug.http.parse_options_header( r.headers["Content-Disposition"] ) filename = options.get("filename") if filename is None: filename = url.split("/")[-1] filename = secure_filename(filename) assert len(filename) > 0 # TODO check content-length against safety limit path = os.path.abspath(os.path.join(folder, filename)) assert path.startswith(folder) with open(path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) return path def get_http_client_ip(remote_addr, forwarded_for, trusted_proxies): try: trusted_ip_set = netaddr.IPSet(trusted_proxies) except netaddr.AddrFormatError: # something's wrong with one of these addresses, let's add them one by one trusted_ip_set = netaddr.IPSet() for trusted_proxy in trusted_proxies: try: trusted_ip_set.add(trusted_proxy) except netaddr.AddrFormatError: logging.getLogger(__name__).error( f"Trusted proxy {trusted_proxy} is not a correctly formatted IP address or subnet" ) if forwarded_for is not None and sanitize_address(remote_addr) in trusted_ip_set: for addr in ( sanitize_address(addr.strip()) for addr in reversed(forwarded_for.split(",")) ): if addr not in trusted_ip_set: return addr return sanitize_address(remote_addr)
9,805
Python
.py
251
29.541833
121
0.612781
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
21,899
fixes.py
OctoPrint_OctoPrint/src/octoprint/util/fixes.py
""" This module contains a functions that monkey patch third party dependencies in the one or other way. """ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
198
Python
.py
4
48.25
100
0.766839
OctoPrint/OctoPrint
8,222
1,667
264
AGPL-3.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)