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,900 | dev.py | OctoPrint_OctoPrint/src/octoprint/util/dev.py | """
This module provides a bunch of utility methods and helpers FOR DEVELOPMENT ONLY.
"""
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
import contextlib
import time
@contextlib.contextmanager
def duration_log(context=None, log=None):
"""
Context manager to log the duration of the wrapped code block.
If no ``log`` function is provided will use a ``debug`` python logger for
``octoprint.util.dev``.
``context`` can be set to give some textual context in the output.
Arguments:
context (str): A custom string to give some textual context in the output.
log (callable): The log function to use to log the execution duration.
"""
if log is None:
import logging
log = logging.getLogger(__name__).debug
start = time.monotonic()
try:
yield
finally:
end = time.monotonic()
duration = end - start
if context:
message = "Execution of {name} took {duration}s"
else:
message = "Execution of codeblock took {duration}s"
log(message.format(name=context, duration=duration))
def log_duration(log=None, with_args=False):
"""
Decorator that logs the execution duration of the annotated function.
Arguments:
log (callable): The logging function to use.
with_args (bool): Whether to include the calling arguments in the logged
output or not.
"""
def decorator(f):
def wrapped(*args, **kwargs):
if with_args:
args_str = ", ".join(map(lambda x: repr(x), args))
kwargs_str = ", ".join(
map(
lambda item: f"{item[0]}={repr(item[1])}",
kwargs.items(),
)
)
sep = ", " if args_str and kwargs_str else ""
arguments = "".join([args_str, sep, kwargs_str])
else:
arguments = "..."
context = f"{f.__name__}({arguments})"
with duration_log(context=context, log=log):
return f(*args, **kwargs)
return wrapped
return decorator
| 2,218 | Python | .py | 58 | 28.948276 | 87 | 0.587961 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,901 | connectivity.py | OctoPrint_OctoPrint/src/octoprint/util/connectivity.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 logging
import threading
import time
from octoprint.util.net import resolve_host, server_reachable
class ConnectivityChecker:
"""
Regularly checks for online connectivity.
Tries to open a connection to the provided ``host`` and ``port`` every ``interval``
seconds and sets the ``online`` status accordingly.
If a ``name``is provided, also tries to resolve that name to a valid IP address
during connectivity check and only set ``online`` to ``True`` if that succeeds as well.
"""
def __init__(self, interval, host, port, name=None, enabled=True, on_change=None):
self._interval = interval
self._host = host
self._port = port
self._name = name
self._enabled = enabled
self._on_change = on_change
self._logger = logging.getLogger(__name__ + ".connectivity_checker")
# we initialize the online flag to True if we are not enabled (we don't know any better
# but these days it's probably a sane default)
self._connection_working = not self._enabled
self._resolution_working = not self._enabled or self._name is None
self._check_worker = None
self._check_mutex = threading.RLock()
self._run()
@property
def online(self):
"""Current online status, True if online, False if offline."""
with self._check_mutex:
return self._online
@property
def _online(self):
return self._connection_working and self._resolution_working
@property
def host(self):
"""DNS host to query."""
with self._check_mutex:
return self._host
@host.setter
def host(self, value):
with self._check_mutex:
self._host = value
@property
def port(self):
"""DNS port to query."""
with self._check_mutex:
return self._port
@port.setter
def port(self, value):
with self._check_mutex:
self._port = value
@property
def name(self):
with self._check_mutex:
return self._name
@name.setter
def name(self, value):
with self._check_mutex:
self._name = value
@property
def interval(self):
"""Interval between consecutive automatic checks."""
return self._interval
@interval.setter
def interval(self, value):
self._interval = value
@property
def enabled(self):
"""Whether the check is enabled or not."""
return self._enabled
@enabled.setter
def enabled(self, value):
with self._check_mutex:
old_enabled = self._enabled
self._enabled = value
if not self._enabled:
if self._check_worker is not None:
self._check_worker.cancel()
old_value = self._online
self._connection_working = self._resolution_working = True
if old_value != self._online:
self._trigger_change(old_value, self._online)
elif self._enabled and not old_enabled:
self._run()
def check_immediately(self):
"""Check immediately and return result."""
with self._check_mutex:
self._perform_check()
return self.online
def log_full_report(self):
with self._check_mutex:
self._logger.info(
"Connectivity state is currently: {}".format(
self._map_online(self.online)
)
)
self.log_details()
def log_details(self):
self._logger.info(
"Connecting to {}:{} is {}".format(
self._host,
self._port,
self._map_working(self._connection_working),
)
)
if self._name:
self._logger.info(
"Resolving {} is {}".format(
self._name,
self._map_working(self._resolution_working),
)
)
def as_dict(self):
result = {
"online": self.online,
"enabled": self.enabled,
"connection_ok": self._connection_working,
"connection_check": f"{self._host}:{self._port}",
}
if self._name:
result.update(
resolution_ok=self._resolution_working, resolution_check=self._name
)
return result
def _run(self):
from octoprint.util import RepeatedTimer
if not self._enabled:
return
if self._check_worker is not None:
self._check_worker.cancel()
self._check_worker = RepeatedTimer(
self._interval, self._perform_check, run_first=True
)
self._check_worker.start()
def _perform_check(self):
if not self._enabled:
return
with self._check_mutex:
self._logger.debug(
"Checking against {}:{} if we are online...".format(
self._host, self._port
)
)
old_value = self._online
for _ in range(3):
connection_working = server_reachable(self._host, port=self._port)
if self._name:
if connection_working:
self._logger.debug(f"Checking if we can resolve {self._name}...")
resolution_working = len(resolve_host(self._name)) > 0
else:
resolution_working = False
else:
resolution_working = True
if not (connection_working and resolution_working):
# retry up to 3 times
time.sleep(1.0)
continue
# all good
break
self._connection_working = connection_working
self._resolution_working = resolution_working
new_value = self._online
if old_value != new_value:
self._trigger_change(old_value, new_value)
def _trigger_change(self, old_value, new_value):
self._log_change_report(old_value, new_value, include_details=not new_value)
if callable(self._on_change):
self._on_change(
old_value,
new_value,
connection_working=self._connection_working,
resolution_working=self._resolution_working,
)
def _log_change_report(self, old_value, new_value, include_details=False):
self._logger.info(
"Connectivity changed from {} to {}".format(
self._map_online(old_value),
self._map_online(new_value),
)
)
if include_details:
self.log_details()
def _map_working(self, value):
return "working" if value else "not working"
def _map_online(self, value):
return "online" if value else "offline"
| 7,245 | Python | .py | 191 | 26.769634 | 103 | 0.560029 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,902 | jinja.py | OctoPrint_OctoPrint/src/octoprint/util/jinja.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 jinja2 import nodes
from jinja2.ext import Extension
from jinja2.loaders import (
BaseLoader,
ChoiceLoader,
FileSystemLoader,
PrefixLoader,
TemplateNotFound,
split_template_path,
)
from webassets import Bundle
class FilteredFileSystemLoader(FileSystemLoader):
"""
Jinja2 ``FileSystemLoader`` subclass that allows filtering templates.
Only such templates will be accessible for whose paths the provided
``path_filter`` filter function returns True.
``path_filter`` will receive the actual path on disc and should behave just
like callables provided to Python's internal ``filter`` function, returning
``True`` if the path is cleared and ``False`` if it is supposed to be removed
from results and hence ``filter(path_filter, iterable)`` should be
equivalent to ``[item for item in iterable if path_filter(item)]``.
If ``path_filter`` is not set or not a ``callable``, the loader will
behave just like the regular Jinja2 ``FileSystemLoader``.
"""
def __init__(self, searchpath, path_filter=None, **kwargs):
FileSystemLoader.__init__(self, searchpath, **kwargs)
self.path_filter = path_filter
def get_source(self, environment, template):
if callable(self.path_filter):
pieces = split_template_path(template)
if not self._combined_filter(os.path.join(*pieces)):
raise TemplateNotFound(template)
return FileSystemLoader.get_source(self, environment, template)
def list_templates(self):
result = FileSystemLoader.list_templates(self)
if callable(self.path_filter):
result = sorted(filter(self._combined_filter, result))
return result
def _combined_filter(self, path):
filter_results = map(
lambda x: not os.path.exists(os.path.join(x, path))
or self.path_filter(os.path.join(x, path)),
self.searchpath,
)
return all(filter_results)
class SelectedFilesLoader(BaseLoader):
def __init__(self, files, encoding="utf-8"):
self.files = files
self.encoding = encoding
def get_source(self, environment, template):
if template not in self.files:
raise TemplateNotFound(template)
from jinja2.utils import open_if_exists
path = self.files[template]
f = open_if_exists(path)
if f is None:
raise TemplateNotFound(template)
try:
contents = f.read().decode(self.encoding)
finally:
f.close()
mtime = os.path.getmtime(path)
def up_to_date():
try:
return os.path.getmtime(path) == mtime
except OSError:
return False
return contents, path, up_to_date
def list_templates(self):
return self.files.keys()
class SelectedFilesWithConversionLoader(SelectedFilesLoader):
def __init__(self, files, encoding="utf-8", conversion=None):
SelectedFilesLoader.__init__(self, files, encoding=encoding)
self.conversion = conversion
def get_source(self, environment, template):
contents = SelectedFilesLoader.get_source(self, environment, template)
if callable(self.conversion):
contents = self.conversion(contents[0]), contents[1], contents[2]
return contents
class PrefixChoiceLoader(BaseLoader):
def __init__(self, loader):
self.loader = loader
def get_source(self, environment, template):
for prefix in sorted(self.loader.mapping.keys()):
try:
return self.loader.mapping[prefix].get_source(environment, template)
except TemplateNotFound:
pass
raise TemplateNotFound(template)
class WarningLoader(BaseLoader):
"""
Logs a warning if the loader is used to successfully load a template.
"""
def __init__(self, loader, warning_message):
self.loader = loader
self.warning_message = warning_message
def get_source(self, environment, template):
import logging
try:
contents, filename, up_to_date = self.loader.get_source(environment, template)
logging.getLogger(__name__).warning(
self.warning_message.format(template=template, filename=filename)
)
return contents, filename, up_to_date
except TemplateNotFound:
raise
def get_all_template_paths(loader):
def walk_folder(folder):
files = []
walk_dir = os.walk(folder, followlinks=True)
for dirpath, _, filenames in walk_dir:
for filename in filenames:
path = os.path.join(dirpath, filename)
files.append(path)
return files
def collect_templates_for_loader(loader):
if isinstance(loader, SelectedFilesLoader):
import copy
return copy.copy(list(loader.files.values()))
elif isinstance(loader, FilteredFileSystemLoader):
result = []
for folder in loader.searchpath:
result += walk_folder(folder)
return list(filter(loader.path_filter, result))
elif isinstance(loader, FileSystemLoader):
result = []
for folder in loader.searchpath:
result += walk_folder(folder)
return result
elif isinstance(loader, PrefixLoader):
result = []
for subloader in loader.mapping.values():
result += collect_templates_for_loader(subloader)
return result
elif isinstance(loader, ChoiceLoader):
result = []
for subloader in loader.loaders:
result += collect_templates_for_loader(subloader)
return result
return []
return collect_templates_for_loader(loader)
def get_all_asset_paths(env, verifyExist=True):
result = []
def get_paths(bundle):
r = []
for content in bundle.resolve_contents():
try:
if not content:
continue
if isinstance(content[1], Bundle):
r += get_paths(content[1])
else:
path = content[1]
if verifyExist is True and not os.path.isfile(path):
continue
r.append(path)
except IndexError:
# intentionally ignored
pass
return r
for bundle in env:
result += get_paths(bundle)
return result
class ExceptionHandlerExtension(Extension):
tags = {"try"}
def __init__(self, environment):
super().__init__(environment)
self._logger = logging.getLogger(__name__)
def parse(self, parser):
token = next(parser.stream)
lineno = token.lineno
filename = parser.name
error = parser.parse_expression()
args = [error, nodes.Const(filename), nodes.Const(lineno)]
try:
body = parser.parse_statements(["name:endtry"], drop_needle=True)
node = nodes.CallBlock(
self.call_method("_handle_body", args), [], [], body
).set_lineno(lineno)
except Exception as e:
# that was expected
self._logger.exception("Caught exception while parsing template")
node = nodes.CallBlock(
self.call_method(
"_handle_error",
[nodes.Const(self._format_error(error, e, filename, lineno))],
),
[],
[],
[],
).set_lineno(lineno)
return node
def _handle_body(self, error, filename, lineno, caller):
try:
return caller()
except Exception as e:
self._logger.exception(
f"Caught exception while compiling template {filename} at line {lineno}"
)
error_string = self._format_error(error, e, filename, lineno)
return error_string if error_string else ""
def _handle_error(self, error, caller):
return error if error else ""
def _format_error(self, error, exception, filename, lineno):
if not error:
return ""
try:
return error.format(exception=exception, filename=filename, lineno=lineno)
except Exception:
self._logger.exception(
f"Error while compiling exception output for template {filename} at line {lineno}"
)
return "Unknown error"
trycatch = ExceptionHandlerExtension
class MarkdownFilter:
def __init__(self, app, **markdown_options):
self._markdown_options = markdown_options
app.jinja_env.filters.setdefault("markdown", self)
def __call__(self, stream):
from markdown import Markdown
from markupsafe import Markup
# Markdown is not thread safe
markdown = Markdown(**self._markdown_options)
return Markup(markdown.convert(stream))
| 9,351 | Python | .py | 228 | 30.991228 | 103 | 0.61868 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,903 | text.py | OctoPrint_OctoPrint/src/octoprint/util/text.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 re
from emoji import demojize
from octoprint.util import to_unicode
from octoprint.vendor.awesome_slugify import Slugify
_UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
_SLUGIFIES = {}
def demojify(text):
text = to_unicode(text)
text = remove_unicode_variations(text)
return demojize(text, delimiters=("", ""))
def sanitize(text, safe_chars="-_.", demoji=True):
"""
Sanitizes text by running it through slugify and optionally emoji translating.
Examples:
>>> sanitize("Hello World!")
'Hello-World'
>>> sanitize("Hello World!", safe_chars="-_. ")
'Hello World'
>>> sanitize("\u2764")
'red_heart'
>>> sanitize("\u2764\ufe00")
'red_heart'
>>> sanitize("\u2764", demoji=False)
''
Args:
text: the text to sanitize
safe_chars: characters to consider safe and to keep after sanitization
emoji: whether to also convert emoji to text
Returns: the sanitized text
"""
slugify = _SLUGIFIES.get(safe_chars)
if slugify is None:
slugify = Slugify()
slugify.safe_chars = safe_chars
_SLUGIFIES[safe_chars] = slugify
text = to_unicode(text)
if demoji:
text = demojify(text)
return slugify(text)
def remove_unicode_variations(text):
return _UNICODE_VARIATIONS.sub("", text)
| 1,535 | Python | .py | 43 | 30.72093 | 103 | 0.679756 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,904 | __init__.py | OctoPrint_OctoPrint/src/octoprint/util/__init__.py | """
This module bundles commonly used utility methods or helper classes that are used in multiple places within
OctoPrint's source code.
"""
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
import codecs
import collections
import contextlib
import copy
import logging
import os
import pickle
import queue
import re
import shutil
import sys
import tempfile
import threading
import time
import traceback
import warnings
import zlib
from collections.abc import Iterable, MutableMapping, Set
from functools import wraps
from glob import escape as glob_escape # noqa: F401
from time import monotonic as monotonic_time # noqa: F401
from typing import Union
from frozendict import frozendict
from octoprint import UMASK
from octoprint.util.connectivity import ConnectivityChecker # noqa: F401
from octoprint.util.files import ( # noqa: F401
find_collision_free_name,
get_dos_filename,
silent_remove,
)
from octoprint.util.net import ( # noqa: F401
address_for_client,
interface_addresses,
server_reachable,
)
logger = logging.getLogger(__name__)
def to_bytes(
s_or_u: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict"
) -> bytes:
"""
Make sure ``s_or_u`` is a byte string.
Arguments:
s_or_u (str or bytes): The value to convert
encoding (str): encoding to use if necessary, see :meth:`python:str.encode`
errors (str): error handling to use if necessary, see :meth:`python:str.encode`
Returns:
bytes: converted bytes.
"""
if s_or_u is None:
return s_or_u
if not isinstance(s_or_u, (str, bytes)):
s_or_u = str(s_or_u)
if isinstance(s_or_u, str):
return s_or_u.encode(encoding, errors=errors)
else:
return s_or_u
def to_unicode(
s_or_u: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict"
) -> str:
"""
Make sure ``s_or_u`` is a string (str).
Arguments:
s_or_u (str or bytes): The value to convert
encoding (str): encoding to use if necessary, see :meth:`python:bytes.decode`
errors (str): error handling to use if necessary, see :meth:`python:bytes.decode`
Returns:
str: converted string.
"""
if s_or_u is None:
return s_or_u
if not isinstance(s_or_u, (str, bytes)):
s_or_u = str(s_or_u)
if isinstance(s_or_u, bytes):
return s_or_u.decode(encoding, errors=errors)
else:
return s_or_u
def sortable_value(value, default_value=""):
if value is None:
return default_value
return value
sv = sortable_value
def pp(value):
"""
>>> pp(dict())
'dict()'
>>> pp(dict(a=1, b=2, c=3))
'dict(a=1, b=2, c=3)'
>>> pp(set())
'set()'
>>> pp({"a", "b"})
"{'a', 'b'}"
>>> pp(["a", "b", "d", "c"])
"['a', 'b', 'd', 'c']"
>>> pp(("a", "b", "d", "c"))
"('a', 'b', 'd', 'c')"
>>> pp("foo")
"'foo'"
>>> pp([dict(a=1, b=2), {"a", "c", "b"}, (1, 2), None, 1, True, "foo"])
"[dict(a=1, b=2), {'a', 'b', 'c'}, (1, 2), None, 1, True, 'foo']"
"""
if isinstance(value, dict):
# sort by keys
r = "dict("
r += ", ".join(map(lambda i: i[0] + "=" + pp(i[1]), sorted(value.items())))
r += ")"
return r
elif isinstance(value, set):
if len(value):
# filled set: sort
r = "{"
r += ", ".join(map(pp, sorted(value)))
r += "}"
return r
else:
# empty set
return "set()"
elif isinstance(value, list):
return "[" + ", ".join(map(pp, value)) + "]"
elif isinstance(value, tuple):
return "(" + ", ".join(map(pp, value)) + ")"
else:
return repr(value)
def warning_decorator_factory(warning_type):
def specific_warning(
message, stacklevel=1, since=None, includedoc=None, extenddoc=False
):
def decorator(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
# we need to increment the stacklevel by one because otherwise we'll get the location of our
# func_wrapper in the log, instead of our caller (which is the real caller of the wrapped function)
warnings.warn(message, warning_type, stacklevel=stacklevel + 1)
return func(*args, **kwargs)
if includedoc is not None and since is not None:
docstring = "\n.. deprecated:: {since}\n {message}\n\n".format(
since=since, message=includedoc
)
if (
extenddoc
and hasattr(func_wrapper, "__doc__")
and func_wrapper.__doc__ is not None
):
docstring = func_wrapper.__doc__ + "\n" + docstring
func_wrapper.__doc__ = docstring
return func_wrapper
return decorator
return specific_warning
def warning_factory(warning_type):
def specific_warning(
message, stacklevel=1, since=None, includedoc=None, extenddoc=False
):
def decorator(o):
def wrapper(f):
def new(*args, **kwargs):
warnings.warn(message, warning_type, stacklevel=stacklevel + 1)
return f(*args, **kwargs)
return new
output = o.__class__.__new__(o.__class__, o)
unwrappable_names = (
"__weakref__",
"__class__",
"__dict__",
"__doc__",
"__str__",
"__repr__",
"__getattribute__",
"__setattr__",
)
for method_name in dir(o):
if method_name in unwrappable_names:
continue
setattr(output, method_name, wrapper(getattr(o, method_name)))
if includedoc is not None and since is not None:
docstring = "\n.. deprecated:: {since}\n {message}\n\n".format(
since=since, message=includedoc
)
if (
extenddoc
and hasattr(wrapper, "__doc__")
and wrapper.__doc__ is not None
):
docstring = wrapper.__doc__ + "\n" + docstring
wrapper.__doc__ = docstring
return output
return decorator
return specific_warning
deprecated = warning_decorator_factory(DeprecationWarning)
"""
A decorator for deprecated methods. Logs a deprecation warning via Python's `:mod:`warnings` module including the
supplied ``message``. The call stack level used (for adding the source location of the offending call to the
warning) can be overridden using the optional ``stacklevel`` parameter. If both ``since`` and ``includedoc`` are
provided, a deprecation warning will also be added to the function's docstring by providing or extending its ``__doc__``
property.
Arguments:
message (string): The message to include in the deprecation warning.
stacklevel (int): Stack level for including the caller of the offending method in the logged warning. Defaults to 1,
meaning the direct caller of the method. It might make sense to increase this in case of the function call
happening dynamically from a fixed position to not shadow the real caller (e.g. in case of overridden
``getattr`` methods).
includedoc (string): Message about the deprecation to include in the wrapped function's docstring.
extenddoc (boolean): If True the original docstring of the wrapped function will be extended by the deprecation
message, if False (default) it will be replaced with the deprecation message.
since (string): Version since when the function was deprecated, must be present for the docstring to get extended.
Returns:
function: The wrapped function with the deprecation warnings in place.
"""
variable_deprecated = warning_factory(DeprecationWarning)
"""
A function for deprecated variables. Logs a deprecation warning via Python's `:mod:`warnings` module including the
supplied ``message``. The call stack level used (for adding the source location of the offending call to the
warning) can be overridden using the optional ``stacklevel`` parameter.
Arguments:
message (string): The message to include in the deprecation warning.
stacklevel (int): Stack level for including the caller of the offending method in the logged warning. Defaults to 1,
meaning the direct caller of the method. It might make sense to increase this in case of the function call
happening dynamically from a fixed position to not shadow the real caller (e.g. in case of overridden
``getattr`` methods).
since (string): Version since when the function was deprecated, must be present for the docstring to get extended.
Returns:
value: The value of the variable with the deprecation warnings in place.
"""
pending_deprecation = warning_decorator_factory(PendingDeprecationWarning)
"""
A decorator for methods pending deprecation. Logs a pending deprecation warning via Python's `:mod:`warnings` module
including the supplied ``message``. The call stack level used (for adding the source location of the offending call to
the warning) can be overridden using the optional ``stacklevel`` parameter. If both ``since`` and ``includedoc`` are
provided, a deprecation warning will also be added to the function's docstring by providing or extending its ``__doc__``
property.
Arguments:
message (string): The message to include in the deprecation warning.
stacklevel (int): Stack level for including the caller of the offending method in the logged warning. Defaults to 1,
meaning the direct caller of the method. It might make sense to increase this in case of the function call
happening dynamically from a fixed position to not shadow the real caller (e.g. in case of overridden
``getattr`` methods).
extenddoc (boolean): If True the original docstring of the wrapped function will be extended by the deprecation
message, if False (default) it will be replaced with the deprecation message.
includedoc (string): Message about the deprecation to include in the wrapped function's docstring.
since (string): Version since when the function was deprecated, must be present for the docstring to get extended.
Returns:
function: The wrapped function with the deprecation warnings in place.
"""
variable_pending_deprecation = warning_factory(PendingDeprecationWarning)
"""
A decorator for variables pending deprecation. Logs a pending deprecation warning via Python's `:mod:`warnings` module
including the supplied ``message``. The call stack level used (for adding the source location of the offending call to
the warning) can be overridden using the optional ``stacklevel`` parameter.
Arguments:
message (string): The message to include in the deprecation warning.
stacklevel (int): Stack level for including the caller of the offending method in the logged warning. Defaults to 1,
meaning the direct caller of the method. It might make sense to increase this in case of the function call
happening dynamically from a fixed position to not shadow the real caller (e.g. in case of overridden
``getattr`` methods).
since (string): Version since when the function was deprecated, must be present for the docstring to get extended.
Returns:
value: The value of the variable with the deprecation warnings in place.
"""
# TODO rename to_unicode to to_str and deprecate to_unicode in 2.0.0
to_str = deprecated(
"to_str has been renamed to to_bytes and in a future version will become the new to_unicode",
includedoc="to_str has been renamed to to_bytes and in a future version will become the new to_unicode",
since="1.3.11",
)(to_bytes)
to_native_str = deprecated(
"to_native_str is no longer needed, use to_unicode instead",
includedoc="to_native_str is no longer needed, use to_unicode instead",
since="1.8.0",
)(to_unicode)
def get_formatted_size(num):
"""
Formats the given byte count as a human readable rounded size expressed in the most pressing unit among B(ytes),
K(ilo)B(ytes), M(ega)B(ytes), G(iga)B(ytes) and T(era)B(ytes), with one decimal place.
Based on http://stackoverflow.com/a/1094933/2028598
Arguments:
num (int): The byte count to format
Returns:
string: The formatted byte count.
"""
for x in ["B", "KB", "MB", "GB"]:
if num < 1024:
return f"{num:3.1f}{x}"
num /= 1024
return "{:3.1f}{}".format(num, "TB")
def is_allowed_file(filename, extensions):
"""
Determines if the provided ``filename`` has one of the supplied ``extensions``. The check is done case-insensitive.
Arguments:
filename (string): The file name to check against the extensions.
extensions (list): The extensions to check against, a list of strings
Return:
boolean: True if the file name's extension matches one of the allowed extensions, False otherwise.
"""
return "." in filename and filename.rsplit(".", 1)[1].lower() in (
x.lower() for x in extensions
)
def get_formatted_timedelta(d):
"""
Formats a timedelta instance as "HH:MM:ss" and returns the resulting string.
Arguments:
d (datetime.timedelta): The timedelta instance to format
Returns:
string: The timedelta formatted as "HH:MM:ss"
"""
if d is None:
return None
hours = d.days * 24 + d.seconds // 3600
minutes = (d.seconds % 3600) // 60
seconds = d.seconds % 60
return "%02d:%02d:%02d" % (hours, minutes, seconds)
def get_formatted_datetime(d):
"""
Formats a datetime instance as "YYYY-mm-dd HH:MM" and returns the resulting string.
Arguments:
d (datetime.datetime): The datetime instance to format
Returns:
string: The datetime formatted as "YYYY-mm-dd HH:MM"
"""
if d is None:
return None
return d.strftime("%Y-%m-%d %H:%M")
def get_class(name):
"""
Retrieves the class object for a given fully qualified class name.
Arguments:
name (string): The fully qualified class name, including all modules separated by ``.``
Returns:
type: The class if it could be found.
Raises:
ImportError
"""
import importlib
mod_name, cls_name = name.rsplit(".", 1)
m = importlib.import_module(mod_name)
try:
return getattr(m, cls_name)
except AttributeError:
raise ImportError("No module named " + name)
def get_fully_qualified_classname(o):
"""
Returns the fully qualified class name for an object.
Based on https://stackoverflow.com/a/2020083
Args:
o: the object of which to determine the fqcn
Returns:
(str) the fqcn of the object
"""
module = getattr(o.__class__, "__module__", None)
if module is None:
return o.__class__.__name__
return module + "." + o.__class__.__name__
def get_exception_string(fmt="{type}: '{message}' @ {file}:{function}:{line}"):
"""
Retrieves the exception info of the last raised exception and returns it as a string formatted as
``<exception type>: <exception message> @ <source file>:<function name>:<line number>``.
Returns:
string: The formatted exception information.
"""
location_info = traceback.extract_tb(sys.exc_info()[2])[0]
exception = {
"type": str(sys.exc_info()[0].__name__),
"message": str(sys.exc_info()[1]),
"file": os.path.basename(location_info[0]),
"function": location_info[2],
"line": location_info[1],
}
return fmt.format(**exception)
def sanitize_ascii(line):
if not isinstance(line, (str, bytes)):
raise ValueError(
"Expected str but got {} instead".format(
line.__class__.__name__ if line is not None else None
)
)
return to_unicode(line, encoding="ascii", errors="replace").rstrip()
def filter_non_ascii(line):
"""
Filter predicate to test if a line contains non ASCII characters.
Arguments:
line (string): The line to test
Returns:
boolean: True if the line contains non ASCII characters, False otherwise.
"""
try:
to_bytes(to_unicode(line, encoding="ascii"), encoding="ascii")
return False
except ValueError:
return True
def filter_non_utf8(line):
try:
to_bytes(to_unicode(line, encoding="utf-8"), encoding="utf-8")
return False
except ValueError:
return True
def chunks(l, n): # noqa: E741
"""
Yield successive n-sized chunks from l.
Taken from http://stackoverflow.com/a/312464/2028598
"""
for i in range(0, len(l), n):
yield l[i : i + n]
def is_running_from_source():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
return os.path.isdir(os.path.join(root, "src")) and os.path.isfile(
os.path.join(root, "setup.py")
)
def fast_deepcopy(obj):
# the best way to implement this would be as a C module, that way we'd be able to use
# the fast path every time.
try:
# implemented in C and much faster than deepcopy:
# https://stackoverflow.com/a/29385667
return pickle.loads(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL))
except (AttributeError, pickle.PicklingError):
# fall back when something unpickable is found
return copy.deepcopy(obj)
def dict_merge(a, b, leaf_merger=None, in_place=False):
"""
Recursively deep-merges two dictionaries.
Based on https://www.xormedia.com/recursively-merge-dictionaries-in-python/
Example::
>>> a = dict(foo="foo", bar="bar", fnord=dict(a=1))
>>> b = dict(foo="other foo", fnord=dict(b=2, l=["some", "list"]))
>>> expected = dict(foo="other foo", bar="bar", fnord=dict(a=1, b=2, l=["some", "list"]))
>>> dict_merge(a, b) == expected
True
>>> dict_merge(a, None) == a
True
>>> dict_merge(None, b) == b
True
>>> dict_merge(None, None) == dict()
True
>>> def leaf_merger(a, b):
... if isinstance(a, list) and isinstance(b, list):
... return a + b
... raise ValueError()
>>> result = dict_merge(dict(l1=[3, 4], l2=[1], a="a"), dict(l1=[1, 2], l2="foo", b="b"), leaf_merger=leaf_merger)
>>> result.get("l1") == [3, 4, 1, 2]
True
>>> result.get("l2") == "foo"
True
>>> result.get("a") == "a"
True
>>> result.get("b") == "b"
True
>>> c = dict(foo="foo")
>>> dict_merge(c, {"bar": "bar"}) is c
False
>>> dict_merge(c, {"bar": "bar"}, in_place=True) is c
True
Arguments:
a (dict): The dictionary to merge ``b`` into
b (dict): The dictionary to merge into ``a``
leaf_merger (callable): An optional callable to use to merge leaves (non-dict values)
in_place (boolean): If set to True, a will be merged with b in place, meaning a will be modified
Returns:
dict: ``b`` deep-merged into ``a``
"""
if a is None:
a = {}
if b is None:
b = {}
if not isinstance(b, dict):
return b
if in_place:
result = a
else:
result = fast_deepcopy(a)
for k, v in b.items():
if k in result and isinstance(result[k], dict):
result[k] = dict_merge(
result[k], v, leaf_merger=leaf_merger, in_place=in_place
)
else:
merged = None
if k in result and callable(leaf_merger):
try:
merged = leaf_merger(result[k], v)
except ValueError:
# can't be merged by leaf merger
pass
if merged is None:
merged = fast_deepcopy(v)
result[k] = merged
return result
def dict_sanitize(a, b):
"""
Recursively deep-sanitizes ``a`` based on ``b``, removing all keys (and
associated values) from ``a`` that do not appear in ``b``.
Example::
>>> a = dict(foo="foo", bar="bar", fnord=dict(a=1, b=2, l=["some", "list"]))
>>> b = dict(foo=None, fnord=dict(a=None, b=None))
>>> expected = dict(foo="foo", fnord=dict(a=1, b=2))
>>> dict_sanitize(a, b) == expected
True
>>> dict_clean(a, b) == expected
True
Arguments:
a (dict): The dictionary to clean against ``b``.
b (dict): The dictionary containing the key structure to clean from ``a``.
Results:
dict: A new dict based on ``a`` with all keys (and corresponding values) found in ``b`` removed.
"""
from copy import deepcopy
if not isinstance(b, dict):
return a
result = deepcopy(a)
for k, v in a.items():
if k not in b:
del result[k]
elif isinstance(v, dict):
result[k] = dict_sanitize(v, b[k])
else:
result[k] = deepcopy(v)
return result
dict_clean = deprecated(
"dict_clean has been renamed to dict_sanitize",
includedoc="Replaced by :func:`dict_sanitize`",
)(dict_sanitize)
def dict_minimal_mergediff(source, target):
"""
Recursively calculates the minimal dict that would be needed to be deep merged with
a in order to produce the same result as deep merging a and b.
Example::
>>> a = dict(foo=dict(a=1, b=2), bar=dict(c=3, d=4))
>>> b = dict(bar=dict(c=3, d=5), fnord=None)
>>> c = dict_minimal_mergediff(a, b)
>>> c == dict(bar=dict(d=5), fnord=None)
True
>>> dict_merge(a, c) == dict_merge(a, b)
True
Arguments:
source (dict): Source dictionary
target (dict): Dictionary to compare to source dictionary and derive diff for
Returns:
dict: The minimal dictionary to deep merge on ``source`` to get the same result
as deep merging ``target`` on ``source``.
"""
if not isinstance(source, dict) or not isinstance(target, dict):
raise ValueError("source and target must be dictionaries")
if source == target:
# shortcut: if both are equal, we return an empty dict as result
return {}
from copy import deepcopy
all_keys = set(list(source.keys()) + list(target.keys()))
result = {}
for k in all_keys:
if k not in target:
# key not contained in b => not contained in result
continue
if k in source:
# key is present in both dicts, we have to take a look at the value
value_source = source[k]
value_target = target[k]
if value_source != value_target:
# we only need to look further if the values are not equal
if isinstance(value_source, dict) and isinstance(value_target, dict):
# both are dicts => deeper down it goes into the rabbit hole
result[k] = dict_minimal_mergediff(value_source, value_target)
else:
# new b wins over old a
result[k] = deepcopy(value_target)
else:
# key is new, add it
result[k] = deepcopy(target[k])
return result
def dict_contains_keys(keys, dictionary):
"""
Recursively deep-checks if ``dictionary`` contains all keys found in ``keys``.
Example::
>>> positive = dict(foo="some_other_bar", fnord=dict(b=100))
>>> negative = dict(foo="some_other_bar", fnord=dict(b=100, d=20))
>>> dictionary = dict(foo="bar", fnord=dict(a=1, b=2, c=3))
>>> dict_contains_keys(positive, dictionary)
True
>>> dict_contains_keys(negative, dictionary)
False
Arguments:
a (dict): The dictionary to check for the keys from ``b``.
b (dict): The dictionary whose keys to check ``a`` for.
Returns:
boolean: True if all keys found in ``b`` are also present in ``a``, False otherwise.
"""
if not isinstance(keys, dict) or not isinstance(dictionary, dict):
return False
for k, v in keys.items():
if k not in dictionary:
return False
elif isinstance(v, dict):
if not dict_contains_keys(v, dictionary[k]):
return False
return True
def dict_flatten(dictionary, prefix="", separator="."):
"""
Flatten a dictionary.
Example::
>>> data = {'a': {'a1': 'a1', 'a2': 'a2'}, 'b': 'b'}
>>> expected = {'a.a1': 'a1', 'a.a2': 'a2', 'b': 'b'}
>>> actual = dict_flatten(data)
>>> shared = {(k, actual[k]) for k in actual if k in expected and actual[k] == expected[k]}
>>> len(shared) == len(expected)
True
Args:
dictionary: the dictionary to flatten
prefix: the key prefix, initially an empty string
separator: key separator, '.' by default
Returns: a flattened dict
"""
result = {}
for k, v in dictionary.items():
key = prefix + separator + k if prefix else k
if isinstance(v, MutableMapping):
result.update(dict_flatten(v, prefix=key, separator=separator))
else:
result[key] = v
return result
class fallback_dict(dict):
def __init__(self, custom, *fallbacks):
self.custom = custom
self.fallbacks = fallbacks
def __getitem__(self, item):
for dictionary in self._all():
if item in dictionary:
return dictionary[item]
raise KeyError()
def __setitem__(self, key, value):
self.custom[key] = value
def __delitem__(self, key):
# TODO: mark as deleted and leave fallbacks alone?
for dictionary in self._all():
if key in dictionary:
del dictionary[key]
def __contains__(self, key):
return any((key in dictionary) for dictionary in self._all())
def keys(self):
result = set()
for dictionary in self._all():
for k in dictionary.keys():
if k in result:
continue
result.add(k)
yield k
def values(self):
result = set()
for dictionary in self._all():
for k in dictionary:
if k in result:
continue
result.add(k)
yield k
def items(self):
result = set()
for dictionary in self._all():
for k, v in dictionary.items():
if k in result:
continue
result.add(k)
yield k, v
def _all(self):
yield self.custom
yield from self.fallbacks
def dict_filter(dictionary, filter_function):
"""
Filters a dictionary with the provided filter_function
Example::
>>> data = dict(key1="value1", key2="value2", other_key="other_value", foo="bar", bar="foo")
>>> dict_filter(data, lambda k, v: k.startswith("key")) == dict(key1="value1", key2="value2")
True
>>> dict_filter(data, lambda k, v: v.startswith("value")) == dict(key1="value1", key2="value2")
True
>>> dict_filter(data, lambda k, v: k == "foo" or v == "foo") == dict(foo="bar", bar="foo")
True
>>> dict_filter(data, lambda k, v: False) == dict()
True
>>> dict_filter(data, lambda k, v: True) == data
True
>>> dict_filter(None, lambda k, v: True)
Traceback (most recent call last):
...
AssertionError
>>> dict_filter(data, None)
Traceback (most recent call last):
...
AssertionError
Arguments:
dictionary (dict): The dictionary to filter
filter_function (callable): The filter function to apply, called with key and
value of an entry in the dictionary, must return ``True`` for values to
keep and ``False`` for values to strip
Returns:
dict: A shallow copy of the provided dictionary, stripped of the key-value-pairs
for which the ``filter_function`` returned ``False``
"""
assert isinstance(dictionary, dict)
assert callable(filter_function)
return {k: v for k, v in dictionary.items() if filter_function(k, v)}
# Source: http://stackoverflow.com/a/6190500/562769
class DefaultOrderedDict(collections.OrderedDict):
def __init__(self, default_factory=None, *a, **kw):
if default_factory is not None and not callable(default_factory):
raise TypeError("first argument must be callable")
collections.OrderedDict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return collections.OrderedDict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory is None:
args = tuple()
else:
args = (self.default_factory,)
return type(self), args, None, None, list(self.items())
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
def __deepcopy__(self, memo):
import copy
return type(self)(self.default_factory, copy.deepcopy(list(self.items())))
# noinspection PyMethodOverriding
def __repr__(self):
return "OrderedDefaultDict({}, {})".format(
self.default_factory,
collections.OrderedDict.__repr__(self),
)
class Object:
pass
def guess_mime_type(data):
import filetype
return filetype.guess_mime(data)
def parse_mime_type(mime):
import cgi
if not mime or not isinstance(mime, (str, bytes)):
raise ValueError("mime must be a non empty str")
mime, params = cgi.parse_header(mime)
if mime == "*":
mime = "*/*"
parts = mime.split("/") if "/" in mime else None
if not parts or len(parts) != 2:
raise ValueError("mime must be a mime type of format type/subtype")
mime_type, mime_subtype = parts
return mime_type.strip(), mime_subtype.strip(), params
def mime_type_matches(mime, other):
if not isinstance(mime, tuple):
mime = parse_mime_type(mime)
if not isinstance(other, tuple):
other = parse_mime_type(other)
mime_type, mime_subtype, _ = mime
other_type, other_subtype, _ = other
type_matches = mime_type == other_type or mime_type == "*" or other_type == "*"
subtype_matches = (
mime_subtype == other_subtype or mime_subtype == "*" or other_subtype == "*"
)
return type_matches and subtype_matches
@contextlib.contextmanager
def atomic_write(
filename,
mode="w+b",
encoding="utf-8",
prefix="tmp",
suffix="",
permissions=None,
max_permissions=0o777,
):
if permissions is None:
permissions = 0o664 & ~UMASK
if os.path.exists(filename):
permissions |= os.stat(filename).st_mode
permissions &= max_permissions
# Ensure we create the file in the target dir so our move is atomic. See #3719
dir = os.path.dirname(filename)
kwargs = {
"mode": mode,
"prefix": prefix,
"suffix": suffix,
"dir": dir,
"delete": False,
}
if "b" not in mode:
kwargs["encoding"] = encoding
fd = tempfile.NamedTemporaryFile(**kwargs)
try:
try:
yield fd
finally:
fd.close()
os.chmod(fd.name, permissions)
shutil.move(fd.name, filename)
finally:
silent_remove(fd.name)
@contextlib.contextmanager
def tempdir(ignore_errors=False, onerror=None, **kwargs):
import shutil
import tempfile
dirpath = tempfile.mkdtemp(**kwargs)
try:
yield dirpath
finally:
shutil.rmtree(dirpath, ignore_errors=ignore_errors, onerror=onerror)
@contextlib.contextmanager
def temppath(prefix=None, suffix=""):
import tempfile
temp = tempfile.NamedTemporaryFile(
prefix=prefix if prefix is not None else tempfile.template,
suffix=suffix,
delete=False,
)
try:
temp.close()
yield temp.name
finally:
os.remove(temp.name)
TemporaryDirectory = tempfile.TemporaryDirectory
@deprecated("Please use open with '-sig' encoding instead", since="1.8.0")
def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs):
# TODO Remove in 2.0.0
import codecs
assert "b" not in mode, "binary mode not support by bom_aware_open"
codec = codecs.lookup(encoding)
encoding = codec.name
if kwargs is None:
kwargs = {}
potential_bom_attribute = "BOM_" + codec.name.replace("utf-", "utf").upper()
if "r" in mode and hasattr(codecs, potential_bom_attribute):
# these encodings might have a BOM, so let's see if there is one
bom = getattr(codecs, potential_bom_attribute)
with open(filename, mode="rb") as f:
header = f.read(4)
if header.startswith(bom):
encoding += "-sig"
return open(filename, encoding=encoding, mode=mode, **kwargs)
BOMS = {
"utf-8-sig": codecs.BOM_UTF8,
"utf-16-le": codecs.BOM_UTF16_LE,
"utf-16-be": codecs.BOM_UTF16_BE,
"utf-32-le": codecs.BOM_UTF32_LE,
"utf-32-be": codecs.BOM_UTF32_BE,
}
def get_bom(filename, encoding):
"""
Check if the file has a BOM and if so return it.
Params:
filename (str): The file to check.
encoding (str): The encoding to check for.
Returns:
(bytes) the BOM or None if there is no BOM.
"""
with open(filename, mode="rb") as f:
header = f.read(4)
for enc, bom in BOMS.items():
if header.startswith(bom) and encoding.lower() == enc:
return bom
return None
def is_hidden_path(path):
if path is None:
# we define a None path as not hidden here
return False
path = to_unicode(path)
filename = os.path.basename(path)
if filename.startswith("."):
# filenames starting with a . are hidden
return True
if sys.platform == "win32":
# if we are running on windows we also try to read the hidden file
# attribute via the windows api
try:
import ctypes
attrs = ctypes.windll.kernel32.GetFileAttributesW(path)
assert attrs != -1 # INVALID_FILE_ATTRIBUTES == -1
return bool(attrs & 2) # FILE_ATTRIBUTE_HIDDEN == 2
except (AttributeError, AssertionError):
pass
# if we reach that point, the path is not hidden
return False
def thaw_frozendict(obj):
if not isinstance(obj, (dict, frozendict)):
raise ValueError("obj must be a dict or frozendict instance")
# only true love can thaw a frozen dict
letitgo = {}
for key, value in obj.items():
if isinstance(value, (dict, frozendict)):
letitgo[key] = thaw_frozendict(value)
else:
letitgo[key] = copy.deepcopy(value)
return letitgo
thaw_immutabledict = deprecated(
"thaw_immutabledict has been renamed back to thaw_frozendict", since="1.8.0"
)(thaw_frozendict)
def utmify(link, source=None, medium=None, name=None, term=None, content=None):
if source is None:
return link
import urllib.parse as urlparse
from collections import OrderedDict
from urllib.parse import urlencode
# inspired by https://stackoverflow.com/a/2506477
parts = list(urlparse.urlparse(link))
# parts[4] is the url query
query = OrderedDict(urlparse.parse_qs(parts[4]))
query["utm_source"] = source
if medium is not None:
query["utm_medium"] = medium
if name is not None:
query["utm_name"] = name
if term is not None:
query["utm_term"] = term
if content is not None:
query["utm_content"] = content
parts[4] = urlencode(query, doseq=True)
return urlparse.urlunparse(parts)
class RepeatedTimer(threading.Thread):
"""
This class represents an action that should be run repeatedly in an interval. It is similar to python's
own :class:`threading.Timer` class, but instead of only running once the ``function`` will be run again and again,
sleeping the stated ``interval`` in between.
RepeatedTimers are started, as with threads, by calling their ``start()`` method. The timer can be stopped (in
between runs) by calling the :func:`cancel` method. The interval the time waited before execution of a loop may
not be exactly the same as the interval specified by the user.
For example:
.. code-block:: python
def hello():
print("Hello World!")
t = RepeatedTimer(1.0, hello)
t.start() # prints "Hello World!" every second
Another example with dynamic interval and loop condition:
.. code-block:: python
count = 0
maximum = 5
factor = 1
def interval():
global count
global factor
return count * factor
def condition():
global count
global maximum
return count <= maximum
def hello():
print("Hello World!")
global count
count += 1
t = RepeatedTimer(interval, hello, run_first=True, condition=condition)
t.start() # prints "Hello World!" 5 times, printing the first one
# directly, then waiting 1, 2, 3, 4s in between (adaptive interval)
Arguments:
interval (float or callable): The interval between each ``function`` call, in seconds. Can also be a callable
returning the interval to use, in case the interval is not static.
function (callable): The function to call.
args (list or tuple): The arguments for the ``function`` call. Defaults to an empty list.
kwargs (dict): The keyword arguments for the ``function`` call. Defaults to an empty dict.
run_first (boolean): If set to True, the function will be run for the first time *before* the first wait period.
If set to False (the default), the function will be run for the first time *after* the first wait period.
condition (callable): Condition that needs to be True for loop to continue. Defaults to ``lambda: True``.
on_condition_false (callable): Callback to call when the timer finishes due to condition becoming false. Will
be called before the ``on_finish`` callback.
on_cancelled (callable): Callback to call when the timer finishes due to being cancelled. Will be called
before the ``on_finish`` callback.
on_finish (callable): Callback to call when the timer finishes, either due to being cancelled or since
the condition became false.
daemon (bool): daemon flag to set on underlying thread.
"""
def __init__(
self,
interval,
function,
args=None,
kwargs=None,
run_first=False,
condition=None,
on_condition_false=None,
on_cancelled=None,
on_finish=None,
daemon=True,
):
threading.Thread.__init__(self)
if args is None:
args = []
if kwargs is None:
kwargs = {}
if condition is None:
condition = lambda: True
if not callable(interval):
self.interval = lambda: interval
else:
self.interval = interval
self.function = function
self.finished = threading.Event()
self.args = args
self.kwargs = kwargs
self.run_first = run_first
self.condition = condition
self.on_condition_false = on_condition_false
self.on_cancelled = on_cancelled
self.on_finish = on_finish
self.daemon = daemon
def cancel(self):
self._finish(self.on_cancelled)
def run(self):
while self.condition():
if self.run_first:
# if we are to run the function BEFORE waiting for the first time
self.function(*self.args, **self.kwargs)
# make sure our condition is still met before running into the downtime
if not self.condition():
break
# wait, but break if we are cancelled
self.finished.wait(self.interval())
if self.finished.is_set():
return
if not self.run_first:
# if we are to run the function AFTER waiting for the first time
self.function(*self.args, **self.kwargs)
# we'll only get here if the condition was false
self._finish(self.on_condition_false)
def _finish(self, *callbacks):
self.finished.set()
for callback in callbacks:
if not callable(callback):
continue
callback()
if callable(self.on_finish):
self.on_finish()
class ResettableTimer(threading.Thread):
"""
This class represents an action that should be run after a specified amount of time. It is similar to python's
own :class:`threading.Timer` class, with the addition of being able to reset the counter to zero.
ResettableTimers are started, as with threads, by calling their ``start()`` method. The timer can be stopped (in
between runs) by calling the :func:`cancel` method. Resetting the counter can be done with the :func:`reset` method.
For example:
.. code-block:: python
def hello():
print("Ran hello() at {}").format(time.time())
t = ResettableTimer(60.0, hello)
t.start()
print("Started at {}").format(time.time())
time.sleep(30)
t.reset()
print("Reset at {}").format(time.time())
Arguments:
interval (float or callable): The interval before calling ``function``, in seconds. Can also be a callable
returning the interval to use, in case the interval is not static.
function (callable): The function to call.
args (list or tuple): The arguments for the ``function`` call. Defaults to an empty list.
kwargs (dict): The keyword arguments for the ``function`` call. Defaults to an empty dict.
on_cancelled (callable): Callback to call when the timer finishes due to being cancelled.
on_reset (callable): Callback to call when the timer is reset.
daemon (bool): daemon flag to set on underlying thread.
"""
def __init__(
self,
interval,
function,
args=None,
kwargs=None,
on_reset=None,
on_cancelled=None,
daemon=True,
):
threading.Thread.__init__(self)
self._event = threading.Event()
self._mutex = threading.Lock()
self.is_reset = True
if args is None:
args = []
if kwargs is None:
kwargs = {}
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.on_cancelled = on_cancelled
self.on_reset = on_reset
self.daemon = daemon
def run(self):
while self.is_reset:
with self._mutex:
self.is_reset = False
self._event.wait(self.interval)
if not self._event.isSet():
self.function(*self.args, **self.kwargs)
with self._mutex:
self._event.set()
def cancel(self):
with self._mutex:
self._event.set()
if callable(self.on_cancelled):
self.on_cancelled()
def reset(self, interval=None):
with self._mutex:
if interval:
self.interval = interval
self.is_reset = True
self._event.set()
self._event.clear()
if callable(self.on_reset):
self.on_reset()
class CountedEvent:
def __init__(self, value=0, minimum=0, maximum=None, **kwargs):
self._counter = 0
self._min = minimum
self._max = kwargs.get("max", maximum)
self._mutex = threading.RLock()
self._event = threading.Event()
self._internal_set(value)
@property
def min(self):
return self._min
@min.setter
def min(self, val):
with self._mutex:
self._min = val
@property
def max(self):
return self._max
@max.setter
def max(self, val):
with self._mutex:
self._max = val
@property
def is_set(self):
return self._event.is_set
@property
def counter(self):
with self._mutex:
return self._counter
def set(self):
with self._mutex:
self._internal_set(self._counter + 1)
def clear(self, completely=False):
with self._mutex:
if completely:
self._internal_set(0)
else:
self._internal_set(self._counter - 1)
def reset(self):
self.clear(completely=True)
def wait(self, timeout=None):
self._event.wait(timeout)
def blocked(self):
return self.counter <= 0
def acquire(self, blocking=1):
return self._mutex.acquire(blocking=blocking)
def release(self):
return self._mutex.release()
def _internal_set(self, value):
self._counter = value
if self._counter <= 0:
if self._min is not None and self._counter < self._min:
self._counter = self._min
self._event.clear()
else:
if self._max is not None and self._counter > self._max:
self._counter = self._max
self._event.set()
class InvariantContainer:
def __init__(self, initial_data=None, guarantee_invariant=None):
from threading import RLock
if guarantee_invariant is None:
guarantee_invariant = lambda data: data
self._data = []
self._mutex = RLock()
self._invariant = guarantee_invariant
if initial_data is not None and isinstance(initial_data, Iterable):
for item in initial_data:
self.append(item)
def append(self, item):
with self._mutex:
self._data.append(item)
self._data = self._invariant(self._data)
def remove(self, item):
with self._mutex:
self._data.remove(item)
self._data = self._invariant(self._data)
def __len__(self):
return len(self._data)
def __iter__(self):
return self._data.__iter__()
class PrependableQueue(queue.Queue):
def __init__(self, maxsize=0):
queue.Queue.__init__(self, maxsize=maxsize)
def prepend(self, item, block=True, timeout=True):
from time import time as _time
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise queue.Full
elif timeout is None:
while self._qsize() >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0:
raise queue.Full
self.not_full.wait(remaining)
self._prepend(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def _prepend(self, item):
self.queue.appendleft(item)
class TypedQueue(PrependableQueue):
def __init__(self, maxsize=0):
PrependableQueue.__init__(self, maxsize=maxsize)
self._lookup = set()
def put(self, item, item_type=None, *args, **kwargs):
PrependableQueue.put(self, (item, item_type), *args, **kwargs)
def get(self, *args, **kwargs):
item, _ = PrependableQueue.get(self, *args, **kwargs)
return item
def prepend(self, item, item_type=None, *args, **kwargs):
PrependableQueue.prepend(self, (item, item_type), *args, **kwargs)
def _put(self, item):
_, item_type = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(
item_type, f"Type {item_type} is already in queue"
)
else:
self._lookup.add(item_type)
PrependableQueue._put(self, item)
def _get(self):
item = PrependableQueue._get(self)
_, item_type = item
if item_type is not None:
self._lookup.discard(item_type)
return item
def _prepend(self, item):
_, item_type = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(
item_type, f"Type {item_type} is already in queue"
)
else:
self._lookup.add(item_type)
PrependableQueue._prepend(self, item)
class TypeAlreadyInQueue(Exception):
def __init__(self, t, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.type = t
class CaseInsensitiveSet(Set):
"""
Basic case insensitive set
Any str values will be stored and compared in lower case. Other value types are left as-is.
"""
def __init__(self, *args):
self.data = {x.lower() if isinstance(x, str) else x for x in args}
def __contains__(self, item):
if isinstance(item, str):
return item.lower() in self.data
else:
return item in self.data
def __iter__(self):
return iter(self.data)
def __len__(self):
return len(self.data)
# originally from https://stackoverflow.com/a/5967539
def natural_key(text):
return [int(c) if c.isdigit() else c for c in re.split(r"(\d+)", text)]
def count(gen):
"""Used instead of len(generator), which doesn't work"""
n = 0
for _ in gen:
n += 1
return n
def fqfn(f):
if hasattr(f, "__self__"):
# bound method
return "{}.{}.{}".format(
f.__self__.__class__.__module__, f.__self__.__class__.__name__, f.__name__
)
else:
return f"{f.__module__}.{f.__name__}"
def time_this(
logtarget="octoprint.util.timings",
expand_logtarget=False,
message="{func} took {timing:.2f}ms",
incl_func_args=False,
log_enter=False,
message_enter="Entering {func}...",
):
def decorator(f):
func = fqfn(f)
lt = logtarget
if expand_logtarget:
lt += "." + func
logger = logging.getLogger(lt)
@wraps(f)
def wrapper(*args, **kwargs):
data = {"func": func, "func_args": "?", "func_kwargs": "?"}
if incl_func_args and logger.isEnabledFor(logging.DEBUG):
data.update(
func_args=",".join(map(repr, args)),
func_kwargs=",".join(
map(lambda x: f"{x[0]}={x[1]!r}", kwargs.items())
),
)
if log_enter:
logger.debug(message_enter.format(**data), extra=data)
start = time.time()
try:
return f(*args, **kwargs)
finally:
timing = (time.time() - start) * 1000
if logger.isEnabledFor(logging.DEBUG):
data.update(timing=timing)
logger.debug(message.format(**data), extra=data)
return wrapper
return decorator
def generate_api_key():
import uuid
return "".join("%02X" % z for z in bytes(uuid.uuid4().bytes))
def map_boolean(value, true_text, false_text):
return true_text if value else false_text
def serialize(filename, data, encoding="utf-8", compressed=True):
"""
Serializes data to a file
In the current implementation this uses json.dumps.
If `compressed` is True (the default), the serialized data put through zlib.compress.
Supported data types are listed at the bottom of
:func:`octoprint.util.comprehensive_json`, and include some data types that are not
supported by json.dumps by default.
This is not thread-safe, if concurrent access is required, the caller needs to ensure
that only one thread is writing to the file at any given time.
Arguments:
filename (str): The file to write to
data (object): The data to serialize
encoding (str): The encoding to use for the file
compressed (bool): Whether to compress the data before writing it to the file
"""
from octoprint.util import json
serialized = json.serializing.dumps(data).encode(encoding)
if compressed:
serialized = zlib.compress(serialized)
with open(filename, "wb") as f:
f.write(serialized)
def deserialize(filename, encoding="utf-8"):
"""
Deserializes data from a file
In the current implementation this uses json.loads and - if the file is found to be
compressed - zlib.decompress.
Arguments:
filename (str): The file to deserialize from
encoding (str): The encoding to use for the file, defaults to utf-8
Returns:
The deserialized data structure
"""
with open(filename, "rb") as f:
serialized = f.read()
try:
serialized = zlib.decompress(serialized)
except zlib.error:
pass
from octoprint.util import json
return json.serializing.loads(serialized.decode(encoding))
| 54,507 | Python | .py | 1,373 | 31.383103 | 122 | 0.611156 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,905 | yaml.py | OctoPrint_OctoPrint/src/octoprint/util/yaml.py | from typing import Any, Dict, Hashable, TextIO, Union
def load_from_file(
file: TextIO = None, path: str = None
) -> Union[Dict[Hashable, Any], list, None]:
"""
Safely and performantly loads yaml data from the given source. Either a
path or a file must be passed in.
"""
if path is not None:
assert file is None
with open(path, encoding="utf-8-sig") as f:
return load_from_file(file=f)
if file is not None:
assert path is None
assert path is not None or file is not None, "this function requires an input file"
import yaml
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader
return yaml.load(file, Loader=SafeLoader)
def _save_to_file_base(data, file=None, path=None, pretty=False, **kwargs):
if path is not None:
assert file is None
with open(path, "w", encoding="utf-8") as f:
return _save_to_file_base(data, file=f, pretty=pretty, **kwargs)
if file is not None:
assert path is None
import yaml
try:
from yaml import CSafeDumper as SafeDumper
except ImportError:
from yaml import SafeDumper
# make multiline strings look better by using block scalars
def _block_scalar_str_presenter(dumper, data):
return dumper.represent_scalar(
"tag:yaml.org,2002:str", data, style="|" if "\n" in data else None
)
SafeDumper.add_representer(str, _block_scalar_str_presenter)
if pretty:
# make each element go on a new line and indent by 2
kwargs.update(default_flow_style=False, indent=2)
return yaml.dump(
data,
stream=file,
Dumper=SafeDumper,
allow_unicode=True, # no good reason not to allow it these days
**kwargs
)
def save_to_file(data, file=None, path=None, pretty=False, **kwargs):
"""
Safely and performantly dumps the `data` to yaml.
To dump to a string, use `yaml.dump()`.
:type data: object
:param data: the data to be serialized
:type file: typing.TextIO | None
:type path: str | None
:type pretty: bool
:param pretty: formats the output yaml into a more human-friendly format
"""
assert file is not None or path is not None, "this function requires an output file"
_save_to_file_base(data, file=file, path=path, pretty=pretty, **kwargs)
def dump(data, pretty=False, **kwargs):
"""
Safely and performantly dumps the `data` to a yaml string.
:param data: the data to be serialized
:param pretty: formats the output yaml into a more human-friendly format
:param kwargs: any other args to be passed to the internal yaml.dump() call.
:return: yaml-serialized data
:rtype: str
"""
return _save_to_file_base(data, file=None, pretty=pretty, **kwargs)
| 2,876 | Python | .py | 72 | 33.569444 | 88 | 0.670262 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,906 | paths.py | OctoPrint_OctoPrint/src/octoprint/util/paths.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"
def normalize(path, expand_user=True, expand_vars=True, real=True, **kwargs):
import os
if path is None:
return None
if expand_user:
path = os.path.expanduser(path)
if expand_vars:
path = os.path.expandvars(path)
path = os.path.abspath(path)
if real:
path = os.path.realpath(path)
return path
| 595 | Python | .py | 15 | 34.266667 | 103 | 0.679443 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,907 | comm.py | OctoPrint_OctoPrint/src/octoprint/util/comm.py | __author__ = "Gina Häußge <osd@foosel.net> based on work by David Braam"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2013 David Braam, Gina Häußge & others - Released under terms of the AGPLv3 License"
"""
The code in this file is based on Cura.util.machineCom from the Cura project from late 2012
(https://github.com/daid/Cura).
"""
import contextlib
import copy
import fnmatch
import glob
import logging
import os
import queue
import re
import threading
import time
from collections import deque, namedtuple
import serial
import wrapt
import octoprint.plugin
from octoprint.events import Events, eventManager
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings
from octoprint.systemcommands import system_command_manager
from octoprint.util import (
CountedEvent,
PrependableQueue,
RepeatedTimer,
ResettableTimer,
TypeAlreadyInQueue,
TypedQueue,
chunks,
dict_merge,
filter_non_ascii,
filter_non_utf8,
get_bom,
get_dos_filename,
get_exception_string,
sanitize_ascii,
to_unicode,
)
from octoprint.util.files import m20_timestamp_to_unix_timestamp
from octoprint.util.platform import get_os, set_close_exec
try:
import winreg
except ImportError:
try:
import _winreg as winreg # type: ignore
except ImportError:
pass
_logger = logging.getLogger(__name__)
# a bunch of regexes we'll need for the communication parsing...
regex_float_pattern = r"[-+]?[0-9]*\.?[0-9]+"
regex_positive_float_pattern = r"[+]?[0-9]*\.?[0-9]+"
regex_int_pattern = r"\d+"
regex_command = re.compile(
r"^\s*((?P<codeGM>[GM]\d+)(\.(?P<subcode>\d+))?|(?P<codeT>T)\d+|(?P<codeF>F)\d+)"
)
"""Regex for a GCODE command."""
regex_float = re.compile(regex_float_pattern)
"""Regex for a float value."""
regexes_parameters = {
"floatE": re.compile(r"(^|[^A-Za-z])[Ee](?P<value>%s)" % regex_float_pattern),
"floatF": re.compile(r"(^|[^A-Za-z])[Ff](?P<value>%s)" % regex_float_pattern),
"floatP": re.compile(r"(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
"floatR": re.compile(r"(^|[^A-Za-z])[Rr](?P<value>%s)" % regex_float_pattern),
"floatS": re.compile(r"(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
"floatX": re.compile(r"(^|[^A-Za-z])[Xx](?P<value>%s)" % regex_float_pattern),
"floatY": re.compile(r"(^|[^A-Za-z])[Yy](?P<value>%s)" % regex_float_pattern),
"floatZ": re.compile(r"(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
"intN": re.compile(r"(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
"intS": re.compile(r"(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_int_pattern),
"intT": re.compile(r"(^|[^A-Za-z])[Tt](?P<value>%s)" % regex_int_pattern),
}
"""Regexes for parsing various GCODE command parameters."""
regex_minMaxError = re.compile(r"Error:[0-9]\n")
"""Regex matching first line of min/max errors from the firmware."""
regex_marlinKillError = re.compile(
r"Heating failed|Thermal Runaway|Thermal Malfunction|MAXTEMP triggered|MINTEMP triggered|Invalid extruder number|Watchdog barked|KILL caused"
)
"""Regex matching first line of kill causing errors from Marlin."""
regex_sdPrintingByte = re.compile(r"(?P<current>[0-9]+)/(?P<total>[0-9]+)")
"""Regex matching SD printing status reports.
Groups will be as follows:
* ``current``: current byte position in file being printed
* ``total``: total size of file being printed
"""
regex_sdFileOpened = re.compile(
r"File opened:\s*(?P<name>.*?)\s+Size:\s*(?P<size>%s)" % regex_int_pattern
)
"""Regex matching "File opened" messages from the firmware.
Groups will be as follows:
* ``name``: name of the file reported as having been opened (str)
* ``size``: size of the file in bytes (int)
"""
regex_temp = re.compile(
r"(^|\s)(?P<sensor>B|C|T(?P<toolnum>\d*)|([\w]+)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?"
% (regex_float_pattern, regex_float_pattern)
)
"""Regex matching temperature entries in line.
Groups will be as follows:
* ``sensor``: whole sensor designator, incl. optional ``toolnum``, e.g. "T1", "B",
"C" or anything custom (str)
* ``toolnum``: tool number, if provided, only for T0, T1, etc (int)
* ``actual``: actual temperature (float)
* ``target``: target temperature, if provided (float)
"""
regex_repetierTempExtr = re.compile(
r"TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_float_pattern
)
"""Regex for matching target temp reporting from Repetier.
Groups will be as follows:
* ``toolnum``: number of the extruder to which the target temperature
report belongs (int)
* ``target``: new target temperature (float)
"""
regex_repetierTempBed = re.compile(r"TargetBed:(?P<target>%s)" % regex_float_pattern)
"""Regex for matching target temp reporting from Repetier for beds.
Groups will be as follows:
* ``target``: new target temperature (float)
"""
regex_position = re.compile(
r"X:\s*(?P<x>{float})\s*Y:\s*(?P<y>{float})\s*Z:\s*(?P<z>{float})\s*((E:\s*(?P<e>{float}))|(?P<es>(E\d+:\s*{float}\s*)+))".format(
float=regex_float_pattern
)
)
"""Regex for matching position reporting.
Groups will be as follows:
* ``x``: X coordinate
* ``y``: Y coordinate
* ``z``: Z coordinate
* ``e``: E coordinate if present, or
* ``es``: multiple E coordinates if present, to be parsed further with regex_e_positions
"""
regex_e_positions = re.compile(rf"E(?P<id>\d+):\s*(?P<value>{regex_float_pattern})")
"""Regex for matching multiple E coordinates in a position report.
Groups will be as follows:
* ``id``: id of the extruder or which the position is reported
* ``value``: reported position value
"""
regex_firmware_splitter = re.compile(r"(^|\s+)([A-Z][A-Z0-9_]*):")
"""Regex to use for splitting M115 responses."""
regex_resend_linenumber = re.compile(r"(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
regex_serial_devices = re.compile(r"^(?:ttyUSB|ttyACM|tty\.usb|cu\.|cuaU|ttyS|rfcomm).*")
"""Regex used to filter out valid tty devices"""
MINIMAL_SD_TIMESTAMP = 1212012000
# May 29th 2008 = RepRap 1.0 "Darwin" achieves self-replication
SDFileData = namedtuple("SDFileData", ["name", "size", "timestamp", "longname"])
def serialList():
if os.name == "nt":
candidates = []
try:
key = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM"
)
i = 0
while True:
candidates += [winreg.EnumValue(key, i)[1]]
i += 1
except Exception:
pass
else:
candidates = []
try:
with os.scandir("/dev") as it:
for entry in it:
if regex_serial_devices.match(entry.name):
candidates.append(entry.path)
except Exception:
logging.getLogger(__name__).exception(
"Could not scan /dev for serial ports on the system"
)
# additional ports
additionalPorts = settings().get(["serial", "additionalPorts"])
if additionalPorts:
for additional in additionalPorts:
candidates += glob.glob(additional)
hooks = octoprint.plugin.plugin_manager().get_hooks(
"octoprint.comm.transport.serial.additional_port_names"
)
for name, hook in hooks.items():
try:
candidates += hook(candidates)
except Exception:
logging.getLogger(__name__).exception(
"Error while retrieving additional "
"serial port names from hook {}".format(name)
)
# blacklisted ports
blacklistedPorts = settings().get(["serial", "blacklistedPorts"])
if blacklistedPorts:
for pattern in settings().get(["serial", "blacklistedPorts"]):
candidates = list(
filter(lambda x: not fnmatch.fnmatch(x, pattern), candidates)
)
# last used port = first to try, move to start
prev = settings().get(["serial", "port"])
if prev in candidates:
candidates.remove(prev)
candidates.insert(0, prev)
return candidates
def baudrateList(candidates=None):
if candidates is None:
# sorted by likelihood
candidates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
# additional baudrates prepended, sorted descending
additionalBaudrates = settings().get(["serial", "additionalBaudrates"])
for additional in sorted(additionalBaudrates, reverse=True):
try:
candidates.insert(0, int(additional))
except Exception:
_logger.warning(
f"{additional} is not a valid additional baudrate, ignoring it"
)
# blacklisted baudrates
blacklistedBaudrates = settings().get(["serial", "blacklistedBaudrates"])
if blacklistedBaudrates:
for baudrate in blacklistedBaudrates:
candidates.remove(baudrate)
# last used baudrate = first to try, move to start
prev = settings().getInt(["serial", "baudrate"])
if prev in candidates:
candidates.remove(prev)
candidates.insert(0, prev)
return candidates
gcodeToEvent = {
# pause for user input
"M226": Events.WAITING,
"M0": Events.WAITING,
"M1": Events.WAITING,
# dwell command
"G4": Events.DWELL,
# part cooler
"M245": Events.COOLING,
# part conveyor
"M240": Events.CONVEYOR,
# part ejector
"M40": Events.EJECT,
# user alert
"M300": Events.ALERT,
# home print head
"G28": Events.HOME,
# emergency stop
"M112": Events.E_STOP,
# motors on/off
"M80": Events.POWER_ON,
"M81": Events.POWER_OFF,
# filament change
"M600": Events.FILAMENT_CHANGE,
"M701": Events.FILAMENT_CHANGE,
"M702": Events.FILAMENT_CHANGE,
}
class PositionRecord:
_standard_attrs = {"x", "y", "z", "e", "f", "t"}
@classmethod
def valid_e(cls, attr):
if not attr.startswith("e"):
return False
try:
int(attr[1:])
except ValueError:
return False
return True
def __init__(self, *args, **kwargs):
attrs = self._attrs(*kwargs.keys())
for attr in attrs:
setattr(self, attr, kwargs.get(attr))
def copy_from(self, other):
# make sure all standard attrs and attrs from other are set
attrs = self._attrs(*dir(other))
for attr in attrs:
setattr(self, attr, getattr(other, attr))
# delete attrs other doesn't have
attrs = {key for key in dir(self) if self.valid_e(key)} - attrs
for attr in attrs:
delattr(self, attr)
def as_dict(self):
attrs = self._attrs(*dir(self))
return {attr: getattr(self, attr) for attr in attrs}
def _attrs(self, *args):
return self._standard_attrs | {key for key in args if self.valid_e(key)}
def reset(self):
for attr in self._attrs(*dir(self)):
setattr(self, attr, None)
class TemperatureRecord:
RESERVED_IDENTIFIER_REGEX = re.compile(r"B|C|T\d*")
def __init__(self):
self._tools = {}
self._bed = (None, None)
self._chamber = (None, None)
self._custom = {}
def copy_from(self, other):
self._tools = other.tools
self._bed = other.bed
def set_tool(self, tool, actual=None, target=None):
current = self._tools.get(tool, (None, None))
self._tools[tool] = self._to_new_tuple(current, actual, target)
def set_bed(self, actual=None, target=None):
current = self._bed
self._bed = self._to_new_tuple(current, actual, target)
def set_chamber(self, actual=None, target=None):
current = self._chamber
self._chamber = self._to_new_tuple(current, actual, target)
def set_custom(self, identifier, actual=None, target=None):
if self.RESERVED_IDENTIFIER_REGEX.fullmatch(identifier):
raise ValueError(f"{identifier} is a reserved identifier")
current = self._custom.get(identifier, (None, None))
self._custom[identifier] = self._to_new_tuple(current, actual, target)
@property
def tools(self):
return dict(self._tools)
@property
def bed(self):
return self._bed
@property
def chamber(self):
return self._chamber
@property
def custom(self):
return dict(self._custom)
def as_script_dict(self):
result = {}
tools = self.tools
for tool, data in tools.items():
result[tool] = {"actual": data[0], "target": data[1]}
bed = self.bed
result["b"] = {"actual": bed[0], "target": bed[1]}
chamber = self.chamber
result["c"] = {"actual": chamber[0], "target": chamber[1]}
custom = self.custom
for identifier, data in custom.items():
result[identifier] = {"actual": data[0], "target": data[1]}
return result
@classmethod
def _to_new_tuple(cls, current, actual, target):
if current is None or not isinstance(current, tuple) or len(current) != 2:
current = (None, None)
if actual is None and target is None:
return current
old_actual, old_target = current
if actual is None:
return old_actual, target
elif target is None:
return actual, old_target
else:
return actual, target
class MachineCom:
STATE_NONE = 0
STATE_OPEN_SERIAL = 1
STATE_DETECT_SERIAL = 2
STATE_CONNECTING = 3
STATE_OPERATIONAL = 4
STATE_STARTING = 5
STATE_PRINTING = 6
STATE_PAUSED = 7
STATE_PAUSING = 8
STATE_RESUMING = 9
STATE_FINISHING = 10
STATE_CLOSED = 11
STATE_ERROR = 12
STATE_CLOSED_WITH_ERROR = 13
STATE_TRANSFERING_FILE = 14
STATE_CANCELLING = 15
# be sure to add anything here that signifies an operational state
OPERATIONAL_STATES = (
STATE_PRINTING,
STATE_STARTING,
STATE_OPERATIONAL,
STATE_PAUSED,
STATE_CANCELLING,
STATE_PAUSING,
STATE_RESUMING,
STATE_FINISHING,
STATE_TRANSFERING_FILE,
)
# be sure to add anything here that signifies a printing state
PRINTING_STATES = (
STATE_STARTING,
STATE_PRINTING,
STATE_CANCELLING,
STATE_PAUSING,
STATE_RESUMING,
STATE_FINISHING,
)
CAPABILITY_AUTOREPORT_TEMP = "AUTOREPORT_TEMP"
CAPABILITY_AUTOREPORT_SD_STATUS = "AUTOREPORT_SD_STATUS"
CAPABILITY_AUTOREPORT_POS = "AUTOREPORT_POS"
CAPABILITY_BUSY_PROTOCOL = "BUSY_PROTOCOL"
CAPABILITY_EMERGENCY_PARSER = "EMERGENCY_PARSER"
CAPABILITY_CHAMBER_TEMP = "CHAMBER_TEMPERATURE"
CAPABILITY_EXTENDED_M20 = "EXTENDED_M20"
CAPABILITY_LFN_WRITE = "LFN_WRITE"
CAPABILITY_SUPPORT_ENABLED = "enabled"
CAPABILITY_SUPPORT_DETECTED = "detected"
CAPABILITY_SUPPORT_DISABLED = "disabled"
DETECTION_RETRIES = 3
def __init__(
self, port=None, baudrate=None, callbackObject=None, printerProfileManager=None
):
self._logger = logging.getLogger(__name__)
self._serialLogger = logging.getLogger("SERIAL")
self._phaseLogger = logging.getLogger(__name__ + ".command_phases")
if port is None:
port = settings().get(["serial", "port"])
if baudrate is None:
settingsBaudrate = settings().getInt(["serial", "baudrate"])
if settingsBaudrate is None:
baudrate = 0
else:
baudrate = settingsBaudrate
if callbackObject is None:
callbackObject = MachineComPrintCallback()
self._port = port
self._baudrate = baudrate
self._callback = callbackObject
self._printerProfileManager = printerProfileManager
self._state = self.STATE_NONE
self._serial = None
self._detection_candidates = []
self._detection_retry = self.DETECTION_RETRIES
self._temperatureTargetSetThreshold = 25
self._tempOffsets = {}
self._command_queue = CommandQueue()
self._currentZ = None
self._currentF = None
self._heatupWaitStartTime = None
self._heatupWaitTimeLost = 0.0
self._pauseWaitStartTime = None
self._pauseWaitTimeLost = 0.0
self._currentTool = 0
self._toolBeforeChange = None
self._toolBeforeHeatup = None
self._known_invalid_tools = set()
self._known_invalid_custom_temps = set()
self._known_broken_temperature_hooks = set()
self._long_running_command = False
self._heating = False
self._dwelling_until = False
self._connection_closing = False
self._timeout = None
self._ok_timeout = None
self._timeout_intervals = {}
for key, value in (
settings().get(["serial", "timeout"], merged=True, asdict=True).items()
):
try:
self._timeout_intervals[key] = float(value)
except ValueError:
pass
self._consecutive_timeouts = 0
self._consecutive_timeout_maximums = {}
for key, value in (
settings()
.get(["serial", "maxCommunicationTimeouts"], merged=True, asdict=True)
.items()
):
try:
self._consecutive_timeout_maximums[key] = int(value)
except ValueError:
pass
self._max_write_passes = settings().getInt(["serial", "maxWritePasses"])
self._hello_command = settings().get(["serial", "helloCommand"])
self._hello_sent = 0
self._trigger_ok_for_m29 = settings().getBoolean(["serial", "triggerOkForM29"])
self._alwaysSendChecksum = settings().getBoolean(["serial", "alwaysSendChecksum"])
self._neverSendChecksum = settings().getBoolean(["serial", "neverSendChecksum"])
self._sendChecksumWithUnknownCommands = settings().getBoolean(
["serial", "sendChecksumWithUnknownCommands"]
)
self._unknownCommandsNeedAck = settings().getBoolean(
["serial", "unknownCommandsNeedAck"]
)
self._sdAlwaysAvailable = settings().getBoolean(["serial", "sdAlwaysAvailable"])
self._sdRelativePath = settings().getBoolean(["serial", "sdRelativePath"])
self._sdLowerCase = settings().getBoolean(["serial", "sdLowerCase"])
self._sdCancelCommand = settings().get(["serial", "sdCancelCommand"])
self._blockWhileDwelling = settings().getBoolean(["serial", "blockWhileDwelling"])
self._send_m112_on_error = settings().getBoolean(["serial", "sendM112OnError"])
self._disable_sd_printing_detection = settings().getBoolean(
["serial", "disableSdPrintingDetection"]
)
self._current_line = 1
self._line_mutex = threading.RLock()
self._resendDelta = None
self._capability_support = {
self.CAPABILITY_AUTOREPORT_TEMP: settings().getBoolean(
["serial", "capabilities", "autoreport_temp"]
),
self.CAPABILITY_AUTOREPORT_SD_STATUS: settings().getBoolean(
["serial", "capabilities", "autoreport_sdstatus"]
),
self.CAPABILITY_AUTOREPORT_POS: settings().getBoolean(
["serial", "capabilities", "autoreport_pos"]
),
self.CAPABILITY_BUSY_PROTOCOL: settings().getBoolean(
["serial", "capabilities", "busy_protocol"]
),
self.CAPABILITY_EMERGENCY_PARSER: settings().getBoolean(
["serial", "capabilities", "emergency_parser"]
),
self.CAPABILITY_CHAMBER_TEMP: settings().getBoolean(
["serial", "capabilities", "chamber_temp"]
),
self.CAPABILITY_EXTENDED_M20: settings().getBoolean(
["serial", "capabilities", "extended_m20"]
),
self.CAPABILITY_LFN_WRITE: settings().getBoolean(
["serial", "capabilities", "lfn_write"]
),
}
last_line_count = settings().getInt(["serial", "lastLineBufferSize"])
self._lastLines = deque([], last_line_count)
self._lastCommError = None
self._lastResendNumber = None
self._currentResendCount = 0
self._currentConsecutiveResendNumber = None
self._currentConsecutiveResendCount = 0
self._maxConsecutiveResends = settings().getInt(
["serial", "maxConsecutiveResends"]
)
self._errorValue = ""
self._firmware_detection = settings().getBoolean(["serial", "firmwareDetection"])
self._firmware_info_received = False
self._firmware_capabilities_received = False
self._firmware_info = {}
self._firmware_capabilities = {}
self._defer_sd_refresh = settings().getBoolean(["serial", "waitToLoadSdFileList"])
self._temperature_autoreporting = False
self._sdstatus_autoreporting = False
self._pos_autoreporting = False
self._busy_protocol_detected = False
self._busy_protocol_support = False
self._trigger_ok_after_resend = settings().get(
["serial", "supportResendsWithoutOk"]
)
self._resend_ok_timer = None
self._resendActive = False
terminal_log_size = settings().getInt(["serial", "terminalLogSize"])
self._terminal_log = deque([], min(20, terminal_log_size))
self._disconnect_on_errors = settings().getBoolean(
["serial", "disconnectOnErrors"]
)
self._ignore_errors = settings().getBoolean(
["serial", "ignoreErrorsFromFirmware"]
)
self._log_resends = settings().getBoolean(["serial", "logResends"])
# don't log more resends than 5 / 60s
self._log_resends_rate_start = None
self._log_resends_rate_count = 0
self._log_resends_max = 5
self._log_resends_rate_frame = 60
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
self._checksum_requiring_commands = settings().get(
["serial", "checksumRequiringCommands"]
)
self._blocked_commands = settings().get(["serial", "blockedCommands"])
self._ignored_commands = settings().get(["serial", "ignoredCommands"])
self._pausing_commands = settings().get(["serial", "pausingCommands"])
self._emergency_commands = settings().get(["serial", "emergencyCommands"])
self._sanity_check_tools = settings().getBoolean(["serial", "sanityCheckTools"])
self._ack_max = settings().getInt(["serial", "ackMax"])
self._clear_to_send = CountedEvent(
name="comm.clear_to_send", minimum=None, maximum=self._ack_max
)
self._send_queue = SendQueue()
self._temperature_timer = None
self._sd_status_timer = None
self._consecutive_not_sd_printing = 0
self._consecutive_not_sd_printing_maximum = settings().getInt(
["serial", "maxNotSdPrinting"]
)
self._job_queue = JobQueue()
self._transmitted_lines = 0
self._received_resend_requests = 0
self._resend_ratio_start = settings().getInt(["serial", "resendRatioStart"])
self._resend_ratio_threshold = (
settings().getInt(["serial", "resendRatioThreshold"]) / 100
)
self._resend_ratio_reported = False
# hooks
self._pluginManager = octoprint.plugin.plugin_manager()
self._gcode_hooks = {
"queuing": self._pluginManager.get_hooks(
"octoprint.comm.protocol.gcode.queuing"
),
"queued": self._pluginManager.get_hooks(
"octoprint.comm.protocol.gcode.queued"
),
"sending": self._pluginManager.get_hooks(
"octoprint.comm.protocol.gcode.sending"
),
"sent": self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sent"),
}
self._received_message_hooks = self._pluginManager.get_hooks(
"octoprint.comm.protocol.gcode.received"
)
self._error_message_hooks = self._pluginManager.get_hooks(
"octoprint.comm.protocol.gcode.error"
)
self._atcommand_hooks = {
"queuing": self._pluginManager.get_hooks(
"octoprint.comm.protocol.atcommand.queuing"
),
"sending": self._pluginManager.get_hooks(
"octoprint.comm.protocol.atcommand.sending"
),
}
self._firmware_info_hooks = {
"info": self._pluginManager.get_hooks(
"octoprint.comm.protocol.firmware.info"
),
"capabilities": self._pluginManager.get_hooks(
"octoprint.comm.protocol.firmware.capabilities"
),
"capability_report": self._pluginManager.get_hooks(
"octoprint.comm.protocol.firmware.capability_report"
),
}
self._printer_action_hooks = self._pluginManager.get_hooks(
"octoprint.comm.protocol.action"
)
self._gcodescript_hooks = self._pluginManager.get_hooks(
"octoprint.comm.protocol.scripts"
)
self._serial_factory_hooks = self._pluginManager.get_hooks(
"octoprint.comm.transport.serial.factory"
)
self._temperature_hooks = self._pluginManager.get_hooks(
"octoprint.comm.protocol.temperatures.received"
)
# SD status data
self._sdEnabled = settings().getBoolean(["feature", "sdSupport"])
self._sdAvailable = False
self._sdFileList = False
self._sdFileLongName = False
self._sdFiles = {}
self._sdFilesAvailable = threading.Event()
self._sdFileToSelect = None
self._sdFileToSelectUser = None
self._ignore_select = False
self._manualStreaming = False
self.last_temperature = TemperatureRecord()
self.pause_temperature = TemperatureRecord()
self.cancel_temperature = TemperatureRecord()
self.last_position = PositionRecord()
self.pause_position = PositionRecord()
self.cancel_position = PositionRecord()
self.last_fanspeed = None
self.pause_fanspeed = None
self.cancel_fanspeed = None
self._record_pause_data = False
self._record_cancel_data = False
self._suppress_scripts = set()
self._suppress_scripts_mutex = threading.RLock()
self._action_users = {}
self._action_users_mutex = threading.RLock()
self._pause_position_timer = None
self._pause_mutex = threading.RLock()
self._cancel_position_timer = None
self._cancel_mutex = threading.RLock()
self._log_position_on_pause = settings().getBoolean(
["serial", "logPositionOnPause"]
)
self._log_position_on_cancel = settings().getBoolean(
["serial", "logPositionOnCancel"]
)
self._abort_heatup_on_cancel = settings().getBoolean(
["serial", "abortHeatupOnCancel"]
)
# serial encoding
self._serial_encoding = settings().get(["serial", "encoding"])
# action commands
self._enable_shutdown_action_command = settings().getBoolean(
["serial", "enableShutdownActionCommand"]
)
# print job
self._currentFile = None
self._job_on_hold = CountedEvent()
# multithreading locks
self._jobLock = threading.RLock()
self._sendingLock = threading.RLock()
# monitoring thread
self._monitoring_active = True
self.monitoring_thread = threading.Thread(
target=self._monitor, name="comm._monitor"
)
self.monitoring_thread.daemon = True
# sending thread
self._send_queue_active = True
self.sending_thread = threading.Thread(
target=self._send_loop, name="comm.sending_thread"
)
self.sending_thread.daemon = True
def start(self):
# doing this here instead of __init__ combats a race condition where
# self._comm in the printer interface is still None on first pushs from
# the comm layer during detection
self.monitoring_thread.start()
self.sending_thread.start()
def __del__(self):
self.close()
@property
def _active(self):
return self._monitoring_active and self._send_queue_active
def _capability_supported(self, cap):
return self._capability_support.get(
cap, False
) and self._firmware_capabilities.get(cap, False)
@property
def received_resends(self):
return self._received_resend_requests
@property
def transmitted_lines(self):
return self._transmitted_lines
@property
def resend_ratio(self):
if self._transmitted_lines:
return self._received_resend_requests / self._transmitted_lines
else:
return 0.0
def _reevaluate_resend_ratio(self):
resend_ratio = self.resend_ratio
if (
resend_ratio >= self._resend_ratio_threshold
and self._transmitted_lines > self._resend_ratio_start
and not self._resend_ratio_reported
):
message = (
"Over {:.0f}% of transmitted lines have triggered resend requests "
"({:.2f}%). The communication with the printer is unreliable. "
"Please see https://faq.octoprint.org/communication-errors.".format(
self._resend_ratio_threshold * 100, resend_ratio * 100
)
)
self._log(message)
self._logger.warning(message)
self._resend_ratio_reported = True
##~~ internal state management
def _changeState(self, newState):
if self._state == newState:
return
if newState == self.STATE_CLOSED or newState == self.STATE_CLOSED_WITH_ERROR:
if settings().getBoolean(["feature", "sdSupport"]):
self._sdFileList = False
self._sdFiles = {}
self._callback.on_comm_sd_files([])
if self._currentFile is not None:
if self.isBusy():
self._recordFilePosition()
self._currentFile.close()
oldState = self.getStateString()
self._state = newState
text = 'Changing monitoring state from "{}" to "{}"'.format(
oldState, self.getStateString()
)
self._log(text)
self._logger.info(text)
self._callback.on_comm_state_change(newState)
def _dual_log(self, message, level=logging.ERROR, prefix=""):
self._logger.log(level, message)
self._log(prefix + message)
def _log(self, message):
message = to_unicode(message)
self._terminal_log.append(message)
self._callback.on_comm_log(message)
self._serialLogger.debug(message)
def _to_logfile_with_terminal(self, message=None, level=logging.INFO):
log = "Last lines in terminal:\n" + "\n".join(
map(lambda x: f"| {x}", list(self._terminal_log))
)
if message is not None:
log = message + "\n| " + log
self._logger.log(level, log)
def _addToLastLines(self, cmd):
self._lastLines.append(cmd)
##~~ getters
def getState(self):
return self._state
def getStateId(self, state=None):
if state is None:
state = self._state
possible_states = list(
filter(lambda x: x.startswith("STATE_"), self.__class__.__dict__.keys())
)
for possible_state in possible_states:
if getattr(self, possible_state) == state:
return possible_state[len("STATE_") :]
return "UNKNOWN"
def getStateString(self, state=None):
if state is None:
state = self._state
if state == self.STATE_NONE:
return "Offline"
elif state == self.STATE_OPEN_SERIAL:
return "Opening serial connection"
elif state == self.STATE_DETECT_SERIAL:
return "Detecting serial connection"
elif state == self.STATE_CONNECTING:
return "Connecting"
elif state == self.STATE_OPERATIONAL:
return "Operational"
elif state == self.STATE_STARTING:
if self.isSdFileSelected():
return "Starting print from SD"
elif self.isStreaming():
return "Starting to send file to SD"
else:
return "Starting"
elif state == self.STATE_PRINTING:
if self.isSdFileSelected():
return "Printing from SD"
elif self.isStreaming():
return "Sending file to SD"
else:
return "Printing"
elif state == self.STATE_CANCELLING:
return "Cancelling"
elif state == self.STATE_PAUSING:
return "Pausing"
elif state == self.STATE_PAUSED:
return "Paused"
elif state == self.STATE_RESUMING:
return "Resuming"
elif state == self.STATE_FINISHING:
return "Finishing"
elif state == self.STATE_CLOSED:
return "Offline"
elif state == self.STATE_ERROR:
return "Error"
elif state == self.STATE_CLOSED_WITH_ERROR:
return "Offline after error"
elif state == self.STATE_TRANSFERING_FILE:
return "Transferring file to SD"
return f"Unknown State ({self._state})"
def getErrorString(self):
return self._errorValue
def isClosedOrError(self):
return self._state in (
self.STATE_ERROR,
self.STATE_CLOSED,
self.STATE_CLOSED_WITH_ERROR,
)
def isError(self):
return self._state in (self.STATE_ERROR, self.STATE_CLOSED_WITH_ERROR)
def isOperational(self):
return self._state in self.OPERATIONAL_STATES
def isPrinting(self):
return self._state in self.PRINTING_STATES
def isCancelling(self):
return self._state == self.STATE_CANCELLING
def isPausing(self):
return self._state == self.STATE_PAUSING
def isResuming(self):
return self._state == self.STATE_RESUMING
def isStarting(self):
return self._state == self.STATE_STARTING
def isFinishing(self):
return self._state == self.STATE_FINISHING
def isSdPrinting(self):
return self.isSdFileSelected() and self.isPrinting()
def isSdFileSelected(self):
return self._currentFile is not None and isinstance(
self._currentFile, PrintingSdFileInformation
)
def isStreaming(self):
return (
self._currentFile is not None
and isinstance(self._currentFile, StreamingGcodeFileInformation)
and not self._currentFile.done
)
def isPaused(self):
return self._state == self.STATE_PAUSED
def isBusy(self):
return (
self.isPrinting()
or self.isPaused()
or self._state in (self.STATE_CANCELLING, self.STATE_PAUSING)
)
def isSdReady(self):
return self._sdAvailable
def getPrintProgress(self):
if self._currentFile is None:
return None
return self._currentFile.getProgress()
def getPrintFilepos(self):
if self._currentFile is None:
return None
return self._currentFile.getFilepos()
def getPrintTime(self):
if self._currentFile is None or self._currentFile.getStartTime() is None:
return None
else:
return (
time.monotonic()
- self._currentFile.getStartTime()
- self._pauseWaitTimeLost
)
def getCleanedPrintTime(self):
printTime = self.getPrintTime()
if printTime is None:
return None
cleanedPrintTime = printTime - self._heatupWaitTimeLost
if cleanedPrintTime < 0:
cleanedPrintTime = 0.0
return cleanedPrintTime
def getTemp(self):
return self.last_temperature.tools
def getBedTemp(self):
return self.last_temperature.bed
def getOffsets(self):
return dict(self._tempOffsets)
def getCurrentTool(self):
return self._currentTool
def getConnection(self):
port = self._port
baudrate = self._baudrate
if self._serial is not None:
if hasattr(self._serial, "port"):
port = self._serial.port
if hasattr(self._serial, "baudrate"):
baudrate = self._serial.baudrate
return port, baudrate
def getTransport(self):
return self._serial
##~~ external interface
@contextlib.contextmanager
def job_put_on_hold(self, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
raise RuntimeError("Could not acquire job_on_hold lock")
self._job_on_hold.set()
try:
yield
finally:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._continue_sending()
self._job_on_hold.release()
@property
def job_on_hold(self):
return self._job_on_hold.counter > 0
def set_job_on_hold(self, value, blocking=True):
trigger = False
# don't run any locking code beyond this...
if not self._job_on_hold.acquire(blocking=blocking):
return False
try:
if value:
self._job_on_hold.set()
else:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
trigger = True
finally:
self._job_on_hold.release()
# locking code is now safe to run again
if trigger:
self._continue_sending()
return True
def close(self, is_error=False, wait=True, timeout=10.0, *args, **kwargs):
"""
Closes the connection to the printer.
If ``is_error`` is False, will attempt to send the ``beforePrinterDisconnected``
gcode script. If ``is_error`` is False and ``wait`` is True, will wait
until all messages in the send queue (including the ``beforePrinterDisconnected``
gcode script) have been sent to the printer.
Arguments:
is_error (bool): Whether the closing takes place due to an error (True)
or not (False, default)
wait (bool): Whether to wait for all messages in the send
queue to be processed before closing (True, default) or not (False)
"""
# legacy parameters
is_error = kwargs.get("isError", is_error)
if self._connection_closing:
return
self._connection_closing = True
if self._temperature_timer is not None:
try:
self._temperature_timer.cancel()
except Exception:
pass
if self._sd_status_timer is not None:
try:
self._sd_status_timer.cancel()
except Exception:
pass
def deactivate_monitoring_and_send_queue():
self._monitoring_active = False
self._send_queue_active = False
if self._serial is not None:
if not is_error and self._state in self.OPERATIONAL_STATES:
self.sendGcodeScript("beforePrinterDisconnected")
if wait:
if timeout is not None:
stop = time.monotonic() + timeout
while (
self._command_queue.unfinished_tasks
or self._send_queue.unfinished_tasks
) and time.monotonic() < stop:
time.sleep(0.1)
else:
self._command_queue.join()
self._send_queue.join()
deactivate_monitoring_and_send_queue()
try:
if hasattr(self._serial, "cancel_read") and callable(
self._serial.cancel_read
):
self._serial.cancel_read()
except Exception:
self._logger.exception(
"Error while cancelling pending reads from the serial port"
)
try:
if hasattr(self._serial, "cancel_write") and callable(
self._serial.cancel_write
):
self._serial.cancel_write()
except Exception:
self._logger.exception(
"Error while cancelling pending writes to the serial port"
)
try:
self._serial.close()
except Exception:
self._logger.exception("Error while trying to close serial port")
is_error = True
else:
deactivate_monitoring_and_send_queue()
self._serial = None
# if we are printing, this will also make sure of firing PRINT_FAILED
if is_error:
self._changeState(self.STATE_CLOSED_WITH_ERROR)
else:
self._changeState(self.STATE_CLOSED)
if settings().getBoolean(["feature", "sdSupport"]):
self._sdFiles = {}
def setTemperatureOffset(self, offsets):
self._tempOffsets.update(offsets)
def fakeOk(self):
self._handle_ok()
def sendCommand(
self,
cmd,
cmd_type=None,
part_of_job=False,
processed=False,
force=False,
on_sent=None,
tags=None,
):
if not isinstance(cmd, QueueMarker):
cmd = to_unicode(cmd, errors="replace")
if not processed:
cmd = process_gcode_line(cmd)
if not cmd:
return False
gcode = gcode_command_for_cmd(cmd)
force = force or gcode in self._emergency_commands
if tags is None:
tags = set()
if part_of_job:
self._job_queue.put((cmd, cmd_type, on_sent, tags | {"source:job"}))
return True
elif (
self.isPrinting()
and not self.isSdFileSelected()
and not self.job_on_hold
and not force
):
try:
self._command_queue.put(
(cmd, cmd_type, on_sent, tags), item_type=cmd_type
)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in command queue: " + e.type)
return False
elif self.isOperational() or force:
return self._sendCommand(cmd, cmd_type=cmd_type, on_sent=on_sent, tags=tags)
def _getGcodeScript(self, scriptName, replacements=None):
context = {}
if replacements is not None and isinstance(replacements, dict):
context.update(replacements)
context.update(
{
"printer_profile": self._printerProfileManager.get_current_or_default(),
"last_position": self.last_position,
"last_temperature": self.last_temperature.as_script_dict(),
"last_fanspeed": self.last_fanspeed,
}
)
if scriptName == "afterPrintPaused" or scriptName == "beforePrintResumed":
context.update(
{
"pause_position": self.pause_position,
"pause_temperature": self.pause_temperature.as_script_dict(),
"pause_fanspeed": self.pause_fanspeed,
}
)
elif scriptName == "afterPrintCancelled":
context.update(
{
"cancel_position": self.cancel_position,
"cancel_temperature": self.cancel_temperature.as_script_dict(),
"cancel_fanspeed": self.cancel_fanspeed,
}
)
scriptLinesPrefix = []
scriptLinesSuffix = []
for name, hook in self._gcodescript_hooks.items():
try:
retval = hook(self, "gcode", scriptName)
except Exception:
self._logger.exception(
f"Error while processing hook {name}.",
extra={"plugin": name},
)
else:
if retval is None:
continue
if not isinstance(retval, (list, tuple)) or len(retval) not in [2, 3, 4]:
continue
def to_list(data, t):
if isinstance(data, str):
data = list(s.strip() for s in data.split("\n"))
if isinstance(data, (list, tuple)):
return list(map(lambda x: (x, t), data))
else:
return None
additional_tags = {f"plugin:{name}"}
if len(retval) == 4:
additional_tags |= set(retval[3])
prefix, suffix = map(lambda x: to_list(x, additional_tags), retval[0:2])
if prefix:
scriptLinesPrefix = list(prefix) + scriptLinesPrefix
if suffix:
scriptLinesSuffix += list(suffix)
if len(retval) == 3:
variables = retval[2]
context = dict_merge(context, {"plugins": {name: variables}})
template = settings().loadScript("gcode", scriptName, context=context)
if template is None:
scriptLines = []
else:
scriptLines = template.split("\n")
scriptLines = scriptLinesPrefix + scriptLines + scriptLinesSuffix
def process(line):
tags = set()
if (
isinstance(line, tuple)
and len(line) == 2
and isinstance(line[0], str)
and isinstance(line[1], set)
):
tags = line[1]
line = line[0]
return process_gcode_line(line), tags
return list(
filter(
lambda x: x[0] is not None and x[0].strip() != "",
map(process, scriptLines),
)
)
def sendGcodeScript(
self, scriptName, replacements=None, tags=None, part_of_job=False
):
if tags is None:
tags = set()
scriptLines = self._getGcodeScript(scriptName, replacements=replacements)
tags_to_use = tags | {
"trigger:comm.send_gcode_script",
"source:script",
f"script:{scriptName}",
}
for line in scriptLines:
if (
isinstance(line, tuple)
and len(line) == 2
and isinstance(line[0], str)
and isinstance(line[1], set)
):
# 2-tuple: line + tags
ttu = tags_to_use | line[1]
line = line[0]
elif isinstance(line, str):
# just a line
ttu = tags_to_use
else:
# whatever
continue
self.sendCommand(line, part_of_job=part_of_job, tags=ttu)
return "\n".join(map(lambda x: x if isinstance(x, str) else x[0], scriptLines))
def startPrint(self, pos=None, tags=None, external_sd=False, user=None):
if not self.isOperational() or self.isPrinting():
return
if self._currentFile is None:
raise ValueError("No file selected for printing")
self._heatupWaitStartTime = None if not self._heating else time.monotonic()
self._heatupWaitTimeLost = 0.0
self._pauseWaitStartTime = 0
self._pauseWaitTimeLost = 0.0
if tags is None:
tags = set()
if "source:plugin" in tags:
for tag in tags:
if tag.startswith("plugin:"):
self._logger.info(f"Starting job on behalf of plugin {tag[7:]}")
elif "source:api" in tags:
self._logger.info(f"Starting job on behalf of user {user}")
try:
with self._jobLock:
self._consecutive_not_sd_printing = 0
self._currentFile.start()
self._changeState(self.STATE_STARTING)
if not self.isSdFileSelected():
self.resetLineNumbers(
part_of_job=True, tags={"trigger:comm.start_print"}
)
self._callback.on_comm_print_job_started(user=user)
if self.isSdFileSelected():
if not external_sd:
# make sure to ignore the "file selected" later on, otherwise we'll reset our progress data
self._ignore_select = True
self.sendCommand(
"M23 {filename}".format(
filename=self._currentFile.getFilename()
),
part_of_job=True,
tags=tags
| {
"trigger:comm.start_print",
},
)
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.pos = pos
self.sendCommand(
f"M26 S{pos}",
part_of_job=True,
tags=tags
| {
"trigger:comm.start_print",
},
)
else:
self._currentFile.pos = 0
self.sendCommand(
"M24",
part_of_job=True,
tags=tags
| {
"trigger:comm.start_print",
},
)
else:
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.seek(pos)
self.sendCommand(
SendQueueMarker(lambda: self._changeState(self.STATE_PRINTING)),
part_of_job=True,
)
# now make sure we actually do something, up until now we only filled up the queue
self._continue_sending()
except Exception:
self._logger.exception("Error while trying to start printing")
self._trigger_error(get_exception_string(), "start_print")
def _get_free_remote_name(self, filename: str) -> str:
if not self._capability_supported(self.CAPABILITY_LFN_WRITE) and valid_file_type(
filename, "gcode"
):
# figure out remote filename
self.refreshSdFiles(blocking=True)
existingSdFiles = list(map(lambda x: x[0], self.getSdFiles()))
remote_name = get_dos_filename(
filename,
existing_filenames=existingSdFiles,
extension="gco",
whitelisted_extensions=["gco", "g"],
)
else:
# either LFN_WRITE is supported, or this is not a gcode file
remote_name = os.path.basename(filename)
return remote_name
def startFileTransfer(self, path, filename, remote=None, special=False, tags=None):
if not self.isOperational() or self.isBusy():
self._logger.info("Printer is not operational or busy")
return
if tags is None:
tags = set()
if remote is None:
remote = "/" + self._get_free_remote_name(filename)
with self._jobLock:
self.resetLineNumbers(tags={"trigger:comm.start_file_transfer"})
if special:
self._currentFile = SpecialStreamingGcodeFileInformation(
path, filename, remote
)
else:
self._currentFile = StreamingGcodeFileInformation(path, filename, remote)
self._currentFile.start()
self.sendCommand(
"M28 %s" % remote,
tags=tags
| {
"trigger:comm.start_file_transfer",
},
)
self._callback.on_comm_file_transfer_started(
filename,
remote,
self._currentFile.getFilesize(),
user=self._currentFile.getUser(),
)
return remote
def cancelFileTransfer(self, tags=None):
if not self.isOperational() or not self.isStreaming():
self._logger.info("Printer is not operational or not streaming")
return
self._finishFileTransfer(failed=True, tags=tags)
def _finishFileTransfer(self, failed=False, tags=None):
if tags is None:
tags = set()
with self._jobLock:
remote = self._currentFile.getRemoteFilename()
self._sendCommand(
"M29",
tags=tags
| {
"trigger:comm.finish_file_transfer",
},
)
if failed:
self.deleteSdFile(remote)
local = self._currentFile.getLocalFilename()
elapsed = self.getPrintTime()
def finalize():
self._currentFile = None
self._changeState(self.STATE_OPERATIONAL)
if failed:
self._callback.on_comm_file_transfer_failed(local, remote, elapsed)
else:
self._callback.on_comm_file_transfer_done(local, remote, elapsed)
self.refreshSdFiles(
tags={
"trigger:comm.finish_file_transfer",
}
)
self._sendCommand(SendQueueMarker(finalize))
def selectFile(self, filename, sd, user=None, tags=None):
if self.isBusy():
return
if tags is None:
tags = set()
if sd:
if not self.isOperational():
# printer is not connected, can't use SD
return
if filename.startswith("/") and self._sdRelativePath:
filename = filename[1:]
self._sdFileToSelect = filename
self._sdFileToSelectUser = user
self.sendCommand(
"M23 %s" % filename,
tags=tags
| {
"trigger:comm.select_file",
},
)
else:
self._currentFile = PrintingGcodeFileInformation(
filename,
offsets_callback=self.getOffsets,
current_tool_callback=self.getCurrentTool,
user=user,
)
self._callback.on_comm_file_selected(
filename, self._currentFile.getFilesize(), False, user=user
)
def unselectFile(self):
if self.isBusy():
return
self._currentFile = None
self._callback.on_comm_file_selected(None, None, False, user=None)
def _cancel_preparation_failed(self):
timeout = self._timeout_intervals.get("positionLogWait", 10.0)
self._log(
"Did not receive parseable position data from printer within {}s, continuing without it".format(
timeout
)
)
self._record_cancel_data = False
self._cancel_preparation_done()
def _cancel_preparation_done(self, check_timer=True, user=None):
if user is None:
with self._action_users_mutex:
try:
user = self._action_users.pop("cancel")
except KeyError:
pass
with self._cancel_mutex:
if self._cancel_position_timer is not None:
self._cancel_position_timer.cancel()
self._cancel_position_timer = None
elif check_timer:
return
self._currentFile.done = True
self._recordFilePosition()
self._callback.on_comm_print_job_cancelled(user=user)
def finalize():
self._changeState(self.STATE_OPERATIONAL)
self.sendCommand(SendQueueMarker(finalize), part_of_job=True)
self._continue_sending()
def cancelPrint(
self,
firmware_error=None,
disable_log_position=False,
user=None,
tags=None,
external_sd=False,
):
cancel_tags = {"trigger:comm.cancel", "trigger:cancel"}
abort_heatup_tags = cancel_tags | {
"trigger:abort_heatup",
}
record_position_tags = cancel_tags | {
"trigger:record_position",
}
if tags is None:
tags = set()
if not self.isOperational():
return
if not self.isBusy() or self._currentFile is None:
# we aren't even printing, nothing to cancel...
return
if self.isCancelling():
# we are already cancelling
return
if "source:plugin" in tags:
for tag in tags:
if tag.startswith("plugin:"):
self._logger.info(f"Cancelling job on behalf of plugin {tag[7:]}")
elif "source:api" in tags:
self._logger.info(f"Cancelling job on behalf of user {user}")
if self.isStreaming():
# we are streaming, we handle cancelling that differently...
self.cancelFileTransfer()
return
self._callback.on_comm_print_job_cancelling(
firmware_error=firmware_error, user=user
)
with self._jobLock:
pos_autoreporting = self._pos_autoreporting
self._changeState(self.STATE_CANCELLING)
def _reenable_pos_autoreport():
if pos_autoreporting:
self._set_autoreport_pos_interval(tags=record_position_tags)
def _on_M400_sent():
# we don't call on_print_job_cancelled on our callback here
# because we do this only after our M114 has been answered
# by the firmware
self.cancel_position.reset()
self._record_cancel_data = True
with self._cancel_mutex:
if self._cancel_position_timer is not None:
self._cancel_position_timer.cancel()
self._cancel_position_timer = ResettableTimer(
self._timeout_intervals.get("positionLogWait", 10.0),
self._cancel_preparation_failed,
)
self._cancel_position_timer.daemon = True
self._cancel_position_timer.start()
self.sendCommand(
"M114",
on_sent=_reenable_pos_autoreport,
part_of_job=True,
tags=tags | record_position_tags,
)
if self._abort_heatup_on_cancel:
# abort any ongoing heatups immediately to get back control over the printer
self.sendCommand(
"M108",
part_of_job=False,
tags=tags | abort_heatup_tags,
force=True,
)
if self.isSdFileSelected():
if not external_sd:
self.sendCommand(
self._sdCancelCommand,
part_of_job=True,
tags=tags | cancel_tags,
) # pause print
self.sendCommand(
"M27",
part_of_job=True,
tags=tags | cancel_tags,
) # get current byte position in file
self.sendCommand(
"M26 S0",
part_of_job=True,
tags=tags | cancel_tags,
) # reset position in file to byte 0
if self._log_position_on_cancel and not disable_log_position:
with self._action_users_mutex:
self._action_users["cancel"] = user
# disable position autoreporting if enabled
if pos_autoreporting:
self._set_autoreport_pos_interval(
interval=0,
part_of_job=True,
tags=tags | record_position_tags,
)
self.sendCommand(
"M400",
on_sent=_on_M400_sent,
part_of_job=True,
tags=tags | record_position_tags,
)
self._continue_sending()
else:
self._cancel_preparation_done(check_timer=False, user=user)
def _pause_preparation_failed(self):
timeout = self._timeout_intervals.get("positionLogWait", 10.0)
self._log(
"Did not receive parseable position data from printer within {}s, continuing without it".format(
timeout
)
)
self._record_pause_data = False
self._pause_preparation_done()
def _pause_preparation_done(self, check_timer=True, suppress_script=False, user=None):
if user is None:
with self._action_users_mutex:
try:
user = self._action_users.pop("pause")
except KeyError:
pass
with self._pause_mutex:
if self._pause_position_timer is not None:
self._pause_position_timer.cancel()
self._pause_position_timer = None
elif check_timer:
return
self._callback.on_comm_print_job_paused(
suppress_script=suppress_script, user=user
)
def finalize():
# only switch to PAUSED if we were still PAUSING, to avoid "swallowing" received resumes during
# pausing
if self._state == self.STATE_PAUSING:
self._changeState(self.STATE_PAUSED)
self.sendCommand(SendQueueMarker(finalize), part_of_job=True)
self._continue_sending()
def setPause(self, pause, local_handling=True, user=None, tags=None):
if self.isStreaming():
return
if not self._currentFile:
return
pause_tags = {"trigger:comm.set_pause", "trigger:pause"}
resume_tags = {"trigger:comm.set_pause", "trigger:resume"}
record_position_tags = pause_tags | {
"trigger:record_position",
}
if tags is None:
tags = set()
if "source:plugin" in tags:
for tag in tags:
if tag.startswith("plugin:"):
self._logger.info(
f"Pausing/resuming job on behalf of plugin {tag[7:]}"
)
elif user:
self._logger.info(f"Pausing/resuming job on behalf of user {user}")
valid_paused_states = (self.STATE_PAUSED, self.STATE_PAUSING)
valid_running_states = (
self.STATE_PRINTING,
self.STATE_STARTING,
self.STATE_RESUMING,
)
if self._state not in valid_paused_states + valid_running_states:
return
with self._jobLock:
pos_autoreporting = self._pos_autoreporting
if not pause and self._state in valid_paused_states:
if self._pauseWaitStartTime:
self._pauseWaitTimeLost = self._pauseWaitTimeLost + (
time.monotonic() - self._pauseWaitStartTime
)
self._pauseWaitStartTime = None
self._changeState(self.STATE_RESUMING)
self._callback.on_comm_print_job_resumed(
suppress_script=not local_handling, user=user
)
if self.isSdFileSelected():
if local_handling:
self.sendCommand(
"M24",
part_of_job=True,
tags=tags | resume_tags,
)
self.sendCommand(
"M27",
part_of_job=True,
tags=tags | resume_tags,
)
def finalize():
if self._state == self.STATE_RESUMING:
self._changeState(self.STATE_PRINTING)
self.sendCommand(SendQueueMarker(finalize), part_of_job=True)
# now make sure we actually do something, up until now we only filled up the queue
self._continue_sending()
elif pause and self._state in valid_running_states:
if not self._pauseWaitStartTime:
self._pauseWaitStartTime = time.monotonic()
self._changeState(self.STATE_PAUSING)
if self.isSdFileSelected() and local_handling:
self.sendCommand(
"M25",
part_of_job=True,
tags=tags | pause_tags,
) # pause print
def _reenable_pos_autoreport():
if pos_autoreporting:
self._set_autoreport_pos_interval(tags=record_position_tags)
def _on_M400_sent():
# we don't call on_print_job_paused on our callback here
# because we do this only after our M114 has been answered
# by the firmware
self.pause_position.reset()
self._record_pause_data = True
with self._pause_mutex:
if self._pause_position_timer is not None:
self._pause_position_timer.cancel()
self._pause_position_timer = None
self._pause_position_timer = ResettableTimer(
self._timeout_intervals.get("positionLogWait", 10.0),
self._pause_preparation_failed,
)
self._pause_position_timer.daemon = True
self._pause_position_timer.start()
self.sendCommand(
"M114",
on_sent=_reenable_pos_autoreport,
part_of_job=True,
tags=tags | record_position_tags,
)
if self._log_position_on_pause and local_handling:
with self._action_users_mutex:
self._action_users["pause"] = user
# disable position autoreporting if enabled
if pos_autoreporting:
self._set_autoreport_pos_interval(
interval=0,
part_of_job=True,
tags=tags | record_position_tags,
)
self.sendCommand(
"M400",
on_sent=_on_M400_sent,
part_of_job=True,
tags=tags | record_position_tags,
)
self._continue_sending()
else:
self._pause_preparation_done(
check_timer=False, suppress_script=not local_handling, user=user
)
def getSdFiles(self):
return list(
map(
lambda x: (
x.name,
x.size,
x.longname if x.longname else x.name,
x.timestamp,
),
self._sdFiles.values(),
)
)
def deleteSdFile(self, filename, tags=None):
if not self._sdEnabled:
return
if tags is None:
tags = set()
if not self.isOperational() or (
self.isBusy()
and isinstance(self._currentFile, PrintingSdFileInformation)
and self._currentFile.getFilename() == filename
):
# do not delete a file from sd we are currently printing from
return
self.sendCommand(
"M30 %s" % filename.lower(),
tags=tags
| {
"trigger:comm.delete_sd_file",
},
)
self.refreshSdFiles()
def refreshSdFiles(self, tags=None, blocking=False, timeout=10):
if not self._sdEnabled:
return
if not self.isOperational() or self.isBusy():
return
if self._defer_sd_refresh and not self._firmware_capabilities_received:
self._logger.debug(
"Deferring sd file refresh until capability report is processed"
)
return
if tags is None:
tags = set()
if self._capability_supported(self.CAPABILITY_EXTENDED_M20):
command = "M20 L T"
else:
command = "M20"
self._sdFilesAvailable.clear()
self.sendCommand(
command,
tags=tags
| {
"trigger:comm.refresh_sd_files",
},
)
if blocking:
self._sdFilesAvailable.wait(timeout=timeout)
def initSdCard(self, tags=None):
if not self._sdEnabled:
return
if not self.isOperational():
return
if tags is None:
tags = set()
self.sendCommand("M21", tags=tags | {"trigger:comm.init_sd_card"})
if self._sdAlwaysAvailable:
self._sdAvailable = True
self.refreshSdFiles()
self._callback.on_comm_sd_state_change(self._sdAvailable)
def releaseSdCard(self, tags=None):
if not self._sdEnabled:
return
if not self.isOperational() or (self.isBusy() and self.isSdFileSelected()):
# do not release the sd card if we are currently printing from it
return
if tags is None:
tags = set()
self.sendCommand(
"M22",
tags=tags
| {
"trigger:comm.release_sd_card",
},
)
self._sdAvailable = False
self._sdFiles = {}
self._callback.on_comm_sd_state_change(self._sdAvailable)
self._callback.on_comm_sd_files(self.getSdFiles())
def sayHello(self, tags=None):
if tags is None:
tags = set()
self.sendCommand(
self._hello_command,
force=True,
tags=tags
| {
"trigger:comm.say_hello",
},
)
self._clear_to_send.set()
self._hello_sent += 1
def resetLineNumbers(self, number=0, part_of_job=False, tags=None):
if not self.isOperational():
return
if tags is None:
tags = set()
self.sendCommand(
f"M110 N{number}",
part_of_job=part_of_job,
tags=tags
| {
"trigger:comm.reset_line_numbers",
},
)
##~~ record aborted file positions
def getFilePosition(self):
if self._currentFile is None:
return None
origin = self._currentFile.getFileLocation()
filename = self._currentFile.getFilename()
pos = self._currentFile.getFilepos()
return {"origin": origin, "filename": filename, "pos": pos}
def _recordFilePosition(self):
if self._currentFile is None:
return
data = self.getFilePosition()
self._callback.on_comm_record_fileposition(
data["origin"], data["filename"], data["pos"]
)
##~~ communication monitoring and handling
def _processTemperatures(self, line):
current_tool = self._currentTool if self._currentTool is not None else 0
current_tool_key = f"T{current_tool}"
maxToolNum, parsedTemps = parse_temperature_line(line, current_tool)
maxToolNum = max(
maxToolNum,
self._printerProfileManager.get_current_or_default()["extruder"]["count"] - 1,
)
for name, hook in self._temperature_hooks.items():
try:
parsedTemps = hook(self, parsedTemps)
self._known_broken_temperature_hooks.discard(name)
if parsedTemps is None or not parsedTemps:
return
except Exception:
level = logging.DEBUG
if name not in self._known_broken_temperature_hooks:
level = logging.ERROR
self._known_broken_temperature_hooks.add(name)
self._logger.log(
level,
f"Error while processing temperatures in {name}",
extra={"plugin": name},
exc_info=True,
)
if current_tool_key in parsedTemps or "T0" in parsedTemps:
shared_nozzle = self._printerProfileManager.get_current_or_default()[
"extruder"
]["sharedNozzle"]
shared_temp = (
parsedTemps[current_tool_key]
if current_tool_key in parsedTemps
else parsedTemps["T0"]
)
for n in range(maxToolNum + 1):
tool = "T%d" % n
if tool not in parsedTemps:
if shared_nozzle:
actual, target = shared_temp
else:
continue
else:
actual, target = parsedTemps[tool]
del parsedTemps[tool]
self.last_temperature.set_tool(n, actual=actual, target=target)
# bed temperature
if "B" in parsedTemps:
actual, target = parsedTemps["B"]
del parsedTemps["B"]
self.last_temperature.set_bed(actual=actual, target=target)
# chamber temperature
if "C" in parsedTemps and (
self._capability_supported(self.CAPABILITY_CHAMBER_TEMP)
or self._printerProfileManager.get_current_or_default()["heatedChamber"]
):
actual, target = parsedTemps["C"]
del parsedTemps["C"]
self.last_temperature.set_chamber(actual=actual, target=target)
# all other injected temperatures or temperature-like entries
for key, data in parsedTemps.items():
if key in self._known_invalid_custom_temps:
continue
try:
actual, target = data
self.last_temperature.set_custom(key, actual=actual, target=target)
except Exception as ex:
if key not in self._known_invalid_custom_temps:
self._known_invalid_custom_temps.add(key)
self._logger.warning(
f"Could not add custom temperature record {key}, skipping it from now on: {ex}",
)
##~~ Serial monitor processing received messages
def _monitor(self):
feedback_controls, feedback_matcher = convert_feedback_controls(
settings().get(["controls"])
)
feedback_errors = []
pause_triggers = convert_pause_triggers(
settings().get(["printerParameters", "pauseTriggers"])
)
disable_external_heatup_detection = not settings().getBoolean(
["serial", "externalHeatupDetection"]
)
self._consecutive_timeouts = 0
# Open the serial port
needs_detection = not (self._port and self._port != "AUTO" and self._baudrate)
try_hello = False
if not needs_detection:
self._changeState(self.STATE_OPEN_SERIAL)
if not self._open_serial(self._port, self._baudrate):
return
try_hello = not settings().getBoolean(["serial", "waitForStartOnConnect"])
self._changeState(self.STATE_CONNECTING)
self._timeout = self._ok_timeout = self._get_new_communication_timeout()
else:
self._changeState(self.STATE_DETECT_SERIAL)
self._perform_detection_step(init=True)
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
# we got cancelled during connection, bail
return
# Start monitoring the serial port
self._log("Connected to: %s, starting monitor" % self._serial)
startSeen = False
supportRepetierTargetTemp = settings().getBoolean(
["serial", "repetierTargetTemp"]
)
supportWait = settings().getBoolean(["serial", "supportWait"])
# enqueue the "hello command" first thing
if try_hello:
self.sayHello()
# we send a second one right away because sometimes there's garbage on the line on first connect
# that can kill oks
self.sayHello()
while self._monitoring_active:
try:
line = self._readline()
if line is None:
break
now = time.monotonic()
if line.strip() != "":
self._consecutive_timeouts = 0
self._timeout = self._get_new_communication_timeout()
if self._dwelling_until and now > self._dwelling_until:
self._dwelling_until = False
if self._resend_ok_timer and line and not line.startswith("ok"):
# we got anything but an ok after a resend request - this means the ok after the resend request
# was in fact missing and we now need to trigger the timer
self._resend_ok_timer.cancel()
self._resendSimulateOk()
##~~ busy protocol handling
if line.startswith("echo:busy:") or line.startswith("busy:"):
# reset the ok timeout, the regular comm timeout has already been reset
self._ok_timeout = self._get_new_communication_timeout()
# make sure the printer sends busy in a small enough interval to match our timeout
if not self._busy_protocol_detected and self._capability_support.get(
self.CAPABILITY_BUSY_PROTOCOL, False
):
to_log = (
"Printer seems to support the busy protocol, will adjust timeouts and set busy "
"interval accordingly"
)
self._log(to_log)
self._logger.info(to_log)
self._busy_protocol_detected = True
busy_interval = max(
int(self._timeout_intervals.get("communicationBusy", 2)) - 1,
1,
)
def busyIntervalSet():
self._logger.info(
"Telling the printer to set the busy interval to our "
'"communicationBusy" timeout - 1s = {}s'.format(
busy_interval
)
)
self._busy_protocol_support = True
self._serial.timeout = (
self._get_communication_timeout_interval()
)
self._set_busy_protocol_interval(
interval=busy_interval, callback=busyIntervalSet
)
if self._state not in (
self.STATE_CONNECTING,
self.STATE_DETECT_SERIAL,
):
continue
##~~ debugging output handling
elif line.startswith("//"):
debugging_output = line[2:].strip()
if debugging_output.startswith("action:"):
action_command = debugging_output[len("action:") :].strip()
if " " in action_command:
action_name, action_params = action_command.split(" ", 1)
action_name = action_name.strip()
else:
action_name = action_command
action_params = ""
if action_name == "start":
if self._currentFile is not None:
self._dual_log(
"(Re)Starting current job on request of the printer...",
level=logging.INFO,
)
self.startPrint(
tags={"trigger:serial.action_command.start"}
)
elif action_name == "cancel":
self._dual_log(
"Cancelling on request of the printer...",
level=logging.INFO,
)
self.cancelPrint(
tags={"trigger:serial.action_command.cancel"}
)
elif action_name == "pause":
self._dual_log(
"Pausing on request of the printer...", level=logging.INFO
)
self.setPause(
True, tags={"trigger:serial.action_command.pause"}
)
elif action_name == "paused":
self._dual_log(
"Printer signalled that it paused, switching state...",
level=logging.INFO,
)
self.setPause(
True,
local_handling=False,
tags={"trigger:serial.action_command.paused"},
)
elif action_name == "resume":
self._dual_log(
"Resuming on request of the printer...",
level=logging.INFO,
)
self.setPause(
False, tags={"trigger:serial.action_command.resume"}
)
elif action_name == "resumed":
self._dual_log(
"Printer signalled that it resumed, switching state...",
level=logging.INFO,
)
self.setPause(
False,
local_handling=False,
tags={"trigger:serial.action_command.resumed"},
)
elif action_name == "disconnect":
self._dual_log(
"Disconnecting on request of the printer...",
level=logging.INFO,
)
self._callback.on_comm_force_disconnect()
elif action_name == "shutdown":
if self._enable_shutdown_action_command:
self._dual_log(
"Shutting down system on request of printer...",
level=logging.WARNING,
)
try:
system_command_manager().perform_system_shutdown()
except Exception as ex:
self._log(f"Error executing system shutdown: {ex}")
else:
self._dual_log(
"Received a shutdown command from the printer, but processing of this command is disabled",
level=logging.WARNING,
)
elif self._sdEnabled and action_name == "sd_inserted":
self._dual_log(
"Printer reported SD card as inserted", level=logging.INFO
)
self._sdAvailable = True
self.refreshSdFiles()
self._callback.on_comm_sd_state_change(self._sdAvailable)
elif self._sdEnabled and action_name == "sd_ejected":
self._dual_log(
"Printer reported SD card as ejected", level=logging.INFO
)
self._sdAvailable = False
self._sdFiles = {}
self._callback.on_comm_sd_state_change(self._sdAvailable)
elif self._sdEnabled and action_name == "sd_updated":
self._dual_log(
"Printer reported a change on the SD card",
level=logging.INFO,
)
self.refreshSdFiles()
for name, hook in self._printer_action_hooks.items():
try:
hook(
self,
line,
action_command,
name=action_name,
params=action_params,
)
except Exception:
self._logger.exception(
"Error while calling hook from plugin "
"{} with action command {}".format(
name, action_command
),
extra={"plugin": name},
)
continue
if self._state not in (
self.STATE_CONNECTING,
self.STATE_DETECT_SERIAL,
):
continue
def convert_line(line):
if line is None:
return None, None
stripped_line = line.strip().strip("\0")
return stripped_line, stripped_line.lower()
##~~ Error handling
line = self._handle_errors(line)
line, lower_line = convert_line(line)
##~~ SD file list
# if we are currently receiving an sd file list, each line is just a filename, so just read it and abort processing
if self._sdEnabled and self._sdFileList and "End file list" not in line:
(filename, size, timestamp, longname) = parse_file_list_line(line)
if valid_file_type(filename, "machinecode"):
if filter_non_ascii(filename):
self._logger.warning(
"Got a file from printer's SD that has a non-ascii filename ({!r}), "
"that shouldn't happen according to the protocol".format(
filename
)
)
elif longname and filter_non_utf8(longname):
self._logger.warning(
"Got a file from printer's SD that has a non-utf8 longname ({!r}), "
"that shouldn't happen according to the protocol".format(
longname
)
)
else:
if not filename.startswith("/"):
# file from the root of the sd -- we'll prepend a /
filename = "/" + filename
if self._sdLowerCase:
filename = filename.lower()
if timestamp is not None and timestamp < MINIMAL_SD_TIMESTAMP:
# sanitize timestamp, when creating a file through serial the firmware usually doesn't know the date
# and sets something ridiculously low (e.g. 2000-01-01), so let's ignore timestamps like that here
timestamp = None
self._sdFiles[filename] = SDFileData(
name=filename,
size=size,
timestamp=timestamp,
longname=longname,
)
continue
elif self._sdFileLongName:
# Response to M33: just one line with the long name. Yay.
#
# As we have NO way to parse the request short name from that, and also no indicator
# on the line that this is in fact a reply to M33 and not just some arbitrary line injected
# by the firmware belonging to some other command and/or an out of band message/autoreport, we have
# to hope for the best here, set our requested filename as a flag and only use the potential mapping
# if it has a valid file extension.
#
# It would have been so much easier if M33's output was something sensible like
# "<short name>: <long name>" or such, but why make things easy...
_, ext = os.path.splitext(lower_line)
if ext and valid_file_type(lower_line, "machinecode"):
data = self._sdFiles.get(self._sdFileLongName)
if data is not None:
self._sdFiles[self._sdFileLongName] = SDFileData(
name=data.name,
size=data.size,
timestamp=data.timestamp,
longname=line,
)
self._sdFileLongName = False
handled = False
# process oks
if line.startswith("ok") or (
self.isPrinting() and supportWait and line == "wait"
):
# ok only considered handled if it's alone on the line, might be
# a response to an M105 or an M114
self._handle_ok()
self._sdFileLongName = False # reset looking for M33 response
needs_further_handling = (
"T:" in line
or "T0:" in line
or "B:" in line
or "C:" in line
or "X:" in line
or "NAME:" in line
)
handled = line == "wait" or line == "ok" or not needs_further_handling
# process resends
elif lower_line.startswith("resend") or lower_line.startswith("rs"):
self._handle_resend_request(line)
handled = True
# process timeouts
elif (
(
(line == "" and now >= self._timeout)
or (
self.isPrinting()
and not self.isSdPrinting()
and (not self.job_on_hold or self._resendActive)
and not self._long_running_command
and not self._heating
and now >= self._ok_timeout
)
)
and (
not self._blockWhileDwelling
or not self._dwelling_until
or now > self._dwelling_until
)
and self._state not in (self.STATE_DETECT_SERIAL,)
):
# We have two timeout variants:
#
# Variant 1: No line at all received within the communication timeout. This can always happen.
#
# Variant 2: No ok received while printing within the communication timeout. This can happen if
# temperatures are auto reported, because then we'll continue to receive data from the
# firmware in fairly regular intervals, even if an ok got lost somewhere and the firmware
# is running dry but not sending a wait.
#
# Both variants can only happen if we are not currently blocked by a dwelling command
self._handle_timeout()
self._ok_timeout = self._get_new_communication_timeout()
# timeout only considered handled if the printer is printing and it was a comm timeout, not an ok
# timeout
handled = self.isPrinting() and line == ""
# we don't have to process the rest if the line has already been handled fully
if handled and self._state not in (
self.STATE_CONNECTING,
self.STATE_DETECT_SERIAL,
):
continue
# wait for the end of the firmware capability report (M115) then notify plugins and refresh sd list if deferred
if (
self._firmware_capabilities
and not self._firmware_capabilities_received
and not lower_line.startswith("cap:")
):
self._firmware_capabilities_received = True
if self._defer_sd_refresh:
# sd list was deferred, refresh it now
self._logger.debug("Performing deferred sd file refresh")
self.refreshSdFiles()
# notify plugins
for name, hook in self._firmware_info_hooks[
"capability_report"
].items():
try:
hook(self, copy.copy(self._firmware_capabilities))
except Exception:
self._logger.exception(
"Error processing firmware reported hook {}:".format(
name
),
extra={"plugin": name},
)
# log firmware capabilities
capability_list = "\n ".join(
[
f"{capability}: {'supported' if enabled else 'not supported'}"
for capability, enabled in self._firmware_capabilities.items()
]
)
self._logger.info(
"Firmware sent the following capability report:\n "
+ capability_list
)
##~~ position report processing
if "X:" in line and "Y:" in line and "Z:" in line:
parsed = parse_position_line(line)
if parsed:
# we don't know T or F when printing from SD since
# there's no way to query it from the firmware and
# no way to track it ourselves when not streaming
# the file - this all sucks sooo much
self.last_position.valid = True
self.last_position.x = parsed.get("x")
self.last_position.y = parsed.get("y")
self.last_position.z = parsed.get("z")
if "e" in parsed:
self.last_position.e = parsed.get("e")
else:
# multiple extruder coordinates provided, find current one
self.last_position.e = (
parsed.get(f"e{self._currentTool}")
if not self.isSdFileSelected()
else None
)
for key in [
x for x in parsed if x.startswith("e") and len(x) > 1
]:
setattr(self.last_position, key, parsed.get(key))
self.last_position.t = (
self._currentTool if not self.isSdFileSelected() else None
)
self.last_position.f = (
self._currentF if not self.isSdFileSelected() else None
)
reason = None
if self._record_pause_data:
reason = "pause"
self._record_pause_data = False
self.pause_position.copy_from(self.last_position)
self.pause_temperature.copy_from(self.last_temperature)
self.pause_fanspeed = self.last_fanspeed
self._pause_preparation_done()
if self._record_cancel_data:
reason = "cancel"
self._record_cancel_data = False
self.cancel_position.copy_from(self.last_position)
self.cancel_temperature.copy_from(self.last_temperature)
self.cancel_fanspeed = self.last_fanspeed
self._cancel_preparation_done()
self._callback.on_comm_position_update(
self.last_position.as_dict(), reason=reason
)
##~~ temperature processing
elif (
" T:" in line
or line.startswith("T:")
or " T0:" in line
or line.startswith("T0:")
or ((" B:" in line or line.startswith("B:")) and "A:" not in line)
):
if (
not disable_external_heatup_detection
and not self._temperature_autoreporting
and not line.strip().startswith("ok")
and not self._heating
and self._firmware_info_received
):
self._logger.info("Externally triggered heatup detected")
self._heating = True
self._heatupWaitStartTime = time.monotonic()
self._processTemperatures(line)
self._callback.on_comm_temperature_update(
self.last_temperature.tools,
self.last_temperature.bed,
self.last_temperature.chamber,
self.last_temperature.custom,
)
elif supportRepetierTargetTemp and (
"TargetExtr" in line or "TargetBed" in line
):
matchExtr = regex_repetierTempExtr.match(line)
matchBed = regex_repetierTempBed.match(line)
if matchExtr is not None:
toolNum = int(matchExtr.group(1))
try:
target = float(matchExtr.group(2))
self.last_temperature.set_tool(toolNum, target=target)
self._callback.on_comm_temperature_update(
self.last_temperature.tools,
self.last_temperature.bed,
self.last_temperature.chamber,
self.last_temperature.custom,
)
except ValueError:
pass
elif matchBed is not None:
try:
target = float(matchBed.group(1))
self.last_temperature.set_bed(target=target)
self._callback.on_comm_temperature_update(
self.last_temperature.tools,
self.last_temperature.bed,
self.last_temperature.chamber,
self.last_temperature.custom,
)
except ValueError:
pass
##~~ Firmware capability report triggered by M115
elif lower_line.startswith("cap:"):
parsed = parse_capability_line(lower_line)
if parsed is not None:
capability, enabled = parsed
self._firmware_capabilities[capability] = enabled
if self._capability_support.get(capability, False):
if capability == self.CAPABILITY_AUTOREPORT_TEMP and enabled:
self._logger.info(
"Firmware states that it supports temperature autoreporting"
)
self._set_autoreport_temperature_interval()
elif (
capability == self.CAPABILITY_AUTOREPORT_SD_STATUS
and enabled
):
self._logger.info(
"Firmware states that it supports sd status autoreporting"
)
self._set_autoreport_sdstatus_interval()
elif capability == self.CAPABILITY_AUTOREPORT_POS and enabled:
self._logger.info(
"Firmware states that it supports position autoreporting"
)
self._set_autoreport_pos_interval()
elif (
capability == self.CAPABILITY_EMERGENCY_PARSER and enabled
):
self._logger.info(
"Firmware states that it supports emergency GCODEs to be sent without waiting for an acknowledgement first"
)
elif capability == self.CAPABILITY_EXTENDED_M20 and enabled:
self._logger.info(
"Firmware states that it supports long filenames"
)
elif capability == self.CAPABILITY_LFN_WRITE and enabled:
self._logger.info(
"Firmware states that it supports writing long filenames"
)
# notify plugins
for name, hook in self._firmware_info_hooks[
"capabilities"
].items():
try:
hook(
self,
capability,
enabled,
copy.copy(self._firmware_capabilities),
)
except Exception:
self._logger.exception(
"Error processing firmware capability hook {}:".format(
name
),
extra={"plugin": name},
)
##~~ firmware name & version
elif "NAME:" in line or line.startswith("NAME."):
# looks like a response to M115
data = parse_firmware_line(line)
firmware_name = data.get("FIRMWARE_NAME")
if firmware_name is None:
# Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even
# report its firmware name properly in response to M115. Wonderful - why stick to established
# protocol when you can do your own thing, right?
#
# Examples:
#
# NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
# NAME. Malyan VER: 3.8 MODEL: M100 HW: HB02
# NAME. Malyan VER: 3.7 MODEL: M300 HW: HG01
#
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
name = data.get("NAME")
ver = data.get("VER")
if name and "malyan" in name.lower() and ver:
firmware_name = name.strip() + " " + ver.strip()
eventManager().fire(
Events.FIRMWARE_DATA, {"name": firmware_name, "data": data}
)
if not self._firmware_info_received and firmware_name:
firmware_name = firmware_name.strip()
self._logger.info(
f'Printer reports firmware name "{firmware_name}"'
)
self._logger.info(f"Firmware info line: {line}")
if self._firmware_detection:
if (
"repetier" in firmware_name.lower()
or "anet_a8" in firmware_name.lower()
):
self._logger.info(
"Detected Repetier firmware, enabling relevant features for issue free communication"
)
self._alwaysSendChecksum = True
self._blockWhileDwelling = True
supportRepetierTargetTemp = True
disable_external_heatup_detection = True
elif "reprapfirmware" in firmware_name.lower():
self._logger.info(
"Detected RepRapFirmware, enabling relevant features for issue free communication"
)
self._sdRelativePath = True
elif "malyan" in firmware_name.lower():
self._logger.info(
"Detected Malyan firmware, enabling relevant features for issue free communication"
)
self._alwaysSendChecksum = True
self._blockWhileDwelling = True
sd_always_available = self._sdAlwaysAvailable
self._sdAlwaysAvailable = True
if not sd_always_available and not self._sdAvailable:
self.initSdCard()
elif "teacup" in firmware_name.lower():
self._logger.info(
"Detected Teacup firmware, enabling relevant features for issue free communication"
)
disable_external_heatup_detection = True # see #2854
elif "klipper" in firmware_name.lower():
self._logger.info(
"Detected Klipper firmware, enabling relevant features for issue free communication"
)
self._unknownCommandsNeedAck = True
elif "ultimaker2" in firmware_name.lower():
self._logger.info(
"Detected Ultimaker2 firmware, enabling relevant features for issue free communication"
)
self._disable_sd_printing_detection = True
elif "prusa-firmware" in firmware_name.lower():
self._logger.info(
"Detected Prusa firmware, enabling relevant features for issue free communication"
)
self._sdLowerCase = True
self._sendChecksumWithUnknownCommands = True
self._unknownCommandsNeedAck = True
self._firmware_info_received = True
self._firmware_info = data
self._firmware_name = firmware_name
# notify plugins
for name, hook in self._firmware_info_hooks["info"].items():
try:
hook(self, firmware_name, copy.copy(data))
except Exception:
self._logger.exception(
"Error processing firmware info hook {}:".format(
name
),
extra={"plugin": name},
)
self._callback.on_comm_firmware_info(
firmware_name, copy.copy(data)
)
##~~ invalid extruder
elif "invalid extruder" in lower_line:
tool = None
match = regexes_parameters["intT"].search(line)
if match:
try:
tool = int(match.group("value"))
except ValueError:
pass # should never happen
if tool is None or tool == self._currentTool:
if self._toolBeforeChange is not None:
fallback_tool = self._toolBeforeChange
else:
fallback_tool = 0
invalid_tool = self._currentTool
if self._sanity_check_tools:
# log to terminal and remember as invalid
message = "T{} reported as invalid, reverting to T{}".format(
invalid_tool, fallback_tool
)
self._log("Warn: " + message)
self._logger.warning(message)
eventManager().fire(
Events.INVALID_TOOL_REPORTED,
{"tool": invalid_tool, "fallback": fallback_tool},
)
self._known_invalid_tools.add(invalid_tool)
# we actually do send a T command here instead of just settings self._currentTool just in case
# we had any scripts or plugins modify stuff due to the prior tool change
self.sendCommand(
f"T{fallback_tool}",
tags={
"trigger:revert_invalid_tool",
},
)
else:
# just log to terminal, user disabled sanity check
self._log(
"T{} reported as invalid by the firmware, but you've "
"disabled tool sanity checking, ignoring".format(
invalid_tool
)
)
##~~ SD Card handling
elif self._sdEnabled:
if (
"SD init fail" in line
or "volume.init failed" in line
or "No media" in line
or "openRoot failed" in line
or "SD Card unmounted" in line
or "SD card released" in line
):
self._sdAvailable = False
self._sdFiles = {}
self._callback.on_comm_sd_state_change(self._sdAvailable)
elif (
"SD card ok" in line or "Card successfully initialized" in line
) and not self._sdAvailable:
self._sdAvailable = True
self.refreshSdFiles()
self._callback.on_comm_sd_state_change(self._sdAvailable)
elif "Begin file list" in line:
self._sdFiles = {}
self._sdFileList = True
elif "End file list" in line:
self._sdFileList = False
self._sdFilesAvailable.set()
self._callback.on_comm_sd_files(self.getSdFiles())
elif "SD printing byte" in line:
# answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d"
match = regex_sdPrintingByte.search(line)
if match:
try:
current = int(match.group("current"))
total = int(match.group("total"))
except Exception:
self._logger.exception(
"Error while parsing SD status report"
)
else:
if (
current == total == 0
and self.isSdPrinting()
and not self.isStarting()
and not self.isStarting()
and not self.isFinishing()
):
# apparently not SD printing - some Marlin versions report it like that for some reason
self._consecutive_not_sd_printing += 1
if (
self._consecutive_not_sd_printing
> self._consecutive_not_sd_printing_maximum
):
self.cancelPrint(external_sd=True)
else:
self._consecutive_not_sd_printing = 0
if self.isSdFileSelected():
# If we are not yet sd printing, the current does not equal the total, is larger
# than zero and has increased since the last time we saw a position report, then
# yes, this looks like we just started printing due to an external trigger.
if (
not self.isSdPrinting()
and current != total
and current > 0
and self._currentFile
and current > self._currentFile.pos
):
self.startPrint(external_sd=True)
self._currentFile.pos = current
if self._currentFile.size == 0:
self._currentFile.size = total
if not self._currentFile.done:
self._callback.on_comm_progress()
elif (
"Not SD printing" in line
and self.isSdPrinting()
and not self.isStarting()
and not self.isFinishing()
):
self._consecutive_not_sd_printing += 1
if (
self._consecutive_not_sd_printing
> self._consecutive_not_sd_printing_maximum
):
# something went wrong, printer is reporting that we actually are not printing right now...
self.cancelPrint(external_sd=True)
elif "File opened" in line and not self._ignore_select:
# answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d"
match = regex_sdFileOpened.search(line)
if match:
name = match.group("name")
size = int(match.group("size"))
else:
name = "Unknown"
size = 0
user = None
if self._sdFileToSelect:
name = self._sdFileToSelect
user = self._sdFileToSelectUser
self._sdFileToSelect = None
self._sdFileToSelectUser = None
self._currentFile = PrintingSdFileInformation(
name, size, user=user
)
elif "File selected" in line:
if self._ignore_select:
self._ignore_select = False
elif self._currentFile is not None and self.isSdFileSelected():
# final answer to M23, at least on Marlin, Repetier and Sprinter: "File selected"
self._callback.on_comm_file_selected(
self._currentFile.getFilename(),
self._currentFile.getFilesize(),
True,
user=self._currentFile.getUser(),
data=self._sdFiles.get(self._currentFile.getFilename()),
)
elif "Writing to file" in line and self.isStreaming():
self._changeState(self.STATE_PRINTING)
elif "Done printing file" in line and self.isSdPrinting():
# printer is reporting file finished printing
self._changeState(self.STATE_FINISHING)
self._currentFile.done = True
self._currentFile.pos = 0
self.sendCommand("M400", part_of_job=True)
self._callback.on_comm_print_job_done()
def finalize():
self._changeState(self.STATE_OPERATIONAL)
self.sendCommand(SendQueueMarker(finalize), part_of_job=True)
self._continue_sending()
elif "Done saving file" in line:
if self._trigger_ok_for_m29:
# workaround for most versions of Marlin out in the wild
# not sending an ok after saving a file
self._handle_ok()
elif "File deleted" in line and line.strip().endswith("ok"):
# buggy Marlin version that doesn't send a proper line break after the "File deleted" statement, fixed in
# current versions
self._handle_ok()
##~~ Message handling
self._callback.on_comm_message(line)
##~~ Parsing for feedback commands
if (
feedback_controls
and feedback_matcher
and "_all" not in feedback_errors
):
try:
self._process_registered_message(
line, feedback_matcher, feedback_controls, feedback_errors
)
except Exception:
# something went wrong while feedback matching
self._logger.exception(
"Error while trying to apply feedback control matching, disabling it"
)
feedback_errors.append("_all")
##~~ Parsing for pause triggers
if pause_triggers and not self.isStreaming():
if (
"enable" in pause_triggers
and pause_triggers["enable"].search(line) is not None
):
self.setPause(True)
elif (
"disable" in pause_triggers
and pause_triggers["disable"].search(line) is not None
):
self.setPause(False)
elif (
"toggle" in pause_triggers
and pause_triggers["toggle"].search(line) is not None
):
self.setPause(not self.isPaused())
### Serial detection
if self._state == self.STATE_DETECT_SERIAL:
if line == "" or time.monotonic() > self._ok_timeout:
self._perform_detection_step()
elif "start" in line or line.startswith("ok"):
self._onConnected()
if "start" in line:
self._clear_to_send.set()
### Connection attempt
elif self._state == self.STATE_CONNECTING:
if "start" in line and not startSeen:
startSeen = True
self.sayHello()
elif line.startswith("ok") or (supportWait and line == "wait"):
if line == "wait":
# if it was a wait we probably missed an ok, so let's simulate that now
self._handle_ok()
self._onConnected()
elif time.monotonic() > self._timeout:
if try_hello and self._hello_sent < 3:
self._log(
"No answer from the printer within the connection timeout, trying another hello"
)
self.sayHello()
else:
self._log(
"There was a timeout while trying to connect to the printer"
)
self.close(wait=False)
### Operational (idle or busy)
elif self._state in (
self.STATE_OPERATIONAL,
self.STATE_STARTING,
self.STATE_PRINTING,
self.STATE_PAUSED,
self.STATE_TRANSFERING_FILE,
):
if line == "start": # exact match, to be on the safe side
with self.job_put_on_hold():
idle = self._state in (self.STATE_OPERATIONAL,)
if idle:
message = (
"Printer sent 'start' while already operational. External reset? "
"Resetting line numbers to be on the safe side"
)
self._log(message)
self._logger.warning(message)
self._on_external_reset()
else:
verb = (
"streaming to SD"
if self.isStreaming()
else "printing"
)
message = (
"Printer sent 'start' while {}. External reset? "
"Aborting job since printer lost state.".format(verb)
)
self._log(message)
self._logger.warning(message)
self._on_external_reset()
self.cancelPrint(disable_log_position=True)
eventManager().fire(
Events.PRINTER_RESET, payload={"idle": idle}
)
except Exception:
self._logger.exception(
"Something crashed inside the serial connection loop, please report this in OctoPrint's bug tracker:"
)
errorMsg = "See octoprint.log for details"
self._log(errorMsg)
self._errorValue = errorMsg
eventManager().fire(
Events.ERROR, {"error": self.getErrorString(), "reason": "crash"}
)
self.close(is_error=True)
self._log("Connection closed, closing down monitor")
def _handle_ok(self):
if self._resend_ok_timer:
self._resend_ok_timer.cancel()
self._resend_ok_timer = None
self._ok_timeout = self._get_new_communication_timeout()
self._clear_to_send.set()
# reset long running commands, persisted current tools and heatup counters on ok
self._long_running_command = False
if self._toolBeforeHeatup is not None:
self._currentTool = self._toolBeforeHeatup
self._toolBeforeHeatup = None
self._finish_heatup()
if self._state not in self.OPERATIONAL_STATES:
return
if self._resendDelta is not None and self._resendNextCommand():
# we processed a resend request and are done here
return
# continue with our queues and the job
self._resendActive = False
self._continue_sending()
def _handle_timeout(self):
if self._state not in self.OPERATIONAL_STATES:
return
general_message = "Configure long running commands or increase communication timeout if that happens regularly on specific commands or long moves."
# figure out which consecutive timeout maximum we have to use
if self._long_running_command:
consecutive_max = self._consecutive_timeout_maximums.get("long", 0)
elif self._state in self.PRINTING_STATES:
consecutive_max = self._consecutive_timeout_maximums.get("printing", 0)
else:
consecutive_max = self._consecutive_timeout_maximums.get("idle", 0)
# now increment the timeout counter
self._consecutive_timeouts += 1
self._logger.debug(f"Now at {self._consecutive_timeouts} consecutive timeouts")
if 0 < consecutive_max < self._consecutive_timeouts:
# too many consecutive timeouts, we give up
message = "No response from printer after {} consecutive communication timeouts, considering it dead.".format(
consecutive_max + 1
)
self._logger.info(message)
self._log(message + " " + general_message)
self._errorValue = (
"Too many consecutive timeouts, printer still connected and alive?"
)
eventManager().fire(
Events.ERROR, {"error": self._errorValue, "reason": "timeout"}
)
self.close(is_error=True)
elif self._resendActive:
# resend active, resend same command instead of triggering a new one
message = "Communication timeout during an active resend, resending same line again to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
if self._resendSameCommand():
self._clear_to_send.set()
elif self._heating:
# blocking heatup active, consider that finished
message = "Timeout while in an active heatup, considering heatup to be over."
self._logger.info(message)
self._finish_heatup()
elif self._long_running_command:
# long running command active, ignore timeout
self._logger.debug(
"Ran into a communication timeout, but a command known to be a long runner is currently active"
)
elif self._state in self.PRINTING_STATES + (self.STATE_PAUSED,):
# printing, try to tickle the printer
message = "Communication timeout while printing, trying to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
if self._sendCommand(
"M105", cmd_type="temperature", tags={"trigger:comm.handle_timeout"}
):
self._clear_to_send.set()
elif self._clear_to_send.blocked():
# timeout while idle and no oks left, let's try to tickle the printer
message = "Communication timeout while idle, trying to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
self._clear_to_send.set()
def _perform_detection_step(self, init=False):
def log(message):
self._log(message)
self._logger.info(f"Serial detection: {message}")
if init:
port = self._port
baudrate = self._baudrate
if port and port != "AUTO":
port_candidates = [port]
else:
port_candidates = serialList()
if baudrate:
baudrate_candidates = [baudrate]
elif len(port_candidates) == 1:
baudrate_candidates = baudrateList()
else:
# if we have no baudrate and more than one port we limit tested baudrates to
# the two most common plus any additionally configured ones
baudrate_candidates = baudrateList([115200, 250000])
self._detection_candidates = [
(p, b) for p in port_candidates for b in baudrate_candidates
]
self._detection_retry = self.DETECTION_RETRIES
log(
"Performing autodetection with {} "
"port/baudrate candidates: {}".format(
len(self._detection_candidates),
", ".join(
map(
lambda x: f"{x[0]}@{x[1]}",
self._detection_candidates,
)
),
)
)
def attempt_handshake():
self._detection_retry += 1
timeout = self._get_communication_timeout_interval()
log(
"Handshake attempt #{} with timeout {}s".format(
self._detection_retry, timeout
)
)
try:
if self._serial.timeout != timeout:
self._serial.timeout = timeout
self._timeout = self._ok_timeout = time.monotonic() + timeout
except Exception:
self._log(
"Unexpected error while setting timeout {}: {}".format(
timeout, get_exception_string()
)
)
self._logger.exception(
f"Unexpected error while setting timeout {timeout}"
)
else:
self._do_send_without_checksum(b"", log=False) # new line to reset things
self.sayHello(
tags={
"trigger:detection",
}
)
while (
len(self._detection_candidates) > 0
or self._detection_retry < self.DETECTION_RETRIES
):
if self._state not in (self.STATE_DETECT_SERIAL,):
return
if self._detection_retry < self.DETECTION_RETRIES:
if self._serial is None:
self._detection_retry = self.DETECTION_RETRIES
continue
attempt_handshake()
return
else:
(p, b) = self._detection_candidates.pop(0)
try:
log(f"Trying port {p}, baudrate {b}")
if self._serial is None or self._serial.port != p:
if not self._open_serial(p, b, trigger_errors=False):
log(
"Could not open port {}, baudrate {}, skipping".format(
p, b
)
)
continue
else:
self._serial.baudrate = b
self._detection_retry = 0
attempt_handshake()
return
except Exception:
self._log(
"Unexpected error while setting baudrate {}: {}".format(
b, get_exception_string()
)
)
self._logger.exception(f"Unexpected error while setting baudrate {b}")
error_text = "No more candidates to test, and no working port/baudrate combination detected."
self._trigger_error(error_text, "autodetect")
def _finish_heatup(self):
if self._heating:
if self._heatupWaitStartTime:
self._heatupWaitTimeLost = self._heatupWaitTimeLost + (
time.monotonic() - self._heatupWaitStartTime
)
self._heatupWaitStartTime = None
self._heating = False
def _continue_sending(self):
# Ensure we have at least one line in the send queue, but don't spam it
while self._active and not self._send_queue.qsize():
job_active = self._state in (
self.STATE_STARTING,
self.STATE_PRINTING,
) and not (
self._currentFile is None or self._currentFile.done or self.isSdPrinting()
)
if self._send_from_command_queue():
# we found something in the command queue to send
return True
elif self.job_on_hold:
# job is on hold, that means we must not send from either job queue or file
return False
elif self._send_from_job_queue():
# we found something in the job queue to send
return True
elif job_active and self._send_from_job():
# we sent the next line from the file
return True
elif not job_active:
# nothing sent but also no job active, so we can just return false
return False
self._logger.debug(
"No command enqueued on ok while printing, doing another iteration"
)
def _process_registered_message(
self, line, feedback_matcher, feedback_controls, feedback_errors
):
feedback_match = feedback_matcher.search(line)
if feedback_match is None:
return
for match_key in feedback_match.groupdict():
try:
feedback_key = match_key[len("group") :]
if (
feedback_key not in feedback_controls
or feedback_key in feedback_errors
or feedback_match.group(match_key) is None
):
continue
matched_part = feedback_match.group(match_key)
if feedback_controls[feedback_key]["matcher"] is None:
continue
match = feedback_controls[feedback_key]["matcher"].search(matched_part)
if match is None:
continue
outputs = {}
for template_key, template in feedback_controls[feedback_key][
"templates"
].items():
try:
output = template.format(*match.groups())
except KeyError:
output = template.format(**match.groupdict())
except Exception:
self._logger.debug(
"Could not process template {}: {}".format(
template_key, template
),
exc_info=1,
)
output = None
if output is not None:
outputs[template_key] = output
eventManager().fire(
Events.REGISTERED_MESSAGE_RECEIVED,
{"key": feedback_key, "matched": matched_part, "outputs": outputs},
)
except Exception:
self._logger.exception(
"Error while trying to match feedback control output, disabling key {key}".format(
key=match_key
)
)
feedback_errors.append(match_key)
def _poll_temperature(self):
"""
Polls the temperature.
If the printer is not operational, capable of auto-reporting temperatures, closing the connection, not printing
from sd, busy with a long running command or heating, no poll will be done.
"""
if (
self.isOperational()
and not self._temperature_autoreporting
and not self._connection_closing
and not self.isStreaming()
and not self._long_running_command
and not self._heating
and not self._dwelling_until
and not self._manualStreaming
):
self.sendCommand(
"M105",
cmd_type="temperature_poll",
tags={"trigger:comm.poll_temperature"},
)
def _poll_sd_status(self):
"""
Polls the sd printing status.
If the printer is not operational, closing the connection, not printing from sd, busy with a long running
command or heating, no poll will be done.
"""
if (
self.isOperational()
and not self._sdstatus_autoreporting
and not self._connection_closing
and (
self.isSdFileSelected()
and not self._disable_sd_printing_detection
or self.isSdPrinting()
)
and not self._long_running_command
and not self._dwelling_until
and not self._heating
):
self.sendCommand(
"M27", cmd_type="sd_status_poll", tags={"trigger:comm.poll_sd_status"}
)
def _set_autoreport_temperature_interval(self, interval=None):
if interval is None:
try:
interval = int(self._timeout_intervals.get("temperatureAutoreport", 2))
except Exception:
interval = 2
self.sendCommand(
f"M155 S{interval}",
tags={"trigger:comm.set_autoreport_temperature_interval"},
)
def _set_autoreport_sdstatus_interval(self, interval=None):
if interval is None:
try:
interval = int(self._timeout_intervals.get("sdStatusAutoreport", 1))
except Exception:
interval = 1
self.sendCommand(
f"M27 S{interval}",
tags={"trigger:comm.set_autoreport_sdstatus_interval"},
)
def _set_autoreport_pos_interval(self, interval=None, part_of_job=False, tags=None):
if tags is None:
tags = set()
if interval is None:
try:
interval = int(self._timeout_intervals.get("posAutoreport", 5))
except Exception:
interval = 5
self.sendCommand(
f"M154 S{interval}",
part_of_job=part_of_job,
tags=tags | {"trigger:comm.set_autoreport_pos_interval"},
)
def _set_busy_protocol_interval(self, interval=None, callback=None):
if interval is None:
try:
interval = max(
int(self._timeout_intervals.get("communicationBusy", 3)) - 1, 1
)
except Exception:
interval = 2
self.sendCommand(
f"M113 S{interval}",
tags={"trigger:comm.set_busy_protocol_interval"},
on_sent=callback,
)
def _onConnected(self):
self._serial.timeout = self._get_communication_timeout_interval()
self._temperature_timer = RepeatedTimer(
self._get_temperature_timer_interval, self._poll_temperature, run_first=True
)
self._temperature_timer.start()
self._sd_status_timer = RepeatedTimer(
self._get_sd_status_timer_interval, self._poll_sd_status, run_first=True
)
self._sd_status_timer.start()
self._changeState(self.STATE_OPERATIONAL)
self.resetLineNumbers(
tags={
"trigger:comm.on_connected",
}
)
self.sendCommand(
"M115",
tags={
"trigger:comm.on_connected",
},
)
if self._sdAvailable:
self.refreshSdFiles(tags={"trigger:comm.on_connected"})
else:
self.initSdCard(tags={"trigger:comm.on_connected"})
payload = {"port": self._port, "baudrate": self._baudrate}
eventManager().fire(Events.CONNECTED, payload)
self.sendGcodeScript("afterPrinterConnected", replacements={"event": payload})
def _on_external_reset(self):
# hold queue processing, clear queues and acknowledgements, reset line number and last lines
with self._send_queue.blocked():
self._clear_to_send.reset()
with self._command_queue.blocked():
self._command_queue.clear()
self._send_queue.clear()
with self._line_mutex:
self._current_line = 0
self._lastLines.clear()
self.sayHello(tags={"trigger:comm.on_external_reset"})
self.resetLineNumbers(tags={"trigger:comm.on_external_reset"})
if self._temperature_autoreporting:
self._set_autoreport_temperature_interval()
if self._sdstatus_autoreporting:
self._set_autoreport_sdstatus_interval()
if self._pos_autoreporting:
self._set_autoreport_pos_interval()
if self._busy_protocol_support:
self._set_busy_protocol_interval()
self._consecutive_not_sd_printing = 0
def _get_temperature_timer_interval(self):
busy_default = 4.0
target_default = 2.0
def get(key, default):
interval = self._timeout_intervals.get(key, default)
if interval <= 0:
interval = 1.0
return interval
if self.isBusy():
return get("temperature", busy_default)
tools = self.last_temperature.tools
for temp in [tools[k][1] for k in tools.keys()]:
if temp and temp > self._temperatureTargetSetThreshold:
return get("temperatureTargetSet", target_default)
bed = self.last_temperature.bed
if (
bed
and len(bed) > 1
and bed[1] is not None
and bed[1] > self._temperatureTargetSetThreshold
):
return get("temperatureTargetSet", target_default)
return get("temperature", busy_default)
def _get_sd_status_timer_interval(self):
interval = self._timeout_intervals.get("sdStatus", 1.0)
if interval <= 0:
interval = 1.0
return interval
def _get_communication_timeout_interval(self):
# special rules during serial detection
if self._state in (self.STATE_DETECT_SERIAL,):
if self._detection_retry == 0:
# first try
return self._timeout_intervals.get("detectionFirst", 10.0)
else:
# consecutive tries
return self._timeout_intervals.get("detectionConsecutive", 2.0)
# communication timeout
if self._busy_protocol_support:
comm_timeout = self._timeout_intervals.get("communicationBusy", 2.0)
else:
comm_timeout = self._timeout_intervals.get("communication", 30.0)
# temperature interval
if self._temperature_autoreporting:
temperature_timeout = self._timeout_intervals.get(
"temperatureAutoreport", 2.0
)
else:
temperature_timeout = self._get_temperature_timer_interval()
# use the max of both, add a second to temperature to avoid race conditions
return max(comm_timeout, temperature_timeout + 1)
def _get_new_communication_timeout(self):
return time.monotonic() + self._get_communication_timeout_interval()
def _send_from_command_queue(self):
# We loop here to make sure that if we do NOT send the first command
# from the queue, we'll send the second (if there is one). We do not
# want to get stuck here by throwing away commands.
while True:
if self.isStreaming():
# command queue irrelevant
return False
try:
entry = self._command_queue.get(block=False)
except queue.Empty:
# nothing in command queue
return False
try:
if isinstance(entry, tuple):
if not len(entry) == 4:
# something with that entry is broken, ignore it and fetch
# the next one
continue
cmd, cmd_type, callback, tags = entry
else:
cmd = entry
cmd_type = None
callback = None
tags = None
if self._sendCommand(cmd, cmd_type=cmd_type, on_sent=callback, tags=tags):
# we actually did add this cmd to the send queue, so let's
# return, we are done here
return True
finally:
self._command_queue.task_done()
def _open_serial(self, port, baudrate, trigger_errors=True):
def default(_, p, b, timeout):
# connect to regular serial port
self._dual_log(
f"Connecting to port {port}, baudrate {baudrate}",
level=logging.INFO,
)
serial_port_args = {
"baudrate": baudrate,
"timeout": timeout,
"write_timeout": 0,
}
if settings().getBoolean(["serial", "exclusive"]):
serial_port_args["exclusive"] = True
try:
serial_obj = serial.Serial(**serial_port_args)
serial_obj.port = str(p)
use_parity_workaround = settings().get(["serial", "useParityWorkaround"])
needs_parity_workaround = get_os() == "linux" and os.path.exists(
"/etc/debian_version"
) # See #673
if use_parity_workaround == "always" or (
needs_parity_workaround and use_parity_workaround == "detect"
):
serial_obj.parity = serial.PARITY_ODD
serial_obj.open()
serial_obj.close()
serial_obj.parity = serial.PARITY_NONE
serial_obj.open()
except serial.SerialException:
self._logger.info(
f"Failed to connect: Port {p} is busy or does not exist"
)
return None
# Set close_exec flag on serial handle, see #3212
if hasattr(serial_obj, "fd"):
# posix
set_close_exec(serial_obj.fd)
elif hasattr(serial_obj, "_port_handle"):
# win32
# noinspection PyProtectedMember
set_close_exec(serial_obj._port_handle)
if settings().getBoolean(["serial", "lowLatency"]):
if hasattr(serial_obj, "set_low_latency_mode"):
try:
serial_obj.set_low_latency_mode(True)
except Exception:
self._logger.exception(
"Could not set low latency mode on serial port, continuing without"
)
else:
self._logger.info(
"Platform doesn't support low latency mode on serial port"
)
return BufferedReadlineWrapper(serial_obj)
serial_factories = list(self._serial_factory_hooks.items()) + [
("default", default)
]
for name, factory in serial_factories:
try:
serial_obj = factory(
self,
port,
baudrate,
settings().getFloat(["serial", "timeout", "connection"]),
)
except Exception:
exception_string = get_exception_string()
if trigger_errors:
self._trigger_error(
"Connection error, see Terminal tab", "connection"
)
error_message = (
"Unexpected error while connecting to "
"serial port {}, baudrate {} from hook {}: {}".format(
port, baudrate, name, exception_string
)
)
self._log(error_message)
self._logger.exception(error_message)
return False
if serial_obj is not None:
# first hook to succeed wins, but any can pass on to the next
self._serial = serial_obj
self._clear_to_send.reset()
return True
return False
_recoverable_communication_errors = (
"no line number with checksum",
"missing linenumber",
)
_resend_request_communication_errors = (
"line number", # since this error class gets checked after recoverable
# communication errors, we can use this broad term here
"linenumber", # since this error class gets checked after recoverable
# communication errors, we can use this broad term here
"checksum", # since this error class gets checked after recoverable
# communication errors, we can use this broad term here
"format error",
"expected line",
)
_sd_card_errors = (
"volume.init",
"openroot",
"workdir",
"error writing to file",
"cannot open",
"open failed",
"cannot enter",
)
_fatal_errors = ("kill() called", "fatal:")
def _handle_errors(self, line):
if line is None:
return
lower_line = line.lower()
if lower_line.startswith("fatal:"):
# hello Repetier firmware -_-
line = "Error:" + line
lower_line = line.lower()
if lower_line.startswith("error:") or line.startswith("!!"):
if regex_minMaxError.match(line):
# special delivery for firmware that goes "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
line = line.rstrip() + self._readline()
lower_line = line.lower()
elif regex_marlinKillError.search(line):
# special delivery for marlin kill errors that are split across multiple error lines
next_line = self._readline().strip()
if next_line.lower().startswith("error:"):
next_line = next_line[6:].strip()
line = line.rstrip() + " - " + next_line
lower_line = line.lower()
stripped_error = (
line[6:] if lower_line.startswith("error:") else line[2:]
).strip()
if any(x in lower_line for x in self._recoverable_communication_errors):
# manually trigger an ack for comm errors the printer doesn't send a resend request for but
# from which we can recover from by just pushing on (because that then WILL trigger a fitting
# resend request)
self._handle_ok()
elif any(x in lower_line for x in self._resend_request_communication_errors):
# skip comm errors that the printer sends a resend request for anyhow
self._lastCommError = stripped_error
elif any(x in lower_line for x in self._sd_card_errors):
# skip errors with the SD card
pass
elif "unknown command" in lower_line:
# ignore unknown command errors, it could be a typo or some missing feature
pass
elif not self.isError():
# handle everything else
for name, hook in self._error_message_hooks.items():
try:
ret = hook(self, stripped_error)
except Exception:
self._logger.exception(
f"Error while processing hook {name}:",
extra={"plugin": name},
)
else:
if ret:
return line
self._to_logfile_with_terminal(
"Received an error from the printer's firmware: {}".format(
stripped_error
),
level=logging.WARN,
)
if not self._ignore_errors:
if self._disconnect_on_errors or any(
map(lambda x: x in lower_line, self._fatal_errors)
):
self._trigger_error(stripped_error, "firmware")
elif self.isPrinting():
consequence = "cancel"
payload = self._payload_for_error(
"firmware", consequence=consequence, error=stripped_error
)
self._callback.on_comm_error(
stripped_error,
"firmware",
consequence=consequence,
faq=payload.get("faq"),
logs=payload.get("logs"),
)
self.cancelPrint(firmware_error=stripped_error)
self._clear_to_send.set()
else:
self._log(
"WARNING! Received an error from the printer's firmware, ignoring that as configured "
"but you might want to investigate what happened here! Error: {}".format(
stripped_error
)
)
self._clear_to_send.set()
# finally return the line
return line
def _trigger_error(self, text, reason, close=True):
self._errorValue = text
self._changeState(self.STATE_ERROR)
trigger_m112 = (
self._send_m112_on_error
and not self.isSdPrinting()
and reason not in ("connection", "autodetect")
)
if close and trigger_m112:
consequence = "emergency"
elif close:
consequence = "disconnect"
else:
consequence = None
payload = self._payload_for_error(reason, consequence=consequence)
self._callback.on_comm_error(
text,
reason,
consequence=consequence,
faq=payload.get("faq"),
logs=payload.get("logs"),
)
eventManager().fire(Events.ERROR, payload)
if close:
if trigger_m112:
self._trigger_emergency_stop(close=False)
self.close(is_error=True)
_error_faqs = {
"mintemp": ("mintemp",),
"maxtemp": ("maxtemp",),
"thermal-runaway": ("runaway",),
"heating-failed": ("heating failed",),
"probing-failed": (
"probing failed",
"bed leveling",
"reference point",
"bltouch",
),
}
def _payload_for_error(self, reason, consequence=None, error=None):
if error is None:
error = self.getErrorString()
payload = {"error": error, "reason": reason}
if consequence:
payload["consequence"] = consequence
if reason == "firmware":
payload["logs"] = list(self._terminal_log)
error_lower = error.lower()
for faq, triggers in self._error_faqs.items():
if any(trigger in error_lower for trigger in triggers):
payload["faq"] = "firmware-" + faq
break
return payload
def _readline(self):
if self._serial is None:
return None
try:
ret = self._serial.readline()
except Exception as ex:
if not self._connection_closing:
self._logger.exception("Unexpected error while reading from serial port")
self._log(
"Unexpected error while reading serial port, please consult octoprint.log for details: %s"
% (get_exception_string())
)
if isinstance(ex, serial.SerialException):
self._dual_log(
"Please see https://faq.octoprint.org/serialerror for possible reasons of this.",
level=logging.ERROR,
)
self._errorValue = get_exception_string(fmt="{type}: {message}")
self.close(is_error=True)
return None
null_pos = ret.find(b"\x00")
try:
ret = ret.decode("utf-8")
except UnicodeDecodeError:
ret = ret.decode("latin1")
if ret != "":
try:
self._log(f"Recv: {sanitize_ascii(ret)}")
except ValueError as e:
self._log(f"WARN: While reading last line: {e}")
self._log(f"Recv: {ret!r}")
if null_pos >= 0:
self._logger.warning("Received line:")
self._logger.warning("| {}".format(ret.replace("\0", "\\x00").rstrip()))
self._dual_log(
"The received line contains at least one null byte character at position {}, "
"this hints at some data corruption going on".format(null_pos),
level=logging.WARNING,
prefix="WARN",
)
for name, hook in self._received_message_hooks.items():
try:
ret = hook(self, ret)
except Exception:
self._logger.exception(
f"Error while processing hook {name}:",
extra={"plugin": name},
)
else:
if ret is None:
return ""
return ret
def _get_next_from_job(self):
if self._currentFile is None:
return None, None, None
try:
line, pos, lineno = self._currentFile.getNext()
except OSError:
self._log(
"There was an error reading from the file that's being printed, cancelling the print. Please "
"consult octoprint.log for details on the error."
)
self.cancelPrint()
return None, None, None
if line is None:
if isinstance(self._currentFile, StreamingGcodeFileInformation):
self._finishFileTransfer()
else:
self._changeState(self.STATE_FINISHING)
self.sendCommand("M400", part_of_job=True)
self._callback.on_comm_print_job_done()
def finalize():
self._changeState(self.STATE_OPERATIONAL)
return SendQueueMarker(finalize), None, None
return line, pos, lineno
def _send_from_job(self):
with self._jobLock:
while self._active:
# we loop until we've actually enqueued a line for sending
if self._state not in (self.STATE_STARTING, self.STATE_PRINTING):
# we are no longer printing, return false
return False
elif self.job_on_hold:
# job is on hold, return false
return False
line, pos, lineno = self._get_next_from_job()
if isinstance(line, QueueMarker):
self.sendCommand(line, part_of_job=True)
self._callback.on_comm_progress()
# end of file, return false so that the next round in continue_sending will process
# what we just enqueued (any scripts + marker)
return False
elif line is None:
# end of file, return false
return False
result = self._sendCommand(
line,
tags={
"source:file",
f"filepos:{pos}",
f"fileline:{lineno}",
},
)
self._callback.on_comm_progress()
if result:
# line from file sent, return true
return True
self._logger.debug(
'Command "{}" from file not enqueued, doing another iteration'.format(
line
)
)
def _send_from_job_queue(self):
try:
line, cmd_type, on_sent, tags = self._job_queue.get_nowait()
result = self._sendCommand(
line, cmd_type=cmd_type, on_sent=on_sent, tags=tags
)
if result:
# line from script sent, return true
return True
except queue.Empty:
pass
return False
def _handle_resend_request(self, line):
self._received_resend_requests += 1
self._reevaluate_resend_ratio()
try:
lineToResend = parse_resend_line(line)
if lineToResend is None:
return False
if self._resendDelta is None and lineToResend == self._current_line == 1:
# We probably just handled a resend and this request originates from lines sent before that
self._logger.info(
"Got a resend request for line 1 which is also our current line. It looks "
"like we just handled a reset and this is a left over of this"
)
return False
elif self._resendDelta is None and lineToResend == self._current_line:
# We don't expect to have an active resend request and the printer is requesting a resend of
# a line we haven't yet sent.
#
# This means the printer got a line from us with N = self._current_line - 1 but had already
# acknowledged that. This can happen if the last line was resent due to a timeout during
# an active (prior) resend request.
#
# We will ignore this resend request and just continue normally.
self._logger.info(
"Ignoring resend request for line %d == current line, we haven't sent that yet so "
"the printer got N-1 twice from us, probably due to a timeout"
% lineToResend
)
return False
lastCommError = self._lastCommError
self._lastCommError = None
resendDelta = self._current_line - lineToResend
if (
lastCommError is not None
and (
"line number" in lastCommError.lower()
or "expected line" in lastCommError.lower()
)
and lineToResend == self._lastResendNumber
and self._resendDelta is not None
and self._currentResendCount < resendDelta
):
self._logger.info(
"Ignoring resend request for line %d, that still originates from lines we sent "
"before we got the first resend request" % lineToResend
)
self._currentResendCount += 1
return True
if self._currentConsecutiveResendNumber == lineToResend:
self._currentConsecutiveResendCount += 1
if self._currentConsecutiveResendCount >= self._maxConsecutiveResends:
# printer keeps requesting the same line again and again, something is severely broken here
error_text = "Printer keeps requesting line {} again and again, communication stuck".format(
lineToResend
)
self._log(error_text)
self._logger.warning(error_text)
self._trigger_error(error_text, "resend_loop")
else:
self._currentConsecutiveResendNumber = lineToResend
self._currentConsecutiveResendCount = 0
self._resendActive = True
self._resendDelta = resendDelta
self._lastResendNumber = lineToResend
self._currentResendCount = 0
self._resendCheckPossibility(lineToResend)
# if we log resends, make sure we don't log more resends than the set rate within a window
#
# this it to prevent the log from getting flooded for extremely bad communication issues
if self._log_resends:
now = time.monotonic()
new_rate_window = (
self._log_resends_rate_start is None
or self._log_resends_rate_start + self._log_resends_rate_frame < now
)
in_rate = self._log_resends_rate_count < self._log_resends_max
if new_rate_window or in_rate:
if new_rate_window:
self._log_resends_rate_start = now
self._log_resends_rate_count = 0
self._to_logfile_with_terminal(
"Got a resend request from the printer: requested line = {}, "
"current line = {}".format(lineToResend, self._current_line)
)
self._log_resends_rate_count += 1
self._send_queue.resend_active = True
return True
finally:
if self._trigger_ok_after_resend == "always":
self._handle_ok()
elif self._trigger_ok_after_resend == "detect":
self._resend_ok_timer = threading.Timer(
self._timeout_intervals.get("resendOk", 1.0), self._resendSimulateOk
)
self._resend_ok_timer.start()
def _resendSimulateOk(self):
self._resend_ok_timer = None
self._handle_ok()
self._logger.info(
"Firmware didn't send an 'ok' with their resend request. That's a known bug "
"with some firmware variants out there. Simulating an ok to continue..."
)
def _resendSameCommand(self):
return self._resendNextCommand(again=True)
def _resendNextCommand(self, again=False):
self._lastCommError = None
# Make sure we are only handling one sending job at a time
with self._sendingLock:
if again:
# If we are about to send the last line from the active resend request
# again, we first need to increment resend delta. It might already
# be set to None if the last resend line was already sent, so
# if that's the case we set it to 0. It will then be incremented,
# the last line will be sent again, and then the delta will be
# decremented and set to None again, completing the cycle.
if self._resendDelta is None:
self._resendDelta = 0
self._resendDelta += 1
elif self._resendDelta is None:
# we might enter this twice in quick succession if we get triggered by the
# resend_ok_timer, so make sure that resendDelta is actually still set (see #2632)
return False
lineNumber = self._current_line - self._resendDelta
if not self._resendCheckPossibility(lineNumber):
# Something has gone wrong if we get here, but we already logged and
# handled it.
return False
cmd = self._lastLines[-self._resendDelta].decode(self._serial_encoding)
result = self._enqueue_for_sending(cmd, linenumber=lineNumber, resend=True)
self._resendDelta -= 1
if self._resendDelta <= 0:
# reset everything BUT the resendActive flag - that will have to stay active until we receive
# our next ok!
self._resendDelta = None
self._lastResendNumber = None
self._currentResendCount = 0
self._send_queue.resend_active = False
return result
def _resendCheckPossibility(self, lineno):
if (
self._resendDelta > len(self._lastLines)
or len(self._lastLines) == 0
or self._resendDelta < 0
):
error_text = "Should resend line {} but no sufficient history is available, can't resend".format(
lineno
)
self._log(error_text)
self._logger.warning(
error_text
+ ". Line to resend is {}, current line is {}, line history has {} entries.".format(
lineno, self._current_line, len(self._lastLines)
)
)
if self.isPrinting():
# abort the print & disconnect, there's nothing we can do to rescue it
self._trigger_error(error_text, "resend")
else:
# reset resend delta, we can't do anything about it
self._resendDelta = None
return False
else:
return True
def _sendCommand(self, cmd, cmd_type=None, on_sent=None, tags=None):
# Make sure we are only handling one sending job at a time
with self._sendingLock:
if self._serial is None:
return False
if isinstance(cmd, QueueMarker):
if isinstance(cmd, SendQueueMarker):
self._enqueue_for_sending(cmd)
return True
else:
return False
gcode, subcode = gcode_and_subcode_for_cmd(cmd)
if not self.isStreaming():
# trigger the "queuing" phase only if we are not streaming to sd right now
results = self._process_command_phase(
"queuing",
cmd,
command_type=cmd_type,
gcode=gcode,
subcode=subcode,
tags=tags,
)
if not results:
# command is no more, return
return False
else:
results = [(cmd, cmd_type, gcode, subcode, tags)]
# process helper
def process(cmd, cmd_type, gcode, subcode, on_sent=None, tags=None):
if cmd is None:
# no command, next entry
return False
if gcode and gcode in gcodeToEvent:
# if this is a gcode bound to an event, trigger that now
eventManager().fire(gcodeToEvent[gcode])
# process @ commands
if gcode is None and cmd.startswith("@"):
self._process_atcommand_phase("queuing", cmd, tags=tags)
# actually enqueue the command for sending
if self._enqueue_for_sending(
cmd, command_type=cmd_type, on_sent=on_sent, tags=tags
):
if not self.isStreaming():
# trigger the "queued" phase only if we are not streaming to sd right now
self._process_command_phase(
"queued",
cmd,
cmd_type,
gcode=gcode,
subcode=subcode,
tags=tags,
)
return True
else:
return False
# split off the final command, because that needs special treatment
if len(results) > 1:
last_command = results[-1]
results = results[:-1]
else:
last_command = results[0]
results = []
# track if we enqueued anything at all
enqueued_something = False
# process all but the last ...
for cmd, cmd_type, gcode, subcode, tags in results:
enqueued_something = (
process(cmd, cmd_type, gcode, subcode, tags=tags)
or enqueued_something
)
# ... and then process the last one with the on_sent callback attached
cmd, cmd_type, gcode, subcode, tags = last_command
enqueued_something = (
process(cmd, cmd_type, gcode, subcode, on_sent=on_sent, tags=tags)
or enqueued_something
)
return enqueued_something
##~~ send loop handling
def _enqueue_for_sending(
self,
command,
linenumber=None,
command_type=None,
on_sent=None,
resend=False,
tags=None,
):
"""
Enqueues a command and optional linenumber to use for it in the send queue.
Arguments:
command (str or SendQueueMarker): The command to send.
linenumber (int): The line number with which to send the command. May be ``None`` in which case the command
will be sent without a line number and checksum.
command_type (str): Optional command type, if set and command type is already in the queue the
command won't be enqueued
on_sent (callable): Optional callable to call after command has been sent to printer.
resend (bool): Whether this is a resent command
tags (set of str or None): Tags to attach to this command
"""
try:
target = "send"
if resend:
target = "resend"
self._send_queue.put(
(command, linenumber, command_type, on_sent, False, tags),
item_type=command_type,
target=target,
)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in send queue: " + e.type)
return False
def _use_up_clear(self, gcode):
# we only need to use up a clear if the command we just sent was either a gcode command or if we also
# require ack's for unknown commands
eats_clear = self._unknownCommandsNeedAck
if gcode is not None:
eats_clear = True
if eats_clear:
# if we need to use up a clear, do that now
self._clear_to_send.clear()
return eats_clear
def _send_loop(self):
"""
The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for
sending (through received ``ok`` responses from the printer's firmware.
"""
self._clear_to_send.wait()
while self._send_queue_active:
try:
# wait until we have something in the queue
try:
entry = self._send_queue.get()
except queue.Empty:
# I haven't yet been able to figure out *why* this can happen but according to #3096 and SERVER-2H
# an Empty exception can fly here due to resend_active being True but nothing being in the resend
# queue of the send queue. So we protect against this possibility...
continue
try:
# make sure we are still active
if not self._send_queue_active:
break
# sleep if we are dwelling
now = time.monotonic()
if (
self._blockWhileDwelling
and self._dwelling_until
and now < self._dwelling_until
):
time.sleep(self._dwelling_until - now)
self._dwelling_until = False
# fetch command, command type and optional linenumber and sent callback from queue
command, linenumber, command_type, on_sent, processed, tags = entry
if isinstance(command, SendQueueMarker):
command.run()
self._continue_sending()
continue
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
# at hand here and only clear our clear_to_send flag later if that's the case
gcode, subcode = gcode_and_subcode_for_cmd(command)
if linenumber is not None:
# line number predetermined - this only happens for resends, so we'll use the number and
# send directly without any processing (since that already took place on the first sending!)
self._use_up_clear(gcode)
self._do_send_with_checksum(
command.encode(self._serial_encoding), linenumber
)
else:
if not processed:
# trigger "sending" phase if we didn't so far
results = self._process_command_phase(
"sending",
command,
command_type,
gcode=gcode,
subcode=subcode,
tags=tags,
)
if not results:
# No, we are not going to send this, that was a last-minute bail.
# However, since we already are in the send queue, our _monitor
# loop won't be triggered with the reply from this unsent command
# now, so we try to tickle the processing of any active
# command queues manually
self._continue_sending()
# and now let's fetch the next item from the queue
continue
# we explicitly throw away plugin hook results that try
# to perform command expansion in the sending/sent phase,
# so "results" really should only have more than one entry
# at this point if our core code contains a bug
assert len(results) == 1
# we only use the first (and only!) entry here
command, _, gcode, subcode, tags = results[0]
if command.strip() == "":
self._logger.info(
"Refusing to send an empty line to the printer"
)
# same here, tickle the queues manually
self._continue_sending()
# and fetch the next item
continue
# handle @ commands
if gcode is None and command.startswith("@"):
self._process_atcommand_phase("sending", command, tags=tags)
# tickle...
self._continue_sending()
# ... and fetch the next item
continue
# now comes the part where we increase line numbers and send stuff - no turning back now
used_up_clear = self._use_up_clear(gcode)
self._do_send(command, gcode=gcode)
if not used_up_clear:
# If we didn't use up a clear we need to tickle the read queue - there might
# not be a reply to this command, so our _monitor loop will stay waiting until
# timeout. We definitely do not want that, so we tickle the queue manually here
self._continue_sending()
# trigger "sent" phase and use up one "ok"
if on_sent is not None and callable(on_sent):
# we have a sent callback for this specific command, let's execute it now
on_sent()
self._process_command_phase(
"sent",
command,
command_type,
gcode=gcode,
subcode=subcode,
tags=tags,
)
finally:
# no matter _how_ we exit this block, we signal that we
# are done processing the last fetched queue entry
self._send_queue.task_done()
# now we just wait for the next clear and then start again
self._clear_to_send.wait()
except Exception:
self._logger.exception("Caught an exception in the send loop")
self._log("Closing down send loop")
def _log_command_phase(self, phase, command, *args, **kwargs):
if self._phaseLogger.isEnabledFor(logging.DEBUG):
output_parts = [
f"phase: {phase}",
"command: {}".format(to_unicode(command, errors="replace")),
]
if kwargs.get("command_type"):
output_parts.append("command_type: {}".format(kwargs["command_type"]))
if kwargs.get("gcode"):
output_parts.append("gcode: {}".format(kwargs["gcode"]))
if kwargs.get("subcode"):
output_parts.append("subcode: {}".format(kwargs["subcode"]))
if kwargs.get("tags"):
output_parts.append(
"tags: [ {} ]".format(", ".join(sorted(kwargs["tags"])))
)
self._phaseLogger.debug(" | ".join(output_parts))
def _process_command_phase(
self, phase, command, command_type=None, gcode=None, subcode=None, tags=None
):
if gcode is None:
gcode, subcode = gcode_and_subcode_for_cmd(command)
results = [(command, command_type, gcode, subcode, tags)]
self._log_command_phase(
phase,
command,
command_type=command_type,
gcode=gcode,
subcode=subcode,
tags=tags,
)
if (self.isStreaming() and self.isPrinting()) or phase not in (
"queuing",
"queued",
"sending",
"sent",
):
return results
# send it through the phase specific handlers provided by plugins
for name, hook in self._gcode_hooks[phase].items():
try:
new_results = []
for command, command_type, gcode, subcode, tags in results:
hook_results = hook(
self,
phase,
command,
command_type,
gcode,
subcode=subcode,
tags=tags,
)
normalized = _normalize_command_handler_result(
command,
command_type,
gcode,
subcode,
tags,
hook_results,
tags_to_add={
"source:rewrite",
f"phase:{phase}",
f"plugin:{name}",
},
)
# make sure we don't allow multi entry results in anything but the queuing phase
if phase not in ("queuing",) and len(normalized) > 1:
self._logger.error(
"Error while processing hook {name} for phase {phase} and command {command}: "
"Hook returned multi-entry result for phase {phase} and command {command}. "
"That's not supported, if you need to do multi expansion of commands you "
"need to do this in the queuing phase. Ignoring hook result and sending "
"command as-is.".format(
name=name,
phase=phase,
command=to_unicode(command, errors="replace"),
),
extra={"plugin": name},
)
new_results.append((command, command_type, gcode, subcode, tags))
else:
new_results += normalized
except Exception:
self._logger.exception(
"Error while processing hook {name} for phase "
"{phase}:".format(
name=name,
phase=phase,
),
extra={"plugin": name},
)
else:
if not new_results:
# hook handler returned None or empty list for all commands, so
# we'll stop here and return a full out empty result
return []
results = new_results
# if it's a gcode command send it through the specific handler if it exists
new_results = []
modified = False
for command, command_type, gcode, subcode, tags in results:
if gcode is not None:
gcode_handler = "_gcode_" + gcode + "_" + phase
if hasattr(self, gcode_handler):
handler_results = getattr(self, gcode_handler)(
command, cmd_type=command_type, subcode=subcode, tags=tags
)
new_results += _normalize_command_handler_result(
command, command_type, gcode, subcode, tags, handler_results
)
modified = True
else:
new_results.append((command, command_type, gcode, subcode, tags))
else:
new_results.append((command, command_type, gcode, subcode, tags))
if modified:
if not new_results:
# gcode handler returned None or empty list for all commands, so we'll stop here and return a full out empty result
return []
else:
results = new_results
# send it through the phase specific command handler if it exists
command_phase_handler = "_command_phase_" + phase
if hasattr(self, command_phase_handler):
new_results = []
for command, command_type, gcode, subcode, tags in results:
handler_results = getattr(self, command_phase_handler)(
command,
cmd_type=command_type,
gcode=gcode,
subcode=subcode,
tags=tags,
)
new_results += _normalize_command_handler_result(
command, command_type, gcode, subcode, tags, handler_results
)
results = new_results
# finally return whatever we resulted on
return results
def _process_atcommand_phase(self, phase, command, tags=None):
if (self.isStreaming() and self.isPrinting()) or phase not in (
"queuing",
"sending",
):
return
split = command.split(None, 1)
if len(split) == 2:
atcommand = split[0]
parameters = split[1]
else:
atcommand = split[0]
parameters = ""
atcommand = atcommand[1:]
# send it through the phase specific handlers provided by plugins
for name, hook in self._atcommand_hooks[phase].items():
try:
hook(self, phase, atcommand, parameters, tags=tags)
except Exception:
self._logger.exception(
"Error while processing hook {} for "
"phase {} and command {}:".format(
name, phase, to_unicode(atcommand, errors="replace")
),
extra={"plugin": name},
)
# trigger built-in handler if available
handler = getattr(self, f"_atcommand_{atcommand}_{phase}", None)
if callable(handler):
try:
handler(atcommand, parameters, tags=tags)
except Exception:
self._logger.exception(
"Error in handler for phase {} and command {}".format(
phase, to_unicode(atcommand, errors="replace")
)
)
##~~ actual sending via serial
def _needs_checksum(self, gcode=None):
command_requiring_checksum = (
gcode is not None and gcode in self._checksum_requiring_commands
)
command_allowing_checksum = (
gcode is not None or self._sendChecksumWithUnknownCommands
)
return command_requiring_checksum or (
command_allowing_checksum and self._checksum_enabled
)
@property
def _checksum_enabled(self):
return not self._neverSendChecksum and (
(self.isPrinting() and self._currentFile and self._currentFile.checksum)
or self._manualStreaming
or self._alwaysSendChecksum
or not self._firmware_info_received
)
def _do_send(self, command, gcode=None):
command_to_send = command.encode(self._serial_encoding, errors="replace")
if self._needs_checksum(gcode):
self._do_increment_and_send_with_checksum(command_to_send)
else:
self._do_send_without_checksum(command_to_send)
def _do_increment_and_send_with_checksum(self, cmd):
with self._line_mutex:
linenumber = self._current_line
self._addToLastLines(cmd)
self._current_line += 1
self._do_send_with_checksum(cmd, linenumber)
def _do_send_with_checksum(self, command, linenumber):
command_to_send = (
b"N" + str(linenumber).encode(self._serial_encoding) + b" " + command
)
checksum = 0
for c in bytearray(command_to_send):
checksum ^= c
command_to_send = (
command_to_send + b"*" + str(checksum).encode(self._serial_encoding)
)
self._do_send_without_checksum(command_to_send)
def _do_send_without_checksum(self, cmd, log=True):
if self._serial is None:
return
if log:
self._log("Send: " + cmd.decode(self._serial_encoding))
cmd += b"\n"
written = 0
passes = 0
while written < len(cmd):
to_send = cmd[written:]
old_written = written
try:
result = self._serial.write(to_send)
if result is None or not isinstance(result, int):
# probably some plugin not returning the written bytes, assuming all of them
written += len(cmd)
else:
written += result
except serial.SerialTimeoutException:
self._log("Serial timeout while writing to serial port, trying again.")
try:
result = self._serial.write(to_send)
if result is None or not isinstance(result, int):
# probably some plugin not returning the written bytes, assuming all of them
written += len(cmd)
else:
written += result
except Exception as ex:
if not self._connection_closing:
self._logger.exception(
"Unexpected error while writing to serial port"
)
self._log(
"Unexpected error while writing to serial port: %s"
% (get_exception_string())
)
if isinstance(ex, serial.SerialException):
self._dual_log(
"Please see https://faq.octoprint.org/serialerror for possible reasons of this.",
level=logging.INFO,
)
self._errorValue = get_exception_string(fmt="{type}: {message}")
self.close(is_error=True)
break
except Exception as ex:
if not self._connection_closing:
self._logger.exception(
"Unexpected error while writing to serial port"
)
self._log(
"Unexpected error while writing to serial port: %s"
% (get_exception_string())
)
if isinstance(ex, serial.SerialException):
self._dual_log(
"Please see https://faq.octoprint.org/serialerror for possible reasons of this.",
level=logging.INFO,
)
self._errorValue = get_exception_string(fmt="{type}: {message}")
self.close(is_error=True)
break
if old_written == written:
# nothing written this pass
passes += 1
if passes > self._max_write_passes:
# nothing written in max consecutive passes, we give up
message = "Could not write anything to the serial port in {} tries, something appears to be wrong with the printer communication".format(
self._max_write_passes
)
self._dual_log(message, level=logging.ERROR)
self._errorValue = "Could not write to serial port"
self.close(is_error=True)
break
# if we have failed to write data after an initial retry then the printer/system
# may be busy, so give things a little time before we try again. Extend this
# period each time we fail until either we write the data or run out of retry attempts.
if passes > 1:
time.sleep((passes - 1) / 10)
self._transmitted_lines += 1
##~~ command handlers
## gcode
def _gcode_T_queuing(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
current_tool = self._currentTool
new_tool = int(toolMatch.group("value"))
if not self._validate_tool(new_tool):
message = (
"Not queuing T{}, that tool doesn't exist according to the printer profile or "
"was reported as invalid by the firmware. Make sure your "
"printer profile is set up correctly.".format(new_tool)
)
self._log("Warn: " + message)
eventManager().fire(
Events.COMMAND_SUPPRESSED,
{
"command": cmd,
"message": message,
"severity": "warn",
},
)
return (None,)
before = self._getGcodeScript(
"beforeToolChange",
replacements={"tool": {"old": current_tool, "new": new_tool}},
)
after = self._getGcodeScript(
"afterToolChange",
replacements={"tool": {"old": current_tool, "new": new_tool}},
)
def convert(data):
result = []
for d in data:
if isinstance(d, tuple) and len(d) == 2:
result.append((d[0], None, d[1]))
elif isinstance(d, str):
result.append(d)
return result
return convert(before) + [cmd] + convert(after)
def _gcode_T_sending(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
new_tool = int(toolMatch.group("value"))
if not self._validate_tool(new_tool):
message = (
"Not sending T{}, that tool doesn't exist according to "
"the printer profile or was reported as invalid by the "
"firmware. Make sure your printer profile is set up "
"correctly.".format(new_tool)
)
self._log("Warn: " + message)
self._logger.warning(message)
eventManager().fire(
Events.COMMAND_SUPPRESSED,
{
"command": cmd,
"message": message,
"severity": "warn",
},
)
return (None,)
def _gcode_T_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
new_tool = int(toolMatch.group("value"))
self._toolBeforeChange = self._currentTool
self._currentTool = new_tool
eventManager().fire(
Events.TOOL_CHANGE,
{"old": self._toolBeforeChange, "new": self._currentTool},
)
def _gcode_G0_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
if "Z" in cmd or "F" in cmd:
# track Z
match = regexes_parameters["floatZ"].search(cmd)
if match:
try:
z = float(match.group("value"))
if self._currentZ != z:
self._currentZ = z
self._callback.on_comm_z_change(z)
except ValueError:
pass
# track F
match = regexes_parameters["floatF"].search(cmd)
if match:
try:
f = float(match.group("value"))
self._currentF = f
except ValueError:
pass
_gcode_G1_sent = _gcode_G0_sent
def _gcode_G28_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
if "F" in cmd:
match = regexes_parameters["floatF"].search(cmd)
if match:
try:
f = float(match.group("value"))
self._currentF = f
except ValueError:
pass
def _gcode_M28_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
if not self.isStreaming():
self._log(
"Detected manual streaming. Disabling temperature polling. Finish writing with M29. "
"Do NOT attempt to print while manually streaming!"
)
self._manualStreaming = True
def _gcode_M29_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
if self._manualStreaming:
self._log(
"Manual streaming done. Re-enabling temperature polling. All is well."
)
self._manualStreaming = False
def _gcode_M140_queuing(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
message = (
'Not sending "{}", printer profile has no heated bed. Either '
"configure a heated bed or remove bed commands from your "
"GCODE.".format(cmd)
)
self._log("Warn: " + message)
self._logger.warning(message)
eventManager().fire(
Events.COMMAND_SUPPRESSED,
{"command": cmd, "message": message, "severity": "warn"},
)
return (None,) # Don't send bed commands if we don't have a heated bed
_gcode_M190_queuing = _gcode_M140_queuing
def _gcode_M141_queuing(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
if not self._printerProfileManager.get_current_or_default()["heatedChamber"]:
message = (
'Not sending "{}", printer profile has no heated chamber. Either '
"configure a heated chamber or remove chamber commands from your "
"GCODE.".format(cmd)
)
self._log("Warn: " + message)
self._logger.warning(message)
eventManager().fire(
Events.COMMAND_SUPPRESSED,
{"command": cmd, "message": message, "severity": "warn"},
)
return (
None,
) # Don't send chamber commands if we don't have a heated chamber
_gcode_M191_queuing = _gcode_M141_queuing
def _gcode_M104_sent(
self,
cmd,
cmd_type=None,
gcode=None,
subcode=None,
wait=False,
support_r=False,
*args,
**kwargs,
):
toolNum = self._currentTool
toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
toolNum = int(toolMatch.group("value"))
if wait:
self._toolBeforeHeatup = self._currentTool
self._currentTool = toolNum
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
if match and self.last_temperature.tools.get(toolNum) is not None:
try:
target = float(match.group("value"))
self.last_temperature.set_tool(toolNum, target=target)
self._callback.on_comm_temperature_update(
self.last_temperature.tools,
self.last_temperature.bed,
self.last_temperature.chamber,
self.last_temperature.custom,
)
except ValueError:
pass
def _gcode_M140_sent(
self,
cmd,
cmd_type=None,
gcode=None,
subcode=None,
wait=False,
support_r=False,
*args,
**kwargs,
):
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
if match:
try:
target = float(match.group("value"))
self.last_temperature.set_bed(target=target)
self._callback.on_comm_temperature_update(
self.last_temperature.tools,
self.last_temperature.bed,
self.last_temperature.chamber,
self.last_temperature.custom,
)
except ValueError:
pass
def _gcode_M141_sent(
self,
cmd,
cmd_type=None,
gcode=None,
subcode=None,
wait=False,
support_r=False,
*args,
**kwargs,
):
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
if match:
try:
target = float(match.group("value"))
self.last_temperature.set_chamber(target=target)
self._callback.on_comm_temperature_update(
self.last_temperature.tools,
self.last_temperature.bed,
self.last_temperature.chamber,
self.last_temperature.custom,
)
except ValueError:
pass
def _gcode_M109_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
self._heatupWaitStartTime = time.monotonic()
self._long_running_command = True
self._heating = True
self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M190_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
self._heatupWaitStartTime = time.monotonic()
self._long_running_command = True
self._heating = True
self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M191_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
self._heatupWaitStartTime = time.monotonic()
self._long_running_command = True
self._heating = True
self._gcode_M141_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M116_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
self._heatupWaitStartTime = time.monotonic()
self._long_running_command = True
self._heating = True
def _gcode_M155_sending(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
match = regexes_parameters["intS"].search(cmd)
if match:
interval = int(match.group("value"))
self._temperature_autoreporting = self._firmware_capabilities.get(
self.CAPABILITY_AUTOREPORT_TEMP, False
) and (interval > 0)
def _gcode_M27_sending(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
match = regexes_parameters["intS"].search(cmd)
if match:
interval = int(match.group("value"))
self._sdstatus_autoreporting = self._firmware_capabilities.get(
self.CAPABILITY_AUTOREPORT_SD_STATUS, False
) and (interval > 0)
def _gcode_M154_sending(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
match = regexes_parameters["intS"].search(cmd)
if match:
interval = int(match.group("value"))
self._pos_autoreporting = self._firmware_capabilities.get(
self.CAPABILITY_AUTOREPORT_SD_STATUS, False
) and (interval > 0)
def _gcode_M33_sending(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
parts = cmd.split(None, 1)
if len(parts) > 1:
filename = parts[1].strip()
if not filename.startswith("/"):
filename = "/" + filename
self._sdFileLongName = filename
def _gcode_M110_sending(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
newLineNumber = 0
match = regexes_parameters["intN"].search(cmd)
if match:
newLineNumber = int(match.group("value"))
with self._line_mutex:
self._logger.info(
f"M110 detected, setting current line number to {newLineNumber}"
)
# send M110 command with new line number
self._current_line = newLineNumber
# after a reset of the line number we have no way to determine what line exactly the printer now wants
self._lastLines.clear()
self._resendDelta = None
def _trigger_emergency_stop(self, close=True):
self._logger.info("Force-sending M112 to the printer")
# emergency stop, jump the queue with the M112, regardless of whether the EMERGENCY_PARSER capability is
# available or not
#
# send the M112 once without and with checksum
self._do_send_without_checksum(b"M112")
self._do_increment_and_send_with_checksum(b"M112")
# No idea if the printer is still listening or if M112 won. Just in case
# we'll now try to also manually make sure all heaters are shut off - better
# safe than sorry. We do this ignoring the queue since at this point it
# is irrelevant whether the printer has sent enough ack's or not, we
# are going to shutdown the connection in a second anyhow.
for tool in range(
self._printerProfileManager.get_current_or_default()["extruder"]["count"]
):
self._do_increment_and_send_with_checksum(
f"M104 T{tool} S0".encode(self._serial_encoding)
)
if self._printerProfileManager.get_current_or_default()["heatedBed"]:
self._do_increment_and_send_with_checksum(b"M140 S0")
if close:
# close to reset host state
error_text = "Closing serial port due to emergency stop M112."
self._log(error_text)
self._errorValue = error_text
self.close(is_error=True)
# fire the M112 event since we sent it and we're going to prevent the caller from seeing it
gcode = "M112"
if gcode in gcodeToEvent:
eventManager().fire(gcodeToEvent[gcode])
def _gcode_M112_queuing(self, *args, **kwargs):
self._trigger_emergency_stop()
return (None,)
def _gcode_M114_queued(self, *args, **kwargs):
self._reset_position_timers()
_gcode_M114_sent = _gcode_M114_queued
def _gcode_G4_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
# we are intending to dwell for a period of time, increase the timeout to match
p_match = regexes_parameters["floatP"].search(cmd)
s_match = regexes_parameters["floatS"].search(cmd)
_timeout = 0
if p_match:
_timeout = float(p_match.group("value")) / 1000
elif s_match:
_timeout = float(s_match.group("value"))
self._timeout = self._get_new_communication_timeout() + _timeout
self._dwelling_until = time.monotonic() + _timeout
def _gcode_M106_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
s_match = regexes_parameters["intS"].search(cmd)
fanspeed = 0
if s_match:
fanspeed = int(s_match.group("value"))
self.last_fanspeed = fanspeed
def _gcode_M107_sent(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
self.last_fanspeed = 0
def _emergency_force_send(self, cmd, message, gcode=None, *args, **kwargs):
# only jump the queue with our command if the EMERGENCY_PARSER capability is available
if not self._capability_supported(self.CAPABILITY_EMERGENCY_PARSER):
return
self._logger.info(message)
# use up an ok since we will get one back for this command and don't want to get out of sync
used_up_clear = self._use_up_clear(gcode)
self._do_send(cmd, gcode=gcode)
if not used_up_clear:
self._continue_sending()
return (None,)
def _validate_tool(self, tool):
return not self._sanity_check_tools or (
tool
< self._printerProfileManager.get_current_or_default()["extruder"]["count"]
and tool not in self._known_invalid_tools
)
def _reset_position_timers(self):
if self._cancel_position_timer:
self._cancel_position_timer.reset()
if self._pause_position_timer:
self._pause_position_timer.reset()
## atcommands
def _atcommand_pause_queuing(self, command, parameters, tags=None, *args, **kwargs):
if tags is None:
tags = set()
if "script:afterPrintPaused" not in tags:
self.setPause(True, tags={"trigger:atcommand_pause"})
def _atcommand_cancel_queuing(self, command, parameters, tags=None, *args, **kwargs):
if tags is None:
tags = set()
if "script:afterPrintCancelled" not in tags:
self.cancelPrint(tags={"trigger:atcommand_cancel"})
_atcommand_abort_queuing = _atcommand_cancel_queuing
def _atcommand_resume_queuing(self, command, parameters, tags=None, *args, **kwargs):
if tags is None:
tags = set()
if "script:beforePrintResumed" not in tags:
self.setPause(False, tags={"trigger:atcommand_resume"})
##~~ command phase handlers
def _command_phase_queuing(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
if gcode is not None:
tags = kwargs.get("tags")
if tags is None:
tags = set()
if gcode in self._emergency_commands and gcode != "M112":
return self._emergency_force_send(
cmd,
f"Force-sending {gcode} to the printer",
gcode=gcode,
*args,
**kwargs,
)
if (
self.isPrinting()
and gcode in self._pausing_commands
and "trigger:cancel" not in tags
and "trigger:pause" not in tags
):
self._logger.info(f"Pausing print job due to command {gcode}")
self.setPause(True)
if gcode in self._blocked_commands:
message = "Not sending {} to printer, it's configured as a blocked command".format(
gcode
)
self._log("Info: " + message)
self._logger.info(message)
eventManager().fire(
Events.COMMAND_SUPPRESSED,
{
"command": cmd,
"message": message,
"severity": "warn",
},
)
return (None,)
if gcode in self._ignored_commands:
message = "Not sending {} to printer, it's configured as an ignored command".format(
gcode
)
self._log("Info: " + message)
self._logger.info(message)
eventManager().fire(
Events.COMMAND_SUPPRESSED,
{
"command": cmd,
"message": message,
"severity": "info",
},
)
return (None,)
def _command_phase_sending(
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
):
if (
gcode is not None
and gcode in self._long_running_commands
or cmd in self._long_running_commands
):
self._long_running_command = True
### MachineCom callback ################################################################################################
class MachineComPrintCallback:
def on_comm_log(self, message):
pass
def on_comm_temperature_update(self, temp, bedTemp, chamberTemp, customTemp):
pass
def on_comm_position_update(self, position, reason=None):
pass
def on_comm_state_change(self, state):
pass
def on_comm_message(self, message):
pass
def on_comm_error(self, error, reason, consequence=None, faq=None, logs=None):
pass
def on_comm_progress(self):
pass
def on_comm_print_job_started(self, suppress_script=False, user=None):
pass
def on_comm_print_job_failed(self, reason=None):
pass
def on_comm_print_job_done(self, suppress_script=False):
pass
def on_comm_print_job_cancelling(self, firmware_error=None, user=None):
pass
def on_comm_print_job_cancelled(self, suppress_script=False, user=None):
pass
def on_comm_print_job_paused(self, suppress_script=False, user=None):
pass
def on_comm_print_job_resumed(self, suppress_script=False, user=None):
pass
def on_comm_z_change(self, newZ):
pass
def on_comm_file_selected(self, filename, filesize, sd, user=None, data=None):
pass
def on_comm_sd_state_change(self, sdReady):
pass
def on_comm_sd_files(self, files):
pass
def on_comm_file_transfer_started(
self, local_filename, remote_filename, filesize, user=None
):
pass
def on_comm_file_transfer_done(self, local_filename, remote_filename, elapsed):
pass
def on_comm_file_transfer_failed(self, local_filename, remote_filename, elapsed):
pass
def on_comm_force_disconnect(self):
pass
def on_comm_record_fileposition(self, origin, name, pos):
pass
def on_comm_firmware_info(self, firmware_name, firmware_data):
pass
### Printing file information classes ##################################################################################
class PrintingFileInformation:
"""
Encapsulates information regarding the current file being printed: file name, current position, total size and
time the print started.
Allows to reset the current file position to 0 and to calculate the current progress as a floating point
value between 0 and 1.
"""
checksum = True
def __init__(self, filename, user=None):
self._logger = logging.getLogger(__name__)
self._filename = filename
self._user = user
self._pos = 0
self._size = None
self._start_time = None
self._done = False
def getStartTime(self):
return self._start_time
def getFilename(self):
return self._filename
def getFilesize(self):
return self._size
def getFilepos(self):
return self._pos
def getFileLocation(self):
return FileDestinations.LOCAL
def getUser(self):
return self._user
def getProgress(self):
"""
The current progress of the file, calculated as relation between file position and absolute size. Returns -1
if file size is None or < 1.
"""
if self._size is None or not self._size > 0:
return -1
return self._pos / self._size
def reset(self):
"""
Resets the current file position to 0.
"""
self._pos = 0
def start(self):
"""
Marks the print job as started and remembers the start time.
"""
self._start_time = time.monotonic()
self._done = False
def close(self):
"""
Closes the print job.
"""
pass
@property
def done(self):
return self._done
@done.setter
def done(self, value):
self._done = value
class PrintingSdFileInformation(PrintingFileInformation):
"""
Encapsulates information regarding an ongoing print from SD.
"""
checksum = False
def __init__(self, filename, size, user=None):
PrintingFileInformation.__init__(self, filename, user=user)
self._size = size
def getFileLocation(self):
return FileDestinations.SDCARD
@property
def size(self):
return self._size
@size.setter
def size(self, value):
self._size = value
@property
def pos(self):
return self._pos
@pos.setter
def pos(self, value):
self._pos = value
class PrintingGcodeFileInformation(PrintingFileInformation):
"""
Encapsulates information regarding an ongoing direct print. Takes care of the needed file handle and ensures
that the file is closed in case of an error.
"""
def __init__(
self, filename, offsets_callback=None, current_tool_callback=None, user=None
):
PrintingFileInformation.__init__(self, filename, user=user)
self._handle = None
self._handle_mutex = threading.RLock()
self._offsets_callback = offsets_callback
self._current_tool_callback = current_tool_callback
if not os.path.exists(self._filename) or not os.path.isfile(self._filename):
raise OSError("File %s does not exist" % self._filename)
self._size = os.stat(self._filename).st_size
self._pos = 0
self._read_lines = 0
def seek(self, offset):
with self._handle_mutex:
if self._handle is None:
return
self._handle.seek(offset)
self._pos = self._handle.tell()
self._read_lines = 0
def start(self):
"""
Opens the file for reading and determines the file size.
"""
PrintingFileInformation.start(self)
with self._handle_mutex:
bom = get_bom(self._filename, encoding="utf-8-sig")
self._handle = open(
self._filename, encoding="utf-8-sig", errors="replace", newline=""
)
self._pos = self._handle.tell()
if bom:
# Apparently we found an utf-8 bom in the file.
# We need to add its length to our pos because it will
# be stripped transparently and we'll have no chance
# catching that.
self._pos += len(bom)
self._read_lines = 0
def close(self):
"""
Closes the file if it's still open.
"""
PrintingFileInformation.close(self)
with self._handle_mutex:
if self._handle is not None:
try:
self._handle.close()
except Exception:
pass
self._handle = None
def getNext(self):
"""
Retrieves the next line for printing.
"""
with self._handle_mutex:
if self._handle is None:
self._logger.warning(f"File {self._filename} is not open for reading")
return None, None, None
try:
offsets = (
self._offsets_callback()
if self._offsets_callback is not None
else None
)
current_tool = (
self._current_tool_callback()
if self._current_tool_callback is not None
else None
)
processed = None
while processed is None:
if self._handle is None:
# file got closed just now
self._pos = self._size
self._done = True
self._report_stats()
return None, None, None
# we need to manually keep track of our pos here since
# codecs' readline will make our handle's tell not
# return the actual number of bytes read, but also the
# already buffered bytes (for detecting the newlines)
line = self._handle.readline()
self._pos += len(line.encode("utf-8"))
if not line:
self.close()
processed = self._process(line, offsets, current_tool)
self._read_lines += 1
return processed, self._pos, self._read_lines
except Exception as e:
self.close()
self._logger.exception("Exception while processing line")
raise e
def _process(self, line, offsets, current_tool):
return process_gcode_line(line, offsets=offsets, current_tool=current_tool)
def _report_stats(self):
duration = time.monotonic() - self._start_time
self._logger.info(f"Finished in {duration:.3f} s.")
pass
class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
def __init__(self, path, localFilename, remoteFilename, user=None):
PrintingGcodeFileInformation.__init__(self, path, user=user)
self._localFilename = localFilename
self._remoteFilename = remoteFilename
def start(self):
PrintingGcodeFileInformation.start(self)
self._start_time = time.monotonic()
def getLocalFilename(self):
return self._localFilename
def getRemoteFilename(self):
return self._remoteFilename
def _process(self, line, offsets, current_tool):
return process_gcode_line(line)
def _report_stats(self):
duration = time.monotonic() - self._start_time
read_lines = self._read_lines
if duration > 0 and read_lines > 0:
stats = {
"lines": read_lines,
"rate": read_lines / duration,
"time_per_line": duration * 1000 / read_lines,
"duration": duration,
}
self._logger.info(
"Finished in {duration:.3f} s. Approx. transfer rate of {rate:.3f} lines/s or {time_per_line:.3f} ms per line".format(
**stats
)
)
class SpecialStreamingGcodeFileInformation(StreamingGcodeFileInformation):
"""
For streaming files to the printer that aren't GCODE.
Difference to regular StreamingGcodeFileInformation: no checksum requirement, only rudimentary line processing
(stripping of whitespace from the end and ignoring of empty lines)
"""
checksum = False
def _process(self, line, offsets, current_tool):
line = line.rstrip()
if not len(line):
return None
return line
class JobQueue(PrependableQueue):
pass
class CommandQueue(TypedQueue):
def __init__(self, *args, **kwargs):
TypedQueue.__init__(self, *args, **kwargs)
self._unblocked = threading.Event()
self._unblocked.set()
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def get(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.get(self, *args, **kwargs)
def put(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.put(self, *args, **kwargs)
def clear(self):
cleared = []
while True:
try:
cleared.append(TypedQueue.get(self, False))
TypedQueue.task_done(self)
except queue.Empty:
break
return cleared
class SendQueue(PrependableQueue):
def __init__(self, maxsize=0):
PrependableQueue.__init__(self, maxsize=maxsize)
self._unblocked = threading.Event()
self._unblocked.set()
self._resend_queue = PrependableQueue()
self._send_queue = PrependableQueue()
self._lookup = set()
self._resend_active = False
@property
def resend_active(self):
return self._resend_active
@resend_active.setter
def resend_active(self, resend_active):
with self.mutex:
self._resend_active = resend_active
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def prepend(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.prepend(
self, (item, item_type, target), block=block, timeout=timeout
)
def put(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.put(
self, (item, item_type, target), block=block, timeout=timeout
)
def get(self, block=True, timeout=None):
self._unblocked.wait()
item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout)
return item
def clear(self):
cleared = []
while True:
try:
cleared.append(PrependableQueue.get(self, False))
PrependableQueue.task_done(self)
except queue.Empty:
break
return cleared
def _put(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(
item_type, f"Type {item_type} is already in queue"
)
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.put(item)
else:
self._send_queue.put(item)
pass
def _prepend(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(
item_type, f"Type {item_type} is already in queue"
)
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.prepend(item)
else:
self._send_queue.prepend(item)
def _get(self):
if self.resend_active:
item = self._resend_queue.get(block=False)
else:
try:
item = self._resend_queue.get(block=False)
except queue.Empty:
item = self._send_queue.get(block=False)
_, item_type, _ = item
if item_type is not None:
if item_type in self._lookup:
self._lookup.remove(item_type)
return item
def _qsize(self):
if self.resend_active:
return self._resend_queue.qsize()
else:
return self._resend_queue.qsize() + self._send_queue.qsize()
_temp_command_regex = re.compile(
r"^M(?P<command>104|109|140|190)(\s+T(?P<tool>\d+)|\s+[SR](?P<temperature>[-+]?\d*\.?\d*))+"
)
def apply_temperature_offsets(line, offsets, current_tool=None):
if offsets is None:
return line
match = _temp_command_regex.match(line)
if match is None:
return line
groups = match.groupdict()
if not groups.get("temperature"):
return line
offset = 0
if current_tool is not None and groups["command"] in ("104", "109"):
# extruder temperature, determine which one and retrieve corresponding offset
tool_num = current_tool
if "tool" in groups and groups["tool"] is not None:
tool_num = int(groups["tool"])
tool_key = "tool%d" % tool_num
offset = offsets[tool_key] if tool_key in offsets and offsets[tool_key] else 0
elif groups["command"] in ("140", "190"):
# bed temperature
offset = offsets["bed"] if "bed" in offsets else 0
if offset == 0:
return line
try:
temperature = float(groups["temperature"])
except ValueError:
_logger.warning(
f"Could not parse target temperature, ignoring line for offset application: {line}"
)
return line
if temperature == 0:
return line
return (
line[: match.start("temperature")]
+ "%f" % (temperature + offset)
+ line[match.end("temperature") :]
)
def strip_comment(line):
if ";" not in line:
# shortcut
return line
escaped = False
result = []
for c in line:
if c == ";" and not escaped:
break
result += c
escaped = (c == "\\") and not escaped
return "".join(result)
def process_gcode_line(line, offsets=None, current_tool=None):
line = strip_comment(line).strip()
if not len(line):
return None
if offsets is not None:
line = apply_temperature_offsets(line, offsets, current_tool=current_tool)
return line
def convert_pause_triggers(configured_triggers):
if not configured_triggers:
return {}
triggers = {"enable": [], "disable": [], "toggle": []}
for trigger in configured_triggers:
if "regex" not in trigger or "type" not in trigger:
continue
try:
regex = trigger["regex"]
t = trigger["type"]
if t in triggers:
# make sure regex is valid
re.compile(regex)
# add to type list
triggers[t].append(regex)
except Exception as exc:
# invalid regex or something like this
_logger.debug("Problem with trigger %r: %s", trigger, str(exc))
result = {}
for t in triggers.keys():
if len(triggers[t]) > 0:
result[t] = re.compile(
"|".join(map(lambda pattern: f"({pattern})", triggers[t]))
)
return result
def convert_feedback_controls(configured_controls):
if not configured_controls:
return {}, None
def preprocess_feedback_control(control, result):
if "key" in control and "regex" in control and "template" in control:
# key is always the md5sum of the regex
key = control["key"]
if result[key]["pattern"] is None or result[key]["matcher"] is None:
# regex has not been registered
try:
result[key]["matcher"] = re.compile(control["regex"])
result[key]["pattern"] = control["regex"]
except Exception as exc:
_logger.warning(
"Invalid regex {regex} for custom control: {exc}".format(
regex=control["regex"], exc=str(exc)
)
)
result[key]["templates"][control["template_key"]] = control["template"]
elif "children" in control:
for c in control["children"]:
preprocess_feedback_control(c, result)
def prepare_result_entry():
return {"pattern": None, "matcher": None, "templates": {}}
from collections import defaultdict
feedback_controls = defaultdict(prepare_result_entry)
for control in configured_controls:
preprocess_feedback_control(control, feedback_controls)
feedback_pattern = []
for match_key, entry in feedback_controls.items():
if entry["matcher"] is None or entry["pattern"] is None:
continue
feedback_pattern.append(
"(?P<group{key}>{pattern})".format(key=match_key, pattern=entry["pattern"])
)
feedback_matcher = re.compile("|".join(feedback_pattern))
return feedback_controls, feedback_matcher
def canonicalize_temperatures(parsed, current):
"""
Canonicalizes the temperatures provided in parsed.
Will make sure that returned result only contains extruder keys
like Tn, so always qualified with a tool number.
The algorithm for cleaning up the parsed keys is the following:
* If ``T`` is not included with the reported extruders, return
* If more than just ``T`` is reported:
* If both ``T`` and ``T0`` are reported, remove ``T`` from
the result.
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
* return
Arguments:
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
to canonicalize
current (int): the current active extruder
Returns:
dict: the canonicalized version of ``parsed``
"""
reported_extruders = list(filter(lambda x: x.startswith("T"), parsed.keys()))
if "T" not in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
current_tool_key = "T%d" % current
result = dict(parsed)
if len(reported_extruders) > 1:
if "T0" in reported_extruders:
# Both T and T0 are present, let's check if Tc is too.
# If it is, we just throw away T (it's redundant). It
# it isn't, we first copy T to Tc, then throw T away.
#
# The easier construct would be to always overwrite Tc
# with T and throw away T, but that assumes that if
# both are present, T has the same value as Tc. That
# might not necessarily be the case (weird firmware)
# so we err on the side of caution here and trust Tc
# over T.
if current_tool_key not in reported_extruders:
# T and T0 are present, but Tc is missing - copy
# T to Tc
result[current_tool_key] = result["T"]
# throw away T, it's redundant (now)
del result["T"]
else:
# So T is there, but T0 isn't. That looks like Smoothieware which
# always reports the first extruder T0 as T:
#
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result["T0"] = result["T"]
del result["T"]
else:
# We only have T. That can mean two things:
#
# * we only have one extruder at all, or
# * we are currently parsing a response to M109/M190, which on
# some firmwares doesn't report the full M105 output while
# waiting for the target temperature to be reached but only
# reports the current tool and bed
#
# In both cases it is however safe to just move our T over
# to Tc in the parsed data, current should always stay
# 0 for single extruder printers. E.g. for current_tool == 1:
#
# T:<T1>
#
# becomes
#
# T1:<T1>
result[current_tool_key] = result["T"]
del result["T"]
return result
def _validate_m20_timestamp(timestamp):
try:
m20_timestamp_to_unix_timestamp(timestamp)
except ValueError:
return False
return True
def parse_file_list_line(line):
longname = None
size = None
timestamp = None
fileinfo = line.split(None, 3)
if len(fileinfo) == 4:
# name, size, timestamp, long name or name, size, long name with spaces
filename, size, timestamp, longname = fileinfo
if not _validate_m20_timestamp(timestamp):
# longname with spaces. Split line again with twice split limit to get longname right in case
# of multiple whitespace characters in it.
filename, size, longname = line.split(None, 2)
timestamp = None
elif len(fileinfo) == 3:
# name, size, long name or name, size, timestamp
filename, size, third = fileinfo
if _validate_m20_timestamp(third):
timestamp = third
else:
longname = third
elif len(fileinfo) == 2:
# name, size
filename, size = fileinfo
else:
# name
filename = line
if size is not None:
try:
size = int(size)
except ValueError:
# whatever that was, it was not an integer, so we'll just use the whole line as filename and set size/timestamp/longname to None
filename = line
size = None
timestamp = None
longname = None
else:
if timestamp is not None:
# size was valid and we have timestamp, so try to use it
try:
timestamp = m20_timestamp_to_unix_timestamp(timestamp)
except ValueError:
timestamp = None
if longname is not None:
if longname[0] == '"' and longname[-1] == '"':
# apparently some firmwares enclose the long name in quotes...
longname = longname[1:-1]
return (filename, size, timestamp, longname)
def parse_temperature_line(line, current):
"""
Parses the provided temperature line.
The result will be a dictionary mapping from the extruder or bed key to
a tuple with current and target temperature. The result will be canonicalized
with :func:`canonicalize_temperatures` before returning.
Arguments:
line (str): the temperature line to parse
current (int): the current active extruder
Returns:
tuple: a 2-tuple with the maximum tool number and a dict mapping from
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
"""
result = {}
max_tool_num = 0
for match in re.finditer(regex_temp, line):
values = match.groupdict()
sensor = values["sensor"]
if sensor in result:
# sensor already seen, let's not overwrite stuff
continue
toolnum = values.get("toolnum", None)
tool_number = int(toolnum) if toolnum is not None and len(toolnum) else None
if tool_number and tool_number > max_tool_num:
max_tool_num = tool_number
try:
actual = float(values["actual"])
target = None
if values["target"]:
target = float(values["target"])
result[sensor] = (actual, target)
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
return max(max_tool_num, current), canonicalize_temperatures(result, current)
def parse_firmware_line(line):
"""
Parses the provided firmware info line.
The result will be a dictionary mapping from the contained keys to the contained
values.
Valid keys must only contain A-Z, 0-9 and _ and must start with a letter. See the
unit tests for valid and invalid examples. There sadly is no existing specification
of the key format, but this is the format extracted from real life logs.
Arguments:
line (str): the line to parse
Returns:
dict: a dictionary with the parsed data
"""
if line.startswith("NAME."):
# Good job Malyan. Why use a : when you can also just use a ., right? Let's revert that.
line = list(line)
line[4] = ":"
line = "".join(line)
result = {}
split_line = regex_firmware_splitter.split(line.strip())[
1:
] # first entry is empty start of trimmed string
for _, key, value in chunks(split_line, 3):
result[key] = value.strip()
return result
def parse_capability_line(line):
"""
Parses the provided firmware capability line.
Lines are expected to be of the format
Cap:<capability name in caps>:<0 or 1>
e.g.
Cap:AUTOREPORT_TEMP:1
Cap:TOGGLE_LIGHTS:0
Args:
line (str): the line to parse
Returns:
tuple: a 2-tuple of the parsed capability name and whether it's on (true) or off (false), or None if the line
could not be parsed
"""
line = line.lower()
if line.startswith("cap:"):
line = line[len("cap:") :]
parts = line.split(":")
if len(parts) != 2:
# wrong format, can't parse this
return None
capability, flag = parts
if flag not in ("0", "1"):
# wrong format, can't parse this
return None
return capability.upper(), flag == "1"
def parse_resend_line(line):
"""
Parses the provided resend line and returns requested line number.
Args:
line (str): the line to parse
Returns:
int or None: the extracted line number to resend, or None if no number could be extracted
"""
match = regex_resend_linenumber.search(line)
if match is not None:
return int(match.group("n"))
return None
def parse_position_line(line):
"""
Parses the provided M114 response line and returns the parsed coordinates.
Args:
line (str): the line to parse
Returns:
dict or None: the parsed coordinates, or None if no coordinates could be parsed
"""
match = regex_position.search(line)
if match is not None:
result = {
"x": float(match.group("x")),
"y": float(match.group("y")),
"z": float(match.group("z")),
}
if match.group("e") is not None:
# report contains only one E
result["e"] = float(match.group("e"))
elif match.group("es") is not None:
# report contains individual entries for multiple extruders ("E0:... E1:... E2:...")
es = match.group("es")
for m in regex_e_positions.finditer(es):
result["e{}".format(m.group("id"))] = float(m.group("value"))
else:
# apparently no E at all, should never happen but let's still handle this
return None
return result
return None
def gcode_command_for_cmd(cmd):
"""
Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
Arguments:
cmd (str): The command to try to parse.
Returns:
str or None: The GCODE command identifier if it could be parsed, or None if not.
"""
gcode, _ = gcode_and_subcode_for_cmd(cmd)
return gcode
def gcode_and_subcode_for_cmd(cmd):
if not cmd:
return None, None
match = regex_command.search(cmd)
if not match:
return None, None
values = match.groupdict()
if "codeGM" in values and values["codeGM"]:
gcode = values["codeGM"]
elif "codeT" in values and values["codeT"]:
gcode = values["codeT"]
elif (
settings().getBoolean(["serial", "supportFAsCommand"])
and "codeF" in values
and values["codeF"]
):
gcode = values["codeF"]
else:
# this should never happen
return None, None
return gcode, values.get("subcode", None)
def _normalize_command_handler_result(
command, command_type, gcode, subcode, tags, handler_results, tags_to_add=None
):
"""
Normalizes a command handler result.
Handler results can be either ``None``, a single result entry or a list of result
entries.
``None`` results are ignored, the provided ``command``, ``command_type``,
``gcode``, ``subcode`` and ``tags`` are returned in that case (as single-entry list with
one 5-tuple as entry).
Single result entries are either:
* a single string defining a replacement ``command``
* a 1-tuple defining a replacement ``command``
* a 2-tuple defining a replacement ``command`` and ``command_type``
* a 3-tuple defining a replacement ``command`` and ``command_type`` and additional ``tags`` to set
A ``command`` that is ``None`` will lead to the entry being ignored for
the normalized result.
The method returns a list of normalized result entries. Normalized result
entries always are a 4-tuple consisting of ``command``, ``command_type``,
``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
be empty in which case the command is to be suppressed.
Examples:
>>> _normalize_command_handler_result("M105", None, "M105", None, None, None)
[('M105', None, 'M105', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, "M110")
[('M110', None, 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110"])
[('M110', None, 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", "M117 Foobar"])
[('M110', None, 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), "M117 Foobar"])
[('M110', None, 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110", "lineno_reset"), "M117 Foobar"])
[('M110', 'lineno_reset', 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [])
[]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", None])
[('M110', None, 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), (None, "ignored")])
[('M110', None, 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")])
[('M110', None, 'M110', None, None), ('M117 Foobar', 'display_message', 'M117', None, None), ('M110', 'lineno_reset', 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M117 Foobar"])
[('M110', None, 'M110', None, {'tag1', 'tag2'}), ('M117 Foobar', None, 'M117', None, {'tag1', 'tag2'})]
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M105", "M117 Foobar"], tags_to_add={"tag3"})
[('M110', None, 'M110', None, {'tag1', 'tag2', 'tag3'}), ('M105', None, 'M105', None, {'tag1', 'tag2'}), ('M117 Foobar', None, 'M117', None, {'tag1', 'tag2', 'tag3'})]
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", ("M105", "temperature_poll"), "M117 Foobar"], tags_to_add={"tag3"})
[('M110', None, 'M110', None, {'tag1', 'tag2', 'tag3'}), ('M105', 'temperature_poll', 'M105', None, {'tag1', 'tag2', 'tag3'}), ('M117 Foobar', None, 'M117', None, {'tag1', 'tag2', 'tag3'})]
Arguments:
command (str or None): The command for which the handler result was
generated
command_type (str or None): The command type for which the handler
result was generated
gcode (str or None): The GCODE for which the handler result was
generated
subcode (str or None): The GCODE subcode for which the handler result
was generated
tags (set of str or None): The tags associated with the GCODE for which
the handler result was generated
handler_results: The handler result(s) to normalized. Can be either
a single result entry or a list of result entries.
tags_to_add (set of str or None): List of tags to add to expanded result
entries
Returns:
(list) - A list of normalized handler result entries, which are
5-tuples consisting of ``command``, ``command_type``, ``gcode``
``subcode`` and ``tags``, the latter three of which may be ``None``.
"""
original = (command, command_type, gcode, subcode, tags)
if handler_results is None:
# handler didn't return anything, we'll just continue
return [original]
if not isinstance(handler_results, list):
handler_results = [
handler_results,
]
result = []
for handler_result in handler_results:
# we iterate over all handler result entries and process each one
# individually here
if handler_result is None:
# entry is None, we'll ignore that entry and continue
continue
if tags:
# copy the tags
tags = set(tags)
if isinstance(handler_result, str):
# entry is just a string, replace command with it
command = handler_result
if command != original[0]:
# command changed, re-extract gcode and subcode and add tags if necessary
gcode, subcode = gcode_and_subcode_for_cmd(command)
if (
tags_to_add
and isinstance(tags_to_add, set)
and command != original[0]
):
if tags is None:
tags = set()
tags |= tags_to_add
result.append((command, command_type, gcode, subcode, tags))
elif isinstance(handler_result, tuple):
# entry is a tuple, extract command and command_type
hook_result_length = len(handler_result)
handler_tags = None
if hook_result_length == 1:
# handler returned just the command
(command,) = handler_result
elif hook_result_length == 2:
# handler returned command and command_type
command, command_type = handler_result
elif hook_result_length == 3:
# handler returned command, command type and additional tags
command, command_type, handler_tags = handler_result
else:
# handler returned a tuple of an unexpected length, ignore
# and continue
continue
if command is None:
# command is None, ignore it and continue
continue
if command != original[0] or command_type != original[2]:
# command or command_type changed, re-extract gcode and subcode and add tags if necessary
gcode, subcode = gcode_and_subcode_for_cmd(command)
if tags_to_add and isinstance(tags_to_add, set):
if tags is None:
tags = set()
tags |= tags_to_add
if handler_tags and isinstance(handler_tags, set):
# handler provided additional tags, add them
if tags is None:
tags = set()
tags |= handler_tags
result.append((command, command_type, gcode, subcode, tags))
# reset to original
command, command_type, gcode, subcode, tags = original
return result
class QueueMarker:
def __init__(self, callback):
self.callback = callback
def run(self):
if callable(self.callback):
try:
self.callback()
except Exception:
_logger.exception("Error while running callback of QueueMarker")
class SendQueueMarker(QueueMarker):
pass
class BufferedReadlineWrapper(wrapt.ObjectProxy):
def __init__(self, obj):
wrapt.ObjectProxy.__init__(self, obj)
self._buffered = bytearray()
def readline(self, terminator=serial.LF):
termlen = len(terminator)
timeout = serial.Timeout(self._timeout)
while not timeout.expired():
self._buffered += self.read(self.in_waiting)
# check for terminator, if it's there we have found our line
termpos = self._buffered.find(terminator)
if termpos >= 0:
# line: everything up to and incl. the terminator, buffered: rest
line = self._buffered[: termpos + termlen]
del self._buffered[: termpos + termlen]
return bytes(line)
if timeout.expired():
break
c = self.read(1)
if not c:
# EOF
break
self._buffered += c
return b""
# --- Test code for speed testing the comm layer via command line follows
def upload_cli():
"""
Usage: python -m octoprint.util.comm <port> <baudrate> <local path> <remote path>
Uploads <local path> to <remote path> on SD card of printer on port <port>, using baudrate <baudrate>.
"""
import sys
from octoprint.util import Object
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
# fetch port, baudrate, filename and target from commandline
if len(sys.argv) < 5:
print("Usage: comm.py <port> <baudrate> <local path> <target path>")
sys.exit(-1)
port = sys.argv[1]
baudrate = sys.argv[2]
path = sys.argv[3]
target = sys.argv[4]
# init settings & plugin manager
settings(init=True)
octoprint.plugin.plugin_manager(init=True)
# create dummy callback
class MyMachineComCallback(MachineComPrintCallback):
progress_interval = 1
def __init__(self, path, target):
self.finished = threading.Event()
self.finished.clear()
self.comm = None
self.error = False
self.started = False
self._path = path
self._target = target
self._state = None
def on_comm_file_transfer_started(self, filename, filesize, user=None):
# transfer started, report
_logger.info(f"Started file transfer of {filename}, size {filesize}B")
self.started = True
def on_comm_file_transfer_done(self, filename):
# transfer done, report, print stats and finish
_logger.info(f"Finished file transfer of {filename}")
self.finished.set()
def on_comm_state_change(self, state):
self._state = state
if state in (MachineCom.STATE_ERROR, MachineCom.STATE_CLOSED_WITH_ERROR):
# report and exit on errors
_logger.error("Error/closed with error, exiting.")
self.error = True
self.finished.set()
elif state in (MachineCom.STATE_OPERATIONAL,) and not self.started:
def run():
_logger.info(
"Looks like we are operational, waiting a bit for everything to settle"
)
time.sleep(15)
if (
self._state in (MachineCom.STATE_OPERATIONAL,)
and not self.started
):
# start transfer once we are operational
self.comm.startFileTransfer(
self._path, os.path.basename(self._path), self._target
)
thread = threading.Thread(target=run)
thread.daemon = True
thread.start()
callback = MyMachineComCallback(path, target)
# mock printer profile manager
profile = {"heatedBed": False, "extruder": {"count": 1, "sharedNozzle": False}}
printer_profile_manager = Object()
printer_profile_manager.get_current_or_default = lambda: profile
# initialize serial
comm = MachineCom(
port=port,
baudrate=baudrate,
callbackObject=callback,
printerProfileManager=printer_profile_manager,
)
callback.comm = comm
# wait for file transfer to finish
callback.finished.wait()
# close connection
comm.close()
_logger.info("Done, exiting...")
if __name__ == "__main__":
upload_cli()
| 266,176 | Python | .py | 5,932 | 29.744774 | 197 | 0.52287 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,908 | files.py | OctoPrint_OctoPrint/src/octoprint/util/files.py | __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
import datetime
import itertools
import logging
import os.path
import re
def _sfn_really_universal(name):
from octoprint.util.text import sanitize
### taken from pathvalidate library
_WINDOWS_RESERVED_FILE_NAMES = ("CON", "PRN", "AUX", "CLOCK$", "NUL") + tuple(
f"{name:s}{num:d}"
for name, num in itertools.product(("COM", "LPT"), range(1, 10))
)
_MACOS_RESERVED_FILE_NAMES = (":",)
result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_")
root, ext = os.path.splitext(result)
if root.upper() in (_WINDOWS_RESERVED_FILE_NAMES + _MACOS_RESERVED_FILE_NAMES):
root += "_"
return root + ext
def sanitize_filename(name, really_universal=False):
"""
Sanitizes the provided filename. Implementation differs between Python versions.
Under normal operation, ``pathvalidate.sanitize_filename`` will be used, leaving the
name as intact as possible while still being a legal file name under all operating
systems.
Behaviour can be changed by setting ``really_universal`` to ``True``. In this case,
the name will be ASCII-fied, using ``octoprint.util.text.sanitize`` with
safe chars ``-_.()[] `` and all spaces replaced by ``_``. This is the old behaviour.
In all cases, a single leading ``.`` will be removed (as it denotes hidden files
on *nix).
Args:
name: The file name to sanitize. Only the name, no path elements.
really_universal: If ``True``, the old method of sanitization will always
be used. Defaults to ``False``.
Returns:
the sanitized file name
"""
from octoprint.util import to_unicode
name = to_unicode(name)
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
from pathvalidate import sanitize_filename as sfn
if really_universal:
result = _sfn_really_universal(name)
else:
result = sfn(name)
return result.lstrip(".")
def get_dos_filename(
input, existing_filenames=None, extension=None, whitelisted_extensions=None, **kwargs
):
"""
Converts the provided input filename to a 8.3 DOS compatible filename. If ``existing_filenames`` is provided, the
conversion result will be guaranteed not to collide with any of the filenames provided thus.
Uses :func:`find_collision_free_name` internally.
Arguments:
input (string): The original filename incl. extension to convert to the 8.3 format.
existing_filenames (list): A list of existing filenames with which the generated 8.3 name must not collide.
Optional.
extension (string): The .3 file extension to use for the generated filename. If not provided, the extension of
the provided ``filename`` will simply be truncated to 3 characters.
whitelisted_extensions (list): A list of extensions on ``input`` that will be left as-is instead of
exchanging for ``extension``.
kwargs (dict): Additional keyword arguments to provide to :func:`find_collision_free_name`.
Returns:
string: A 8.3 compatible translation of the original filename, not colliding with the optionally provided
``existing_filenames`` and with the provided ``extension`` or the original extension shortened to
a maximum of 3 characters.
Raises:
ValueError: No 8.3 compatible name could be found that doesn't collide with the provided ``existing_filenames``.
Examples:
>>> get_dos_filename("test1234.gco")
'test1234.gco'
>>> get_dos_filename("test1234.gcode")
'test1234.gco'
>>> get_dos_filename("test12345.gco")
'test12~1.gco'
>>> get_dos_filename("Wölfe �.gcode")
'wolfe_~1.gco'
>>> get_dos_filename("💚.gcode")
'green_~1.gco'
>>> get_dos_filename("test1234.fnord", extension="gco")
'test1234.gco'
>>> get_dos_filename("auto0.g", extension="gco")
'auto0.gco'
>>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"])
'auto0.g'
>>> get_dos_filename(None)
>>> get_dos_filename("foo")
'foo'
"""
if input is None:
return None
input = sanitize_filename(input, really_universal=True)
if existing_filenames is None:
existing_filenames = []
if extension is not None:
extension = extension.lower()
if whitelisted_extensions is None:
whitelisted_extensions = []
filename, ext = os.path.splitext(input)
ext = ext.lower()
ext = ext[1:] if ext.startswith(".") else ext
if ext in whitelisted_extensions or extension is None:
extension = ext
return find_collision_free_name(filename, extension, existing_filenames, **kwargs)
def find_collision_free_name(filename, extension, existing_filenames, max_power=2):
"""
Tries to find a collision free translation of "<filename>.<extension>" to the 8.3 DOS compatible format,
preventing collisions with any of the ``existing_filenames``.
First strips all of ``."/\\[]:;=,`` from the filename and extensions, converts them to lower case and truncates
the ``extension`` to a maximum length of 3 characters.
If the filename is already equal or less than 8 characters in length after that procedure and "<filename>.<extension>"
are not contained in the ``existing_files``, that concatenation will be returned as the result.
If not, the following algorithm will be applied to try to find a collision free name::
set counter := power := 1
while counter < 10^max_power:
set truncated := substr(filename, 0, 6 - power + 1) + "~" + counter
set result := "<truncated>.<extension>"
if result is collision free:
return result
counter++
if counter >= 10 ** power:
power++
raise ValueError
This will basically -- for a given original filename of ``some_filename`` and an extension of ``gco`` -- iterate
through names of the format ``some_f~1.gco``, ``some_f~2.gco``, ..., ``some_~10.gco``, ``some_~11.gco``, ...,
``<prefix>~<n>.gco`` for ``n`` less than 10 ^ ``max_power``, returning as soon as one is found that is not colliding.
Arguments:
filename (string): The filename without the extension to convert to 8.3.
extension (string): The extension to convert to 8.3 -- will be truncated to 3 characters if it's longer than
that.
existing_filenames (list): A list of existing filenames to prevent name collisions with.
max_power (int): Limits the possible attempts of generating a collision free name to 10 ^ ``max_power``
variations. Defaults to 2, so the name generation will maximally reach ``<name>~99.<ext>`` before
aborting and raising an exception.
Returns:
string: A 8.3 representation of the provided original filename, ensured to not collide with the provided
``existing_filenames``
Raises:
ValueError: No collision free name could be found.
Examples:
>>> find_collision_free_name("test1234", "gco", [])
'test1234.gco'
>>> find_collision_free_name("test1234", "gcode", [])
'test1234.gco'
>>> find_collision_free_name("test12345", "gco", [])
'test12~1.gco'
>>> find_collision_free_name("test 123", "gco", [])
'test_123.gco'
>>> find_collision_free_name("test1234", "g o", [])
'test1234.g_o'
>>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"])
'test12~2.gco'
>>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]]
>>> find_collision_free_name("test12345", "gco", many_files)
'test1~10.gco'
>>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)]
>>> find_collision_free_name("test12345", "gco", many_more_files)
'test1~99.gco'
>>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"]
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one)
Traceback (most recent call last):
...
ValueError: Can't create a collision free filename
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3)
'test~100.gco'
"""
from octoprint.util import to_unicode
filename = to_unicode(filename)
extension = to_unicode(extension)
if filename.startswith("/"):
filename = filename[1:]
existing_filenames = [
to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames
]
def make_valid(text):
return re.sub(
r"\s+", "_", text.translate({ord(i): None for i in r".\"/\[]:;=,"})
).lower()
filename = make_valid(filename)
extension = make_valid(extension)
extension = extension[:3] if len(extension) > 3 else extension
full_name_format = "{filename}.{extension}" if extension else "{filename}"
result = full_name_format.format(filename=filename, extension=extension)
if len(filename) <= 8 and result not in existing_filenames:
# early exit
return result
counter = 1
power = 1
prefix_format = "{segment}~{counter}"
while counter < (10**max_power):
prefix = prefix_format.format(
segment=filename[: (6 - power + 1)], counter=str(counter)
)
result = full_name_format.format(filename=prefix, extension=extension)
if result not in existing_filenames:
return result
counter += 1
if counter >= 10**power:
power += 1
raise ValueError("Can't create a collision free filename")
def silent_remove(file):
"""
Silently removes a file. Does not raise an error if the file doesn't exist.
Arguments:
file (string): The path of the file to be removed
"""
try:
os.remove(file)
except OSError:
pass
def search_through_file(path, term, regex=False):
if regex:
pattern = term
else:
pattern = re.escape(term)
compiled = re.compile(pattern)
logger = logging.getLogger(__name__)
try:
try:
# try native grep
import sarge
result = sarge.capture_stderr(["grep", "-q", "-E", pattern, path])
if result.stderr.text:
logger.warning(
"Error raised by native grep, falling back to python "
"implementation: {}".format(result.stderr.text.strip())
)
return search_through_file_python(path, term, compiled)
return result.returncode == 0
except ValueError as exc:
if "Command not found" in str(exc):
return search_through_file_python(path, term, compiled)
else:
raise
except Exception:
logger.exception(
"Something unexpectedly went wrong while trying to "
"search for {} in {} via grep".format(term, path)
)
return False
def search_through_file_python(path, term, compiled):
with open(path, encoding="utf8", errors="replace") as f:
for line in f:
if term in line or compiled.match(term):
return True
return False
def unix_timestamp_to_m20_timestamp(unix_timestamp):
"""
Converts unix timestamp to "M20 T" format
which embeds date and time into 32bit int.
Upper 16 bit contain date, lower 16 bit contain time.
https://reprap.org/wiki/G-code#M20:_List_SD_card
Format derived from FAT filesystem timestamps:
https://wiki.osdev.org/FAT
Arguments:
unix_timestamp (int): Unix timestamp in seconds
Returns:
string: M20 T timestamp as hex string
"""
dt = datetime.datetime.fromtimestamp(unix_timestamp)
m20_date = dt.year - 1980 << 9 | dt.month << 5 | dt.day
m20_time = dt.hour << 11 | dt.minute << 5
m20_time |= (dt.second - (dt.second % 2)) // 2
return hex(m20_date << 16 | m20_time)
def m20_timestamp_to_unix_timestamp(timestamp):
"""
Converts "M20 T" timestamp to unix timestamp.
Upper 16 bit contain date, lower 16 bit contain time.
https://reprap.org/wiki/G-code#M20:_List_SD_card
Format derived from FAT filesystem timestamps:
https://wiki.osdev.org/FAT
Arguments:
timestamp (string): M20 T timestamp as hex string
Returns:
int: Unix timestamp in seconds
"""
# Only hex in 0xABC format is valid while int() accepts
# hex without 0x prefix, too.
if not timestamp.startswith("0x"):
raise ValueError("Invalid M20 T timestamp format")
timestamp = int(timestamp, 16)
dt = timestamp >> 16
day = dt & (1 << 5) - 1
month = (dt >> 5) & ((1 << 4) - 1)
year = ((dt >> 9) & (1 << 7) - 1) + 1980
d = datetime.date(year, month, day)
tm = timestamp & (2**16 - 1)
second = (tm & (1 << 5) - 1) * 2
minute = (tm >> 5) & ((1 << 6) - 1)
hour = (tm >> 11) & ((1 << 5) - 1)
t = datetime.time(hour, minute, second)
combined_dt = datetime.datetime.combine(d, t)
return int(combined_dt.timestamp())
| 13,559 | Python | .py | 297 | 37.969697 | 122 | 0.635177 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,909 | commandline.py | OctoPrint_OctoPrint/src/octoprint/util/commandline.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 queue
import re
import time
import warnings
from typing import List, Optional, Tuple, Union
import sarge
from octoprint.util import to_bytes, to_unicode
from octoprint.util.platform import CLOSE_FDS
# These regexes are based on the colorama package
# Author: Jonathan Hartley
# License: BSD-3 (https://github.com/tartley/colorama/blob/master/LICENSE.txt)
# Website: https://github.com/tartley/colorama/
_ANSI_CSI_PATTERN = (
"\001?\033\\[(\\??(?:\\d|;)*)([a-zA-Z])\002?" # Control Sequence Introducer
)
_ANSI_OSC_PATTERN = "\001?\033\\]((?:.|;)*?)(\x07)\002?" # Operating System Command
_ANSI_PATTERN = "|".join([_ANSI_CSI_PATTERN, _ANSI_OSC_PATTERN])
_ANSI_REGEX = re.compile(_ANSI_PATTERN)
def clean_ansi(line: Union[str, bytes]) -> Union[str, bytes]:
"""
Removes ANSI control codes from ``line``.
Note: This function also still supports an input of ``bytes``, leading to an
``output`` of ``bytes``. This if for reasons of backwards compatibility only,
should no longer be used and considered to be deprecated and to be removed in
a future version of OctoPrint. A warning will be logged.
Parameters:
line (str or bytes): the line to process
Returns:
(str or bytes) The line without any ANSI control codes
.. versionchanged:: 1.8.0
Usage as ``clean_ansi(line: bytes) -> bytes`` is now deprecated and will be removed
in a future version of OctoPrint.
"""
# TODO: bytes support is deprecated, remove in 2.0.0
if isinstance(line, bytes):
warnings.warn(
"Calling clean_ansi with bytes is deprecated, call with str instead",
DeprecationWarning,
stacklevel=2,
)
return to_bytes(_ANSI_REGEX.sub("", to_unicode(line)))
return _ANSI_REGEX.sub("", line)
class CommandlineError(Exception):
"""
Raised by :py:func:`~octoprint.util.commandline.CommandLineCaller.checked_call` on non zero return codes
Arguments:
returncode (int): the return code of the command
stdout (str): the stdout output produced by the command
stderr (str): the stderr output produced by the command
"""
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
class CommandlineCaller:
"""
The CommandlineCaller is a utility class that allows running command line commands while logging their stdout
and stderr via configurable callback functions.
Callbacks are expected to have a signature matching
.. code-block:: python
def callback(*lines):
do_something_with_the_passed_lines()
The class utilizes sarge underneath.
Example:
.. code-block:: python
from octoprint.util.commandline import CommandLineCaller, CommandLineError
def log(prefix, *lines):
for line in lines:
print("{} {}".format(prefix, line))
def log_stdout(*lines):
log(">>>", *lines)
def log_stderr(*lines):
log("!!!", *lines)
def log_call(*lines)
log("---", *lines)
caller = CommandLineCaller()
caller.on_log_call = log_call
caller.on_log_stdout = log_stdout
caller.on_log_stderr = log_stderr
try:
caller.checked_call(["some", "command", "with", "parameters"])
except CommandLineError as err:
print("Command returned {}".format(err.returncode))
else:
print("Command finished successfully")
"""
def __init__(self):
self._logger = logging.getLogger(__name__)
self.on_log_call = lambda *args, **kwargs: None
"""Callback for the called command line"""
self.on_log_stdout = lambda *args, **kwargs: None
"""Callback for stdout output"""
self.on_log_stderr = lambda *args, **kwargs: None
"""Callback for stderr output"""
def checked_call(
self, command: Union[str, List[str], Tuple[str]], **kwargs
) -> Tuple[int, List[str], List[str]]:
"""
Calls a command and raises an error if it doesn't return with return code 0
Args:
command (list, tuple or str): command to call
kwargs (dict): additional keyword arguments to pass to the sarge ``run`` call (note that ``_async``,
``stdout`` and ``stderr`` will be overwritten)
Returns:
(tuple) a 3-tuple of return code, full stdout and full stderr output
Raises:
CommandlineError
"""
returncode, stdout, stderr = self.call(command, **kwargs)
if returncode != 0:
raise CommandlineError(returncode, stdout, stderr)
return returncode, stdout, stderr
def call(
self,
command: Union[str, List[str], Tuple[str]],
delimiter: bytes = b"\n",
buffer_size: int = -1,
logged: bool = True,
output_timeout: float = 0.5,
**kwargs,
) -> Tuple[Optional[int], List[str], List[str]]:
"""
Calls a command
Args:
command (list, tuple or str): command to call
kwargs (dict): additional keyword arguments to pass to the sarge ``run`` call (note that ``_async``,
``stdout`` and ``stderr`` will be overwritten)
Returns:
(tuple) a 3-tuple of return code, full stdout and full stderr output
"""
p = self.non_blocking_call(
command, delimiter=delimiter, buffer_size=buffer_size, logged=logged, **kwargs
)
if p is None:
return None, [], []
all_stdout = []
all_stderr = []
def process_lines(lines, logger):
if not lines:
return []
processed = self._preprocess_lines(
*map(lambda x: to_unicode(x, errors="replace"), lines)
)
if logged:
logger(*processed)
return list(processed)
def process_stdout(lines):
return process_lines(lines, self._log_stdout)
def process_stderr(lines):
return process_lines(lines, self._log_stderr)
try:
# read lines from stdout and stderr until the process is finished
while p.commands[0].poll() is None:
# this won't be a busy loop, the readline calls will block up to the timeout
all_stderr += process_stderr(p.stderr.readlines(timeout=output_timeout))
all_stdout += process_stdout(p.stdout.readlines(timeout=output_timeout))
finally:
p.close()
all_stderr += process_stderr(p.stderr.readlines())
all_stdout += process_stdout(p.stdout.readlines())
return p.returncode, all_stdout, all_stderr
def non_blocking_call(
self,
command: Union[str, List, Tuple],
delimiter: bytes = b"\n",
buffer_size: int = -1,
logged: bool = True,
**kwargs,
) -> Optional[sarge.Pipeline]:
if isinstance(command, (list, tuple)):
joined_command = " ".join(command)
else:
joined_command = command
self._logger.debug(f"Calling: {joined_command}")
if logged:
self.on_log_call(joined_command)
kwargs.update(
{
"close_fds": CLOSE_FDS,
"async_": True,
"stdout": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
"stderr": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
}
)
p = sarge.run(command, **kwargs)
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
if not p.commands[0].process:
# the process might have been set to None in case of any exception
self._logger.error(f"Error while trying to run command {joined_command}")
return None
return p
def _log_stdout(self, *lines):
self.on_log_stdout(*lines)
def _log_stderr(self, *lines):
self.on_log_stderr(*lines)
def _preprocess_lines(self, *lines):
return lines
class DelimiterCapture(sarge.Capture):
def __init__(self, delimiter=b"\n", *args, **kwargs):
self._delimiter = delimiter
sarge.Capture.__init__(self, *args, **kwargs)
def readline(self, size=-1, block=True, timeout=None):
if not self.streams_open():
block = False
timeout = None
else:
timeout = timeout or self.timeout
if self.current is None:
try:
self.current = self.buffer.get(block, timeout)
except queue.Empty:
self.current = b""
while self._delimiter not in self.current:
try:
self.current += self.buffer.get(block, timeout)
except queue.Empty:
break
if self._delimiter not in self.current:
result = self.current
self.current = None
else:
i = self.current.index(self._delimiter)
if 0 < size < i:
i = size - 1
result = self.current[: i + 1]
self.current = self.current[i + 1 :]
return result
| 9,955 | Python | .py | 239 | 32.322176 | 113 | 0.604748 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,910 | version.py | OctoPrint_OctoPrint/src/octoprint/util/version.py | """
This module provides a bunch of utility methods and helpers for version handling.
"""
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
import logging
import pkg_resources
from octoprint import __version__
def get_octoprint_version_string():
return __version__
def get_octoprint_version(cut=None, **kwargs):
octoprint_version_string = normalize_version(get_octoprint_version_string())
return get_comparable_version(octoprint_version_string, cut=cut, **kwargs)
def is_released_octoprint_version(version=None):
if version is None:
version = get_octoprint_version()
return is_release(version)
def is_stable_octoprint_version(version=None):
if version is None:
version = get_octoprint_version()
return is_stable(version)
def is_octoprint_compatible(*compatibility_entries, **kwargs):
"""
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
Arguments:
compatibility_entries (str): compatibility string(s) to test against, result will be `True` if any match
is found
octoprint_version (tuple or SetuptoolsVersion): optional OctoPrint version to match against, if not current
base version will be determined via :func:`get_octoprint_version`.
Returns:
(bool) ``True`` if any of the provided compatibility entries matches or there are no entries, else ``False``
"""
logger = logging.getLogger(__name__)
if not compatibility_entries:
return True
octoprint_version = kwargs.get("octoprint_version")
if octoprint_version is None:
octoprint_version = get_octoprint_version(base=True)
for octo_compat in compatibility_entries:
try:
if not any(
octo_compat.startswith(c)
for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")
):
octo_compat = f">={octo_compat}"
s = pkg_resources.Requirement.parse("OctoPrint" + octo_compat)
if octoprint_version in s:
break
except Exception:
logger.exception(
"Something is wrong with this compatibility string for OctoPrint: {}".format(
octo_compat
)
)
else:
return False
return True
def get_python_version_string():
from platform import python_version
version_string = normalize_version(python_version())
return version_string
def get_python_version():
return get_comparable_version(get_python_version_string())
def is_python_compatible(compat, **kwargs):
if not compat:
return True
python_version = kwargs.get("python_version")
if python_version is None:
python_version = get_python_version_string()
s = pkg_resources.Requirement.parse("Python" + compat)
return python_version in s
def get_comparable_version(version_string, cut=None, **kwargs):
"""
Args:
version_string: The version string for which to create a comparable version instance
cut: optional, how many version digits to remove (e.g., cut=1 will turn 1.2.3 into 1.2).
Defaults to ``None``, meaning no further action. Settings this to 0 will remove
anything up to the last digit, e.g. dev or rc information.
Returns:
A comparable version
"""
if "base" in kwargs and kwargs.get("base", False) and cut is None:
cut = 0
if cut is not None and (cut < 0 or not isinstance(cut, int)):
raise ValueError("level must be a positive integer")
version_string = normalize_version(version_string)
version = pkg_resources.parse_version(version_string)
if cut is not None:
if isinstance(version, tuple):
# old setuptools
base_version = []
for part in version:
if part.startswith("*"):
break
base_version.append(part)
if 0 < cut < len(base_version):
base_version = base_version[:-cut]
base_version.append("*final")
version = tuple(base_version)
else:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
if cut is not None:
parts = version.base_version.split(".")
if 0 < cut < len(parts):
reduced = parts[:-cut]
version = pkg_resources.parse_version(
".".join(str(x) for x in reduced)
)
return version
def is_stable(version):
"""
>>> import pkg_resources
>>> is_stable(pkg_resources.parse_version("1.3.6rc3"))
False
>>> is_stable(pkg_resources.parse_version("1.3.6rc3.dev2+g1234"))
False
>>> is_stable(pkg_resources.parse_version("1.3.6"))
True
>>> is_stable(pkg_resources.parse_version("1.3.6.post1+g1234"))
True
>>> is_stable(pkg_resources.parse_version("1.3.6.post1.dev0+g1234"))
False
>>> is_stable(pkg_resources.parse_version("1.3.7.dev123+g23545"))
False
"""
if isinstance(version, str):
version = get_comparable_version(version)
if not is_release(version):
return False
if isinstance(version, tuple):
return "*a" not in version and "*b" not in version and "*c" not in version
else:
return not version.is_prerelease
def is_release(version):
"""
>>> import pkg_resources
>>> is_release(pkg_resources.parse_version("1.3.6rc3"))
True
>>> is_release(pkg_resources.parse_version("1.3.6rc3.dev2+g1234"))
False
>>> is_release(pkg_resources.parse_version("1.3.6"))
True
>>> is_release(pkg_resources.parse_version("1.3.6.post1+g1234"))
True
>>> is_release(pkg_resources.parse_version("1.3.6.post1.dev0+g1234"))
False
>>> is_release(pkg_resources.parse_version("1.3.7.dev123+g23545"))
False
"""
if isinstance(version, str):
version = get_comparable_version(version)
if isinstance(version, tuple):
# old setuptools
return "*@" not in version
else:
# new setuptools
return "dev" not in version.public
pass
def is_prerelease(version):
if isinstance(version, str):
version = get_comparable_version(version)
if isinstance(version, tuple):
# old setuptools
return any(map(lambda x: x in version, ("*a", "*b", "*c", "*rc")))
else:
# new setuptools
return version.is_prerelease
def normalize_version(version):
# Debian has the python version set to 2.7.15+ which is not PEP440 compliant (bug 914072)
if version.endswith("+"):
version = version[:-1]
if version[0].lower() == "v":
version = version[1:]
return version.strip()
| 6,927 | Python | .py | 174 | 31.770115 | 120 | 0.632129 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,911 | pip.py | OctoPrint_OctoPrint/src/octoprint/util/pip.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 site
import sys
import threading
from typing import List
import pkg_resources
import sarge
from octoprint.util.platform import CLOSE_FDS
from .commandline import CommandlineCaller, clean_ansi
_cache = {"version": {}, "setup": {}}
_cache_mutex = threading.RLock()
OUTPUT_SUCCESS = "Successfully installed"
"""Start of successful result line"""
OUTPUT_FAILURE = "Could not install"
"""Start of failure result line"""
OUTPUT_ERROR = "ERROR:"
"""Start of error line"""
OUTPUT_ALREADY_INSTALLED = "Requirement already satisfied"
"""Start of a line indicating some package was already installed in this version"""
OUTPUT_PYTHON_MISMATCH = "requires a different Python:"
"""Line segment indicating a mismatch of python_requires version"""
OUTPUT_PYTHON_SYNTAX = "SyntaxError: invalid syntax"
"""Line segment indicating a syntax error, could be a python mismatch, e.g. f-strings"""
OUTPUT_POTENTIAL_EGG_PROBLEM_POSIX = "No such file or directory"
"""Line indicating a potential egg problem on Posix"""
OUTPUT_POTENTIAL_EGG_PROBLEM_WINDOWS = "The system cannot find the file specified"
"""Line indicating a potential egg problem on Windows"""
def is_already_installed(lines):
"""
Returns whether the given output lines indicates the packages was already installed
or not.
This is currently determined by an empty result line and any line starting with
"Requirement already satisfied".
Args:
lines (list of str): the output to parse, stdout or stderr
Returns:
bool: True if detected, False otherwise
"""
result_line = get_result_line(lines) # neither success nor failure reported
return (
not result_line
and not any(line.strip().startswith(OUTPUT_ERROR) for line in lines)
and any(line.strip().startswith(OUTPUT_ALREADY_INSTALLED) for line in lines)
)
def is_python_mismatch(lines):
"""
Returns whether the given output lines indicates a Python version mismatch.
This is currently determined by either a syntax error or an explicit "requires a
different Python" line.
Args:
lines (list of str): the output to parse, stdout or stderr
Returns:
bool: True if detected, False otherwise
"""
return any(
OUTPUT_PYTHON_MISMATCH in line or OUTPUT_PYTHON_SYNTAX in line for line in lines
)
def is_egg_problem(lines):
"""
Returns whether the given output lines indicates an occurrence of the "egg-problem".
If something (target or dependency of target) was installed as an egg at an earlier
date (e.g. thanks to just running python setup.py install), pip install will throw an
error after updating that something to a newer (non-egg) version since it will still
have the egg on its sys.path and expect to read data from it.
See commit 8ad0aadb52b9ef354cad1b33bd4882ae2fbdb8d6 for more details.
Args:
lines (list of str): the output to parse, stdout or stderr
Returns:
bool: True if detected, False otherwise
"""
return any(
".egg" in line
and (
OUTPUT_POTENTIAL_EGG_PROBLEM_POSIX in line
or OUTPUT_POTENTIAL_EGG_PROBLEM_WINDOWS in line
)
for line in lines
)
def get_result_line(lines):
"""
Returns the success or failure line contained in the output.
pip might generate more lines after the actual result line, which is why
we can't just take the final line. So instead we look for the last line
starting with either "Successfully installed" or "Could not install".
If neither can be found, an empty string will be returned, which should also
be considered a failure to install.
Args:
lines (list of str): the output to parse, stdout or stderr
Returns:
str: the last result line, or an empty string if none was found, in which case
failure should be resumed
"""
possible_results = list(
filter(
lambda x: x.startswith(OUTPUT_SUCCESS) or x.startswith(OUTPUT_FAILURE),
lines,
)
)
if not possible_results:
return ""
return possible_results[-1]
class UnknownPip(Exception):
pass
class PipCaller(CommandlineCaller):
process_dependency_links = pkg_resources.Requirement.parse("pip>=1.5")
no_cache_dir = pkg_resources.Requirement.parse("pip>=1.6")
disable_pip_version_check = pkg_resources.Requirement.parse("pip>=6.0")
no_use_wheel = pkg_resources.Requirement.parse("pip==1.5.0")
broken = pkg_resources.Requirement.parse("pip>=6.0.1,<=6.0.3")
@classmethod
def clean_install_command(cls, args, pip_version, virtual_env, use_user, force_user):
logger = logging.getLogger(__name__)
args = list(args)
# strip --process-dependency-links for versions that don't support it
if (
pip_version not in cls.process_dependency_links
and "--process-dependency-links" in args
):
logger.debug(
"Found --process-dependency-links flag, version {} doesn't need that yet though, removing.".format(
pip_version
)
)
args.remove("--process-dependency-links")
# strip --no-cache-dir for versions that don't support it
if pip_version not in cls.no_cache_dir and "--no-cache-dir" in args:
logger.debug(
"Found --no-cache-dir flag, version {} doesn't support that yet though, removing.".format(
pip_version
)
)
args.remove("--no-cache-dir")
# strip --disable-pip-version-check for versions that don't support it
if (
pip_version not in cls.disable_pip_version_check
and "--disable-pip-version-check" in args
):
logger.debug(
"Found --disable-pip-version-check flag, version {} doesn't support that yet though, removing.".format(
pip_version
)
)
args.remove("--disable-pip-version-check")
# add --no-use-wheel for versions that otherwise break
if pip_version in cls.no_use_wheel and "--no-use-wheel" not in args:
logger.debug(f"Version {pip_version} needs --no-use-wheel to properly work.")
args.append("--no-use-wheel")
# remove --user if it's present and a virtual env is detected
if "--user" in args:
if virtual_env or not site.ENABLE_USER_SITE:
logger.debug("Virtual environment detected, removing --user flag.")
args.remove("--user")
# otherwise add it if necessary
elif not virtual_env and site.ENABLE_USER_SITE and (use_user or force_user):
logger.debug("pip needs --user flag for installations.")
args.append("--user")
return args
def __init__(
self, configured=None, ignore_cache=False, force_sudo=False, force_user=False
):
CommandlineCaller.__init__(self)
self._logger = logging.getLogger(__name__)
self.configured = configured
self.refresh = False
self.ignore_cache = ignore_cache
self.force_sudo = force_sudo
self.force_user = force_user
self._command = None
self._version = None
self._version_string = None
self._use_sudo = False
self._use_user = False
self._virtual_env = False
self._install_dir = None
self.trigger_refresh()
self.on_log_call = lambda *args, **kwargs: None
self.on_log_stdout = lambda *args, **kwargs: None
self.on_log_stderr = lambda *args, **kwargs: None
def _reset(self):
self._command = None
self._version = None
self._version_string = None
self._use_sudo = False
self._use_user = False
self._install_dir = None
def __le__(self, other):
return self.version is not None and self.version <= other
def __lt__(self, other):
return self.version is not None and self.version < other
def __ge__(self, other):
return self.version is not None and self.version >= other
def __gt__(self, other):
return self.version is not None and self.version > other
@property
def command(self):
return self._command
@property
def version(self):
return self._version
@property
def version_string(self):
return self._version_string
@property
def install_dir(self):
return self._install_dir
@property
def use_sudo(self):
return self._use_sudo
@property
def use_user(self):
return self._use_user
@property
def virtual_env(self):
return self._virtual_env
@property
def available(self):
return self._command is not None
def trigger_refresh(self):
self._reset()
try:
self._setup_pip()
except Exception:
self._logger.exception("Error while discovering pip command")
self._command = None
self._version = None
self.refresh = False
def execute(self, *args, **kwargs):
if self.refresh:
self.trigger_refresh()
if self._command is None:
raise UnknownPip()
arg_list = list(args)
if "install" in arg_list:
arg_list = self.clean_install_command(
arg_list, self.version, self._virtual_env, self.use_user, self.force_user
)
# add args to command
if isinstance(self._command, list):
command = self._command + list(arg_list)
else:
command = [self._command] + list(arg_list)
# add sudo if necessary
if self._use_sudo or self.force_sudo:
command = ["sudo"] + command
return self.call(command, **kwargs)
def _setup_pip(self):
pip_command, pip_sudo = self._get_pip_command()
if pip_command is None:
return
# Determine the pip version
self._logger.debug("Going to figure out pip's version")
pip_version, version_segment = self._get_pip_version(pip_command)
if pip_version is None:
return
if pip_version in self.__class__.broken:
self._logger.error(
"This version of pip is known to have bugs that make it incompatible with how it needs "
"to be used by OctoPrint. Please upgrade your pip version."
)
return
# Now figure out if pip belongs to a virtual environment and if the
# default installation directory is writable.
#
# The idea is the following: If OctoPrint is installed globally,
# the site-packages folder is probably not writable by our user.
# However, the user site-packages folder as usable by providing the
# --user parameter during install is. This we may not use though if
# the provided pip belongs to a virtual env (since that hiccups hard).
#
# So we figure out the installation directory, check if it's writable
# and if not if pip belongs to a virtual environment. Only if the
# installation directory is NOT writable by us but we also don't run
# in a virtual environment may we proceed with the --user parameter.
ok, pip_user, pip_virtual_env, pip_install_dir = self._check_pip_setup(
pip_command
)
if not ok:
if pip_install_dir:
self._logger.error(
"Cannot use this pip install, can't write to the install dir and also can't use "
"--user for installing. Check your setup and the permissions on {}.".format(
pip_install_dir
)
)
else:
self._logger.error(
"Cannot use this pip install, something's wrong with the python environment. "
"Check the lines before."
)
return
self._command = pip_command
self._version = pip_version
self._version_string = version_segment
self._use_sudo = pip_sudo
self._use_user = pip_user
self._virtual_env = pip_virtual_env
self._install_dir = pip_install_dir
def _get_pip_command(self):
pip_command = self.configured
if pip_command is not None and pip_command.startswith("sudo "):
pip_command = pip_command[len("sudo ") :]
pip_sudo = True
else:
pip_sudo = False
if pip_command is None:
pip_command = self.autodetect_pip()
return pip_command, pip_sudo
@classmethod
def autodetect_pip(cls):
commands = [
[sys.executable, "-m", "pip"],
[
os.path.join(
os.path.dirname(sys.executable),
"pip.exe" if sys.platform == "win32" else "pip",
)
],
# this should be our last resort since it might fail thanks to using pip programmatically like
# that is not officially supported or sanctioned by the pip developers
[
sys.executable,
"-c",
"import sys; sys.argv = ['pip'] + sys.argv[1:]; import pip; pip.main()",
],
]
for command in commands:
p = sarge.run(
command + ["--version"],
close_fds=CLOSE_FDS,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
)
if p.returncode == 0:
logging.getLogger(__name__).info(
'Using "{}" as command to invoke pip'.format(" ".join(command))
)
return command
return None
@classmethod
def to_sarge_command(cls, pip_command, *args):
if isinstance(pip_command, list):
sarge_command = pip_command
else:
sarge_command = [pip_command]
return sarge_command + list(args)
def _get_pip_version(self, pip_command):
# Debugging this with PyCharm/IntelliJ with Python plugin and no output is being
# generated? PyCharm bug. Disable "Attach to subprocess automatically when debugging"
# in IDE Settings or patch pydevd.py
# -> https://youtrack.jetbrains.com/issue/PY-18365#comment=27-1290453
pip_command_str = pip_command
if isinstance(pip_command_str, list):
pip_command_str = " ".join(pip_command_str)
with _cache_mutex:
if not self.ignore_cache and pip_command_str in _cache["version"]:
self._logger.debug(
f"Using cached pip version information for {pip_command_str}"
)
return _cache["version"][pip_command_str]
sarge_command = self.to_sarge_command(pip_command, "--version")
p = sarge.run(
sarge_command,
close_fds=CLOSE_FDS,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
)
if p.returncode != 0:
self._logger.warning(
f"Error while trying to run pip --version: {p.stderr.text}"
)
return None, None
output = PipCaller._preprocess(p.stdout.text)
# output should look something like this:
#
# pip <version> from <path> (<python version>)
#
# we'll just split on whitespace and then try to use the second entry
if not output.startswith("pip"):
self._logger.warning(
"pip command returned unparsable output, can't determine version: {}".format(
output
)
)
split_output = list(map(lambda x: x.strip(), output.split()))
if len(split_output) < 2:
self._logger.warning(
"pip command returned unparsable output, can't determine version: {}".format(
output
)
)
version_segment = split_output[1]
try:
pip_version = pkg_resources.parse_version(version_segment)
except Exception:
self._logger.exception(
"Error while trying to parse version string from pip command"
)
return None, None
self._logger.info(f"Version of pip is {version_segment}")
result = pip_version, version_segment
_cache["version"][pip_command_str] = result
return result
def _check_pip_setup(self, pip_command):
pip_command_str = pip_command
if isinstance(pip_command_str, list):
pip_command_str = " ".join(pip_command_str)
with _cache_mutex:
if not self.ignore_cache and pip_command_str in _cache["setup"]:
self._logger.debug(
f"Using cached pip setup information for {pip_command_str}"
)
return _cache["setup"][pip_command_str]
# This is horribly ugly and I'm sorry...
#
# While we can figure out the install directory, if that's writable and if a virtual environment
# is active for pip that belongs to our sys.executable python instance by just checking some
# variables, we can't for stuff like third party software we allow to update via the software
# update plugin.
#
# What we do instead for these situations is try to install the testballoon dummy package, which
# collects that information for us. The install fails expectedly and pip prints the required
# information together with its STDOUT (until pip v19) or STDERR (from pip v20 on).
#
# Yeah, I'm not happy with that either. But as long as there's no way to otherwise figure
# out for a generic pip command whether OctoPrint can even install anything with that
# and if so how, well, that's how we'll have to do things.
import os
testballoon = os.path.join(
os.path.realpath(os.path.dirname(__file__)), "piptestballoon"
)
sarge_command = self.to_sarge_command(pip_command, "install", ".")
try:
# our testballoon is no real package, so this command will fail - that's ok though,
# we only need the output produced within the pip environment
p = sarge.run(
sarge_command,
close_fds=CLOSE_FDS,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
cwd=testballoon,
)
except Exception:
self._logger.exception(
"Error while trying to install testballoon to figure out pip setup"
)
return False, False, False, None
output = p.stdout.text + p.stderr.text
data = {}
for line in output.split("\n"):
if (
"PIP_INSTALL_DIR=" in line
or "PIP_VIRTUAL_ENV=" in line
or "PIP_WRITABLE=" in line
):
key, value = line.split("=", 2)
data[key.strip()] = value.strip()
install_dir_str = data.get("PIP_INSTALL_DIR", None)
virtual_env_str = data.get("PIP_VIRTUAL_ENV", None)
writable_str = data.get("PIP_WRITABLE", None)
if (
install_dir_str is not None
and virtual_env_str is not None
and writable_str is not None
):
install_dir = install_dir_str
virtual_env = virtual_env_str == "True"
writable = writable_str == "True"
can_use_user_flag = not virtual_env and site.ENABLE_USER_SITE
ok = writable or can_use_user_flag
user_flag = not writable and can_use_user_flag
self._logger.info(
"pip installs to {} (writable -> {}), --user flag needed -> {}, "
"virtual env -> {}".format(
install_dir,
"yes" if writable else "no",
"yes" if user_flag else "no",
"yes" if virtual_env else "no",
)
)
self._logger.info("==> pip ok -> {}".format("yes" if ok else "NO!"))
# ok, enable user flag, virtual env yes/no, installation dir
result = ok, user_flag, virtual_env, install_dir
_cache["setup"][pip_command_str] = result
return result
else:
self._logger.error(
"Could not detect desired output from testballoon install, got this instead: {!r}".format(
data
)
)
return False, False, False, None
def _preprocess_lines(self, *lines: List[str]) -> List[str]:
return list(map(self._preprocess, lines))
@staticmethod
def _preprocess(text: str) -> str:
"""
Strips ANSI and VT100 cursor control characters from line.
Parameters:
text (str): The text to process
Returns:
(str) The processed text, stripped of ANSI and VT100 cursor show/hide codes
Example::
>>> text = 'some text with some\x1b[?25h ANSI codes for \x1b[31mred words\x1b[39m and\x1b[?25l also some cursor control codes'
>>> PipCaller._preprocess(text)
'some text with some ANSI codes for red words and also some cursor control codes'
"""
return clean_ansi(text)
class LocalPipCaller(PipCaller):
"""
The LocalPipCaller always uses the pip instance associated with
sys.executable.
"""
def _get_pip_command(self):
return self.autodetect_pip(), False
def _check_pip_setup(self, pip_command):
import os
import sys
from distutils.sysconfig import get_python_lib
virtual_env = hasattr(sys, "real_prefix") or (
hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
)
install_dir = get_python_lib()
writable = os.access(install_dir, os.W_OK)
can_use_user_flag = not virtual_env and site.ENABLE_USER_SITE
user_flag = not writable and can_use_user_flag
ok = writable or can_use_user_flag
self._logger.info(
"pip installs to {} (writable -> {}), --user flag needed -> {}, "
"virtual env -> {}".format(
install_dir,
"yes" if writable else "no",
"yes" if user_flag else "no",
"yes" if virtual_env else "no",
)
)
self._logger.info("==> pip ok -> {}".format("yes" if ok else "NO!"))
return ok, user_flag, virtual_env, install_dir
def create_pip_caller(command=None, **kwargs):
if command is None:
return LocalPipCaller(**kwargs)
else:
return PipCaller(configured=command, **kwargs)
| 23,857 | Python | .py | 546 | 32.659341 | 138 | 0.589809 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,912 | tz.py | OctoPrint_OctoPrint/src/octoprint/util/tz.py | __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
import datetime
LOCAL_TZ = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
UTC_TZ = datetime.timezone.utc
def is_timezone_aware(dt: datetime.datetime) -> bool:
return dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None
| 342 | Python | .py | 6 | 54.666667 | 87 | 0.777108 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,913 | gcodeInterpreter.py | OctoPrint_OctoPrint/src/octoprint/util/gcodeInterpreter.py | __author__ = "Gina Häußge <osd@foosel.net> based on work by David Braam"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2013 David Braam, Gina Häußge - Released under terms of the AGPLv3 License"
import base64
import codecs
import io
import logging
import math
import os
import re
import zlib
class Vector3D:
"""
3D vector value
Supports addition, subtraction and multiplication with a scalar value (float, int) as well as calculating the
length of the vector.
Examples:
>>> a = Vector3D(1.0, 1.0, 1.0)
>>> b = Vector3D(4.0, 4.0, 4.0)
>>> a + b == Vector3D(5.0, 5.0, 5.0)
True
>>> b - a == Vector3D(3.0, 3.0, 3.0)
True
>>> abs(a - b) == Vector3D(3.0, 3.0, 3.0)
True
>>> a * 2 == Vector3D(2.0, 2.0, 2.0)
True
>>> a * 2 == 2 * a
True
>>> a.length == math.sqrt(a.x ** 2 + a.y ** 2 + a.z ** 2)
True
>>> copied_a = Vector3D(a)
>>> a == copied_a
True
>>> copied_a.x == a.x and copied_a.y == a.y and copied_a.z == a.z
True
"""
def __init__(self, *args):
if len(args) == 3:
(self.x, self.y, self.z) = args
elif len(args) == 1:
# copy constructor
other = args[0]
if not isinstance(other, Vector3D):
raise ValueError("Object to copy must be a Vector3D instance")
self.x = other.x
self.y = other.y
self.z = other.z
@property
def length(self):
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
def __add__(self, other):
try:
if len(other) == 3:
return Vector3D(self.x + other[0], self.y + other[1], self.z + other[2])
except TypeError:
# doesn't look like a 3-tuple
pass
try:
return Vector3D(self.x + other.x, self.y + other.y, self.z + other.z)
except AttributeError:
# also doesn't look like a Vector3D
pass
raise TypeError(
"other must be a Vector3D instance or a list or tuple of length 3"
)
def __sub__(self, other):
try:
if len(other) == 3:
return Vector3D(self.x - other[0], self.y - other[1], self.z - other[2])
except TypeError:
# doesn't look like a 3-tuple
pass
try:
return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z)
except AttributeError:
# also doesn't look like a Vector3D
pass
raise TypeError(
"other must be a Vector3D instance or a list or tuple of length 3"
)
def __mul__(self, other):
try:
return Vector3D(self.x * other, self.y * other, self.z * other)
except TypeError:
# doesn't look like a scalar
pass
raise ValueError("other must be a float or int value")
def __rmul__(self, other):
return self.__mul__(other)
def __abs__(self):
return Vector3D(abs(self.x), abs(self.y), abs(self.z))
def __eq__(self, other):
if not isinstance(other, Vector3D):
return False
return self.x == other.x and self.y == other.y and self.z == other.z
def __str__(self):
return "Vector3D(x={}, y={}, z={}, length={})".format(
self.x, self.y, self.z, self.length
)
class MinMax3D:
"""
Tracks minimum and maximum of recorded values
Examples:
>>> minmax = MinMax3D()
>>> minmax.record(Vector3D(2.0, 2.0, 2.0))
>>> minmax.min.x == 2.0 == minmax.max.x and minmax.min.y == 2.0 == minmax.max.y and minmax.min.z == 2.0 == minmax.max.z
True
>>> minmax.record(Vector3D(1.0, 2.0, 3.0))
>>> minmax.min.x == 1.0 and minmax.min.y == 2.0 and minmax.min.z == 2.0
True
>>> minmax.max.x == 2.0 and minmax.max.y == 2.0 and minmax.max.z == 3.0
True
>>> minmax.size == Vector3D(1.0, 0.0, 1.0)
True
>>> empty = MinMax3D()
>>> empty.size == Vector3D(0.0, 0.0, 0.0)
True
>>> weird = MinMax3D(min_z=-1.0)
>>> weird.record(Vector3D(2.0, 2.0, 2.0))
>>> weird.record(Vector3D(1.0, 2.0, 3.0))
>>> weird.min.z == -1.0
True
>>> weird.size == Vector3D(1.0, 0.0, 4.0)
True
"""
def __init__(
self,
min_x=None,
min_y=None,
min_z=None,
max_x=None,
max_y=None,
max_z=None,
):
min_x = min_x if min_x is not None else float("inf")
min_y = min_y if min_y is not None else float("inf")
min_z = min_z if min_z is not None else float("inf")
max_x = max_x if max_x is not None else -float("inf")
max_y = max_y if max_y is not None else -float("inf")
max_z = max_z if max_z is not None else -float("inf")
self.min = Vector3D(min_x, min_y, min_z)
self.max = Vector3D(max_x, max_y, max_z)
def record(self, coordinate):
"""
Records the coordinate, storing the min and max values.
The input vector components must not be None.
"""
self.min.x = min(self.min.x, coordinate.x)
self.min.y = min(self.min.y, coordinate.y)
self.min.z = min(self.min.z, coordinate.z)
self.max.x = max(self.max.x, coordinate.x)
self.max.y = max(self.max.y, coordinate.y)
self.max.z = max(self.max.z, coordinate.z)
@property
def size(self):
result = Vector3D()
for c in "xyz":
min = getattr(self.min, c)
max = getattr(self.max, c)
value = abs(max - min) if max >= min else 0.0
setattr(result, c, value)
return result
@property
def dimensions(self):
size = self.size
return {"width": size.x, "depth": size.y, "height": size.z}
@property
def area(self):
return {
"minX": None if math.isinf(self.min.x) else self.min.x,
"minY": None if math.isinf(self.min.y) else self.min.y,
"minZ": None if math.isinf(self.min.z) else self.min.z,
"maxX": None if math.isinf(self.max.x) else self.max.x,
"maxY": None if math.isinf(self.max.y) else self.max.y,
"maxZ": None if math.isinf(self.max.z) else self.max.z,
}
class AnalysisAborted(Exception):
def __init__(self, reenqueue=True, *args, **kwargs):
self.reenqueue = reenqueue
Exception.__init__(self, *args, **kwargs)
regex_command = re.compile(
r"^\s*((?P<codeGM>[GM]\d+)(\.(?P<subcode>\d+))?|(?P<codeT>T)(?P<tool>\d+))"
)
"""Regex for a GCODE command."""
class gcode:
def __init__(self, incl_layers=False, progress_callback=None):
self._logger = logging.getLogger(__name__)
self.extrusionAmount = [0]
self.extrusionVolume = [0]
self.totalMoveTimeMinute = 0
self.filename = None
self._abort = False
self._reenqueue = True
self._filamentDiameter = 0
self._print_minMax = MinMax3D()
self._travel_minMax = MinMax3D()
self._progress_callback = progress_callback
self._incl_layers = incl_layers
self._layers = []
self._current_layer = None
def _track_layer(self, pos, arc=None):
if not self._incl_layers:
return
if self._current_layer is None or self._current_layer["z"] != pos.z:
self._current_layer = {"z": pos.z, "minmax": MinMax3D(), "commands": 1}
self._layers.append(self._current_layer)
elif self._current_layer:
self._current_layer["minmax"].record(pos)
if arc is not None:
self._addArcMinMax(
self._current_layer["minmax"],
arc["startAngle"],
arc["endAngle"],
arc["center"],
arc["radius"],
)
def _track_command(self):
if self._current_layer:
self._current_layer["commands"] += 1
@property
def dimensions(self):
return self._print_minMax.dimensions
@property
def travel_dimensions(self):
return self._travel_minMax.dimensions
@property
def printing_area(self):
return self._print_minMax.area
@property
def travel_area(self):
return self._travel_minMax.area
@property
def layers(self):
return [
{
"num": num + 1,
"z": layer["z"],
"commands": layer["commands"],
"bounds": {
"minX": layer["minmax"].min.x,
"maxX": layer["minmax"].max.x,
"minY": layer["minmax"].min.y,
"maxY": layer["minmax"].max.y,
},
}
for num, layer in enumerate(self._layers)
]
def load(
self,
filename,
throttle=None,
speedx=6000,
speedy=6000,
offsets=None,
max_extruders=10,
g90_extruder=False,
bed_z=0.0,
):
self._print_minMax.min.z = self._travel_minMax.min.z = bed_z
if os.path.isfile(filename):
self.filename = filename
self._fileSize = os.stat(filename).st_size
with codecs.open(filename, encoding="utf-8", errors="replace") as f:
self._load(
f,
throttle=throttle,
speedx=speedx,
speedy=speedy,
offsets=offsets,
max_extruders=max_extruders,
g90_extruder=g90_extruder,
)
def abort(self, reenqueue=True):
self._abort = True
self._reenqueue = reenqueue
def _load(
self,
gcodeFile,
throttle=None,
speedx=6000,
speedy=6000,
offsets=None,
max_extruders=10,
g90_extruder=False,
):
lineNo = 0
readBytes = 0
pos = Vector3D(0.0, 0.0, 0.0)
currentE = [0.0]
totalExtrusion = [0.0]
maxExtrusion = [0.0]
currentExtruder = 0
totalMoveTimeMinute = 0.0
relativeE = False
relativeMode = False
duplicationMode = False
scale = 1.0
fwretractTime = 0
fwretractDist = 0
fwrecoverTime = 0
feedrate = min(speedx, speedy)
if feedrate == 0:
# some somewhat sane default if axes speeds are insane...
feedrate = 2000
if offsets is None or not isinstance(offsets, (list, tuple)):
offsets = []
if len(offsets) < max_extruders:
offsets += [(0, 0)] * (max_extruders - len(offsets))
for line in gcodeFile:
if self._abort:
raise AnalysisAborted(reenqueue=self._reenqueue)
lineNo += 1
readBytes += len(line.encode("utf-8"))
if isinstance(gcodeFile, (io.IOBase, codecs.StreamReaderWriter)):
percentage = readBytes / self._fileSize
elif isinstance(gcodeFile, (list)):
percentage = lineNo / len(gcodeFile)
else:
percentage = None
try:
if (
self._progress_callback is not None
and (lineNo % 1000 == 0)
and percentage is not None
):
self._progress_callback(percentage)
except Exception as exc:
self._logger.debug(
"Progress callback %r error: %s", self._progress_callback, exc
)
if ";" in line:
comment = line[line.find(";") + 1 :].strip()
if comment.startswith("filament_diameter"):
# Slic3r
filamentValue = comment.split("=", 1)[1].strip()
try:
self._filamentDiameter = float(filamentValue)
except ValueError:
try:
self._filamentDiameter = float(
filamentValue.split(",")[0].strip()
)
except ValueError:
self._filamentDiameter = 0.0
elif comment.startswith("CURA_PROFILE_STRING") or comment.startswith(
"CURA_OCTO_PROFILE_STRING"
):
# Cura 15.04.* & OctoPrint Cura plugin
if comment.startswith("CURA_PROFILE_STRING"):
prefix = "CURA_PROFILE_STRING:"
else:
prefix = "CURA_OCTO_PROFILE_STRING:"
curaOptions = self._parseCuraProfileString(comment, prefix)
if "filament_diameter" in curaOptions:
try:
self._filamentDiameter = float(
curaOptions["filament_diameter"]
)
except ValueError:
self._filamentDiameter = 0.0
elif comment.startswith("filamentDiameter,"):
# Simplify3D
filamentValue = comment.split(",", 1)[1].strip()
try:
self._filamentDiameter = float(filamentValue)
except ValueError:
self._filamentDiameter = 0.0
line = line[0 : line.find(";")]
match = regex_command.search(line)
gcode = tool = None
if match:
values = match.groupdict()
if "codeGM" in values and values["codeGM"]:
gcode = values["codeGM"]
elif "codeT" in values and values["codeT"]:
gcode = values["codeT"]
tool = int(values["tool"])
# G codes
if gcode in ("G0", "G1", "G00", "G01"): # Move
x = getCodeFloat(line, "X")
y = getCodeFloat(line, "Y")
z = getCodeFloat(line, "Z")
e = getCodeFloat(line, "E")
f = getCodeFloat(line, "F")
if x is not None or y is not None or z is not None:
# this is a move
move = True
else:
# print head stays on position
move = False
oldPos = pos
# Use new coordinates if provided. If not provided, use prior coordinates (minus tool offset)
# in absolute and 0.0 in relative mode.
newPos = Vector3D(
x * scale if x is not None else (0.0 if relativeMode else pos.x),
y * scale if y is not None else (0.0 if relativeMode else pos.y),
z * scale if z is not None else (0.0 if relativeMode else pos.z),
)
if relativeMode:
# Relative mode: add to current position
pos += newPos
else:
# Absolute mode: apply tool offsets
pos = newPos
if f is not None and f != 0:
feedrate = f
if e is not None:
if relativeMode or relativeE:
# e is already relative, nothing to do
pass
else:
e -= currentE[currentExtruder]
totalExtrusion[currentExtruder] += e
currentE[currentExtruder] += e
maxExtrusion[currentExtruder] = max(
maxExtrusion[currentExtruder], totalExtrusion[currentExtruder]
)
if currentExtruder == 0 and len(currentE) > 1 and duplicationMode:
# Copy first extruder length to other extruders
for i in range(1, len(currentE)):
totalExtrusion[i] += e
currentE[i] += e
maxExtrusion[i] = max(maxExtrusion[i], totalExtrusion[i])
else:
e = 0
# If move, calculate new min/max coordinates
if move:
self._travel_minMax.record(oldPos)
self._travel_minMax.record(pos)
if e > 0:
# store as print move if extrusion is > 0
self._print_minMax.record(oldPos)
self._print_minMax.record(pos)
# move time in x, y, z, will be 0 if no movement happened
moveTimeXYZ = abs((oldPos - pos).length / feedrate)
# time needed for extruding, will be 0 if no extrusion happened
extrudeTime = abs(e / feedrate)
# time to add is maximum of both
totalMoveTimeMinute += max(moveTimeXYZ, extrudeTime)
# process layers if there's extrusion
if e:
self._track_layer(pos)
if gcode in ("G2", "G3", "G02", "G03"): # Arc Move
x = getCodeFloat(line, "X")
y = getCodeFloat(line, "Y")
z = getCodeFloat(line, "Z")
e = getCodeFloat(line, "E")
i = getCodeFloat(line, "I")
j = getCodeFloat(line, "J")
r = getCodeFloat(line, "R")
f = getCodeFloat(line, "F")
# this is a move or print head stays on position
move = (
x is not None
or y is not None
or z is not None
or i is not None
or j is not None
or r is not None
)
oldPos = pos
# Use new coordinates if provided. If not provided, use prior coordinates (minus tool offset)
# in absolute and 0.0 in relative mode.
newPos = Vector3D(
x * scale if x is not None else (0.0 if relativeMode else pos.x),
y * scale if y is not None else (0.0 if relativeMode else pos.y),
z * scale if z is not None else (0.0 if relativeMode else pos.z),
)
if relativeMode:
# Relative mode: add to current position
pos += newPos
else:
# Absolute mode: apply tool offsets
pos = newPos
if f is not None and f != 0:
feedrate = f
# get radius and offset
i = 0 if i is None else i
j = 0 if j is None else j
r = math.sqrt(i * i + j * j) if r is None else r
# calculate angles
centerArc = Vector3D(oldPos.x + i, oldPos.y + j, oldPos.z)
startAngle = math.atan2(oldPos.y - centerArc.y, oldPos.x - centerArc.x)
endAngle = math.atan2(pos.y - centerArc.y, pos.x - centerArc.x)
arcAngle = endAngle - startAngle
if gcode in ("G2", "G02"):
startAngle, endAngle = endAngle, startAngle
arcAngle = -arcAngle
if startAngle < 0:
startAngle += math.pi * 2
if endAngle < 0:
endAngle += math.pi * 2
if arcAngle < 0:
arcAngle += math.pi * 2
# from now on we only think in counter-clockwise direction
if e is not None:
if relativeMode or relativeE:
# e is already relative, nothing to do
pass
else:
e -= currentE[currentExtruder]
totalExtrusion[currentExtruder] += e
currentE[currentExtruder] += e
maxExtrusion[currentExtruder] = max(
maxExtrusion[currentExtruder], totalExtrusion[currentExtruder]
)
if currentExtruder == 0 and len(currentE) > 1 and duplicationMode:
# Copy first extruder length to other extruders
for i in range(1, len(currentE)):
totalExtrusion[i] += e
currentE[i] += e
maxExtrusion[i] = max(maxExtrusion[i], totalExtrusion[i])
else:
e = 0
# If move, calculate new min/max coordinates
if move:
self._travel_minMax.record(oldPos)
self._travel_minMax.record(pos)
self._addArcMinMax(
self._travel_minMax, startAngle, endAngle, centerArc, r
)
if e > 0:
# store as print move if extrusion is > 0
self._print_minMax.record(oldPos)
self._print_minMax.record(pos)
self._addArcMinMax(
self._print_minMax, startAngle, endAngle, centerArc, r
)
# calculate 3d arc length
arcLengthXYZ = math.sqrt((oldPos.z - pos.z) ** 2 + (arcAngle * r) ** 2)
# move time in x, y, z, will be 0 if no movement happened
moveTimeXYZ = abs(arcLengthXYZ / feedrate)
# time needed for extruding, will be 0 if no extrusion happened
extrudeTime = abs(e / feedrate)
# time to add is maximum of both
totalMoveTimeMinute += max(moveTimeXYZ, extrudeTime)
# process layers if there's extrusion
if e:
self._track_layer(
pos,
{
"startAngle": startAngle,
"endAngle": endAngle,
"center": centerArc,
"radius": r,
},
)
elif gcode == "G4": # Delay
S = getCodeFloat(line, "S")
if S is not None:
totalMoveTimeMinute += S / 60
P = getCodeFloat(line, "P")
if P is not None:
totalMoveTimeMinute += P / 60 / 1000
elif gcode == "G10": # Firmware retract
totalMoveTimeMinute += fwretractTime
elif gcode == "G11": # Firmware retract recover
totalMoveTimeMinute += fwrecoverTime
elif gcode == "G20": # Units are inches
scale = 25.4
elif gcode == "G21": # Units are mm
scale = 1.0
elif gcode == "G28": # Home
x = getCodeFloat(line, "X")
y = getCodeFloat(line, "Y")
z = getCodeFloat(line, "Z")
origin = Vector3D(0.0, 0.0, 0.0)
if x is None and y is None and z is None:
pos = origin
else:
pos = Vector3D(pos)
if x is not None:
pos.x = origin.x
if y is not None:
pos.y = origin.y
if z is not None:
pos.z = origin.z
elif gcode == "G90": # Absolute position
relativeMode = False
if g90_extruder:
relativeE = False
elif gcode == "G91": # Relative position
relativeMode = True
if g90_extruder:
relativeE = True
elif gcode == "G92":
x = getCodeFloat(line, "X")
y = getCodeFloat(line, "Y")
z = getCodeFloat(line, "Z")
e = getCodeFloat(line, "E")
if e is None and x is None and y is None and z is None:
# no parameters, set all axis to 0
currentE[currentExtruder] = 0.0
pos.x = 0.0
pos.y = 0.0
pos.z = 0.0
else:
# some parameters set, only set provided axes
if e is not None:
currentE[currentExtruder] = e
if x is not None:
pos.x = x
if y is not None:
pos.y = y
if z is not None:
pos.z = z
# M codes
elif gcode == "M82": # Absolute E
relativeE = False
elif gcode == "M83": # Relative E
relativeE = True
elif gcode in ("M207", "M208"): # Firmware retract settings
s = getCodeFloat(line, "S")
f = getCodeFloat(line, "F")
if s is not None and f is not None:
if gcode == "M207":
# Ensure division is valid
if f > 0:
fwretractTime = s / f
else:
fwretractTime = 0
fwretractDist = s
else:
if f > 0:
fwrecoverTime = (fwretractDist + s) / f
else:
fwrecoverTime = 0
elif gcode == "M605": # Duplication/Mirroring mode
s = getCodeInt(line, "S")
if s in [2, 4, 5, 6]:
# Duplication / Mirroring mode selected. Printer firmware copies extrusion commands
# from first extruder to all other extruders
duplicationMode = True
else:
duplicationMode = False
# T codes
elif tool is not None:
if tool > max_extruders:
self._logger.warning(
"GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis"
% tool
)
elif tool == currentExtruder:
pass
else:
pos.x -= (
offsets[currentExtruder][0]
if currentExtruder < len(offsets)
else 0
)
pos.y -= (
offsets[currentExtruder][1]
if currentExtruder < len(offsets)
else 0
)
currentExtruder = tool
pos.x += (
offsets[currentExtruder][0]
if currentExtruder < len(offsets)
else 0
)
pos.y += (
offsets[currentExtruder][1]
if currentExtruder < len(offsets)
else 0
)
if len(currentE) <= currentExtruder:
for _ in range(len(currentE), currentExtruder + 1):
currentE.append(0.0)
if len(maxExtrusion) <= currentExtruder:
for _ in range(len(maxExtrusion), currentExtruder + 1):
maxExtrusion.append(0.0)
if len(totalExtrusion) <= currentExtruder:
for _ in range(len(totalExtrusion), currentExtruder + 1):
totalExtrusion.append(0.0)
if gcode or tool:
self._track_command()
if throttle is not None:
throttle(lineNo, readBytes)
if self._progress_callback is not None:
self._progress_callback(100.0)
self.extrusionAmount = maxExtrusion
self.extrusionVolume = [0] * len(maxExtrusion)
for i in range(len(maxExtrusion)):
radius = self._filamentDiameter / 2
self.extrusionVolume[i] = (
self.extrusionAmount[i] * (math.pi * radius * radius)
) / 1000
self.totalMoveTimeMinute = totalMoveTimeMinute
def _parseCuraProfileString(self, comment, prefix):
return {
key: value
for (key, value) in map(
lambda x: x.split(b"=", 1),
zlib.decompress(base64.b64decode(comment[len(prefix) :])).split(b"\b"),
)
}
def _intersectsAngle(self, start, end, angle):
if end < start and angle == 0:
# angle crosses 0 degrees
return True
else:
return start <= angle <= end
def _addArcMinMax(self, minmax, startAngle, endAngle, centerArc, radius):
startDeg = math.degrees(startAngle)
endDeg = math.degrees(endAngle)
if self._intersectsAngle(startDeg, endDeg, 0):
# arc crosses positive x
minmax.max.x = max(minmax.max.x, centerArc.x + radius)
if self._intersectsAngle(startDeg, endDeg, 90):
# arc crosses positive y
minmax.max.y = max(minmax.max.y, centerArc.y + radius)
if self._intersectsAngle(startDeg, endDeg, 180):
# arc crosses negative x
minmax.min.x = min(minmax.min.x, centerArc.x - radius)
if self._intersectsAngle(startDeg, endDeg, 270):
# arc crosses negative y
minmax.min.y = min(minmax.min.y, centerArc.y - radius)
def get_result(self):
result = {
"total_time": self.totalMoveTimeMinute,
"extrusion_length": self.extrusionAmount,
"extrusion_volume": self.extrusionVolume,
"dimensions": self.dimensions,
"printing_area": self.printing_area,
"travel_dimensions": self.travel_dimensions,
"travel_area": self.travel_area,
}
if self._incl_layers:
result["layers"] = self.layers
return result
def getCodeInt(line, code):
return getCode(line, code, int)
def getCodeFloat(line, code):
return getCode(line, code, float)
def getCode(line, code, c):
n = line.find(code) + 1
if n < 1:
return None
m = line.find(" ", n)
try:
if m < 0:
result = c(line[n:])
else:
result = c(line[n:m])
except ValueError:
return None
if math.isnan(result) or math.isinf(result):
return None
return result
| 31,001 | Python | .py | 751 | 26.541944 | 123 | 0.484782 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,914 | encoding.py | OctoPrint_OctoPrint/src/octoprint/util/json/encoding.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 json
from collections import OrderedDict
from typing import Any, Callable, Dict
try:
from typing import OrderedDict as OrderedDictType
except ImportError:
OrderedDictType = Dict # py3.7.{0,1}
from frozendict import frozendict
from octoprint.util import to_unicode
class JsonEncoding:
encoders: OrderedDictType[type, Callable[[Any], Any]] = OrderedDict()
@classmethod
def add_encoder(cls, typ: type, encoder: Callable[[Any], Any]) -> None:
"""
Add an encoder for a type.
:param typ: the type to add an encoder for
:param encoder: the encoder. Must take a single argument and return a
tuple (name, parameters...)
"""
cls.encoders[typ] = encoder
@classmethod
def remove_encoder(cls, typ):
try:
del cls.encoders[typ]
except KeyError:
pass
@classmethod
def dumps(cls, obj: Any) -> str:
"""
Dump an object to JSON, handles additional types that the JSON encoder can't, like
bytes and frozendicts.
"""
return json.dumps(
obj,
default=cls.encode,
separators=(",", ":"),
indent=None,
allow_nan=False,
)
@classmethod
def loads(cls, s: str) -> Any:
return json.loads(s)
@classmethod
def encode(cls, obj):
for type, encoder in cls.encoders.items():
if isinstance(obj, type):
return encoder(obj)
raise TypeError(f"Unserializable type {type(obj)}")
JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj))
JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj))
dumps = JsonEncoding.dumps
loads = JsonEncoding.loads
| 1,937 | Python | .py | 54 | 28.814815 | 103 | 0.649893 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,915 | __init__.py | OctoPrint_OctoPrint/src/octoprint/util/json/__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 octoprint.util import deprecated
from . import serializing # noqa: F401
from .encoding import JsonEncoding, dumps, loads # noqa: F401
dump = deprecated(
"dump has been renamed to dumps, please adjust your implementation",
includedoc="dump has been renamed to dumps",
since="1.8.0",
)(dumps)
| 505 | Python | .py | 10 | 48 | 103 | 0.752033 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,916 | serializing.py | OctoPrint_OctoPrint/src/octoprint/util/json/serializing.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 base64
import datetime
import json
import time
from collections import OrderedDict
from typing import Any, Callable, Dict, List
try:
from typing import OrderedDict as OrderedDictType
except ImportError:
OrderedDictType = Dict # py3.7.{0,1}
from frozendict import frozendict
from .encoding import JsonEncoding
class SerializableJsonEncoding(JsonEncoding):
"""
A JSON encoding that can serialize and deserialize objects, including additional
objects otherwise not serializable by the standard JSON encoder:
* ``bytes``
* ``frozendict.frozendict``
* ``datetime.datetime``
* ``time.struct_time``
"""
encoders: OrderedDictType[type, Callable[[Any], Any]] = OrderedDict()
decoders: OrderedDictType[str, Callable[[dict], object]] = OrderedDict()
@classmethod
def add_decoder(cls, classname, decoder):
cls.decoders[classname] = decoder
@classmethod
def remove_decoder(cls, classname):
try:
del cls.decoders[classname]
except KeyError:
pass
@classmethod
def dumps(cls, obj: Any) -> str:
return json.dumps(
cls.encode(obj), separators=(",", ":"), indent=None, allow_nan=False
)
@classmethod
def loads(cls, s: str) -> Any:
return json.loads(s, object_hook=cls.decode)
@classmethod
def encode(cls, val):
"""
Recursively replace all instances of encodable types with their encoded
value. This is useful over the ``default=`` functionality of the JSON
encoder because JSON will not call default for tuples, lists, ints, etc:
https://docs.python.org/3/library/json.html#json.JSONEncoder
Cannot handle circular references.
"""
if isinstance(val, tuple(cls.encoders.keys())):
# we can't directly index into the encoders dict because
# we need to be able to handle subclasses
encoder = next(
encoder for typ, encoder in cls.encoders.items() if isinstance(val, typ)
)
return cls.encode(encoder(val))
elif isinstance(val, dict):
return {k: cls.encode(v) for k, v in val.items()}
elif isinstance(val, (tuple, list)):
return [cls.encode(v) for v in val]
elif isinstance(val, (bool, int, float, str)) or val is None:
return val
else:
raise TypeError(f"Unserializable type {type(val)}")
@classmethod
def decode(cls, dct):
"""
Recursively replace all instances of decodable types with their decoded
values.
You'll want to have used ``class_encode()`` in your encoder to get this
to work properly.
"""
if "__jsonclass__" not in dct:
return dct
if len(dct["__jsonclass__"]) == 0:
raise ValueError("__jsonclass__ must not be empty")
decoded_name = dct["__jsonclass__"][0]
params = dct["__jsonclass__"][1:]
for classname, decoder in cls.decoders.items():
if decoded_name == classname:
return decoder(*params)
return dct
def class_encode(name: str, *params: Any) -> Dict[str, List]:
"""
Encode a class name and parameters into a serializable dict. You'll
probably want to use this if you're going to set a custom decoder.
This stores the class names in a format inspired by the JSON-RPC spec at
https://www.jsonrpc.org/specification_v1#a3.JSONClasshinting
"""
return {"__jsonclass__": [name] + list(params)}
# frozendict
SerializableJsonEncoding.add_encoder(
frozendict, lambda obj: class_encode("frozendict.frozendict", dict(obj))
)
SerializableJsonEncoding.add_decoder("frozendict.frozendict", lambda obj: frozendict(obj))
# bytes
SerializableJsonEncoding.add_encoder(
bytes, lambda obj: class_encode("bytes", base64.b85encode(obj).decode("ascii"))
)
SerializableJsonEncoding.add_decoder("bytes", lambda obj: base64.b85decode(obj))
# time.struct_time
def _struct_time_decoder(params):
if len(params) == 9 and all(isinstance(p, int) and p >= 0 for p in params):
return time.struct_time(params)
raise ValueError(f"Invalid time.struct_time params `{params}`")
SerializableJsonEncoding.add_encoder(
time.struct_time, lambda obj: class_encode("time.struct_time", list(obj))
)
SerializableJsonEncoding.add_decoder("time.struct_time", _struct_time_decoder)
# datetime.datetime
SerializableJsonEncoding.add_encoder(
datetime.datetime, lambda obj: class_encode("datetime.datetime", obj.isoformat())
)
SerializableJsonEncoding.add_decoder(
"datetime.datetime", lambda params: datetime.datetime.fromisoformat(params)
)
# shortcut for dumps and loads
dumps = SerializableJsonEncoding.dumps
loads = SerializableJsonEncoding.loads
| 5,046 | Python | .py | 121 | 35.272727 | 103 | 0.68392 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,917 | __init__.py | OctoPrint_OctoPrint/src/octoprint/util/platform/__init__.py | """
This module bundles platform specific flags and implementations.
"""
__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
try:
import fcntl
except ImportError:
fcntl = None
# set_close_exec
if fcntl is not None and hasattr(fcntl, "FD_CLOEXEC"):
def set_close_exec(handle):
"""Set ``close_exec`` flag on handle, if supported by the OS."""
flags = fcntl.fcntl(handle, fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(handle, fcntl.F_SETFD, flags)
elif sys.platform == "win32":
def set_close_exec(handle):
"""Set ``close_exec`` flag on handle, if supported by the OS."""
import ctypes
import ctypes.wintypes
# see https://msdn.microsoft.com/en-us/library/ms724935(v=vs.85).aspx
SetHandleInformation = ctypes.windll.kernel32.SetHandleInformation
SetHandleInformation.argtypes = (
ctypes.wintypes.HANDLE,
ctypes.wintypes.DWORD,
ctypes.wintypes.DWORD,
)
SetHandleInformation.restype = ctypes.c_bool
HANDLE_FLAG_INHERIT = 0x00000001
result = SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0)
if not result:
raise ctypes.GetLastError()
else:
def set_close_exec(handle):
"""Set ``close_exec`` flag on handle, if supported by the OS."""
# no-op
pass
# default close_fds settings
CLOSE_FDS = True
"""
Default setting for close_fds parameter to Popen/sarge.run.
Set ``close_fds`` on every sub process to this to ensure file handlers will be closed
on child processes on platforms.
"""
# current os
_OPERATING_SYSTEMS = {
"windows": ["win32"],
"linux": lambda x: x.startswith("linux"),
"macos": ["darwin"],
"freebsd": lambda x: x.startswith("freebsd"),
}
OPERATING_SYSTEM_UNMAPPED = "unmapped"
def get_os():
"""
Returns a canonical OS identifier.
Currently the following OS are recognized: ``win32``, ``linux`` (``sys.platform`` = ``linux*``),
``macos`` (``sys.platform`` = ``darwin``) and ``freebsd`` (``sys.platform`` = ``freebsd*``).
Returns:
(str) mapped OS identifier
"""
for identifier, platforms in _OPERATING_SYSTEMS.items():
if (callable(platforms) and platforms(sys.platform)) or (
isinstance(platforms, list) and sys.platform in platforms
):
return identifier
else:
return OPERATING_SYSTEM_UNMAPPED
def is_os_compatible(compatibility_entries, current_os=None):
"""
Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries``
Returns:
(bool) True if the os is compatible, False otherwise
"""
if len(compatibility_entries) == 0:
# shortcut - no compatibility info means we are compatible
return True
if current_os is None:
current_os = get_os()
negative_entries = list(
map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries))
)
positive_entries = list(
filter(lambda x: not x.startswith("!"), compatibility_entries)
)
negative_match = False
if negative_entries:
# check if we are blacklisted
negative_match = current_os in negative_entries or any(
map(lambda x: sys.platform.startswith(x), negative_entries)
)
positive_match = True
if positive_entries:
# check if we are whitelisted
positive_match = current_os in positive_entries or any(
map(lambda x: sys.platform.startswith(x), positive_entries)
)
return positive_match and not negative_match
| 3,810 | Python | .py | 99 | 32.090909 | 111 | 0.660418 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,918 | setup.py | OctoPrint_OctoPrint/src/octoprint/util/piptestballoon/setup.py | """
This "python package" doesn't actually install. This is intentional. It is merely
used to figure out some information about the environment a specific pip call
is running under (installation dir, whether it belongs to a virtual environment,
whether the install location is writable by the current user), and for that it
only needs to be invoked by pip, the pip call doesn't have to be successful
however.
Any output (STDOUT and STDERR) produced by this script is captured by pip and,
until pip v19, printed via its STDOUT, from pip v20 on, via its STDERR. The
parsing script hence needs to capture both to support all pip versions.
"""
import os
import sys
from distutils.command.install import install as cmd_install
from distutils.dist import Distribution
cmd = cmd_install(Distribution())
cmd.finalize_options()
install_dir = cmd.install_lib
virtual_env = hasattr(sys, "real_prefix") or (
hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
)
writable = os.access(install_dir, os.W_OK)
lines = [
f"PIP_INSTALL_DIR={install_dir}",
f"PIP_VIRTUAL_ENV={virtual_env}",
f"PIP_WRITABLE={writable}",
]
# write to stdout
for line in lines:
print(line, file=sys.stdout)
sys.stdout.flush()
# fail intentionally
sys.exit(-1)
| 1,258 | Python | .py | 33 | 36.272727 | 81 | 0.774035 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,919 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/logging/__init__.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 os
from flask import abort, jsonify, request, url_for
from flask_babel import gettext
from werkzeug.exceptions import BadRequest
from werkzeug.utils import secure_filename
import octoprint.plugin
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
from octoprint.server import NO_CONTENT
from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado
from octoprint.settings import settings
from octoprint.util import is_hidden_path, yaml
class LoggingPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.BlueprintPlugin,
):
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "MANAGE",
"name": "Logging management",
"description": gettext(
"Allows to download and delete log files and list and set log levels."
),
"default_groups": [ADMIN_GROUP],
"roles": ["manage"],
}
]
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_all(self):
files = self._getLogFiles()
free, total = self._get_usage()
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
serial_log_enabled = self._settings.global_get_boolean(["serial", "log"])
plugintimings_log_enabled = self._settings.global_get_boolean(
["devel", "pluginTimings"]
)
return jsonify(
logs={"files": files, "free": free, "total": total},
setup={"loggers": loggers, "levels": levels},
serial_log={"enabled": serial_log_enabled},
plugintimings_log={"enabled": plugintimings_log_enabled},
)
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_log_files(self):
files = self._getLogFiles()
free, total = self._get_usage()
return jsonify(files=files, free=free, total=total)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def download_log(self, filename):
return redirect_to_tornado(
request, url_for("index") + "downloads/logs/" + filename
)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def delete_log(self, filename):
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
if (
not os.path.exists(secure)
or is_hidden_path(secure)
or not filename.endswith(".log")
):
abort(404)
os.remove(secure)
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_setup(self):
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
return jsonify(loggers=loggers, levels=levels)
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_levels_api(self):
return jsonify(self._get_logging_levels())
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def set_logging_levels_api(self):
if "application/json" not in request.headers["Content-Type"]:
abort(400, description="Expected content-type JSON")
try:
json_data = request.json
except BadRequest:
abort(400, description="Malformed JSON body in request")
if not isinstance(json_data, dict):
abort(400, description="Invalid log level configuration")
# TODO validate further
self._set_logging_levels(json_data)
return self.get_logging_levels_api()
def is_blueprint_protected(self):
return False
def is_blueprint_csrf_protected(self):
return True
def _get_usage(self):
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False))
return usage.free, usage.total
def _getLogFiles(self):
files = []
basedir = settings().getBaseFolder("logs", check_writable=False)
for entry in os.scandir(basedir):
if is_hidden_path(entry.path) or not entry.name.endswith(".log"):
continue
if not entry.is_file():
continue
files.append(
{
"name": entry.name,
"date": int(entry.stat().st_mtime),
"size": entry.stat().st_size,
"refs": {
"resource": url_for(
".download_log", filename=entry.name, _external=True
),
"download": url_for("index", _external=True)
+ "downloads/logs/"
+ entry.name,
},
}
)
return files
def _get_available_loggers(self):
return list(
filter(
lambda x: self._is_managed_logger(x),
self._logger.manager.loggerDict.keys(),
)
)
def _get_logging_file(self):
# TODO this might not be the logging config we are actually using here (command line parameter...)
return os.path.join(self._settings.getBaseFolder("base"), "logging.yaml")
def _get_logging_config(self):
logging_file = self._get_logging_file()
config_from_file = {}
if os.path.exists(logging_file) and os.path.isfile(logging_file):
config_from_file = yaml.load_from_file(path=logging_file)
return config_from_file
def _get_logging_levels(self):
config = self._get_logging_config()
if config is None or not isinstance(config, dict):
return {}
return {
key: value.get("level")
for key, value in config.get("loggers", {}).items()
if isinstance(value, dict) and "level" in value
}
def _set_logging_levels(self, new_levels):
import logging
config = self._get_logging_config()
# clear all configured logging levels
if "loggers" in config:
purge = []
for component, data in config["loggers"].items():
if not self._is_managed_logger(component):
continue
try:
del data["level"]
self._logger.manager.loggerDict[component].setLevel(logging.INFO)
except KeyError:
pass
if len(data) == 0:
purge.append(component)
for component in purge:
del config["loggers"][component]
else:
config["loggers"] = {}
# update all logging levels
for logger, level in new_levels.items():
if logger not in config["loggers"]:
config["loggers"][logger] = {}
config["loggers"][logger]["level"] = level
# delete empty entries
config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)}
# save
with octoprint.util.atomic_write(
self._get_logging_file(), mode="wt", max_permissions=0o666
) as f:
yaml.save_to_file(config, file=f, pretty=True)
# set runtime logging levels now
for logger, level in new_levels.items():
self._logger.info(f"Setting logger {logger} level to {level}")
level_val = logging.getLevelName(level)
logging.getLogger(logger).setLevel(level_val)
def _is_managed_logger(self, logger):
return logger and (logger.startswith("octoprint") or logger.startswith("tornado"))
def get_template_configs(self):
return [
{
"type": "navbar",
"template": "logging_navbar_seriallog.jinja2",
"suffix": "_seriallog",
},
{
"type": "navbar",
"template": "logging_navbar_plugintimingslog.jinja2",
"suffix": "_plugintimingslog",
},
{"type": "settings", "name": gettext("Logging"), "custom_bindings": True},
]
def get_assets(self):
return {
"js": ["js/logging.js"],
"clientjs": ["clientjs/logging.js"],
"less": ["less/logging.less"],
"css": ["css/logging.css"],
}
__plugin_name__ = "Logging"
__plugin_author__ = "Shawn Bruce, based on work by Gina Häußge and Marc Hannappel"
__plugin_description__ = "Provides access to OctoPrint's logs and logging configuration."
__plugin_disabling_discouraged__ = gettext(
"Without this plugin you will no longer be able to retrieve "
"OctoPrint's logs or modify the current logging levels through "
"the web interface."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = LoggingPlugin()
__plugin_hooks__ = {
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
| 9,980 | Python | .py | 236 | 32.224576 | 106 | 0.603692 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,920 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/corewizard/__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"
from flask_babel import gettext
import octoprint.plugin
from .subwizards import Subwizards
class CoreWizardPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
Subwizards,
):
# ~~ TemplatePlugin API
def get_template_configs(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
names = self._get_subwizard_attrs("_get_", "_wizard_name")
additional = self._get_subwizard_attrs(
"_get_", "_additional_wizard_template_data"
)
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = {
key: value
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
}
result = list()
for key, method in required.items():
if not callable(method):
continue
if not method():
continue
if key not in names:
continue
name = names[key]()
if not name:
continue
config = {
"type": "wizard",
"name": name,
"template": f"corewizard_{key}_wizard.jinja2",
"div": f"wizard_plugin_corewizard_{key}",
"suffix": f"_{key}",
}
if key in additional:
additional_result = additional[key]()
if additional_result:
config.update(additional_result)
result.append(config)
return result
# ~~ AssetPlugin API
def get_assets(self):
if self.is_wizard_required():
return {"js": ["js/corewizard.js"], "css": ["css/corewizard.css"]}
else:
return {}
# ~~ BlueprintPlugin API
def is_blueprint_csrf_protected(self):
return True
# ~~ WizardPlugin API
def is_wizard_required(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = {
key: value
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
}
any_required = any(map(lambda m: m(), required.values()))
return any_required
def get_wizard_details(self):
result = {}
def add_result(key, method):
result[key] = method()
self._get_subwizard_attrs("_get_", "_wizard_details", add_result)
return result
def get_wizard_version(self):
return 4
# ~~ helpers
def _get_subwizard_attrs(self, start, end, callback=None):
result = {}
for item in dir(self):
if not item.startswith(start) or not item.endswith(end):
continue
key = item[len(start) : -len(end)]
if not key:
continue
attr = getattr(self, item)
if callable(callback):
callback(key, attr)
result[key] = attr
return result
__plugin_name__ = "Core Wizard"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides wizard dialogs for core components and functionality"
__plugin_disabling_discouraged__ = gettext(
"Without this plugin OctoPrint will no longer be able to perform "
"setup steps that might be required after an update."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = CoreWizardPlugin()
| 4,113 | Python | .py | 106 | 28.849057 | 103 | 0.583123 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,921 | subwizards.py | OctoPrint_OctoPrint/src/octoprint/plugins/corewizard/subwizards.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 inspect
import sys
from flask_babel import gettext
import octoprint.plugin
from octoprint.access import ADMIN_GROUP, USER_GROUP
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class ServerCommandsSubwizard:
def _is_servercommands_wizard_firstrunonly(self):
return True
def _is_servercommands_wizard_required(self):
system_shutdown_command = self._settings.global_get(
["server", "commands", "systemShutdownCommand"]
)
system_restart_command = self._settings.global_get(
["server", "commands", "systemRestartCommand"]
)
server_restart_command = self._settings.global_get(
["server", "commands", "serverRestartCommand"]
)
return not (
system_shutdown_command and system_restart_command and server_restart_command
)
def _get_servercommands_wizard_details(self):
return {"required": self._is_servercommands_wizard_required()}
def _get_servercommands_wizard_name(self):
return gettext("Server Commands")
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class AclSubwizard:
def _is_acl_wizard_firstrunonly(self):
return False
def _is_acl_wizard_required(self):
return not self._user_manager.has_been_customized()
def _get_acl_wizard_details(self):
return {"required": self._is_acl_wizard_required()}
def _get_acl_wizard_name(self):
return gettext("Access Control")
def _get_acl_additional_wizard_template_data(self):
return {"mandatory": self._is_acl_wizard_required()}
@octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
def acl_wizard_api(self):
from flask import abort, request
from octoprint.server.api import NO_CONTENT
if (
not self._settings.global_get(["server", "firstRun"])
and self._user_manager.has_been_customized()
):
abort(404)
data = request.get_json(silent=True)
if data is None:
data = request.values
if (
"user" in data
and "pass1" in data
and "pass2" in data
and data["pass1"] == data["pass2"]
):
# configure access control
self._user_manager.add_user(
data["user"],
data["pass1"],
True,
[],
[USER_GROUP, ADMIN_GROUP],
overwrite=True,
)
self._settings.save()
return NO_CONTENT
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class OnlineCheckSubwizard:
def _is_onlinecheck_wizard_firstrunonly(self):
return False
def _is_onlinecheck_wizard_required(self):
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
def _get_onlinecheck_wizard_details(self):
return {"required": self._is_onlinecheck_wizard_required()}
def _get_onlinecheck_wizard_name(self):
return gettext("Online Connectivity Check")
def _get_onlinecheck_additional_wizard_template_data(self):
return {"mandatory": self._is_onlinecheck_wizard_required()}
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class PluginBlacklistSubwizard:
def _is_pluginblacklist_wizard_firstrunonly(self):
return False
def _is_pluginblacklist_wizard_required(self):
return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None
def _get_pluginblacklist_wizard_details(self):
return {"required": self._is_pluginblacklist_wizard_required()}
def _get_pluginblacklist_wizard_name(self):
return gettext("Plugin Blacklist")
def _get_pluginblacklist_additional_wizard_template_data(self):
return {"mandatory": self._is_pluginblacklist_wizard_required()}
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class PrinterProfileSubwizard:
def _is_printerprofile_wizard_firstrunonly(self):
return True
def _is_printerprofile_wizard_required(self):
return (
self._printer_profile_manager.is_default_unmodified()
and self._printer_profile_manager.profile_count == 1
)
def _get_printerprofile_wizard_details(self):
return {"required": self._is_printerprofile_wizard_required()}
def _get_printerprofile_wizard_name(self):
return gettext("Default Printer Profile")
Subwizards = type(
"Subwizards",
tuple(
cls
for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if clsname.endswith("Subwizard")
),
{},
)
| 4,883 | Python | .py | 115 | 34.443478 | 103 | 0.67287 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,922 | util.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/util.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
from octoprint.util.platform import CLOSE_FDS
from .exceptions import ScriptError
def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
do_async = kwargs.get("do_async", kwargs.get("async", False))
import sarge
p = None
try:
p = sarge.run(
command,
close_fds=CLOSE_FDS,
cwd=cwd,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
async_=do_async,
)
except Exception:
logging.getLogger(__name__).exception(f"Error while executing command: {command}")
returncode = p.returncode if p is not None else 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 ScriptError(returncode, stdout, stderr)
if evaluate_returncode and p.returncode != 0:
raise ScriptError(p.returncode, p.stdout.text, p.stderr.text)
if not do_async:
return p.returncode, p.stdout.text, p.stderr.text
| 1,317 | Python | .py | 29 | 38.034483 | 103 | 0.665882 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,923 | cli.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/cli.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"
def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
import click
click.disable_unicode_literals_warning = True
import sys
import requests.exceptions
from octoprint.cli.client import client_options, create_client
@click.command("check")
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
@click.option(
"--only-new", is_flag=True, help="Only show entries with updates available"
)
@client_options
@click.argument("targets", nargs=-1)
def check_command(
force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets
):
"""
Check for updates.
If any TARGETs are provided, only those components will be checked.
\b
Examples:
- octoprint plugins softwareupdate:check
This will check all components for available updates,
utilizing cached version information.
- octoprint plugins softwareupdate:check --force
This will check all components for available updates,
ignoring any cached version information even if it's
still valid.
- octoprint plugins softwareupdate:check octoprint
This will only check OctoPrint itself for available
updates.
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
params = {"force": force}
if targets:
params["targets"] = ",".join(targets)
client = create_client(
settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix,
)
r = client.get("plugin/softwareupdate/check", params=params)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo(f"Could not get update information from server, got {e}")
sys.exit(1)
data = r.json()
status = data["status"]
information = data["information"]
lines = []
octoprint_line = None
for key, info in information.items():
status_text = "Up to date"
if info["updateAvailable"]:
if info["updatePossible"]:
status_text = "Update available"
else:
status_text = "Update available (manual)"
elif only_new:
continue
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(
info["displayName"],
key,
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text,
)
if key == "octoprint":
octoprint_line = line
else:
lines.append(line)
lines.sort()
if octoprint_line:
lines = [octoprint_line] + lines
for line in lines:
click.echo(line)
click.echo()
if status == "current":
click.echo("Everything is up to date")
else:
click.echo("There are updates available!")
@click.command("update")
@click.option("--force", is_flag=True, help="Update even if already up to date")
@client_options
@click.argument("targets", nargs=-1)
def update_command(
force, apikey, host, port, httpuser, httppass, https, prefix, targets
):
"""
Apply updates.
If any TARGETs are provided, only those components will be updated.
\b
Examples:
- octoprint plugins softwareupdate:update
This will update all components with a pending update
that can be updated.
- octoprint plugins softwareupdate:update --force
This will force an update of all registered components
that can be updated, even if they don't have an updated
pending.
- octoprint plugins softwareupdate:update octoprint
This will only update OctoPrint and leave any further
components with pending updates at their current versions.
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
data = {"force": force}
if targets:
data["targets"] = targets
client = create_client(
settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix,
)
flags = {"waiting_for_restart": False, "seen_close": False}
def on_message(ws, msg_type, msg):
if msg_type != "plugin" or msg["plugin"] != "softwareupdate":
return
plugin_message = msg["data"]
if "type" not in plugin_message:
return
plugin_message_type = plugin_message["type"]
plugin_message_data = plugin_message["data"]
if plugin_message_type == "updating":
click.echo(
"Updating {} to {}...".format(
plugin_message_data.get("name", "unknown"),
plugin_message_data.get("version", "n/a"),
)
)
elif plugin_message_type == "update_failed":
click.echo("\t... failed :(")
elif plugin_message_type == "loglines" and "loglines" in plugin_message_data:
for entry in plugin_message_data["loglines"]:
prefix = ">>> " if entry["stream"] == "call" else ""
error = entry["stream"] == "stderr"
click.echo(
"\t{}{}".format(prefix, entry["line"].replace("\n", "\n\t")),
err=error,
)
elif (
plugin_message_type == "success"
or plugin_message_type == "restart_manually"
):
results = (
plugin_message_data["results"]
if "results" in plugin_message_data
else {}
)
if results:
click.echo("The update finished successfully.")
if plugin_message_type == "restart_manually":
click.echo("Please restart the OctoPrint server.")
else:
click.echo("No update necessary")
ws.close()
elif plugin_message_type == "restarting":
flags["waiting_for_restart"] = True
click.echo("Restarting to apply changes...")
elif plugin_message_type == "error":
click.echo("Error")
ws.close()
def on_open(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(" Reconnected!")
else:
click.echo("Connected to server...")
def on_close(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(".", nl=False)
else:
flags["seen_close"] = True
click.echo("Disconnected from server...")
socket = client.create_socket(
on_message=on_message, on_open=on_open, on_close=on_close
)
r = client.post_json("plugin/softwareupdate/update", data=data)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo(f"Could not get update information from server, got {e}")
sys.exit(1)
data = r.json()
to_be_updated = data["order"]
checks = data["checks"]
click.echo("Update in progress, updating:")
for name in to_be_updated:
click.echo(f"\t{name if name not in checks else checks[name]}")
socket.wait()
if flags["waiting_for_restart"]:
if socket.reconnect(timeout=60):
click.echo("The update finished successfully.")
else:
click.echo(
"The update finished successfully but the server apparently didn't restart as expected."
)
click.echo("Please restart the OctoPrint server.")
return [check_command, update_command]
| 8,864 | Python | .py | 212 | 29.216981 | 108 | 0.55029 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,924 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/__init__.py | import datetime
__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 hashlib
import logging
import logging.handlers
import os
import sys
import threading
import time
from concurrent import futures
import flask
import requests
from flask_babel import gettext
import octoprint.plugin
import octoprint.settings
from octoprint.access import ADMIN_GROUP, USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.server import BRANCH, NO_CONTENT, REVISION, VERSION
from octoprint.server.util.flask import (
check_etag,
no_firstrun_access,
with_revalidation_checking,
)
from octoprint.util import RepeatedTimer, dict_merge, get_formatted_size, to_unicode, yaml
from octoprint.util.commandline import CommandlineError
from octoprint.util.pip import create_pip_caller
from octoprint.util.version import (
get_comparable_version,
get_python_version_string,
is_python_compatible,
is_released_octoprint_version,
is_stable,
)
from . import cli, exceptions, updaters, util, version_checks
# OctoPi 0.16+
MINIMUM_PYTHON = "2.7.13"
MINIMUM_SETUPTOOLS = "40.7.1"
MINIMUM_PIP = "19.0.1"
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
##~~ Plugin
class SoftwareUpdatePlugin(
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin,
):
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
CURRENT_TRACKING_TYPES = COMMIT_TRACKING_TYPES + ("httpheader", "jsondata")
RELEASE_TRACKING_TYPES = ("github_release",)
OCTOPRINT_RESTART_TYPES = ("pip", "single_file_plugin")
VALID_RESTART_TYPES = ("octoprint", "environment")
DATA_FORMAT_VERSION = "v4"
CHECK_OVERLAY_KEY = "softwareupdate_check_overlay"
# noinspection PyMissingConstructor
def __init__(self):
self._update_in_progress = False
self._configured_checks_mutex = threading.Lock()
self._configured_checks = None
self._refresh_configured_checks = False
self._get_versions_mutex = threading.RLock()
self._get_versions_data = None
self._get_versions_data_ready = threading.Event()
self._version_cache = {}
self._version_cache_ttl = 0
self._version_cache_path = None
self._version_cache_dirty = False
self._version_cache_timestamp = None
self._overlay_cache = {}
self._overlay_cache_ttl = 0
self._overlay_cache_timestamp = None
self._update_log = []
self._update_log_path = None
self._update_log_dirty = False
self._update_log_mutex = threading.RLock()
self._queued_updates = {"targets": [], "force": True}
self._queued_updates_abort_timer = None
self._print_cancelled = False
self._environment_supported = True
self._environment_versions = {}
self._environment_ready = threading.Event()
self._storage_sufficient = True
self._storage_info = {}
self._console_logger = None
self._get_throttled = lambda: False
def initialize(self):
self._console_logger = logging.getLogger(
"octoprint.plugins.softwareupdate.console"
)
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
self._version_cache_path = os.path.join(
self.get_plugin_data_folder(), "versioncache.yaml"
)
self._load_version_cache()
self._update_log_path = os.path.join(
self.get_plugin_data_folder(), "updatelog.yaml"
)
self._load_update_log()
self._overlay_cache_ttl = self._settings.get_int(["check_overlay_ttl"]) * 60
def refresh_checks(name, plugin):
self._refresh_configured_checks = True
self._send_client_message("update_versions")
self._plugin_lifecycle_manager.add_callback("enabled", refresh_checks)
self._plugin_lifecycle_manager.add_callback("disabled", refresh_checks)
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "CHECK",
"name": "Check",
"description": gettext("Allows to check for software updates"),
"roles": ["check"],
"default_groups": [USER_GROUP],
},
{
"key": "UPDATE",
"name": "Update",
"description": gettext("Allows to perform software updates"),
"default_groups": [ADMIN_GROUP],
"roles": ["update"],
"dangerous": True,
},
{
"key": "CONFIGURE",
"name": "Configure",
"description": gettext("Allows to configure software update"),
"default_groups": [ADMIN_GROUP],
"roles": ["configure"],
"dangerous": True,
},
]
# Additional bundle contents
def get_additional_bundle_files(self, *args, **kwargs):
console_log = self._settings.get_plugin_logfile_path(postfix="console")
def updatelog():
if not self._update_log:
self._load_update_log()
result = []
for entry in self._update_log:
line = "{datetime} - {display_name} - {current_version} -> {target_version} - {success} - {text}".format(
datetime=entry["datetime"].replace("T", " "),
display_name=entry["display_name"],
current_version=entry["current_version"],
target_version=entry["target_version"],
success="SUCCESS" if entry["success"] else "FAILED",
text=entry["text"]
+ (
" (Release notes: {})".format(entry["release_notes"])
if entry["release_notes"]
else ""
),
)
result.append(line)
return "\n".join(result)
return {
os.path.basename(console_log): console_log,
"plugin_softwareupdate_update.log": updatelog,
}
def on_startup(self, host, port):
console_logging_handler = logging.handlers.RotatingFileHandler(
self._settings.get_plugin_logfile_path(postfix="console"),
maxBytes=2 * 1024 * 1024,
encoding="utf-8",
)
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
console_logging_handler.setLevel(logging.DEBUG)
self._console_logger.addHandler(console_logging_handler)
self._console_logger.setLevel(logging.DEBUG)
self._console_logger.propagate = False
helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if helpers and "get_throttled" in helpers:
self._get_throttled = helpers["get_throttled"]
if self._settings.get_boolean(["ignore_throttled"]):
self._logger.warning(
"!!! THROTTLE STATE IGNORED !!! You have configured the Software Update plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it."
)
def on_after_startup(self):
self._check_environment()
self._check_storage()
self.get_current_versions()
def _get_configured_checks(self):
with self._configured_checks_mutex:
if (
self._refresh_configured_checks
or self._configured_checks is None
or self._check_overlays_stale
):
self._refresh_configured_checks = False
overlays = self._get_check_overlays()
self._configured_checks = self._settings.get(["checks"], merged=True)
update_check_hooks = self._plugin_manager.get_hooks(
"octoprint.plugin.softwareupdate.check_config"
)
check_providers = {}
effective_configs = {}
for name, hook in update_check_hooks.items():
try:
hook_checks = hook()
except Exception:
self._logger.exception(
f"Error while retrieving update information "
f"from plugin {name}",
extra={"plugin": name},
)
else:
for key, default_config in hook_checks.items():
if key in effective_configs or key == "octoprint":
if key == name:
self._logger.warning(
"Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(
name, check_providers.get(key, "unknown hook")
)
)
else:
self._logger.warning(
"Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(
name, key
)
)
continue
check_providers[key] = name
yaml_config = {}
effective_config = copy.deepcopy(default_config)
if key in overlays:
effective_config = dict_merge(
default_config, overlays[key]
)
if key in self._configured_checks:
yaml_config = self._configured_checks[key]
effective_config = dict_merge(
effective_config, yaml_config, in_place=True
)
# Make sure there's nothing persisted in that check that shouldn't be persisted
#
# This used to be part of the settings migration (version 2) due to a bug - it can't
# stay there though since it interferes with manual entries to the checks not
# originating from within a plugin. Hence we do that step now here.
if (
"type" not in effective_config
or effective_config["type"]
not in self.CURRENT_TRACKING_TYPES
):
deletables = ["current", "displayVersion"]
else:
deletables = []
self._clean_settings_check(
key,
yaml_config,
default_config,
delete=deletables,
save=False,
)
if effective_config:
effective_configs[key] = effective_config
else:
self._logger.warning(
"Update for {} is empty or None, ignoring it".format(
key
)
)
# finally set all our internal representations to our processed results
for key, config in effective_configs.items():
self._configured_checks[key] = config
# we only want to process checks that came from plugins for
# which the plugins are still installed and enabled
config_checks = self._settings.get(["checks"])
plugin_and_not_enabled = (
lambda k: k in check_providers
and check_providers[k] not in self._plugin_manager.enabled_plugins
)
obsolete_plugin_checks = list(
filter(plugin_and_not_enabled, config_checks.keys())
)
for key in obsolete_plugin_checks:
self._logger.debug(
"Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(
key, check_providers[key]
)
)
del self._configured_checks[key]
return self._configured_checks
def _check_environment(self):
import pkg_resources
local_pip = create_pip_caller(
command=self._settings.global_get(["server", "commands", "localPipCommand"])
)
# check python and setuptools version
versions = {
"python": get_python_version_string(),
"setuptools": pkg_resources.get_distribution("setuptools").version,
"pip": local_pip.version_string,
}
supported = (
get_comparable_version(versions["python"])
>= get_comparable_version(MINIMUM_PYTHON)
and get_comparable_version(versions["setuptools"])
>= get_comparable_version(MINIMUM_SETUPTOOLS)
and get_comparable_version(versions["pip"])
>= get_comparable_version(MINIMUM_PIP)
)
self._environment_supported = supported
self._environment_versions = versions
self._environment_ready.set()
def _check_storage(self):
import distutils.sysconfig
import tempfile
import psutil
storage_info = {}
paths = {
"python": distutils.sysconfig.get_python_lib(),
"plugins": self._settings.global_get_basefolder("plugins"),
"temp": tempfile.gettempdir(),
}
for key, path in paths.items():
info = {"path": path, "free": None}
try:
data = psutil.disk_usage(path)
info["free"] = data.free
except Exception:
self._logger.exception(f"Error while determining disk usage of {path}")
continue
storage_info[key] = info
if len(storage_info):
free_storage = min(*list(map(lambda x: x["free"], storage_info.values())))
else:
free_storage = None
self._storage_sufficient = (
free_storage is None
or free_storage
>= self._settings.get_int(["minimum_free_storage"]) * 1024 * 1024
)
self._storage_info = storage_info
self._logger.info(
"Minimum free storage across all update relevant locations is {}. "
"That is considered {} for updating.".format(
get_formatted_size(free_storage)
if free_storage is not None
else "unknown",
"sufficient" if self._storage_sufficient else "insufficient",
)
)
@property
def _check_overlays_stale(self):
return (
self._overlay_cache is None
or self._overlay_cache_timestamp is None
or self._overlay_cache_timestamp + self._overlay_cache_ttl < time.time()
)
def _get_check_overlay(self, url):
self._logger.info(f"Fetching check overlays from {url}")
try:
r = requests.get(url, timeout=3.05)
r.raise_for_status()
data = r.json()
except Exception as exc:
self._logger.error(f"Could not fetch check overlay from {url}: {exc}")
return {}
else:
return data
def _get_check_overlays(self, force=False):
if self._check_overlays_stale or force:
if self._connectivity_checker.online:
self._overlay_cache = self._get_check_overlay(
self._settings.get(["check_overlay_url"])
)
if is_python_compatible("<3"):
data = self._get_check_overlay(
self._settings.get(["check_overlay_py2_url"])
)
self._overlay_cache = octoprint.util.dict_merge(
self._overlay_cache, data
)
else:
self._logger.info("Not fetching check overlays, we are offline")
self._overlay_cache = {}
self._overlay_cache_timestamp = time.time()
default_overlay = {}
defaults = self.get_settings_defaults()
for key in defaults["checks"]:
if key in self._overlay_cache:
default_overlay[key] = self._overlay_cache[key]
self._settings.remove_overlay(self.CHECK_OVERLAY_KEY)
if default_overlay:
self._settings.add_overlay(
{"checks": default_overlay}, key=self.CHECK_OVERLAY_KEY
)
return self._overlay_cache
def _load_version_cache(self):
if not os.path.isfile(self._version_cache_path):
return
try:
data = yaml.load_from_file(path=self._version_cache_path)
timestamp = os.stat(self._version_cache_path).st_mtime
except Exception:
self._logger.exception("Error while loading version cache from disk")
else:
try:
if not isinstance(data, dict):
self._logger.info(
"Version cache was created in a different format, not using it"
)
return
if "__version" in data:
data_version = data["__version"]
else:
self._logger.info(
"Can't determine version of OctoPrint version cache was created for, not using it"
)
return
from octoprint import __version__ as octoprint_version
if data_version != octoprint_version:
self._logger.info(
"Version cache was created for another version of OctoPrint, not using it"
)
return
self._version_cache = data
self._version_cache_dirty = False
self._version_cache_timestamp = timestamp
self._logger.info("Loaded version cache from disk")
except Exception:
self._logger.exception("Error parsing in version cache data")
def _save_version_cache(self):
from octoprint import __version__ as octoprint_version
from octoprint.util import atomic_write
self._version_cache["__version"] = octoprint_version
with atomic_write(
self._version_cache_path, mode="wt", max_permissions=0o666
) as file_obj:
yaml.save_to_file(self._version_cache, file=file_obj, pretty=True)
self._version_cache_dirty = False
self._version_cache_timestamp = time.time()
self._logger.info("Saved version cache to disk")
def _invalidate_version_cache(self, target):
self._refresh_configured_checks = True
try:
del self._version_cache[target]
except KeyError:
pass
self._version_cache_dirty = True
def _load_update_log(self):
if not os.path.isfile(self._update_log_path):
return
try:
data = yaml.load_from_file(path=self._update_log_path)
except Exception:
self._logger.exception("Error while loading update log from disk")
else:
# clean up data older than updatelog_cutoff hours
before_cleanup = len(data)
cutoff = (
datetime.datetime.now()
- datetime.timedelta(minutes=self._settings.get_int(["updatelog_cutoff"]))
).strftime(DATETIME_FORMAT)
data = sorted(
list(
filter(
lambda x: x.get("datetime") and x["datetime"] > cutoff,
data,
)
),
key=lambda x: x["datetime"],
)
cleaned_up = len(data) - before_cleanup
if cleaned_up:
self._logger.info(f"Cleaned up {cleaned_up} old update log entries")
with self._update_log_mutex:
self._update_log = data
self._update_log_dirty = False
self._logger.info("Loaded update log from disk")
def _save_update_log(self):
from octoprint.util import atomic_write
with self._update_log_mutex:
with atomic_write(
self._update_log_path, mode="wt", max_permissions=0o666
) as file_obj:
yaml.save_to_file(
sorted(self._update_log, key=lambda x: x["datetime"]),
file=file_obj,
pretty=True,
)
self._update_log_dirty = False
self._logger.info("Saved update log to disk")
def _add_update_log_entry(
self,
target,
current_version,
target_version,
success,
text,
display_name=None,
release_notes="",
save=True,
):
if display_name is None:
display_name = target
with self._update_log_mutex:
self._update_log.append(
{
"datetime": datetime.datetime.now().strftime(DATETIME_FORMAT),
"target": target,
"current_version": current_version,
"target_version": target_version,
"display_name": display_name,
"release_notes": release_notes if release_notes else "",
"success": success,
"text": text,
},
)
self._update_log_dirty = True
if save:
self._save_update_log()
def _is_octoprint_outdated_and_can_update(self):
checks = self._get_configured_checks()
check = checks.get("octoprint", None)
if not check:
return False
check = self._populated_check("octoprint", check)
credentials = self._settings.get(["credentials"], merged=True)
_, update_available, update_possible, _, _ = self._get_current_version(
"octoprint", check, credentials=credentials
)
if not update_available or not update_possible:
return False
restart_type = self._get_restart_type(check)
return self._has_restart_command(restart_type)
def _get_restart_type(self, check):
if check.get("restart") in self.VALID_RESTART_TYPES:
return check["restart"]
elif "pip" in check or check.get("method") in self.OCTOPRINT_RESTART_TYPES:
return "octoprint"
else:
target_restart_type = None
return target_restart_type
def _has_restart_command(self, restart_type):
if restart_type == "octoprint":
return self._system_commands.has_server_restart_command()
elif restart_type == "environment":
return self._system_commands.has_system_restart_command()
else:
return False
# ~~ SettingsPlugin API
def get_settings_defaults(self):
update_script = os.path.join(self._basefolder, "scripts", "update-octoprint.py")
default_update_script = (
'{{python}} "{update_script}" --branch={{branch}} '
'--force={{force}} "{{folder}}" {{target}}'.format(
update_script=update_script
)
)
return {
"checks": {
"octoprint": {
"type": "github_release",
"user": "foosel",
"repo": "OctoPrint",
"method": "pip",
"pip": "https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip",
"update_script": default_update_script,
"restart": "octoprint",
"stable_branch": {
"branch": "master",
"commitish": ["master"],
"name": "Stable",
},
"prerelease_branches": [
{
"branch": "rc/maintenance",
"commitish": ["rc/maintenance"], # maintenance RCs
"name": "Maintenance RCs",
},
{
"branch": "rc/devel",
"commitish": [
"rc/maintenance",
"rc/devel",
], # devel & maintenance RCs
"name": "Devel RCs",
},
],
},
},
"pip_command": None,
"cache_ttl": 24 * 60, # 1 day
"notify_users": True,
"ignore_throttled": False,
"minimum_free_storage": 150,
"check_overlay_url": "https://plugins.octoprint.org/update_check_overlay.json",
"check_overlay_py2_url": "https://plugins.octoprint.org/update_check_overlay_py2.json",
"check_overlay_ttl": 6 * 60, # 6 hours
"updatelog_cutoff": 30 * 24 * 60, # 30 days
"credentials": {
"github": None,
"bitbucket_user": None,
"bitbucket_password": None,
},
}
def on_settings_load(self):
# ensure we don't persist check configs we receive on the API
data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self))
# set credentials flag
credentials = self._settings.get(["credentials"])
data["credentials"] = {}
for key, value in credentials.items():
data["credentials"][f"{key}_set"] = bool(value)
if "checks" in data:
del data["checks"]
checks = self._get_configured_checks()
# ~~ octoprint check settings
if "octoprint" in checks:
data["octoprint_checkout_folder"] = self._get_octoprint_checkout_folder(
checks=checks
)
data["octoprint_tracked_branch"] = self._get_octoprint_tracked_branch(
checks=checks
)
data["octoprint_pip_target"] = self._get_octoprint_pip_target(checks=checks)
data["octoprint_type"] = checks["octoprint"].get("type", None)
try:
data["octoprint_method"] = self._get_update_method(
"octoprint", checks["octoprint"]
)
except exceptions.UnknownUpdateType:
data["octoprint_method"] = "unknown"
stable_branch = None
prerelease_branches = []
branch_mappings = []
if "stable_branch" in checks["octoprint"]:
branch_mappings.append(checks["octoprint"]["stable_branch"])
stable_branch = checks["octoprint"]["stable_branch"]["branch"]
if "prerelease_branches" in checks["octoprint"]:
for mapping in checks["octoprint"]["prerelease_branches"]:
branch_mappings.append(mapping)
prerelease_branches.append(mapping["branch"])
data["octoprint_branch_mappings"] = branch_mappings
data["octoprint_release_channel"] = stable_branch
if checks["octoprint"].get("prerelease", False):
channel = checks["octoprint"].get("prerelease_channel", BRANCH)
if channel in prerelease_branches:
data["octoprint_release_channel"] = channel
else:
data["octoprint_checkout_folder"] = None
data["octoprint_type"] = None
data["octoprint_release_channel"] = None
# ~~ pip check settings
data["pip_enable_check"] = "pip" in checks
data["queued_updates"] = self._queued_updates.get("targets", [])
return data
def get_settings_restricted_paths(self):
return {"never": [["credentials"]]}
def on_settings_save(self, data):
# ~~ plugin settings
defaults = self.get_settings_defaults()
for key in defaults:
if key in (
"checks",
"cache_ttl",
"check_overlay_ttl",
"notify_user",
"minimum_free_storage",
"octoprint_checkout_folder",
"octoprint_type",
"octoprint_release_channel",
"credentials",
):
continue
if key in data:
self._settings.set([key], data[key])
if "cache_ttl" in data:
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
if "check_overlay_ttl" in data:
self._settings.set_int(["check_overlay_ttl"], data["check_overlay_ttl"])
self._overlay_cache_ttl = self._settings.get_int(["check_overlay_ttl"]) * 60
if "notify_users" in data:
self._settings.set_boolean(["notify_users"], data["notify_users"])
if "minimum_free_storage" in data:
self._settings.set_int(["minimum_free_storage"], data["minimum_free_storage"])
self._check_storage()
# ~~ octoprint check settings
updated_octoprint_check_config = False
if "octoprint_checkout_folder" in data:
if data["octoprint_checkout_folder"]:
# force=True as that path is not part of the default config
self._settings.set(
["checks", "octoprint", "checkout_folder"],
data["octoprint_checkout_folder"],
force=True,
)
if self._settings.get(["checks", "octoprint", "update_folder"]):
self._settings.remove(["checks", "octoprint", "update_folder"])
else:
self._settings.remove(["checks", "octoprint", "checkout_folder"])
updated_octoprint_check_config = True
if "octoprint_type" in data:
octoprint_type = data["octoprint_type"]
if octoprint_type == "github_release":
self._settings.set(["checks", "octoprint", "type"], octoprint_type)
self._settings.set(["checks", "octoprint", "method"], "pip")
updated_octoprint_check_config = True
elif octoprint_type == "github_commit":
self._settings.set(["checks", "octoprint", "type"], octoprint_type)
self._settings.set(["checks", "octoprint", "method"], "pip")
updated_octoprint_check_config = True
elif octoprint_type == "git_commit":
self._settings.set(["checks", "octoprint", "type"], octoprint_type)
self._settings.set(["checks", "octoprint", "method"], "update_script")
updated_octoprint_check_config = True
if "octoprint_tracked_branch" in data:
if data["octoprint_tracked_branch"]:
# force=True as that path is not part of the default config
self._settings.set(
["checks", "octoprint", "branch"],
data["octoprint_tracked_branch"],
force=True,
)
else:
self._settings.remove(["checks", "octoprint", "branch"])
updated_octoprint_check_config = True
if "octoprint_pip_target" in data:
self._settings.set(
["checks", "octoprint", "pip"], data["octoprint_pip_target"]
)
updated_octoprint_check_config = True
if "octoprint_release_channel" in data:
prerelease_branches = self._settings.get(
["checks", "octoprint", "prerelease_branches"]
)
if prerelease_branches and data["octoprint_release_channel"] in [
x["branch"] for x in prerelease_branches
]:
# force=True as those paths are not part of the default config
self._settings.set(
["checks", "octoprint", "prerelease"], True, force=True
)
self._settings.set(
["checks", "octoprint", "prerelease_channel"],
data["octoprint_release_channel"],
force=True,
)
else:
self._settings.remove(["checks", "octoprint", "prerelease"])
self._settings.remove(["checks", "octoprint", "prerelease_channel"])
updated_octoprint_check_config = True
if updated_octoprint_check_config:
self._invalidate_version_cache("octoprint")
# ~~ pip check settings
update_pip_check_config = False
if "pip_enable_check" in data:
pip_enable_check = (
data["pip_enable_check"] in octoprint.settings.valid_boolean_trues
)
pip_check_currently_enabled = "pip" in self._settings.get(
["checks"], merged=True
)
if pip_enable_check != pip_check_currently_enabled:
if pip_enable_check:
# force=True as that path is not part of the default config
self._settings.set(
["checks", "pip"],
{
"type": "pypi_release",
"package": "pip",
"pip": "pip=={target_version}",
},
force=True,
)
else:
self._settings.remove(["checks", "pip"])
update_pip_check_config = True
if update_pip_check_config:
self._invalidate_version_cache("pip")
# ~~ credentials
if "credentials" in data:
credentials = data["credentials"]
for key in defaults["credentials"]:
if key in credentials:
self._settings.set(["credentials", key], credentials[key])
def get_settings_version(self):
return 9
def on_settings_migrate(self, target, current=None):
if current is None or current < 6:
# up until & including config version 5 we didn't set the method parameter for the octoprint check
# configuration
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is not None and "octoprint" in configured_checks:
octoprint_check = dict(configured_checks["octoprint"])
if (
"method" not in octoprint_check
and octoprint_check.get("type") == "git_commit"
):
defaults = {
"plugins": {
"softwareupdate": {"checks": {"octoprint": {"method": "pip"}}}
}
}
self._settings.set(
["checks", "octoprint", "method"],
"update_script",
defaults=defaults,
)
if current == 4:
# config version 4 didn't correctly remove the old settings for octoprint_restart_command
# and environment_restart_command
self._settings.set(["environment_restart_command"], None)
self._settings.set(["octoprint_restart_command"], None)
if current is None or current < 5:
# config version 4 and higher moves octoprint_restart_command and
# environment_restart_command to the core configuration
# current plugin commands
configured_octoprint_restart_command = self._settings.get(
["octoprint_restart_command"]
)
configured_environment_restart_command = self._settings.get(
["environment_restart_command"]
)
# current global commands
configured_system_restart_command = self._settings.global_get(
["server", "commands", "systemRestartCommand"]
)
configured_server_restart_command = self._settings.global_get(
["server", "commands", "serverRestartCommand"]
)
# only set global commands if they are not yet set
if (
configured_system_restart_command is None
and configured_environment_restart_command is not None
):
self._settings.global_set(
["server", "commands", "systemRestartCommand"],
configured_environment_restart_command,
)
if (
configured_server_restart_command is None
and configured_octoprint_restart_command is not None
):
self._settings.global_set(
["server", "commands", "serverRestartCommand"],
configured_octoprint_restart_command,
)
# delete current plugin commands from config
self._settings.set(["environment_restart_command"], None)
self._settings.set(["octoprint_restart_command"], None)
if current is None or current == 2 or current == 8:
# No config version and config version 2 and 8 need the same fix, stripping
# accidentally persisted data off the checks.
#
# We used to do the same processing for the plugin entries too here, but that interfered
# with manual configuration entries. Stuff got deleted that wasn't supposed to be deleted.
#
# The problem is that we don't know if an entry we are looking at and which didn't come through
# a plugin hook is simply an entry from a now uninstalled/unactive plugin, or if it was something
# manually configured by the user. So instead of just blindly removing anything that doesn't
# come from a plugin here we instead clean up anything that indeed comes from a plugin
# during run time and leave everything else as is in the hopes that will not cause trouble.
#
# We still handle the "octoprint" entry here though.
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is not None and "octoprint" in configured_checks:
octoprint_check = dict(configured_checks["octoprint"])
if (
"type" not in octoprint_check
or octoprint_check["type"] not in self.CURRENT_TRACKING_TYPES
):
deletables = ["current", "displayName", "displayVersion"]
else:
deletables = []
self._clean_settings_check(
"octoprint",
octoprint_check,
self.get_settings_defaults()["checks"]["octoprint"],
delete=deletables,
save=False,
)
elif current == 1:
# config version 1 had the error that the octoprint check got accidentally
# included in checks["octoprint"], leading to recursion and hence to
# yaml parser errors
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is None:
return
if (
"octoprint" in configured_checks
and "octoprint" in configured_checks["octoprint"]
):
# that's a circular reference, back to defaults
dummy_defaults = {"plugins": {}}
dummy_defaults["plugins"][self._identifier] = {"checks": {}}
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
if current is None or current < 8:
# remove check_providers again
self._settings.remove(["check_providers"])
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
if not data:
# nothing to do
return data
if delete is None:
delete = []
for k in data:
if k in defaults and defaults[k] == data[k]:
delete.append(k)
for k in delete:
if k in data:
del data[k]
dummy_defaults = {"plugins": {}}
dummy_defaults["plugins"][self._identifier] = {"checks": {}}
dummy_defaults["plugins"][self._identifier]["checks"][key] = defaults
if len(data):
self._settings.set(["checks", key], data, defaults=dummy_defaults)
else:
self._settings.remove(["checks", key], defaults=dummy_defaults)
if save:
self._settings.save()
return data
# ~~ BluePrint API
@octoprint.plugin.BlueprintPlugin.route("/updatelog", methods=["GET"])
@no_firstrun_access
@Permissions.ADMIN.require(403)
def get_update_log(self):
def view():
return flask.jsonify(updatelog=list(reversed(self._update_log)))
def etag(lm=None):
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(repr(self._update_log))
return hash.hexdigest()
def lastmodified():
if os.path.exists(self._update_log_path):
return os.stat(self._update_log_path).st_mtime
else:
return 0
return with_revalidation_checking(
etag_factory=etag, lastmodified_factory=lastmodified
)(view)()
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403)
def check_for_update(self):
if (
not Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.can()
and not self._settings.global_get(["server", "firstRun"])
):
flask.abort(403)
request_data = flask.request.values
if "targets" in request_data or "check" in request_data:
check_targets = list(
map(
lambda x: x.strip(),
request_data.get("targets", request_data.get("check", "")).split(","),
)
)
else:
check_targets = None
force = (
request_data.get("force", "false") in octoprint.settings.valid_boolean_trues
)
def view():
self._environment_ready.wait(timeout=10.0)
try:
(
information,
update_available,
update_possible,
) = self.get_current_versions(check_targets=check_targets, force=force)
storage = list()
for key, name in (
("python", gettext("Python package installation folder")),
("plugins", gettext("Plugin folder")),
("temp", gettext("System temporary files")),
):
data = self._storage_info.get(key)
if not data:
continue
s = {"name": name}
s.update(**data)
storage.append(s)
status = "current"
if self._update_in_progress:
status = "inProgress"
elif (
update_available
and update_possible
and self._environment_supported
and self._storage_sufficient
):
status = "updatePossible"
elif update_available:
status = "updateAvailable"
return flask.jsonify(
{
"status": status,
"information": information,
"timestamp": self._version_cache_timestamp,
"environment": {
"supported": self._environment_supported,
"versions": [
{
"name": gettext("Python"),
"current": self._environment_versions.get(
"python", "unknown"
),
"minimum": MINIMUM_PYTHON,
},
{
"name": gettext("pip"),
"current": self._environment_versions.get(
"pip", "unknown"
),
"minimum": MINIMUM_PIP,
},
{
"name": gettext("setuptools"),
"current": self._environment_versions.get(
"setuptools", "unknown"
),
"minimum": MINIMUM_SETUPTOOLS,
},
],
},
"storage": {
"sufficient": self._storage_sufficient,
"free": storage,
},
}
)
except exceptions.ConfigurationInvalid as e:
flask.abort(
500,
description="Update not properly configured, can't proceed: {}".format(
e
),
)
def etag():
checks = self._get_configured_checks()
targets = check_targets
if targets is None:
targets = checks.keys()
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
targets = sorted(targets)
for target in targets:
current_hash = self._get_check_hash(checks.get(target, {}))
if target in self._version_cache and not force:
data = self._version_cache[target]
hash_update(current_hash)
hash_update(
str(
data["timestamp"] + self._version_cache_ttl
>= time.time()
> data["timestamp"]
)
)
hash_update(repr(data["information"]))
hash_update(str(data["available"]))
hash_update(str(data["possible"]))
hash_update(str(data.get("online", None)))
hash_update(",".join(targets))
hash_update(str(self._environment_supported))
hash_update(str(self._version_cache_timestamp))
hash_update(str(self._overlay_cache_timestamp))
hash_update(str(self._connectivity_checker.online))
hash_update(str(self._update_in_progress))
hash_update(self.DATA_FORMAT_VERSION)
return hash.hexdigest()
def condition():
return check_etag(etag())
return with_revalidation_checking(
etag_factory=lambda *args, **kwargs: etag(),
condition=lambda *args, **kwargs: condition(),
unless=lambda: force or self._check_overlays_stale,
)(view)()
@octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"])
def perform_update(self):
if (
not Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.can()
and not self._settings.global_get(["server", "firstRun"])
):
flask.abort(403)
throttled = self._get_throttled()
if (
throttled
and isinstance(throttled, dict)
and throttled.get("current_issue", False)
and not self._settings.get_boolean(["ignore_throttled"])
):
# currently throttled, we refuse to run
message = (
"System is currently throttled, refusing to update "
"anything due to possible stability issues"
)
self._logger.error(message)
flask.abort(
409,
description=message,
)
if not self._environment_supported:
flask.abort(
409,
description="Direct updates are not supported in this Python environment",
)
if not self._storage_sufficient:
flask.abort(409, description="Not enough free disk space for updating")
if "application/json" not in flask.request.headers["Content-Type"]:
flask.abort(400, description="Expected content-type JSON")
json_data = flask.request.get_json(silent=True)
if json_data is None:
flask.abort(400, description="Invalid JSON")
if "targets" in json_data or "checks" in json_data:
targets = list(
map(
lambda x: x.strip(),
json_data.get("targets", json_data.get("check", [])),
)
)
else:
targets = None
force = json_data.get("force", "false") in octoprint.settings.valid_boolean_trues
if self._printer.is_printing() or self._printer.is_paused():
# do not update while a print job is running
# store targets to be run later on print done event
self._queued_updates["targets"] = list(
set(self._queued_updates["targets"] + targets)
)
self._send_client_message(
"queued_updates",
{"targets": self._queued_updates["targets"]},
)
return (
flask.jsonify({"queued": self._queued_updates.get("targets", False)}),
202,
)
to_be_checked, checks = self.perform_updates(targets=targets, force=force)
return flask.jsonify({"order": to_be_checked, "checks": checks})
@octoprint.plugin.BlueprintPlugin.route("/update/queued", methods=["POST"])
@no_firstrun_access
@Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403)
def cancel_queued(self):
if "application/json" not in flask.request.headers["Content-Type"]:
flask.abort(400, description="Expected content-type JSON")
json_data = flask.request.get_json(silent=True)
if json_data is None:
flask.abort(400, description="Invalid JSON")
command = json_data.get("command")
if command == "cancel":
targets = [x.strip() for x in json_data.get("targets", [])]
if targets:
self._queued_updates["targets"] = [
x for x in self._queued_updates["targets"] if x not in targets
]
else:
self._queued_updates["targets"] = []
if not self._queued_updates["targets"] and self._queued_updates_abort_timer:
self._queued_updates_abort_timer.cancel()
self._queued_updates_abort_timer = None
self._send_client_message(
"queued_updates",
{"targets": self._queued_updates["targets"]},
)
return (
flask.jsonify({"queued": self._queued_updates["targets"]}),
202,
)
else:
flask.abort(400, description="Expected a valid command")
@octoprint.plugin.BlueprintPlugin.route("/configure", methods=["POST"])
@no_firstrun_access
@Permissions.PLUGIN_SOFTWAREUPDATE_CONFIGURE.require(403)
def configure_update(self):
json_data = flask.request.get_json(silent=True)
if json_data is None:
flask.abort(400)
checks = self._get_configured_checks()
settings_dirty = False
for target, data in json_data.items():
if target not in checks:
continue
try:
populated_check = self._populated_check(target, checks[target])
except exceptions.UnknownCheckType:
self._logger.debug(f"Ignoring unknown check type for target {target}")
continue
except Exception:
self._logger.exception(
"Error while populating check prior to configuration for target {}".format(
target
)
)
continue
patch = {}
# switched release channel
if "channel" in data:
if (
populated_check["type"] == "github_release"
and "stable_branch" in populated_check
and "prerelease_branches" in populated_check
):
valid_channel = data["channel"] == populated_check[
"stable_branch"
].get("branch") or any(
map(
lambda x: data["channel"] == x.get("branch"),
populated_check["prerelease_branches"],
)
)
prerelease = data["channel"] != populated_check["stable_branch"].get(
"branch"
)
if valid_channel:
patch["prerelease"] = prerelease
patch["prerelease_channel"] = data["channel"]
# disable/enable check
if "disabled" in data:
patch["disabled"] = (
data["disabled"] in octoprint.settings.valid_boolean_trues
)
# do we have changes to apply?
if patch:
current = self._settings.get(["checks", target], incl_defaults=False)
updated = dict_merge(current, patch)
self._settings.set(
["checks", target],
updated,
defaults={"plugins": {"softwareupdate": {"checks": {target: {}}}}},
)
settings_dirty = True
self._invalidate_version_cache(target)
if settings_dirty:
self._settings.save()
return NO_CONTENT
def is_blueprint_protected(self):
return False
def is_blueprint_csrf_protected(self):
return True
# ~~ Asset API
def get_assets(self):
return {
"css": ["css/softwareupdate.css"],
"js": ["js/softwareupdate.js"],
"clientjs": ["clientjs/softwareupdate.js"],
"less": ["less/softwareupdate.less"],
}
##~~ TemplatePlugin API
def get_template_configs(self):
from flask_babel import gettext
templates = [
{"type": "settings", "name": gettext("Software Update")},
]
if self._is_wizard_update_required():
templates.append(
{
"type": "wizard",
"name": gettext("Update?"),
"template": "softwareupdate_wizard_update.jinja2",
"suffix": "_update",
}
)
if self._is_settings_wizard_required():
templates.append(
{
"type": "wizard",
"name": gettext("Software Update"),
"template": "softwareupdate_wizard_settings.jinja2",
"suffix": "_settings",
}
)
return templates
##~~ WizardPlugin API
def _is_wizard_update_required(self):
firstrun = self._settings.global_get(["server", "firstRun"])
return (
firstrun
and self._is_octoprint_outdated_and_can_update()
and not self._is_settings_wizard_required()
)
def _is_settings_wizard_required(self):
checks = self._get_configured_checks()
check = checks.get("octoprint", None)
checkout_folder = self._get_octoprint_checkout_folder(checks=checks)
return check and check.get("method") == "update_script" and not checkout_folder
def is_wizard_required(self):
return self._is_wizard_update_required() or self._is_settings_wizard_required()
def get_wizard_version(self):
return 1
def get_wizard_details(self):
result = {}
if self._is_wizard_update_required():
information, _, _ = self.get_current_versions()
data = information.get("octoprint", {})
result["update"] = data
return result
##~~ EventHandlerPlugin API
def on_event(self, event, payload):
from octoprint.events import Events
if event == Events.PRINT_STARTED:
self._queued_updates_timer_stop()
self._print_cancelled = False
elif (
event == Events.PRINT_DONE
and self._settings.global_get(["webcam", "timelapse", "type"]) == "off"
and len(self._queued_updates.get("targets", [])) > 0
):
self._queued_updates_timer_start()
elif (
event == Events.PRINT_FAILED
and len(self._queued_updates.get("targets", [])) > 0
):
self._send_client_message(
"queued_updates",
{"print_failed": True, "targets": self._queued_updates["targets"]},
)
self._print_cancelled = True
elif (
event == Events.MOVIE_DONE
and self._settings.global_get(["webcam", "timelapse", "type"]) != "off"
and len(self._queued_updates.get("targets", [])) > 0
and not (self._printer.is_printing() or self._printer.is_paused())
and not self._print_cancelled
):
self._queued_updates_timer_start()
elif (
event != Events.CONNECTIVITY_CHANGED
or not payload
or not payload.get("new", False)
):
return
thread = threading.Thread(target=self.get_current_versions)
thread.daemon = True
thread.start()
# ~~ Updater
def get_current_versions(self, check_targets=None, force=False):
"""
Retrieves the current version information for all defined check_targets. Will retrieve information for all
available targets by default.
:param check_targets: an iterable defining the targets to check, if not supplied defaults to all targets
"""
if force:
self._get_check_overlays(force=True)
checks = self._get_configured_checks()
if check_targets is None:
check_targets = list(checks.keys())
# TODO: caching doesn't take check_targets into account!
update_available = False
update_possible = False
information = {}
credentials = self._settings.get(["credentials"], merged=True)
# we don't want to do the same work twice, so let's use a lock
if self._get_versions_mutex.acquire(False):
self._get_versions_data_ready.clear()
try:
futures_to_result = {}
online = self._connectivity_checker.check_immediately()
self._logger.debug(
"Looks like we are {}".format("online" if online else "offline")
)
with futures.ThreadPoolExecutor(max_workers=5) as executor:
for target, check in checks.items():
if target not in check_targets:
continue
if not check:
continue
if "type" not in check:
continue
try:
populated_check = self._populated_check(target, check)
future = executor.submit(
self._get_current_version,
target,
populated_check,
force=force,
credentials=credentials,
)
futures_to_result[future] = (target, populated_check)
except exceptions.UnknownCheckType:
self._logger.warning(
"Unknown update check type for target {}: {}".format(
target, check.get("type", "<n/a>")
)
)
continue
except Exception:
self._logger.exception(
f"Could not check {target} for updates"
)
continue
for future in futures.as_completed(futures_to_result):
target, populated_check = futures_to_result[future]
if future.exception() is not None:
self._logger.error(
"Could not check {} for updates, error: {!r}".format(
target, future.exception()
)
)
continue
(
target_information,
target_update_available,
target_update_possible,
target_online,
target_error,
) = future.result()
target_update_possible = (
target_update_possible and self._environment_supported
)
target_information = dict_merge(
{
"local": {"name": "?", "value": "?"},
"remote": {
"name": "?",
"value": "?",
"release_notes": None,
},
"needs_online": True,
},
target_information,
)
target_disabled = populated_check.get("disabled", False)
target_compatible = populated_check.get("compatible", True)
update_available = update_available or (
target_update_available and not target_disabled
)
update_possible = update_possible or (
target_update_possible
and target_update_available
and not target_disabled
)
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
release_notes = self._get_release_notes(
target_information, populated_check
)
information[target] = {
"updateAvailable": target_update_available,
"updatePossible": target_update_possible,
"information": target_information,
"displayName": populated_check["displayName"],
"displayVersion": populated_check["displayVersion"].format(
octoprint_version=VERSION,
local_name=local_name,
local_value=local_value,
),
"releaseNotes": release_notes,
"online": target_online,
"error": target_error,
"disabled": target_disabled,
"compatible": target_compatible,
"releaseChannels": {},
}
if (
populated_check["type"] == "github_release"
and "stable_branch" in populated_check
and "prerelease_branches" in populated_check
):
# target supports release channels via github branches and releases
def to_release_channel(branch_info):
return {
"name": branch_info["name"],
"channel": branch_info["branch"],
}
stable_channel = populated_check["stable_branch"]["branch"]
current_channel = populated_check.get("prerelease_channel")
release_channels = [
to_release_channel(populated_check["stable_branch"]),
] + list(
map(
to_release_channel,
populated_check["prerelease_branches"],
)
)
information[target]["releaseChannels"] = {
"available": release_channels,
"current": current_channel
if current_channel
else stable_channel,
"stable": stable_channel,
}
if "released_version" in populated_check:
information[target]["releasedVersion"] = populated_check[
"released_version"
]
if self._version_cache_dirty:
self._save_version_cache()
self._get_versions_data = information, update_available, update_possible
finally:
self._get_versions_mutex.release()
self._get_versions_data_ready.set()
else: # something's already in progress, let's wait for it to complete and use its result
self._get_versions_data_ready.wait()
information, update_available, update_possible = self._get_versions_data
return information, update_available, update_possible
def _get_release_notes(self, information, populated_check):
release_notes = None
if information and information["remote"] and information["remote"]["value"]:
if populated_check.get("release_notes"):
release_notes = populated_check["release_notes"]
elif "release_notes" in information["remote"]:
release_notes = information["remote"]["release_notes"]
if release_notes:
release_notes = release_notes.format(
octoprint_version=VERSION,
target_name=information["remote"]["name"],
target_version=information["remote"]["value"],
)
return release_notes
def _get_check_hash(self, check):
def dict_to_sorted_repr(d):
lines = []
for key in sorted(d.keys()):
value = d[key]
if isinstance(value, dict):
lines.append(f"{key!r}: {dict_to_sorted_repr(value)}")
else:
lines.append(f"{key!r}: {value!r}")
return "{" + ", ".join(lines) + "}"
hash = hashlib.md5()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(dict_to_sorted_repr(check))
return hash.hexdigest()
def _get_current_version(
self, target, check, force=False, online=None, credentials=None
):
"""
Determines the current version information for one target based on its check configuration.
"""
current_hash = self._get_check_hash(check)
if online is None:
online = self._connectivity_checker.online
if target in self._version_cache and not force:
data = self._version_cache[target]
if (
data["hash"] == current_hash
and data["timestamp"] + self._version_cache_ttl
>= time.time()
> data["timestamp"]
and data.get("online", None) == online
):
# we also check that timestamp < now to not get confused too much by clock changes
return (
data["information"],
data["available"],
data["possible"],
data["online"],
data.get("error", None),
)
information = {}
update_available = False
error = None
disabled = check.get("disabled", False)
compatible = check.get("compatible", True)
try:
version_checker = self._get_version_checker(target, check)
information, is_current = version_checker.get_latest(
target, check, online=online, credentials=credentials
)
if information is not None:
if (
is_current
and check["type"] in self.CURRENT_TRACKING_TYPES
and check["current"] is None
):
self._persist_check_current(
target, check, information["remote"]["value"]
)
del self._version_cache[target]
self._version_cache_dirty = True
elif not is_current and compatible:
update_available = True
except exceptions.CannotCheckOffline:
update_possible = False
information["needs_online"] = True
except exceptions.UnknownCheckType:
self._logger.warning(
"Unknown check type {} for {}".format(check["type"], target)
)
update_possible = False
error = "unknown_check"
except exceptions.NetworkError:
self._logger.warning(
f"Could not check {target} for updates due to a network error"
)
update_possible = False
error = "network"
except exceptions.ApiCheckError as exc:
self._logger.warning(
f"Could not check {target} for updates due to an API error: {exc}"
)
update_possible = False
error = "api"
except exceptions.RateLimitCheckError as exc:
self._logger.warning(
"Could not check {} for updates due to running into a rate limit: {}".format(
target, exc
)
)
update_possible = False
error = "ratelimit"
except exceptions.CheckError:
self._logger.warning(
f"Could not check {target} for updates due to a check error"
)
update_possible = False
error = "check"
except Exception:
self._logger.exception(f"Could not check {target} for updates")
update_possible = False
error = "unknown"
else:
try:
updater = self._get_updater(target, check)
update_possible = compatible and updater.can_perform_update(
target, check, online=online
)
except Exception:
self._logger.exception(f"Error while checking if {target} can be updated")
update_possible = False
error = "update"
if target == "octoprint" and sys.platform == "win32":
self._logger.info(
"OctoPrint is running on Windows, it cannot be updated through itself due to Windows' file locking behavior. Please update manually."
)
update_possible = False
error = "windows"
self._version_cache[target] = {
"timestamp": time.time(),
"hash": current_hash,
"information": information,
"available": update_available,
"possible": update_possible,
"online": online,
"error": error,
"disabled": disabled,
"compatible": compatible,
}
self._version_cache_dirty = True
return information, update_available, update_possible, online, error
def _queued_updates_timer_start(self):
if self._queued_updates_abort_timer is not None:
return
self._logger.debug("Starting queued updates timer.")
self._timeout_value = 60
self._queued_updates_abort_timer = RepeatedTimer(
1, self._queued_updates_timer_task
)
self._queued_updates_abort_timer.start()
def _queued_updates_timer_stop(self):
if self._queued_updates_abort_timer is not None:
self._queued_updates_abort_timer.cancel()
self._queued_updates_abort_timer = None
self._send_client_message(
"queued_updates",
{
"targets": self._queued_updates["targets"],
"timeout_value": -1,
},
)
def _queued_updates_timer_task(self):
if self._timeout_value is None:
return
self._timeout_value -= 1
if self._timeout_value <= 0:
if self._queued_updates_abort_timer is not None:
self._queued_updates_abort_timer.cancel()
self._queued_updates_abort_timer = None
self.perform_updates(
targets=self._queued_updates["targets"],
force=self._queued_updates["force"],
)
self._queued_updates = {"targets": [], "force": True}
self._send_client_message(
"queued_updates",
{
"targets": self._queued_updates["targets"],
"timeout_value": self._timeout_value,
},
)
def perform_updates(self, force=False, **kwargs):
"""
Performs the updates for the given check_targets. Will update all possible targets by default.
:param targets: an iterable defining the targets to update, if not supplied defaults to all targets
"""
if not self._environment_supported:
self._logger.error("Direct updates are unsupported in this environment")
return [], {}
if not self._storage_sufficient:
self._logger.error("Not enough free disk space for updating")
return [], {}
targets = kwargs.get("targets", kwargs.get("check_targets", None))
checks = self._get_configured_checks()
populated_checks = {}
for target, check in checks.items():
try:
populated_checks[target] = self._populated_check(target, check)
except exceptions.UnknownCheckType:
self._logger.debug(f"Ignoring unknown check type for target {target}")
except Exception:
self._logger.exception(
"Error while populating check prior to update for target {}".format(
target
)
)
if targets is None:
targets = populated_checks.keys()
to_be_updated = sorted(set(targets) & set(populated_checks.keys()))
if "octoprint" in to_be_updated:
to_be_updated.remove("octoprint")
tmp = ["octoprint"] + to_be_updated
to_be_updated = tmp
if "pip" in to_be_updated:
to_be_updated.remove("pip")
tmp = ["pip"] + to_be_updated
to_be_updated = tmp
updater_thread = threading.Thread(
target=self._update_worker, args=(populated_checks, to_be_updated, force)
)
updater_thread.daemon = False
updater_thread.start()
check_data = {
key: check["displayName"] if "displayName" in check else key
for key, check in populated_checks.items()
if key in to_be_updated
}
return to_be_updated, check_data
def _update_worker(self, checks, check_targets, force):
restart_type = None
credentials = self._settings.get(["credentials"], merged=True)
try:
self._update_in_progress = True
target_results = {}
error = False
### iterate over all configured targets
for target in check_targets:
if target not in checks:
continue
check = checks[target]
if not check.get("enabled", True) or not check.get("compatible", True):
continue
if target not in check_targets:
continue
target_error, target_result = self._perform_update(
target, check, force, credentials=credentials
)
error = error or target_error
if target_result is not None:
target_results[target] = target_result
target_restart_type = self._get_restart_type(check)
# if our update requires a restart we have to determine which type
if restart_type is None or (
restart_type == "octoprint"
and target_restart_type == "environment"
):
restart_type = target_restart_type
finally:
# we might have needed to update the config, so we'll save that now
self._settings.save()
# we also need to save our update log changes
self._save_update_log()
# also, we are now longer updating
self._update_in_progress = False
if error:
# if there was an unignorable error, we just return error
self._send_client_message("error", {"results": target_results})
else:
self._save_version_cache()
# otherwise the update process was a success, but we might still have to restart
if restart_type is not None and restart_type in ("octoprint", "environment"):
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
# we can actually perform that
if self._has_restart_command(restart_type):
self._send_client_message(
"restarting",
{"restart_type": restart_type, "results": target_results},
)
try:
self._perform_restart(restart_type)
except exceptions.RestartFailed:
self._send_client_message(
"restart_failed",
{"restart_type": restart_type, "results": target_results},
)
else:
# we don't have this restart type configured, we'll have to display a message that a manual
# restart is needed
self._send_client_message(
"restart_manually",
{"restart_type": restart_type, "results": target_results},
)
else:
self._send_client_message("success", {"results": target_results})
def _perform_update(self, target, check, force, credentials=None):
online = self._connectivity_checker.check_immediately()
information, update_available, update_possible, _, _ = self._get_current_version(
target, check, online=online, credentials=credentials
)
populated_check = self._populated_check(target, check)
def add_update_log(success, text):
self._add_update_log_entry(
target,
information["local"]["value"],
information["remote"]["value"],
success,
text,
display_name=populated_check["displayName"],
release_notes=self._get_release_notes(information, populated_check),
save=False,
)
if not update_available and not force:
add_update_log(False, "Target is already up to date")
return False, None
if not update_possible:
self._logger.warning(
"Cannot perform update for {}, update type is not fully configured".format(
target
)
)
add_update_log(False, "Update not possible, missing information")
return False, None
if not information.get("compatible", True):
self._logger.warning(
"Cannot perform update for {}, update is reported as incompatible".format(
target
)
)
add_update_log(False, "Update is incompatible")
return False, None
# determine the target version to update to
target_version = information["remote"]["value"]
target_error = False
target_result = None
def trigger_event(success, **additional_payload):
from octoprint.events import Events
if success:
# noinspection PyUnresolvedReferences
event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED
else:
# noinspection PyUnresolvedReferences
event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED
payload = copy.copy(additional_payload)
payload.update(
{
"target": target,
"from_version": information["local"]["value"],
"to_version": target_version,
}
)
self._event_bus.fire(event, payload=payload)
### The actual update procedure starts here...
try:
self._logger.info(f"Starting update of {target} to {target_version}...")
self._send_client_message(
"updating",
{
"target": target,
"version": target_version,
"name": populated_check["displayName"],
},
)
updater = self._get_updater(target, check)
if updater is None:
raise exceptions.UnknownUpdateType()
update_result = updater.perform_update(
target,
populated_check,
target_version,
log_cb=self._log,
online=online,
force=force,
)
target_result = ("success", update_result)
self._logger.info(f"Update of {target} to {target_version} successful!")
trigger_event(True)
except exceptions.UnknownUpdateType:
self._logger.warning(
"Update of %s can not be performed, unknown update type" % target
)
self._send_client_message(
"update_failed",
{
"target": target,
"version": target_version,
"name": populated_check["displayName"],
"reason": "Unknown update type",
},
)
add_update_log(False, "Update failed, unknown update type")
return False, None
except exceptions.CannotUpdateOffline:
self._logger.warning(
"Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now"
% target
)
self._send_client_message(
"update_failed",
{
"target": target,
"version": target_version,
"name": populated_check["displayName"],
"reason": "No internet connection",
},
)
add_update_log(False, "No internet connection")
return False, None
except Exception as e:
self._logger.exception(
"Update of %s can not be performed, please also check plugin_softwareupdate_console.log for possible causes of this"
% target
)
trigger_event(False)
if "ignorable" not in populated_check or not populated_check["ignorable"]:
target_error = True
if isinstance(e, exceptions.UpdateError):
target_result = ("failed", e.data)
self._send_client_message(
"update_failed",
{
"target": target,
"version": target_version,
"name": populated_check["displayName"],
"reason": e.data,
},
)
else:
target_result = ("failed", None)
self._send_client_message(
"update_failed",
{
"target": target,
"version": target_version,
"name": populated_check["displayName"],
"reason": "unknown",
},
)
add_update_log(False, "Update failed")
else:
# make sure that any external changes to config.yaml are loaded into the system
self._settings.load()
# persist the new version if necessary for check type
self._persist_check_current(target, check, target_version)
del self._version_cache[target]
self._version_cache_dirty = True
add_update_log(True, "Update successful")
return target_error, target_result
def _persist_check_current(self, target, check, current):
if check["type"] not in self.CURRENT_TRACKING_TYPES:
return
self._settings.load()
dummy_default = {"plugins": {}}
dummy_default["plugins"][self._identifier] = {"checks": {}}
dummy_default["plugins"][self._identifier]["checks"][target] = {"current": None}
self._settings.set(["checks", target, "current"], current, defaults=dummy_default)
# we have to save here (even though that makes us save quite often) since otherwise the next
# load will overwrite our changes we just made
self._settings.save()
check["current"] = current
def _perform_restart(self, restart_type):
"""
Performs a restart using the supplied restart_type.
"""
self._logger.info("Restarting...")
try:
if restart_type == "octoprint":
return self._system_commands.perform_server_restart()
elif restart_type == "environment":
return self._system_commands.perform_system_restart()
except CommandlineError as e:
self._logger.exception(f"Error while restarting of type {restart_type}")
self._logger.warning(f"Restart stdout:\n{e.stdout}")
self._logger.warning(f"Restart stderr:\n{e.stderr}")
raise exceptions.RestartFailed()
def _populated_check(self, target, check):
from flask_babel import gettext
if "type" not in check:
raise exceptions.UnknownCheckType()
result = dict(check)
if target == "octoprint":
displayName = check.get("displayName")
if displayName is None:
# displayName missing or set to None
displayName = gettext("OctoPrint")
result["displayName"] = to_unicode(displayName, errors="replace")
displayVersion = check.get("displayVersion")
if displayVersion is None:
# displayVersion missing or set to None
displayVersion = "{octoprint_version}"
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
result["released_version"] = is_released_octoprint_version()
if check["type"] in self.COMMIT_TRACKING_TYPES:
result["current"] = REVISION if REVISION else "unknown"
else:
result["current"] = VERSION
elif target == "pip":
import pkg_resources
displayName = check.get("displayName")
if displayName is None:
# displayName missing or set to None
displayName = gettext("pip")
result["displayName"] = to_unicode(displayName, errors="replace")
displayVersion = check.get("displayVersion")
if displayVersion is None:
# displayVersion missing or set to None
distribution = pkg_resources.get_distribution("pip")
if distribution:
displayVersion = distribution.version
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
result["pip_command"] = check.get(
"pip_command",
self._settings.global_get(["server", "commands", "localPipCommand"]),
)
else:
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
if result["displayName"] is None:
# displayName missing or None
result["displayName"] = to_unicode(target, errors="replace")
result["displayVersion"] = to_unicode(
check.get("displayVersion", check.get("current")), errors="replace"
)
if result["displayVersion"] is None:
# displayVersion AND current missing or None
result["displayVersion"] = "unknown"
if check["type"] in self.CURRENT_TRACKING_TYPES:
result["current"] = check.get("current", None)
else:
result["current"] = check.get(
"current", check.get("displayVersion", None)
)
if (
check["type"] in self.RELEASE_TRACKING_TYPES
and result["current"]
and (check.get("prerelease", None) or not is_stable(result["current"]))
):
# we are tracking releases and are either also tracking prerelease OR are currently running
# a non stable version => we need to change some parameters
# we compare versions fully, not just the base so that we see a difference
# between RCs + stable for the same version release
result["force_base"] = False
if check["type"] == "github_release":
if check.get("prerelease", None):
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
channel = check.get("prerelease_channel", None)
if channel:
# if we have a release channel, we also set our update_branch here to our release channel
# in case it's not already set
result["update_branch"] = check.get("update_branch", channel)
else:
# we are not tracking prereleases, but aren't on the stable branch either => switch back
# to stable branch on update
result["update_branch"] = check.get(
"update_branch",
check.get("stable_branch", {"branch": "main"})["branch"],
)
if check.get("update_script", None):
# we force an exact version & python inequality check, to be able to downgrade
result["force_exact_version"] = True
result["release_compare"] = "python_unequal"
elif check.get("pip", None):
# we force python inequality check for pip installs, to be able to downgrade
result["release_compare"] = "python_unequal"
if result.get("pip", None):
if "pip_command" not in result:
local_pip_command = self._settings.global_get(
["server", "commands", "localPipCommand"]
)
if local_pip_command:
result["pip_command"] = local_pip_command
return result
def _log(self, lines, prefix=None, stream=None, strip=True):
if strip:
lines = list(map(lambda x: x.strip(), lines))
self._send_client_message(
"loglines",
data={"loglines": [{"line": line, "stream": stream} for line in lines]},
)
for line in lines:
self._console_logger.debug(f"{prefix} {line}")
def _send_client_message(self, message_type, data=None):
self._plugin_manager.send_plugin_message(
self._identifier, {"type": message_type, "data": data}
)
def _get_version_checker(self, target, check):
"""
Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType
if version checker cannot be determined.
"""
if "type" not in check:
raise exceptions.ConfigurationInvalid("no check type defined")
check_type = check["type"]
method = getattr(version_checks, check_type)
if method is None:
raise exceptions.UnknownCheckType()
else:
return method
def _get_update_method(self, target, check, valid_methods=None):
"""
Determines the update method for the given target and check.
If ``valid_methods`` is provided, determine method must be contained
therein to be considered valid.
Raises an ``UnknownUpdateType`` exception if method cannot be determined
or validated.
"""
method = None
if "method" in check:
method = check["method"]
else:
if "update_script" in check:
method = "update_script"
elif "pip" in check:
method = "pip"
elif "python_updater" in check:
method = "python_updater"
if method is None or (valid_methods and method not in valid_methods):
raise exceptions.UnknownUpdateType()
return method
def _get_updater(self, target, check):
"""
Retrieves the updater for the given target and check configuration. Will raise an UnknownUpdateType if updater
cannot be determined.
"""
method = self._get_update_method(target, check)
if method is None:
raise exceptions.UnknownUpdateType()
updater = getattr(updaters, method)
if updater is None:
raise exceptions.UnknownUpdateType()
return updater
def _get_octoprint_checkout_folder(self, checks=None):
if checks is None:
checks = self._get_configured_checks()
if "octoprint" not in checks:
return None
if "checkout_folder" in checks["octoprint"]:
return checks["octoprint"]["checkout_folder"]
elif "update_folder" in checks["octoprint"]:
return checks["octoprint"]["update_folder"]
return None
def _get_octoprint_tracked_branch(self, checks=None):
if checks is None:
checks = self._get_configured_checks()
if "octoprint" not in checks:
return None
return checks["octoprint"].get("branch")
def _get_octoprint_pip_target(self, checks=None):
if checks is None:
checks = self._get_configured_checks()
if "octoprint" not in checks:
return None
return checks["octoprint"].get("pip")
def _register_custom_events(*args, **kwargs):
return ["update_succeeded", "update_failed"]
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
__plugin_description__ = "Allows receiving update notifications and performing updates of OctoPrint and plugins"
__plugin_disabling_discouraged__ = gettext(
"Without this plugin OctoPrint will no longer be able to "
"update itself or any of your installed plugins which might put "
"your system at risk."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = SoftwareUpdatePlugin()
global __plugin_helpers__
__plugin_helpers__ = {
"version_checks": version_checks,
"updaters": updaters,
"exceptions": exceptions,
"util": util,
}
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.cli.commands": cli.commands,
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.systeminfo.additional_bundle_files": __plugin_implementation__.get_additional_bundle_files,
}
| 100,285 | Python | .py | 2,185 | 30.373455 | 294 | 0.522255 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,925 | exceptions.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/exceptions.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"
class NoUpdateAvailable(Exception):
pass
class UpdateAlreadyInProgress(Exception):
pass
class UnknownUpdateType(Exception):
pass
class UnknownCheckType(Exception):
pass
class NetworkError(Exception):
def __init__(self, message=None, cause=None):
Exception.__init__(self)
self.message = message
self.cause = cause
def __str__(self):
if self.message is not None:
return self.message
elif self.cause is not None:
return f"NetworkError caused by {self.cause}"
else:
return "NetworkError"
class CheckError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class ApiCheckError(CheckError):
API = "API"
def __init__(self, status_code, message):
self.status_code = status_code
super().__init__(f"{self.API} error: {message} (HTTP {status_code})")
class RateLimitCheckError(CheckError):
def __init__(self, message, remaining=None, limit=None, reset=None):
super().__init__(message)
self.remaining = remaining
self.limit = limit
self.reset = reset
class UpdateError(Exception):
def __init__(self, message, data):
self.message = message
self.data = data
def __str__(self):
return self.message
class ScriptError(Exception):
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
class RestartFailed(Exception):
pass
class ConfigurationInvalid(Exception):
pass
class CannotCheckOffline(Exception):
pass
class CannotUpdateOffline(Exception):
pass
| 1,988 | Python | .py | 58 | 28.068966 | 103 | 0.672996 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,926 | bitbucket_commit.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.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 base64
import logging
import requests
from . import ApiCheckError
BRANCH_HEAD_URL = (
"https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
)
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.bitbucket_commit"
)
class BitbucketApiError(ApiCheckError):
API = "Bitbucket API"
def check_bitbucket_api_response(logger, r, ok_codes=None):
if ok_codes is None:
ok_codes = [requests.codes.ok]
if r.status_code not in ok_codes:
try:
data = r.json()
message = data.get("message", "Unknown error")
except Exception:
message = "Not a valid JSON response"
exc = BitbucketApiError(r.status_code, message)
logger.error(exc.message)
raise exc
def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
from ..exceptions import NetworkError
url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)
headers = {}
if api_user is not None and api_password is not None:
auth_value = base64.b64encode(
b"{user}:{pw}".format(user=api_user, pw=api_password)
)
headers["authorization"] = f"Basic {auth_value}"
try:
r = requests.get(url, headers=headers, timeout=(3.05, 7))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
check_bitbucket_api_response(logger, r)
reference = r.json()
if "hash" not in reference:
raise BitbucketApiError(r.status_code, "No commit hash found in response")
return reference["hash"]
def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
from ..exceptions import ConfigurationInvalid
if "user" not in check or "repo" not in check:
raise ConfigurationInvalid(
"Update configuration for %s of type bitbucket_commit needs all of user and repo"
% target
)
branch = "master"
if "branch" in check and check["branch"] is not None:
branch = check["branch"]
api_user = check.get("api_user")
api_password = check.get("api_password")
if api_user is None and api_password is None and credentials:
api_user = credentials.get("bitbucket_user")
api_password = credentials.get("bitbucket_password")
current = check.get("current")
information = {
"local": {
"name": "Commit {commit}".format(
commit=current if current is not None else "unknown"
),
"value": current,
},
"remote": {"name": "?", "value": "?"},
"needs_online": not check.get("offline", False),
}
if not online and information["needs_online"]:
return information, True
remote_commit = _get_latest_commit(
check["user"], check["repo"], branch, api_user, api_password
)
remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-"
information["remote"] = {"name": remote_name, "value": remote_commit}
is_current = (
current is not None and current == remote_commit
) or remote_commit is None
logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}")
return information, is_current
| 3,465 | Python | .py | 82 | 35.378049 | 103 | 0.657918 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,927 | github_commit.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/github_commit.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 requests
BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{branch}"
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.github_commit"
)
def _get_latest_commit(user, repo, branch, apikey=None):
from ..exceptions import NetworkError
headers = {}
if apikey:
auth = "token " + apikey
headers = {"Authorization": auth}
try:
r = requests.get(
BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch),
timeout=(3.05, 30),
headers=headers,
)
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import check_github_apiresponse, check_github_ratelimit
check_github_ratelimit(logger, r)
check_github_apiresponse(logger, r)
reference = r.json()
if "object" not in reference or "sha" not in reference["object"]:
return None
return reference["object"]["sha"]
def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
from ..exceptions import ConfigurationInvalid
user = check.get("user")
repo = check.get("repo")
if user is None or repo is None:
raise ConfigurationInvalid(
"Update configuration for {} of type github_commit needs user and repo set and not None".format(
target
)
)
branch = "master"
if "branch" in check and check["branch"] is not None:
branch = check["branch"]
current = check.get("current")
information = {
"local": {
"name": "Commit {commit}".format(
commit=current if current is not None else "?"
),
"value": current,
},
"remote": {"name": "?", "value": "?"},
"needs_online": not check.get("offline", False),
}
if not online and information["needs_online"]:
return information, True
apikey = None
if credentials:
apikey = credentials.get("github")
remote_commit = _get_latest_commit(
check["user"], check["repo"], branch, apikey=apikey
)
remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-"
information["remote"] = {"name": remote_name, "value": remote_commit}
is_current = (
current is not None and current == remote_commit
) or remote_commit is None
logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}")
return information, is_current
| 2,771 | Python | .py | 69 | 33.101449 | 108 | 0.641629 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,928 | python_checker.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/python_checker.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 ..exceptions import CannotCheckOffline, ConfigurationInvalid
def get_latest(target, check, full_data=False, online=True, *args, **kwargs):
python_checker = check.get("python_checker")
if python_checker is None or not hasattr(python_checker, "get_latest"):
raise ConfigurationInvalid(
'Update configuration for {} of type python_checker needs python_checker defined and have an attribute "get_latest"'.format(
target
)
)
if not online and not check.get("offline", False):
raise CannotCheckOffline(
"{} isn't marked as 'offline' capable, but we are apparently offline right now".format(
target
)
)
try:
return check["python_checker"].get_latest(
target, check, full_data=full_data, online=online
)
except Exception:
import inspect
args, _, _, _ = inspect.getargspec(check["python_checker"].get_latest)
if "online" not in args:
# old python_checker footprint, simply leave out the online parameter
return check["python_checker"].get_latest(target, check, full_data=full_data)
# some other error, raise again
raise
| 1,485 | Python | .py | 30 | 40.733333 | 136 | 0.656293 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,929 | httpheader.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/httpheader.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 logging
import requests
from ..exceptions import CannotCheckOffline, ConfigurationInvalid, NetworkError
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.etag")
def get_latest(target, check, online=True, *args, **kwargs):
if not online:
raise CannotCheckOffline()
url = check.get("header_url", check.get("url"))
header = check.get("header_name")
if url is None or header is None:
raise ConfigurationInvalid(
"HTTP header version check needs header_url or url and header_name set"
)
current = check.get("current")
method = check.get("header_method", "head")
prefix = check.get("header_prefix", header)
if prefix:
prefix = f"{prefix} "
try:
with requests.request(method, url) as r:
latest = r.headers.get(header)
except Exception as exc:
raise NetworkError(cause=exc)
information = {
"local": {
"name": "{}{}".format(prefix, current if current else "-"),
"value": current,
},
"remote": {
"name": "{}{}".format(prefix, latest if latest else "-"),
"value": latest,
},
}
logger.debug(
"Target: {}, local: {}, remote: {}".format(
target, information["local"]["name"], information["remote"]["name"]
)
)
return information, current is None or current == latest or latest is None
| 1,649 | Python | .py | 41 | 33.04878 | 103 | 0.633229 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,930 | jsondata.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/jsondata.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 logging
import requests
from ..exceptions import CannotCheckOffline, ConfigurationInvalid, NetworkError
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.jsondata")
def get_latest(target, check, online=True, *args, **kwargs):
if not online:
raise CannotCheckOffline()
url = check.get("jsondata")
current = check.get("current")
if url is None:
raise ConfigurationInvalid("jsondata version check needs jsondata set")
try:
with requests.get(url, timeout=(3.05, 7)) as r:
data = r.json()
except Exception as exc:
raise NetworkError(cause=exc)
latest = data.get("version")
information = {
"local": {"name": current if current else "-", "value": current},
"remote": {"name": latest if latest else "-", "value": latest},
}
logger.debug(
"Target: {}, local: {}, remote: {}".format(
target, information["local"]["name"], information["remote"]["name"]
)
)
return information, current is None or current == latest or latest is None
| 1,295 | Python | .py | 29 | 38.517241 | 103 | 0.672785 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,931 | pypi_release.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.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 pkg_resources
import requests
from octoprint.util.version import (
get_comparable_version,
is_prerelease,
is_python_compatible,
)
INFO_URL = "https://pypi.org/pypi/{package}/json"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.pypi_release")
def _filter_out_latest(releases, include_prerelease=False, python_version=None):
"""
Filters out the newest of all matching releases.
Tests:
>>> requires_py2 = ">=2.7.9,<3"
>>> requires_py23 = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
>>> requires_py3 = ">=3.6, <4"
>>> releases = {"1.3.12": [dict(requires_python=requires_py2, upload_time_iso_8601="2019-10-22T10:06:03.190293Z")], "1.4.0rc1": [dict(requires_python=requires_py23, upload_time_iso_8601="2019-11-22T10:06:03.190293Z")], "2.0.0rc1": [dict(requires_python=requires_py3, upload_time_iso_8601="2020-10-22T10:06:03.190293Z")]}
>>> _filter_out_latest(releases, python_version="2.7.9")
'1.3.12'
>>> _filter_out_latest(releases, include_prerelease=True, python_version="2.7.9")
'1.4.0rc1'
>>> _filter_out_latest(releases, include_prerelease=True, python_version="3.6.0")
'2.0.0rc1'
>>> _filter_out_latest(releases, python_version="3.6.0")
"""
releases = [{"version": k, "data": v[0]} for k, v in releases.items()]
# filter out prereleases and versions incompatible to our python
filter_function = lambda release: not is_prerelease(
release["version"]
) and is_python_compatible(
release["data"].get("requires_python", ""), python_version=python_version
)
if include_prerelease:
filter_function = lambda release: is_python_compatible(
release["data"].get("requires_python", ""), python_version=python_version
)
releases = list(filter(filter_function, releases))
if not releases:
return None
# sort by upload date
releases = sorted(
releases, key=lambda release: release["data"].get("upload_time_iso_8601", "")
)
# latest release = last in list
latest = releases[-1]
return latest["version"]
def _get_latest_release(package, include_prerelease):
from ..exceptions import NetworkError
try:
r = requests.get(INFO_URL.format(package=package), timeout=(3.05, 7))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
if not r.status_code == requests.codes.ok:
return None
data = r.json()
if "info" not in data or "version" not in data["info"]:
return None
requires_python = data["info"].get("requires_python")
if requires_python and not is_python_compatible(requires_python):
return None
return _filter_out_latest(data["releases"], include_prerelease=include_prerelease)
def _is_current(release_information):
if release_information["remote"]["value"] is None:
return True
local_version = get_comparable_version(release_information["local"]["value"])
remote_version = get_comparable_version(release_information["remote"]["value"])
return remote_version <= local_version
def get_latest(target, check, online=True, *args, **kwargs):
from ..exceptions import CannotUpdateOffline
if not online and not check.get("offline", False):
raise CannotUpdateOffline()
package = check.get("package")
distribution = pkg_resources.get_distribution(package)
if distribution:
local_version = distribution.version
else:
local_version = None
remote_version = _get_latest_release(
package, include_prerelease=check.get("prerelease", False)
)
information = {
"local": {"name": local_version, "value": local_version},
"remote": {"name": remote_version, "value": remote_version},
}
logger.debug(
"Target: {}, local: {}, remote: {}".format(
target, information["local"]["name"], information["remote"]["name"]
)
)
return information, _is_current(information)
| 4,304 | Python | .py | 93 | 39.967742 | 328 | 0.666028 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,932 | never_current.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/never_current.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"
def get_latest(target, check, online=True, *args, **kwargs):
local_version = check.get("local_version", "1.0.0")
remote_version = check.get("remote_version", "1.0.1")
information = {
"local": {"name": local_version, "value": local_version},
"remote": {"name": remote_version, "value": remote_version},
}
return information, False
| 562 | Python | .py | 10 | 51.2 | 103 | 0.675182 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,933 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/__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"
from ..exceptions import ApiCheckError, RateLimitCheckError
from . import ( # noqa: F401
always_current,
bitbucket_commit,
commandline,
git_commit,
github_commit,
github_release,
httpheader,
jsondata,
never_current,
pypi_release,
python_checker,
)
class GitHubRateLimitCheckError(RateLimitCheckError):
def __init__(self, remaining, ratelimit, reset):
if reset:
message = f"GitHub rate limit exceeded, reset at {reset}"
else:
message = "GitHub rate limit exceeded"
super().__init__(message, remaining=remaining, limit=ratelimit, reset=reset)
class GitHubApiError(ApiCheckError):
API = "GitHub API"
def check_github_apiresponse(logger, r, ok_codes=None):
if ok_codes is None:
ok_codes = (200,)
if r.status_code not in ok_codes:
try:
data = r.json()
message = data.get("message", "Unknown error")
except Exception:
message = "Not a valid JSON response"
exc = GitHubApiError(r.status_code, message)
logger.error(exc.message)
raise exc
def check_github_ratelimit(logger, r):
try:
ratelimit = int(r.headers.get("X-RateLimit-Limit", None))
except Exception:
ratelimit = None
try:
remaining = int(r.headers.get("X-RateLimit-Remaining", None))
except Exception:
remaining = None
reset = r.headers["X-RateLimit-Reset"] if "X-RateLimit-Reset" in r.headers else None
try:
import time
reset = time.strftime("%Y-%m-%d %H:%M", time.gmtime(int(reset)))
except Exception:
reset = None
logger.debug(
"Github rate limit: {}/{}, reset at {}".format(
remaining if remaining is not None else "?",
ratelimit if ratelimit is not None else "?",
reset if reset is not None else "?",
)
)
if remaining == 0:
raise GitHubRateLimitCheckError(remaining, ratelimit, reset)
| 2,244 | Python | .py | 62 | 29.290323 | 103 | 0.645564 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,934 | git_commit.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/git_commit.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 errno
import logging
import subprocess
import sys
from ..exceptions import ConfigurationInvalid
def _get_git_executables():
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
return GITS
def _git(args, cwd, hide_stderr=False):
commands = _get_git_executables()
for c in commands:
try:
p = subprocess.Popen(
[c] + 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
return None, None
else:
return None, None
stdout = p.communicate()[0].strip().decode()
if p.returncode != 0:
return p.returncode, None
return p.returncode, stdout
def get_latest(target, check, online=True, *args, **kwargs):
checkout_folder = check.get("checkout_folder")
if checkout_folder is None:
raise ConfigurationInvalid(
"Update configuration for {} of type git_commit needs checkout_folder set and not None".format(
target
)
)
returncode, local_commit = _git(["rev-parse", "@{0}"], checkout_folder)
if returncode != 0:
return None, True
information = {
"local": {"name": "Commit %s" % local_commit, "value": local_commit},
"remote": {"name": "?", "value": "?"},
"needs_online": not check.get("offline", False),
}
if not online and information["needs_online"]:
return information, True
returncode, _ = _git(["fetch"], checkout_folder)
if returncode != 0:
return information, True
returncode, remote_commit = _git(["rev-parse", "@{u}"], checkout_folder)
if returncode != 0:
return information, True
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
if returncode != 0:
return information, True
if local_commit == remote_commit or remote_commit == base:
information["remote"] = {
"name": "Commit %s" % local_commit,
"value": local_commit,
}
is_current = True
else:
information["remote"] = {
"name": "Commit %s" % remote_commit,
"value": remote_commit,
}
is_current = local_commit == remote_commit
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.git_commit"
)
logger.debug(f"Target: {target}, local: {local_commit}, remote: {remote_commit}")
return information, is_current
| 2,930 | Python | .py | 79 | 29.113924 | 107 | 0.598303 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,935 | github_release.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/github_release.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 requests
from octoprint.util import sv
from octoprint.util.version import get_comparable_version
RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.github_release"
)
def _filter_out_latest(releases, sort_key=None, include_prerelease=False, commitish=None):
"""
Filters out the newest of all matching releases.
Tests:
>>> release_1_2_15 = dict(name="1.2.15", tag_name="1.2.15", html_url="some_url", published_at="2016-07-29T19:53:29Z", prerelease=False, draft=False, target_commitish="prerelease")
>>> release_1_2_16rc1 = dict(name="1.2.16rc1", tag_name="1.2.16rc1", html_url="some_url", published_at="2016-08-29T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> release_1_3_5rc1 = dict(name="1.3.5rc1", tag_name="1.3.5rc1", html_url="some_url", published_at="2017-06-14T10:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master")
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
>>> release_1_4_0rc1_devel = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
>>> _filter_out_latest(releases, include_prerelease=False, commitish=None)
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/maintenance"])
('1.2.16rc2', '1.2.16rc2', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/devel"])
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=None)
('1.4.0rc1', '1.4.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/doesntexist"])
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest([release_1_2_17rc1])
(None, None, None)
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
(None, None, None)
>>> comparable_factory = _get_comparable_factory("python", force_base=True)
>>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, commitish=None, sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/maintenance"], sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/devel"], sort_key=sort_key)
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.4.0rc1', '1.4.0rc1', 'some_url')
"""
nothing = None, None, None
if sort_key is None:
sort_key = lambda release: sv(release.get("published_at", None))
# filter out prereleases and drafts
filter_function = lambda rel: not rel["prerelease"] and not rel["draft"]
if include_prerelease:
if commitish:
filter_function = lambda rel: not rel["draft"] and (
not rel["prerelease"] or rel["target_commitish"] in commitish
)
else:
filter_function = lambda rel: not rel["draft"]
releases = list(filter(filter_function, releases))
if not releases:
return nothing
# sort by sort_key
releases = sorted(releases, key=sort_key)
# latest release = last in list
latest = releases[-1]
return latest["name"], latest["tag_name"], latest.get("html_url", None)
def _get_latest_release(
user,
repo,
compare_type,
include_prerelease=False,
commitish=None,
force_base=True,
apikey=None,
):
from ..exceptions import NetworkError
headers = {}
if apikey:
auth = "token " + apikey
headers = {"Authorization": auth}
try:
r = requests.get(
RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30), headers=headers
)
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import check_github_apiresponse, check_github_ratelimit
check_github_ratelimit(logger, r)
check_github_apiresponse(logger, r)
releases = r.json()
# sanitize
required_fields = {
"name",
"tag_name",
"html_url",
"draft",
"prerelease",
"published_at",
"target_commitish",
}
releases = list(
filter(lambda rel: set(rel.keys()) & required_fields == required_fields, releases)
)
comparable_factory = _get_comparable_factory(compare_type, force_base=force_base)
sort_key = lambda release: comparable_factory(
_get_sanitized_version(release["tag_name"])
)
return _filter_out_latest(
releases,
sort_key=sort_key,
include_prerelease=include_prerelease,
commitish=commitish,
)
def _get_sanitized_version(version_string):
"""
Removes "-..." prefix from version strings.
Tests:
>>> _get_sanitized_version(None)
>>> _get_sanitized_version("1.2.15")
'1.2.15'
>>> _get_sanitized_version("1.2.15-dev12")
'1.2.15'
"""
if version_string is not None and "-" in version_string:
version_string = version_string[: version_string.find("-")]
return version_string
def _get_comparable_version_semantic(version_string, force_base=True):
import semantic_version
version = semantic_version.Version.coerce(version_string, partial=False)
if force_base:
version_string = f"{version.major}.{version.minor}.{version.patch}"
version = semantic_version.Version.coerce(version_string, partial=False)
return version
def _get_sanitized_compare_type(compare_type, custom=None):
if (
compare_type
not in (
"python",
"python_unequal",
"semantic",
"semantic_unequal",
"unequal",
"custom",
)
or compare_type == "custom"
and custom is None
):
compare_type = "python"
return compare_type
def _get_comparable_factory(compare_type, force_base=True):
if compare_type in ("python", "python_unequal"):
return lambda version: get_comparable_version(version, base=force_base)
elif compare_type in ("semantic", "semantic_unequal"):
return lambda version: _get_comparable_version_semantic(
version, force_base=force_base
)
else:
return lambda version: version
def _get_comparator(compare_type, custom=None):
if compare_type in ("python", "semantic"):
return lambda a, b: a >= b
elif compare_type == "custom":
return custom
else:
return lambda a, b: a == b
def _is_current(release_information, compare_type, custom=None, force_base=True):
"""
Checks if the provided release information indicates the version being the most current one.
Tests:
>>> _is_current(dict(remote=dict(value=None)), "python")
True
>>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")), "python")
False
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python")
True
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
False
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
True
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python_unequal", force_base=False)
False
>>> _is_current(dict(local=dict(value="1.3.0.post1+g1014712"), remote=dict(value="1.3.0")), "python")
True
"""
if release_information["remote"]["value"] is None:
return True
compare_type = _get_sanitized_compare_type(compare_type, custom=custom)
comparable_factory = _get_comparable_factory(compare_type, force_base=force_base)
comparator = _get_comparator(compare_type, custom=custom)
sanitized_local = _get_sanitized_version(release_information["local"]["value"])
sanitized_remote = _get_sanitized_version(release_information["remote"]["value"])
try:
return comparator(
comparable_factory(sanitized_local), comparable_factory(sanitized_remote)
)
except Exception:
logger.exception(
"Could not check if version is current due to an error, assuming it is"
)
return True
def get_latest(
target, check, custom_compare=None, online=True, credentials=None, *args, **kwargs
):
from ..exceptions import ConfigurationInvalid
user = check.get("user", None)
repo = check.get("repo", None)
current = check.get("current", None)
if user is None or repo is None or current is None:
raise ConfigurationInvalid(
"Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(
target
)
)
information = {
"local": {"name": current, "value": current},
"remote": {"name": "?", "value": "?", "release_notes": None},
"needs_online": not check.get("offline", False),
}
if not online and information["needs_online"]:
return information, True
include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
# determine valid "commitish" values in case we track prereleases
commitish = None
if include_prerelease and prerelease_channel:
prerelease_branches = check.get("prerelease_branches", None)
if prerelease_branches:
# fetch valid commitish list from configured prerelease_branches for selected channel
commitishes = {
x["branch"]: x.get("commitish", [x["branch"]])
for x in prerelease_branches
}
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
force_base = check.get("force_base", False)
compare_type = _get_sanitized_compare_type(
check.get("release_compare", "python"), custom=custom_compare
)
apikey = None
if credentials:
apikey = credentials.get("github")
remote_name, remote_tag, release_notes = _get_latest_release(
check["user"],
check["repo"],
compare_type,
include_prerelease=include_prerelease,
commitish=commitish,
force_base=force_base,
apikey=apikey,
)
if not remote_name:
if remote_tag:
remote_name = remote_tag
else:
remote_name = "-"
information["remote"] = {
"name": remote_name,
"value": remote_tag,
"release_notes": release_notes,
}
logger.debug(f"Target: {target}, local: {current}, remote: {remote_tag}")
return information, _is_current(
information, compare_type, custom=custom_compare, force_base=force_base
)
| 13,284 | Python | .py | 273 | 41.084249 | 199 | 0.642614 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,936 | commandline.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/commandline.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
from ..exceptions import CannotCheckOffline, ConfigurationInvalid
from ..util import execute
def get_latest(target, check, online=True, *args, **kwargs):
command = check.get("command")
if command is None:
raise ConfigurationInvalid(
"Update configuration for {} of type commandline needs command set and not None".format(
target
)
)
if not online and not check.get("offline", False):
raise CannotCheckOffline(
"{} isn't marked as 'offline' capable, but we are apparently offline right now".format(
target
)
)
returncode, stdout, stderr = execute(command, evaluate_returncode=False)
# We expect command line check commands to
#
# * have a return code of 0 if an update is available, a value != 0 otherwise
# * return the display name of the new version as the final line on stdout
# * return the display name of the current version as the next to final line on stdout
#
# Example output:
# 1.1.0
# 1.1.1
#
# 1.1.0 is the current version, 1.1.1 is the remote version. If only one line is output, it's taken to be the
# display name of the new version
stdout_lines = list(filter(lambda x: len(x.strip()), stdout.splitlines()))
local_name = stdout_lines[-2] if len(stdout_lines) >= 2 else "unknown"
remote_name = stdout_lines[-1] if len(stdout_lines) >= 1 else "unknown"
is_current = returncode != 0
information = {
"local": {
"name": local_name,
"value": local_name,
},
"remote": {"name": remote_name, "value": remote_name},
}
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.github_commit"
)
logger.debug(f"Target: {target}, local: {local_name}, remote: {remote_name}")
return information, is_current
| 2,164 | Python | .py | 49 | 37.326531 | 113 | 0.655878 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,937 | always_current.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/version_checks/always_current.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"
def get_latest(target, check, online=True, *args, **kwargs):
current_version = check.get("current_version", "1.0.0")
information = {
"local": {"name": current_version, "value": current_version},
"remote": {"name": current_version, "value": current_version},
}
return information, True
| 513 | Python | .py | 9 | 52 | 103 | 0.684 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,938 | sleep_a_bit.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.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 time
def can_perform_update(target, check, online=True):
return True
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
duration = check.get("duration", 30)
now = time.monotonic()
end = now + duration
while now < end:
log_cb([f"{end - now}s left..."], prefix=">", stream="output")
time.sleep(5)
now = time.monotonic()
| 607 | Python | .py | 13 | 41.769231 | 103 | 0.681431 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,939 | python_updater.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/updaters/python_updater.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"
def can_perform_update(target, check, online=True):
return (
"python_updater" in check
and check["python_updater"] is not None
and hasattr(check["python_updater"], "perform_update")
and (online or check.get("offline", False))
)
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
from ..exceptions import CannotUpdateOffline
if not online and not check("offline", False):
raise CannotUpdateOffline()
kwargs = {"log_cb": log_cb, "online": online, "force": force}
try:
return check["python_updater"].perform_update(
target, check, target_version, **kwargs
)
except Exception:
import inspect
args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update)
if not all(k in args for k in kwargs):
# old python_updater footprint, leave out what it doesn't understand
old_kwargs = {k: v for k, v in kwargs.items() if k in args}
return check["python_updater"].perform_update(
target, check, target_version, **old_kwargs
)
# some other error, raise again
raise
| 1,447 | Python | .py | 30 | 40.233333 | 103 | 0.648188 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,940 | single_file_plugin.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.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 ast
import logging
import os
import shutil
import tempfile
from octoprint.settings import settings
from octoprint.util.net import download_file
from .. import exceptions
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.updaters.download_single_file_plugin"
)
def can_perform_update(target, check, online=True):
return online or check.get("offline", False)
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
if not online and not check.get("offline", False):
raise exceptions.CannotUpdateOffline()
url = check.get("url")
if url is None:
raise exceptions.ConfigurationInvalid(
"download_single_file_plugin updater needs url set"
)
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_message(*lines):
_log(lines, prefix="#", stream="message")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
folder = None
try:
try:
_log_message(f"Download file from {url}")
folder = tempfile.TemporaryDirectory()
path = download_file(url, folder.name)
except Exception as exc:
raise exceptions.NetworkError(cause=exc)
filename = os.path.basename(path)
_, ext = os.path.splitext(filename)
if ext not in (".py",):
raise exceptions.UpdateError(f"File is not a python file: {filename}", None)
try:
with open(path, "rb") as f:
ast.parse(f.read(), filename=path)
except Exception:
logger.exception(f"Could not parse {path} as python file", None)
raise exceptions.UpdateError(
f"Could not parse {filename} as python file.", None
)
destination = os.path.join(settings().getBaseFolder("plugins"), filename)
try:
_log_message(f"Copy {path} to {destination}")
shutil.copy(path, destination)
except Exception:
logger.exception(f"Could not copy {path} to {destination}")
raise exceptions.UpdateError(f"Could not copy {path} to {destination}", None)
return "ok"
finally:
if folder is not None:
folder.cleanup()
| 2,550 | Python | .py | 62 | 33.064516 | 103 | 0.647368 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,941 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/updaters/__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"
from . import ( # noqa: F401
pip,
python_updater,
single_file_plugin,
sleep_a_bit,
update_script,
)
| 360 | Python | .py | 10 | 32.7 | 103 | 0.697406 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,942 | update_script.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/updaters/update_script.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 sys
from octoprint.util.commandline import CommandlineCaller, CommandlineError
from ..exceptions import CannotUpdateOffline, ConfigurationInvalid, UpdateError
def _get_caller(log_cb=None):
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_stdout(*lines):
_log(lines, prefix=">", stream="stdout")
def _log_stderr(*lines):
_log(lines, prefix="!", stream="stderr")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
caller = CommandlineCaller()
if log_cb is not None:
caller.on_log_call = _log_call
caller.on_log_stdout = _log_stdout
caller.on_log_stderr = _log_stderr
return caller
def can_perform_update(target, check, online=True):
import os
script_configured = bool("update_script" in check and check["update_script"])
folder = None
if "update_folder" in check:
folder = check["update_folder"]
elif "checkout_folder" in check:
folder = check["checkout_folder"]
folder_configured = bool(folder and os.path.isdir(folder))
return (
script_configured
and folder_configured
and (online or check.get("offline", False))
)
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script")
if not online and not check("offline", False):
raise CannotUpdateOffline()
if not can_perform_update(target, check):
raise ConfigurationInvalid(
"checkout_folder and update_folder are missing for update target %s, one is needed"
% target
)
update_script = check["update_script"]
update_branch = check.get("update_branch", "")
force_exact_version = check.get("force_exact_version", False)
folder = check.get(
"update_folder", check.get("checkout_folder")
) # either should be set, tested above
pre_update_script = check.get("pre_update_script", None)
post_update_script = check.get("post_update_script", None)
caller = _get_caller(log_cb=log_cb)
### pre update
if pre_update_script is not None:
logger.debug(f"Target: {target}, running pre-update script: {pre_update_script}")
try:
caller.checked_call(pre_update_script, cwd=folder)
except CommandlineError as e:
logger.exception(
"Target: %s, error while executing pre update script, got returncode %r"
% (target, e.returncode)
)
### update
try:
update_command = update_script.format(
python=sys.executable,
folder=folder,
target=target_version,
branch=update_branch,
force="true" if force_exact_version else "false",
)
logger.debug(f"Target {target}, running update script: {update_command}")
caller.checked_call(update_command, cwd=folder)
except CommandlineError as e:
logger.exception(
"Target: %s, error while executing update script, got returncode %r"
% (target, e.returncode)
)
raise UpdateError(
"Error while executing update script for %s", (e.stdout, e.stderr)
)
### post update
if post_update_script is not None:
logger.debug(
"Target: {}, running post-update script {}...".format(
target, post_update_script
)
)
try:
caller.checked_call(post_update_script, cwd=folder)
except CommandlineError as e:
logger.exception(
"Target: %s, error while executing post update script, got returncode %r"
% (target, e.returncode)
)
return "ok"
| 4,158 | Python | .py | 100 | 33.27 | 103 | 0.639185 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,943 | pip.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/updaters/pip.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 collections
import logging
import threading
from octoprint.util.pip import (
UnknownPip,
create_pip_caller,
is_already_installed,
is_egg_problem,
)
from octoprint.util.version import get_comparable_version
from .. import exceptions
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
console_logger = logging.getLogger(
"octoprint.plugins.softwareupdate.updaters.pip.console"
)
_pip_callers = {}
_pip_caller_mutex = collections.defaultdict(threading.RLock)
def can_perform_update(target, check, online=True):
from .. import MINIMUM_PIP
pip_caller = _get_pip_caller(
command=check["pip_command"] if "pip_command" in check else None
)
return (
"pip" in check
and pip_caller is not None
and pip_caller.available
and pip_caller.version >= get_comparable_version(MINIMUM_PIP)
and (online or check.get("offline", False))
)
def _get_pip_caller(command=None):
global _pip_callers
global _pip_caller_mutex
key = command
if command is None:
key = "__default"
with _pip_caller_mutex[key]:
if key not in _pip_callers:
try:
_pip_callers[key] = create_pip_caller(command=command)
except UnknownPip:
pass
return _pip_callers.get(key)
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
pip_command = check.get("pip_command")
pip_working_directory = check.get("pip_cwd")
if not online and not check.get("offline", False):
raise exceptions.CannotUpdateOffline()
force = force or check.get("force_reinstall", False)
pip_caller = _get_pip_caller(command=pip_command)
if pip_caller is None:
raise exceptions.UpdateError("Can't run pip", None)
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_stdout(*lines):
_log(lines, prefix=">", stream="stdout")
def _log_stderr(*lines):
_log(lines, prefix="!", stream="stderr")
def _log_message(*lines):
_log(lines, prefix="#", stream="message")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
if log_cb is not None:
pip_caller.on_log_call = _log_call
pip_caller.on_log_stdout = _log_stdout
pip_caller.on_log_stderr = _log_stderr
install_arg = check["pip"].format(
target_version=target_version, target=target_version
)
logger.debug(f"Target: {target}, executing pip install {install_arg}")
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
pip_kwargs = {
"env": {"PYTHONWARNINGS": "ignore:DEPRECATION::pip._internal.cli.base_command"}
}
if pip_working_directory is not None:
pip_kwargs.update(cwd=pip_working_directory)
if "dependency_links" in check and check["dependency_links"]:
pip_args += ["--process-dependency-links"]
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
if is_egg_problem(stdout) or is_egg_problem(stderr):
_log_message(
'This looks like an error caused by a specific issue in upgrading Python "eggs"',
"via current versions of pip.",
"Performing a second install attempt as a work around.",
)
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
raise exceptions.UpdateError(
"Error while executing pip install", (stdout, stderr)
)
else:
raise exceptions.UpdateError(
"Error while executing pip install", (stdout, stderr)
)
if not force and is_already_installed(stdout):
_log_message(
"Looks like we were already installed in this version. Forcing a reinstall."
)
force = True
if force:
logger.debug(
"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps"
% (target, install_arg)
)
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
raise exceptions.UpdateError(
"Error while executing pip install --force-reinstall", (stdout, stderr)
)
return "ok"
| 4,842 | Python | .py | 116 | 33.853448 | 103 | 0.639949 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,944 | update-octoprint.py | OctoPrint_OctoPrint/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py | #!/bin/env python
__author__ = "Gina Haeussge <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 errno
import sys
import time
import traceback
# default close_fds settings
if sys.platform == "win32" and sys.version_info < (3, 7):
CLOSE_FDS = False
else:
CLOSE_FDS = True
def _log_call(*lines):
_log(lines, prefix=">", stream="call")
def _log_stdout(*lines):
_log(lines, prefix=" ", stream="stdout")
def _log_stderr(*lines):
_log(lines, prefix=" ", stream="stderr")
def _log(lines, prefix=None, stream=None):
output_stream = sys.stdout
if stream == "stderr":
output_stream = sys.stderr
for line in lines:
to_print = _to_bytes(
"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")),
errors="replace",
)
print(to_print, file=output_stream)
def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a unicode string."""
if isinstance(s_or_u, bytes):
return s_or_u.decode(encoding, errors=errors)
else:
return s_or_u
def _to_bytes(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a str."""
if isinstance(s_or_u, str):
return s_or_u.encode(encoding, errors=errors)
else:
return s_or_u
def _execute(command, **kwargs):
import sarge
if isinstance(command, (list, tuple)):
joined_command = " ".join(command)
else:
joined_command = command
_log_call(joined_command)
kwargs.update(
{
"close_fds": CLOSE_FDS,
"async_": True,
"stdout": sarge.Capture(),
"stderr": sarge.Capture(),
}
)
try:
p = sarge.run(command, **kwargs)
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
if not p.commands[0].process:
# the process might have been set to None in case of any exception
print(
f"Error while trying to run command {joined_command}",
file=sys.stderr,
)
return None, [], []
except Exception:
print(f"Error while trying to run command {joined_command}", file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
all_stdout = []
all_stderr = []
try:
while p.commands[0].poll() is None:
lines = p.stderr.readlines(timeout=0.5)
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stderr(*lines)
all_stderr += lines
lines = p.stdout.readlines(timeout=0.5)
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stdout(*lines)
all_stdout += lines
finally:
p.close()
lines = p.stderr.readlines()
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stderr(*lines)
all_stderr += lines
lines = p.stdout.readlines()
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stdout(*lines)
all_stdout += lines
return p.returncode, all_stdout, all_stderr
def _get_git_executables():
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
return GITS
def _git(args, cwd, git_executable=None):
if git_executable is not None:
commands = [git_executable]
else:
commands = _get_git_executables()
for c in commands:
command = [c] + args
try:
return _execute(command, cwd=cwd)
except OSError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
print(
"Error while trying to run command {}".format(" ".join(command)),
file=sys.stderr,
)
traceback.print_exc(file=sys.stderr)
return None, [], []
except Exception:
print(
"Error while trying to run command {}".format(" ".join(command)),
file=sys.stderr,
)
traceback.print_exc(file=sys.stderr)
return None, [], []
else:
print(
"Unable to find git command, tried {}".format(", ".join(commands)),
file=sys.stderr,
)
return None, [], []
def _python(args, cwd, python_executable, sudo=False):
command = [python_executable] + args
if sudo:
command = ["sudo"] + command
try:
return _execute(command, cwd=cwd)
except Exception:
import traceback
print(
"Error while trying to run command {}".format(" ".join(command)),
file=sys.stderr,
)
traceback.print_exc(file=sys.stderr)
return None, [], []
def _to_error(*lines):
if len(lines) == 1:
if isinstance(lines[0], (list, tuple)):
lines = lines[0]
elif not isinstance(lines[0], (str, bytes)):
lines = [
repr(lines[0]),
]
return "\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines))
def _rescue_changes(git_executable, folder):
print(">>> Running: git diff --shortstat")
returncode, stdout, stderr = _git(
["diff", "--shortstat"], folder, git_executable=git_executable
)
if returncode is None or returncode != 0:
raise RuntimeError(
f'Could not update, "git diff" failed with returncode {returncode}'
)
if stdout and "".join(stdout).strip():
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
import os
import time
timestamp = time.strftime("%Y%m%d%H%M")
patch = os.path.join(folder, f"{timestamp}-preupdate.patch")
print(f">>> Running: git diff and saving output to {patch}")
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
"Could not update, installation directory was dirty and state could not be persisted as a patch to {}".format(
patch
)
)
with open(patch, "w", encoding="utf-8", errors="replace") as f:
for line in stdout:
f.write(line)
return True
return False
def update_source(git_executable, folder, target, force=False, branch=None):
if _rescue_changes(git_executable, folder):
print(">>> Running: git reset --hard")
returncode, stdout, stderr = _git(
["reset", "--hard"], folder, git_executable=git_executable
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git reset --hard" failed with returncode {}'.format(
returncode
)
)
print(">>> Running: git clean -f -d -e *-preupdate.patch")
returncode, stdout, stderr = _git(
["clean", "-f", "-d", "-e", "*-preupdate.patch"],
folder,
git_executable=git_executable,
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git clean -f" failed with returncode {}'.format(
returncode
)
)
print(">>> Running: git fetch")
returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
f'Could not update, "git fetch" failed with returncode {returncode}'
)
if branch is not None and branch.strip() != "":
print(f">>> Running: git checkout {branch}")
returncode, stdout, stderr = _git(
["checkout", branch], folder, git_executable=git_executable
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git checkout" failed with returncode {}'.format(
returncode
)
)
print(">>> Running: git pull")
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
f'Could not update, "git pull" failed with returncode {returncode}'
)
if force:
reset_command = ["reset", "--hard"]
reset_command += [target]
print(">>> Running: git {}".format(" ".join(reset_command)))
returncode, stdout, stderr = _git(
reset_command, folder, git_executable=git_executable
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Error while updating, "git {}" failed with returncode {}'.format(
" ".join(reset_command), returncode
)
)
def install_source(python_executable, folder, user=False, sudo=False):
print(">>> Running: python setup.py clean")
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
if returncode is None or returncode != 0:
print(f'"python setup.py clean" failed with returncode {returncode}')
print("Continuing anyways")
print(">>> Running: python setup.py install")
args = ["setup.py", "install"]
if user:
args.append("--user")
returncode, stdout, stderr = _python(args, folder, python_executable, sudo=sudo)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "python setup.py install" failed with returncode {}'.format(
returncode
)
)
def parse_arguments():
import argparse
boolean_trues = ["true", "yes", "1"]
parser = argparse.ArgumentParser(prog="update-octoprint.py")
parser.add_argument(
"--git",
action="store",
type=str,
dest="git_executable",
help="Specify git executable to use",
)
parser.add_argument(
"--python",
action="store",
type=str,
dest="python_executable",
help="Specify python executable to use",
)
parser.add_argument(
"--force",
action="store",
type=lambda x: x in boolean_trues,
dest="force",
default=False,
help="Set this to true to force the update to only the specified version (nothing newer, nothing older)",
)
parser.add_argument(
"--sudo", action="store_true", dest="sudo", help="Install with sudo"
)
parser.add_argument(
"--user",
action="store_true",
dest="user",
help="Install to the user site directory instead of the general site directory",
)
parser.add_argument(
"--branch",
action="store",
type=str,
dest="branch",
default=None,
help="Specify the branch to make sure is checked out",
)
parser.add_argument(
"folder",
type=str,
help="Specify the base folder of the OctoPrint installation to update",
)
parser.add_argument(
"target", type=str, help="Specify the commit or tag to which to update"
)
args = parser.parse_args()
return args
def main():
args = parse_arguments()
git_executable = None
if args.git_executable:
git_executable = args.git_executable
python_executable = sys.executable
if args.python_executable:
python_executable = args.python_executable
if python_executable.startswith('"'):
python_executable = python_executable[1:]
if python_executable.endswith('"'):
python_executable = python_executable[:-1]
print(f"Python executable: {python_executable!r}")
folder = args.folder
import os
if not os.access(folder, os.W_OK):
raise RuntimeError("Could not update, base folder is not writable")
update_source(
git_executable, folder, args.target, force=args.force, branch=args.branch
)
install_source(python_executable, folder, user=args.user, sudo=args.sudo)
if __name__ == "__main__":
main()
| 12,924 | Python | .py | 346 | 28.465318 | 126 | 0.583073 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,945 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/pluginmanager/__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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import logging
import os
import re
import shutil
import sys
import tempfile
import threading
import time
from datetime import datetime
import filetype
import pkg_resources
import pylru
import requests
import sarge
from flask import Response, abort, jsonify, request
from flask_babel import gettext
import octoprint.plugin
import octoprint.plugin.core
from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
from octoprint.server import safe_mode
from octoprint.server.util.flask import (
check_etag,
ensure_credentials_checked_recently,
no_firstrun_access,
require_credentials_checked_recently,
with_revalidation_checking,
)
from octoprint.settings import valid_boolean_trues
from octoprint.util import RepeatedTimer, deprecated, to_bytes
from octoprint.util.net import download_file
from octoprint.util.pip import (
OUTPUT_SUCCESS,
create_pip_caller,
get_result_line,
is_already_installed,
is_python_mismatch,
)
from octoprint.util.platform import get_os, is_os_compatible
from octoprint.util.version import (
get_octoprint_version,
get_octoprint_version_string,
is_octoprint_compatible,
is_python_compatible,
)
from . import exceptions
_DATA_FORMAT_VERSION = "v3"
DEFAULT_PLUGIN_REPOSITORY = "https://plugins.octoprint.org/plugins.json"
DEFAULT_PLUGIN_NOTICES = "https://plugins.octoprint.org/notices.json"
def map_repository_entry(entry):
if not isinstance(entry, dict):
return None
result = copy.deepcopy(entry)
if "follow_dependency_links" not in result:
result["follow_dependency_links"] = False
if "privacypolicy" not in result:
result["privacypolicy"] = False
result["is_compatible"] = {"octoprint": True, "os": True, "python": True}
if "compatibility" in entry:
if (
"octoprint" in entry["compatibility"]
and entry["compatibility"]["octoprint"] is not None
and isinstance(entry["compatibility"]["octoprint"], (list, tuple))
and len(entry["compatibility"]["octoprint"])
):
result["is_compatible"]["octoprint"] = is_octoprint_compatible(
*entry["compatibility"]["octoprint"]
)
if (
"os" in entry["compatibility"]
and entry["compatibility"]["os"] is not None
and isinstance(entry["compatibility"]["os"], (list, tuple))
and len(entry["compatibility"]["os"])
):
result["is_compatible"]["os"] = is_os_compatible(entry["compatibility"]["os"])
if (
"python" in entry["compatibility"]
and entry["compatibility"]["python"] is not None
and isinstance(entry["compatibility"]["python"], str)
):
result["is_compatible"]["python"] = is_python_compatible(
entry["compatibility"]["python"]
)
else:
# we default to only assume py2 compatibility for now
result["is_compatible"]["python"] = is_python_compatible(">=2.7,<3")
return result
class PluginManagerPlugin(
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.EventHandlerPlugin,
):
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar", ".gz", ".whl")
PYTHON_EXTENSIONS = (".py",)
JSON_EXTENSIONS = (".json",)
# valid pip install URL schemes according to https://pip.pypa.io/en/stable/reference/pip_install/
URL_SCHEMES = (
"http",
"https",
"git",
"git+http",
"git+https",
"git+ssh",
"git+git",
"hg+http",
"hg+https",
"hg+static-http",
"hg+ssh",
"svn",
"svn+svn",
"svn+http",
"svn+https",
"svn+ssh",
"bzr+http",
"bzr+https",
"bzr+ssh",
"bzr+sftp",
"bzr+ftp",
"bzr+lp",
)
OPERATING_SYSTEMS = {
"windows": ["win32"],
"linux": lambda x: x.startswith("linux"),
"macos": ["darwin"],
"freebsd": lambda x: x.startswith("freebsd"),
}
PIP_INAPPLICABLE_ARGUMENTS = {"uninstall": ["--user"]}
RECONNECT_HOOKS = [
"octoprint.comm.protocol.*",
]
# noinspection PyMissingConstructor
def __init__(self):
self._pending_enable = set()
self._pending_disable = set()
self._pending_install = set()
self._pending_uninstall = set()
self._pip_caller = None
self._repository_available = False
self._repository_plugins = []
self._repository_plugins_by_id = {}
self._repository_cache_path = None
self._repository_cache_ttl = 0
self._repository_mtime = None
self._notices = {}
self._notices_available = False
self._notices_cache_path = None
self._notices_cache_ttl = 0
self._notices_mtime = None
self._orphans = None
self._console_logger = None
self._get_throttled = lambda: False
self._install_task = None
self._install_lock = threading.RLock()
self._jsoninstall_lock = threading.Lock()
self._queued_installs = []
self._queued_installs_abort_timer = None
self._print_cancelled = False
def initialize(self):
self._console_logger = logging.getLogger(
"octoprint.plugins.pluginmanager.console"
)
self._repository_cache_path = os.path.join(
self.get_plugin_data_folder(), "plugins.json"
)
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._notices_cache_path = os.path.join(
self.get_plugin_data_folder(), "notices.json"
)
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
self._pip_caller = create_pip_caller(
command=self._settings.global_get(["server", "commands", "localPipCommand"]),
force_user=self._settings.get_boolean(["pip_force_user"]),
)
self._pip_caller.on_log_call = self._log_call
self._pip_caller.on_log_stdout = self._log_stdout
self._pip_caller.on_log_stderr = self._log_stderr
##~~ Body size hook
def increase_upload_bodysize(self, current_max_body_sizes, *args, **kwargs):
# set a maximum body size of 50 MB for plugin archive uploads
return [("POST", r"/upload_file", 50 * 1024 * 1024)]
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "LIST",
"name": "List plugins",
"description": gettext("Allows to list installed plugins."),
"default_groups": [READONLY_GROUP, USER_GROUP, ADMIN_GROUP],
"roles": ["list"],
},
{
"key": "MANAGE",
"name": "Manage plugins",
"description": gettext(
"Allows to enable, disable and uninstall installed plugins."
),
"default_groups": [ADMIN_GROUP],
"roles": ["manage"],
},
{
"key": "INSTALL",
"name": "Install new plugins",
"description": gettext(
'Allows to install new plugins. Includes the "Manage plugins" permission.'
),
"default_groups": [ADMIN_GROUP],
"roles": ["install"],
"permissions": ["PLUGIN_PLUGINMANAGER_MANAGE"],
"dangerous": True,
},
]
# Additional bundle contents
def get_additional_bundle_files(self, *args, **kwargs):
console_log = self._settings.get_plugin_logfile_path(postfix="console")
return {os.path.basename(console_log): console_log}
##~~ StartupPlugin
def on_after_startup(self):
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
console_logging_handler = CleaningTimedRotatingFileHandler(
self._settings.get_plugin_logfile_path(postfix="console"),
when="D",
backupCount=3,
)
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
console_logging_handler.setLevel(logging.DEBUG)
self._console_logger.addHandler(console_logging_handler)
self._console_logger.setLevel(logging.DEBUG)
self._console_logger.propagate = False
helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if helpers and "get_throttled" in helpers:
self._get_throttled = helpers["get_throttled"]
if self._settings.get_boolean(["ignore_throttled"]):
self._logger.warning(
"!!! THROTTLE STATE IGNORED !!! You have configured the Plugin Manager plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it."
)
# decouple repository fetching from server startup
self._fetch_all_data(do_async=True)
##~~ SettingsPlugin
def get_settings_defaults(self):
return {
"repository": DEFAULT_PLUGIN_REPOSITORY,
"repository_ttl": 24 * 60,
"notices": DEFAULT_PLUGIN_NOTICES,
"notices_ttl": 6 * 60,
"pip_args": None,
"pip_force_user": False,
"confirm_disable": False,
"dependency_links": False,
"hidden": [],
"ignore_throttled": False,
}
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"])
##~~ AssetPlugin
def get_assets(self):
return {
"js": ["js/pluginmanager.js"],
"clientjs": ["clientjs/pluginmanager.js"],
"css": ["css/pluginmanager.css"],
"less": ["less/pluginmanager.less"],
}
##~~ TemplatePlugin
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Plugin Manager"),
"template": "pluginmanager_settings.jinja2",
"custom_bindings": True,
},
{
"type": "about",
"name": "Plugin Licenses",
"template": "pluginmanager_about.jinja2",
},
]
def get_template_vars(self):
plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower())
return {
"all": plugins,
"thirdparty": list(filter(lambda p: not p["bundled"], plugins)),
"file_extensions": self.ARCHIVE_EXTENSIONS
+ self.PYTHON_EXTENSIONS
+ self.JSON_EXTENSIONS,
}
def get_template_types(self, template_sorting, template_rules, *args, **kwargs):
return [
(
"about_thirdparty",
{},
{"template": lambda x: x + "_about_thirdparty.jinja2"},
)
]
##~~ BlueprintPlugin
@octoprint.plugin.BlueprintPlugin.route("/upload_file", methods=["POST"])
@no_firstrun_access
@require_credentials_checked_recently
@Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403)
def upload_file(self):
import flask
input_name = "file"
input_upload_path = (
input_name
+ "."
+ self._settings.global_get(["server", "uploads", "pathSuffix"])
)
input_upload_name = (
input_name
+ "."
+ self._settings.global_get(["server", "uploads", "nameSuffix"])
)
if (
input_upload_path not in flask.request.values
or input_upload_name not in flask.request.values
):
abort(400, description="No file included")
upload_path = flask.request.values[input_upload_path]
upload_name = flask.request.values[input_upload_name]
exts = list(
filter(
lambda x: upload_name.lower().endswith(x),
self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS + self.JSON_EXTENSIONS,
)
)
if not len(exts):
abort(
400,
description="File doesn't have a valid extension for a plugin archive or a single file plugin",
)
ext = exts[0]
archive = tempfile.NamedTemporaryFile(delete=False, suffix=ext)
archive.close()
shutil.copy(upload_path, archive.name)
def perform_install(source, name, force=False):
try:
self.command_install(
path=source,
name=name,
force=force,
)
finally:
try:
os.remove(archive.name)
except Exception as e:
self._logger.warning(
"Could not remove temporary file {path} again: {message}".format(
path=archive.name, message=str(e)
)
)
with self._install_lock:
if self._install_task is not None:
abort(409, description="There's already a plugin being installed")
self._install_task = threading.Thread(
target=perform_install,
args=(archive.name, upload_name),
kwargs={
"force": "force" in flask.request.values
and flask.request.values["force"] in valid_boolean_trues
},
)
self._install_task.daemon = True
self._install_task.start()
return jsonify(in_progress=True)
@octoprint.plugin.BlueprintPlugin.route("/export", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
def export_plugin_list(self):
import json
plugins = self.generate_plugins_json(
self._settings,
self._plugin_manager,
repo_plugins=self._repository_plugins_by_id,
)
return Response(
json.dumps(plugins),
mimetype="application/json",
headers={"Content-Disposition": 'attachment; filename="plugin_list.json"'},
)
def _plugin_response(self):
return {
"plugins": self._get_plugins(),
"os": get_os(),
"octoprint": get_octoprint_version_string(),
"pip": {
"available": self._pip_caller.available,
"version": self._pip_caller.version_string,
"install_dir": self._pip_caller.install_dir,
"use_user": self._pip_caller.use_user,
"virtual_env": self._pip_caller.virtual_env,
"additional_args": self._settings.get(["pip_args"]),
"python": sys.executable,
},
"safe_mode": safe_mode,
"online": self._connectivity_checker.online,
"supported_extensions": {
"archive": self.ARCHIVE_EXTENSIONS,
"python": self.PYTHON_EXTENSIONS,
"json": self.JSON_EXTENSIONS,
},
}
@octoprint.plugin.BlueprintPlugin.route("/plugins")
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
def retrieve_plugins(self):
refresh = request.values.get("refresh", "false") in valid_boolean_trues
if refresh or not self._is_notices_cache_valid():
self._notices_available = self._refresh_notices()
def view():
return jsonify(**self._plugin_response())
def etag():
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(repr(self._get_plugins()))
hash_update(repr(self._pip_caller.version_string))
hash_update(str(self._notices_available))
hash_update(repr(self._notices))
hash_update(repr(safe_mode))
hash_update(repr(self._connectivity_checker.online))
hash_update(repr(self.ARCHIVE_EXTENSIONS))
hash_update(repr(self.PYTHON_EXTENSIONS))
hash_update(repr(_DATA_FORMAT_VERSION))
return hash.hexdigest()
def condition():
return check_etag(etag())
return with_revalidation_checking(
etag_factory=lambda *args, **kwargs: etag(),
condition=lambda *args, **kwargs: condition(),
unless=lambda: refresh,
)(view)()
@octoprint.plugin.BlueprintPlugin.route("/plugins/versions")
@Permissions.PLUGIN_PLUGINMANAGER_LIST.require(403)
def retrieve_plugin_list(self):
return jsonify(
{p["key"]: p["version"] for p in self._get_plugins() if p["enabled"]}
)
@octoprint.plugin.BlueprintPlugin.route("/plugins/<string:key>")
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
def retrieve_specific_plugin(self, key):
plugin = self._plugin_manager.get_plugin_info(key, require_enabled=False)
if plugin is None:
return abort(404)
return jsonify(plugin=self._to_external_plugin(plugin))
def _orphan_response(self):
return {"orphan_data": self._get_orphans()}
@octoprint.plugin.BlueprintPlugin.route("/orphans")
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
def retrieve_plugin_orphans(self):
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
abort(403)
refresh = request.values.get("refresh", "false") in valid_boolean_trues
if refresh:
self._get_orphans(refresh=True)
def view():
return jsonify(**self._orphan_response())
def etag():
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(repr(self._get_orphans()))
hash_update(repr(_DATA_FORMAT_VERSION))
return hash.hexdigest()
def condition():
return check_etag(etag())
return with_revalidation_checking(
etag_factory=lambda *args, **kwargs: etag(),
condition=lambda *args, **kwargs: condition(),
unless=lambda: refresh,
)(view)()
def _repository_response(self):
return {
"repository": {
"available": self._repository_available,
"plugins": self._repository_plugins,
}
}
@octoprint.plugin.BlueprintPlugin.route("/repository")
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
def retrieve_plugin_repository(self):
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
abort(403)
refresh = request.values.get("refresh", "false") in valid_boolean_trues
if refresh or not self._is_repository_cache_valid():
self._repository_available = self._refresh_repository()
def view():
return jsonify(**self._repository_response())
def etag():
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(str(self._repository_available))
hash_update(repr(self._repository_plugins))
hash_update(repr(_DATA_FORMAT_VERSION))
return hash.hexdigest()
def condition():
return check_etag(etag())
return with_revalidation_checking(
etag_factory=lambda *args, **kwargs: etag(),
condition=lambda *args, **kwargs: condition(),
unless=lambda: refresh,
)(view)()
def is_blueprint_protected(self):
return False
def is_blueprint_csrf_protected(self):
return True
##~~ EventHandlerPlugin
def on_event(self, event, payload):
from octoprint.events import Events
if event == Events.PRINT_STARTED:
self._queued_installs_timer_stop()
self._print_cancelled = False
elif (
event == Events.PRINT_DONE
and self._settings.global_get(["webcam", "timelapse", "type"]) == "off"
and len(self._queued_installs) > 0
):
self._queued_installs_timer_start()
elif event == Events.PRINT_FAILED and len(self._queued_installs) > 0:
self._send_result_notification(
"queued_installs",
{
"type": "queued_installs",
"print_failed": True,
"queued": self._queued_installs,
},
)
self._print_cancelled = True
elif (
event == Events.MOVIE_DONE
and self._settings.global_get(["webcam", "timelapse", "type"]) != "off"
and len(self._queued_installs) > 0
and not (self._printer.is_printing() or self._printer.is_paused())
and not self._print_cancelled
):
self._queued_installs_timer_start()
elif event == Events.USER_LOGGED_IN and len(self._queued_installs) > 0:
self._send_result_notification(
"queued_installs",
{
"type": "queued_installs",
"queued": self._queued_installs,
},
)
elif (
event != Events.CONNECTIVITY_CHANGED
or not payload
or not payload.get("new", False)
):
return
self._fetch_all_data(do_async=True)
def _queued_installs_timer_start(self):
if self._queued_installs_abort_timer is not None:
return
self._logger.debug("Starting queued updates timer.")
self._timeout_value = 60
self._queued_installs_abort_timer = RepeatedTimer(
1, self._queued_installs_timer_task
)
self._queued_installs_abort_timer.start()
def _queued_installs_timer_stop(self):
if self._queued_installs_abort_timer is not None:
self._queued_installs_abort_timer.cancel()
self._queued_installs_abort_timer = None
self._send_result_notification(
"queued_installs",
{
"type": "queued_installs",
"queued": self._queued_installs,
"timeout_value": -1,
},
)
def _queued_installs_timer_task(self):
if self._timeout_value is None:
return
self._timeout_value -= 1
self._send_result_notification(
"queued_installs",
{
"type": "queued_installs",
"queued": self._queued_installs,
"timeout_value": self._timeout_value,
},
)
if self._timeout_value <= 0:
if self._queued_installs_abort_timer is not None:
self._queued_installs_abort_timer.cancel()
self._queued_installs_abort_timer = None
for plugin in self._queued_installs:
plugin.pop("command")
self.command_install(**plugin)
self._queued_installs = []
##~~ SimpleApiPlugin
def get_api_commands(self):
return {
"install": ["url"],
"uninstall": ["plugin"],
"enable": ["plugin"],
"disable": ["plugin"],
"cleanup": ["plugin"],
"cleanup_all": [],
"refresh_repository": [],
"clear_queued_plugin": ["plugin"],
"clear_queued_installs": [],
}
def on_api_command(self, command, data):
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
abort(403)
if command == "clear_queued_plugin":
if data["plugin"] and data["plugin"] in self._queued_installs:
self._queued_installs.remove(data["plugin"])
return (
jsonify({"queued_installs": self._queued_installs}),
202,
)
elif command == "clear_queued_installs":
self._queued_installs.clear()
return (
jsonify({"queued_installs": self._queued_installs}),
202,
)
elif self._printer.is_printing() or self._printer.is_paused():
# do not update while a print job is running
# store targets to be run later on print done event
if command == "install" and data not in self._queued_installs:
if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can():
abort(403)
ensure_credentials_checked_recently()
self._logger.debug(f"Queuing install of {data}")
self._queued_installs.append(data)
if len(self._queued_installs) > 0:
self._logger.debug(f"Queued installs: {self._queued_installs}")
return (
jsonify({"queued_installs": self._queued_installs}),
202,
)
else:
abort(
409,
description="Printer is currently printing or paused and install could not be queued",
)
elif command == "install":
if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can():
abort(403)
ensure_credentials_checked_recently()
url = data["url"]
plugin_name = data.get("plugin")
from_repo = data.get("from_repo", False)
with self._install_lock:
if self._install_task is not None:
abort(409, description="There's already a plugin being installed")
self._install_task = threading.Thread(
target=self.command_install,
kwargs={
"url": url,
"force": "force" in data and data["force"] in valid_boolean_trues,
"dependency_links": "dependency_links" in data
and data["dependency_links"] in valid_boolean_trues,
"reinstall": plugin_name,
"from_repo": from_repo,
},
)
self._install_task.daemon = True
self._install_task.start()
return jsonify(in_progress=True)
elif command == "uninstall":
plugin_name = data["plugin"]
if plugin_name not in self._plugin_manager.plugins:
abort(404, description="Unknown plugin")
plugin = self._plugin_manager.plugins[plugin_name]
return self.command_uninstall(plugin, cleanup=data.get("cleanup", False))
elif command == "cleanup":
plugin = data["plugin"]
try:
plugin = self._plugin_manager.plugins[plugin]
except KeyError:
# not installed, we are cleaning up left overs, that's ok
pass
return self.command_cleanup(plugin, include_disabled=True)
elif command == "cleanup_all":
return self.command_cleanup_all()
elif command == "enable" or command == "disable":
plugin_name = data["plugin"]
if plugin_name not in self._plugin_manager.plugins:
abort(404, description="Unknown plugin")
plugin = self._plugin_manager.plugins[plugin_name]
return self.command_toggle(plugin, command)
@deprecated(
"Deprecated API endpoint api/plugin/pluginmanager used. "
"Please switch clients to plugin/pluginmanager/*",
since="1.6.0",
)
def on_api_get(self, r):
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
abort(403)
refresh_repository = (
request.values.get("refresh_repository", "false") in valid_boolean_trues
)
if refresh_repository or not self._is_repository_cache_valid():
self._repository_available = self._refresh_repository()
refresh_notices = (
request.values.get("refresh_notices", "false") in valid_boolean_trues
)
if refresh_notices or not self._is_notices_cache_valid():
self._notices_available = self._refresh_notices()
refresh_orphan = (
request.values.get("refresh_orphans", "false") in valid_boolean_trues
)
if refresh_orphan:
self._get_orphans(refresh=True)
result = {}
result.update(**self._plugin_response())
result.update(**self._orphan_response())
result.update(**self._repository_response())
return jsonify(**result)
# noinspection PyMethodMayBeStatic
def _is_archive(self, path):
_, ext = os.path.splitext(path)
if ext in PluginManagerPlugin.ARCHIVE_EXTENSIONS:
return True
kind = filetype.guess(path)
if kind:
return f".{kind.extension}" in PluginManagerPlugin.ARCHIVE_EXTENSIONS
return False
def _is_pythonfile(self, path):
_, ext = os.path.splitext(path)
if ext in PluginManagerPlugin.PYTHON_EXTENSIONS:
import ast
try:
with open(path, "rb") as f:
ast.parse(f.read(), filename=path)
return True
except Exception as exc:
self._logger.exception(f"Could not parse {path} as python file: {exc}")
return False
def _is_jsonfile(self, path):
_, ext = os.path.splitext(path)
if ext in PluginManagerPlugin.JSON_EXTENSIONS:
import json
try:
with open(path) as f:
json.load(f)
return True
except Exception as exc:
self._logger.exception(f"Could not parse {path} as json file: {exc}")
def command_install(
self,
url=None,
path=None,
name=None,
force=False,
reinstall=None,
dependency_links=False,
partial=False,
from_repo=False,
):
folder = None
with self._install_lock:
try:
source = path
source_type = "path"
if url is not None:
# fetch URL
folder = tempfile.TemporaryDirectory()
path = download_file(url, folder.name)
source = url
source_type = "url"
# determine type of path
if self._is_archive(path):
result = self._command_install_archive(
path,
source=source,
source_type=source_type,
force=force,
reinstall=reinstall,
dependency_links=dependency_links,
partial=partial,
from_repo=from_repo,
)
elif self._is_pythonfile(path):
result = self._command_install_pythonfile(
path,
source=source,
source_type=source_type,
name=name,
partial=partial,
from_repo=from_repo,
)
elif self._is_jsonfile(path):
result = self._command_install_jsonfile(
path,
source=source,
source_type=source_type,
name=name,
partial=partial,
from_repo=from_repo,
)
else:
raise exceptions.InvalidPackageFormat()
except requests.exceptions.HTTPError as e:
self._logger.error(f"Could not fetch plugin from server, got {e}")
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": f"Could not fetch plugin from server, got {e}",
}
self._send_result_notification("install", result, partial=partial)
except exceptions.InvalidPackageFormat:
self._logger.error(
"{} is neither an archive nor a python file, can't install that.".format(
source
)
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Could not install plugin from {}, was neither "
"a plugin archive nor a single file plugin".format(source),
}
self._send_result_notification("install", result, partial=partial)
except Exception:
error_msg = (
"Unexpected error while trying to install plugin from {}".format(
source
)
)
self._logger.exception(error_msg)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": error_msg,
}
self._send_result_notification("install", result, partial=partial)
finally:
if folder is not None:
folder.cleanup()
self._install_task = None
return result
# noinspection DuplicatedCode
def _command_install_archive(
self,
path,
source=None,
source_type=None,
force=False,
reinstall=None,
dependency_links=False,
partial=False,
from_repo=False,
):
throttled = self._get_throttled()
if (
throttled
and isinstance(throttled, dict)
and throttled.get("current_issue", False)
and not self._settings.get_boolean(["ignore_throttled"])
):
# currently throttled, we refuse to run
error_msg = (
"System is currently throttled, refusing to install anything"
" due to possible stability issues"
)
self._logger.error(error_msg)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": error_msg,
}
self._send_result_notification("install", result, partial=partial)
return result
from urllib.parse import quote as url_quote
path = os.path.abspath(path)
if os.sep != "/":
# windows gets special handling
drive, loc = os.path.splitdrive(path)
path_url = (
"file:///" + drive.lower() + url_quote(loc.replace(os.sep, "/").lower())
)
shell_quote = lambda x: x # do not shell quote under windows, non posix shell
else:
path_url = "file://" + url_quote(path)
shell_quote = sarge.shell_quote
self._logger.info(f"Installing plugin from {source}")
pip_args = [
"--disable-pip-version-check",
"install",
shell_quote(path_url),
"--no-cache-dir",
]
if dependency_links or self._settings.get_boolean(["dependency_links"]):
pip_args.append("--process-dependency-links")
all_plugins_before = self._plugin_manager.find_plugins(existing={})
try:
_, stdout, stderr = self._call_pip(pip_args)
if not force and is_already_installed(stdout):
self._logger.info(
"Plugin to be installed from {} was already installed, forcing a reinstall".format(
source
)
)
self._log_message(
"Looks like the plugin was already installed. Forcing a reinstall."
)
force = True
except Exception as e:
self._logger.exception(f"Could not install plugin from {source}")
self._logger.exception(f"Reason: {repr(e)}")
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Could not install plugin from {}, see the log for more details".format(
source
),
}
self._send_result_notification("install", result, partial=partial)
return result
if is_python_mismatch(stderr):
return self.handle_python_mismatch(source, source_type, partial=partial)
if force:
# We don't use --upgrade here because that will also happily update all our dependencies - we'd rather
# do that in a controlled manner
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
try:
_, stdout, stderr = self._call_pip(pip_args)
except Exception as e:
self._logger.exception(f"Could not install plugin from {source}")
self._logger.exception(f"Reason: {repr(e)}")
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Could not install plugin from source {}, see the log for more details".format(
source
),
}
self._send_result_notification("install", result, partial=partial)
return result
if is_python_mismatch(stderr):
return self.handle_python_mismatch(source, source_type)
result_line = get_result_line(stdout)
if not result_line:
self._logger.error(
"Installing the plugin from {} failed, could not parse output from pip. "
"See plugin_pluginmanager_console.log for generated output".format(source)
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Could not parse output from pip, see plugin_pluginmanager_console.log "
"for generated output",
}
self._send_result_notification("install", result, partial=partial)
return result
# We'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split
# by whitespace and strip to get all installed packages.
#
# We then need to iterate over all known plugins and see if either the package name or the package name plus
# version number matches one of our installed packages. If it does, that's our installed plugin.
#
# Known issue: This might return the wrong plugin if more than one plugin was installed through this
# command (e.g. due to pulling in another plugin as dependency). It should be safe for now though to
# consider this a rare corner case. Once it becomes a real problem we'll just extend the plugin manager
# so that it can report on more than one installed plugin.
result_line = result_line.strip()
if not result_line.startswith(OUTPUT_SUCCESS):
self._logger.error(
"Installing the plugin from {} failed, pip did not report successful installation".format(
source
)
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Pip did not report successful installation",
}
self._send_result_notification("install", result, partial=partial)
return result
installed = list(
map(lambda x: x.strip(), result_line[len(OUTPUT_SUCCESS) :].split(" "))
)
all_plugins_after = self._plugin_manager.find_plugins(
existing={}, ignore_uninstalled=False
)
new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after)
if new_plugin is None:
self._logger.warning(
"The plugin was installed successfully, but couldn't be found afterwards to "
"initialize properly during runtime. Please restart OctoPrint."
)
result = {
"result": True,
"source": source,
"source_type": source_type,
"needs_restart": True,
"needs_refresh": True,
"needs_reconnect": True,
"was_reinstalled": False,
"plugin": "unknown",
}
self._send_result_notification("install", result, partial=partial)
return result
self._plugin_manager.reload_plugins()
needs_restart = (
self._plugin_manager.is_restart_needing_plugin(new_plugin)
or new_plugin.key in all_plugins_before
or reinstall is not None
)
needs_refresh = new_plugin.implementation and isinstance(
new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin
)
needs_reconnect = (
self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks)
and self._printer.is_operational()
)
is_reinstall = self._plugin_manager.is_plugin_marked(
new_plugin.key, "uninstalled"
)
self._plugin_manager.mark_plugin(
new_plugin.key,
uninstalled=False,
installed=not is_reinstall and needs_restart,
)
self._plugin_manager.log_all_plugins()
self._logger.info(
"The plugin was installed successfully: {}, version {}".format(
new_plugin.name, new_plugin.version
)
)
# noinspection PyUnresolvedReferences
self._event_bus.fire(
Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN,
{
"id": new_plugin.key,
"version": new_plugin.version,
"source": source,
"source_type": source_type,
"from_repo": from_repo,
},
)
result = {
"result": True,
"source": source,
"source_type": source_type,
"needs_restart": needs_restart,
"needs_refresh": needs_refresh,
"needs_reconnect": needs_reconnect,
"was_reinstalled": new_plugin.key in all_plugins_before
or reinstall is not None,
"plugin": self._to_external_plugin(new_plugin),
}
self._send_result_notification("install", result, partial=partial)
return result
def _handle_python_mismatch(self, source, source_type, partial=False):
self._logger.error(
"Installing the plugin from {} failed, pip reported a Python version mismatch".format(
source
)
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Pip reported a Python version mismatch",
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
}
self._send_result_notification("install", result, partial=partial)
return result
# noinspection DuplicatedCode
def _command_install_pythonfile(
self,
path,
source=None,
source_type=None,
name=None,
partial=False,
from_repo=False,
):
if name is None:
name = os.path.basename(path)
self._logger.info(f"Installing single file plugin {name} from {source}")
all_plugins_before = self._plugin_manager.find_plugins(existing={})
destination = os.path.join(self._settings.global_get_basefolder("plugins"), name)
plugin_id, _ = os.path.splitext(name)
# check python compatibility
PYTHON_MISMATCH = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Plugin could not be installed",
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
}
try:
metadata = octoprint.plugin.core.parse_plugin_metadata(path)
except SyntaxError:
self._logger.exception(
"Installing plugin from {} failed, there's a Python version mismatch".format(
source
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result, partial=partial)
return result
pythoncompat = metadata.get(
octoprint.plugin.core.ControlProperties.attr_pythoncompat,
octoprint.plugin.core.ControlProperties.default_pythoncompat,
)
if not is_python_compatible(pythoncompat):
self._logger.exception(
"Installing plugin from {} failed, there's a Python version mismatch".format(
source
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result, partial=partial)
return result
# copy plugin
try:
self._log_call(f"cp {path} {destination}")
shutil.copy(path, destination)
except Exception:
self._logger.exception(f"Installing plugin from {source} failed")
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Plugin could not be copied",
}
self._send_result_notification("install", result, partial=partial)
return result
plugins = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False)
new_plugin = plugins.get(plugin_id)
if new_plugin is None:
self._logger.warning(
"The plugin was installed successfully, but couldn't be found afterwards to "
"initialize properly during runtime. Please restart OctoPrint."
)
result = {
"result": True,
"source": source,
"source_type": source_type,
"needs_restart": True,
"needs_refresh": True,
"needs_reconnect": True,
"was_reinstalled": False,
"plugin": "unknown",
}
self._send_result_notification("install", result, partial=partial)
return result
self._plugin_manager.reload_plugins()
needs_restart = (
self._plugin_manager.is_restart_needing_plugin(new_plugin)
or new_plugin.key in all_plugins_before
)
needs_refresh = new_plugin.implementation and isinstance(
new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin
)
needs_reconnect = (
self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks)
and self._printer.is_operational()
)
self._logger.info(
"The plugin was installed successfully: {}, version {}".format(
new_plugin.name, new_plugin.version
)
)
self._plugin_manager.log_all_plugins()
# noinspection PyUnresolvedReferences
self._event_bus.fire(
Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN,
{
"id": new_plugin.key,
"version": new_plugin.version,
"source": source,
"source_type": source_type,
"from_repo": from_repo,
},
)
result = {
"result": True,
"source": source,
"source_type": source_type,
"needs_restart": needs_restart,
"needs_refresh": needs_refresh,
"needs_reconnect": needs_reconnect,
"was_reinstalled": new_plugin.key in all_plugins_before,
"plugin": self._to_external_plugin(new_plugin),
}
self._send_result_notification("install", result, partial=partial)
return result
def _command_install_jsonfile(
self,
path,
source=None,
source_type=None,
name=None,
partial=False,
from_repo=False,
):
import json
sub_results = []
try:
if not self._jsoninstall_lock.acquire(blocking=False):
self._logger.error(
"Attempting to install from json file from within an install running from a json install - this is not supported"
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Recursive json install",
}
self._send_result_notification("install", result, partial=partial)
return result
if name is None:
name = os.path.basename(path)
self._logger.info(f"Installing plugins from export {name} from {source}")
with open(path) as f:
export = json.load(f)
if not isinstance(export, list):
self._logger.error(
f"Installing plugins from export {name} from {source} failed, export is not a list"
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Invalid export",
}
self._send_result_notification("install", result, partial=partial)
return result
for entry in export:
if isinstance(entry, dict):
archive = entry.get("archive")
name = None
if archive is None:
if not self._repository_available:
continue
key = entry.get("key")
if not key:
continue
repo_entry = self._repository_plugins_by_id.get(key)
if not repo_entry:
continue
archive = repo_entry.get("archive")
if not archive:
continue
elif isinstance(entry, str):
# just a URL?
archive = entry
try:
message = f"Installing plugin from {archive}"
self._logger.info(message)
self._log_message(message)
sub_result = self.command_install(
url=archive, name=name, partial=True, from_repo=from_repo
)
sub_results.append(sub_result)
except Exception:
self._logger.exception(
f"Installing plugin from {archive} failed, continuing with next entry"
)
finally:
self._jsoninstall_lock.release()
result = {
"result": True,
"source": source,
"source_type": source_type,
"sub_results": sub_results,
}
self._send_result_notification("install", result, partial=partial)
return result
def command_uninstall(self, plugin, cleanup=False):
if plugin.key == "pluginmanager":
abort(403, description="Can't uninstall Plugin Manager")
if not plugin.managable:
abort(
403, description="Plugin is not managable and hence cannot be uninstalled"
)
if plugin.bundled:
abort(403, description="Bundled plugins cannot be uninstalled")
if plugin.origin is None:
self._logger.warning(
f"Trying to uninstall plugin {plugin} but origin is unknown"
)
abort(500, description="Could not uninstall plugin, its origin is unknown")
if plugin.implementation:
try:
plugin.implementation.on_plugin_pending_uninstall()
except Exception:
self._logger.exception(
"Error while calling on_plugin_pending_uninstall on the plugin, proceeding regardless"
)
if plugin.origin.type == "entry_point":
# plugin is installed through entry point, need to use pip to uninstall it
origin = plugin.origin[3]
if origin is None:
origin = plugin.origin[2]
pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin]
try:
self._call_pip(pip_args)
except Exception:
self._logger.exception("Could not uninstall plugin via pip")
abort(
500,
description="Could not uninstall plugin via pip, see the log for more details",
)
elif plugin.origin.type == "folder":
import os
import shutil
full_path = os.path.realpath(plugin.location)
if os.path.isdir(full_path):
# plugin is installed via a plugin folder, need to use rmtree to get rid of it
self._log_stdout(f"Deleting plugin from {plugin.location}")
shutil.rmtree(full_path)
elif os.path.isfile(full_path):
self._log_stdout(f"Deleting plugin from {plugin.location}")
os.remove(full_path)
if full_path.endswith(".py"):
pyc_file = f"{full_path}c"
if os.path.isfile(pyc_file):
self._log_stdout(f"Deleting plugin from {pyc_file}")
os.remove(pyc_file)
else:
self._logger.warning(
f"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})"
)
abort(500, description="Could not uninstall plugin, its origin is unknown")
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup
needs_refresh = plugin.implementation and isinstance(
plugin.implementation, octoprint.plugin.ReloadNeedingPlugin
)
needs_reconnect = (
self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks)
and self._printer.is_operational()
)
was_pending_install = self._plugin_manager.is_plugin_marked(
plugin.key, "installed"
)
self._plugin_manager.mark_plugin(
plugin.key,
uninstalled=not was_pending_install and needs_restart,
installed=False,
)
if not needs_restart:
try:
if plugin.enabled:
self._plugin_manager.disable_plugin(plugin.key, plugin=plugin)
except octoprint.plugin.core.PluginLifecycleException as e:
self._logger.exception(f"Problem disabling plugin {plugin.key}")
result = {
"result": False,
"uninstalled": True,
"disabled": False,
"unloaded": False,
"reason": e.reason,
}
self._send_result_notification("uninstall", result)
return jsonify(result)
try:
if plugin.loaded:
self._plugin_manager.unload_plugin(plugin.key)
except octoprint.plugin.core.PluginLifecycleException as e:
self._logger.exception(f"Problem unloading plugin {plugin.key}")
result = {
"result": False,
"uninstalled": True,
"disabled": True,
"unloaded": False,
"reason": e.reason,
}
self._send_result_notification("uninstall", result)
return jsonify(result)
self._plugin_manager.reload_plugins()
# noinspection PyUnresolvedReferences
self._event_bus.fire(
Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN,
{"id": plugin.key, "version": plugin.version},
)
result = {
"result": True,
"needs_restart": needs_restart,
"needs_refresh": needs_refresh,
"needs_reconnect": needs_reconnect,
"plugin": self._to_external_plugin(plugin),
}
self._send_result_notification("uninstall", result)
self._logger.info(f"Plugin {plugin.key} uninstalled")
self._cleanup_disabled(plugin.key)
if cleanup:
self.command_cleanup(plugin.key, result_notifications=False)
return jsonify(result)
def command_cleanup(
self,
plugin,
include_disabled=False,
result_notifications=True,
settings_save=True,
):
if isinstance(plugin, str):
key = result_value = plugin
else:
key = plugin.key
result_value = self._to_external_plugin(plugin)
message = f"Cleaning up plugin {key}..."
self._logger.info(message)
self._log_stdout(message)
# delete plugin settings
self._cleanup_settings(key)
# delete plugin disabled entry
if include_disabled:
self._cleanup_disabled(key)
# delete plugin data folder
result_data = True
if not self._cleanup_data(key):
message = f"Could not delete data folder of plugin {key}"
self._logger.exception(message)
self._log_stderr(message)
result_data = False
if settings_save:
self._settings.save()
result = {"result": result_data, "needs_restart": True, "plugin": result_value}
if result_notifications:
self._send_result_notification("cleanup", result)
# cleaning orphan cache
self._orphans = None
return jsonify(result)
def command_cleanup_all(self):
orphans = self._get_orphans()
cleaned_up = set()
for orphan in sorted(orphans.keys()):
self.command_cleanup(
orphan,
include_disabled=True,
result_notifications=False,
settings_save=False,
)
cleaned_up.add(orphan)
self._settings.save()
result = {
"result": True,
"needs_restart": len(cleaned_up) > 0,
"cleaned_up": sorted(list(cleaned_up)),
}
self._send_result_notification("cleanup_all", result)
self._logger.info(f"Cleaned up all data, {len(cleaned_up)} left overs removed")
# cleaning orphan cache
self._orphans = None
return jsonify(result)
def _cleanup_disabled(self, plugin):
# delete from disabled list
disabled = self._settings.global_get(["plugins", "_disabled"])
try:
disabled.remove(plugin)
except ValueError:
# not in list, ok
pass
self._settings.global_set(["plugins", "_disabled"], disabled)
def _cleanup_settings(self, plugin):
# delete plugin settings
self._settings.global_remove(["plugins", plugin])
self._settings.global_remove(["server", "seenWizards", plugin])
return True
def _cleanup_data(self, plugin):
import os
import shutil
data_folder = os.path.join(self._settings.getBaseFolder("data"), plugin)
if os.path.exists(data_folder):
try:
shutil.rmtree(data_folder)
return True
except Exception:
self._logger.exception(
f"Could not delete plugin data folder at {data_folder}"
)
return False
else:
return True
def command_toggle(self, plugin, command):
if plugin.key == "pluginmanager" or (plugin.hidden and plugin.bundled):
abort(400, description="Can't enable/disable Plugin Manager")
pending = (command == "disable" and plugin.key in self._pending_enable) or (
command == "enable" and plugin.key in self._pending_disable
)
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
needs_refresh = plugin.implementation and isinstance(
plugin.implementation, octoprint.plugin.ReloadNeedingPlugin
)
needs_reconnect = (
self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks)
and self._printer.is_operational()
)
needs_restart_api = (
needs_restart or safe_mode_victim or plugin.forced_disabled
) and not pending
needs_refresh_api = needs_refresh and not pending
needs_reconnect_api = needs_reconnect and not pending
try:
if command == "disable":
self._mark_plugin_disabled(plugin, needs_restart=needs_restart)
elif command == "enable":
self._mark_plugin_enabled(plugin, needs_restart=needs_restart)
except octoprint.plugin.core.PluginLifecycleException as e:
self._logger.exception(
"Problem toggling enabled state of {name}: {reason}".format(
name=plugin.key, reason=e.reason
)
)
result = {"result": False, "reason": e.reason}
except octoprint.plugin.core.PluginNeedsRestart:
result = {
"result": True,
"needs_restart": True,
"needs_refresh": True,
"needs_reconnect": True,
"plugin": self._to_external_plugin(plugin),
}
else:
result = {
"result": True,
"needs_restart": needs_restart_api,
"needs_refresh": needs_refresh_api,
"needs_reconnect": needs_reconnect_api,
"plugin": self._to_external_plugin(plugin),
}
self._send_result_notification(command, result)
return jsonify(result)
def _find_installed_plugin(self, packages, plugins=None):
if plugins is None:
plugins = self._plugin_manager.find_plugins(
existing={}, ignore_uninstalled=False
)
for plugin in plugins.values():
if plugin.origin is None or plugin.origin.type != "entry_point":
continue
package_name = plugin.origin.package_name
package_version = plugin.origin.package_version
versioned_package = f"{package_name}-{package_version}"
if package_name in packages or versioned_package in packages:
# exact match, we are done here
return plugin
else:
# it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a
found = False
for inst in packages:
if inst.startswith(versioned_package):
found = True
break
if found:
return plugin
return None
def _send_result_notification(self, action, result, partial=False):
notification = {
"type": "partial_result" if partial else "result",
"action": action,
}
notification.update(result)
self._plugin_manager.send_plugin_message(self._identifier, notification)
def _call_pip(self, args):
if self._pip_caller is None or not self._pip_caller.available:
raise RuntimeError("No pip available, can't operate")
if "--process-dependency-links" in args:
self._log_message(
"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version"
)
additional_args = self._settings.get(["pip_args"])
if additional_args is not None:
inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(
args[0], list()
)
for inapplicable_argument in inapplicable_arguments:
additional_args = re.sub(
r"(^|\s)" + re.escape(inapplicable_argument) + r"\\b",
"",
additional_args,
)
if additional_args:
args.append(additional_args)
kwargs = {
"env": {
"PYTHONWARNINGS": "ignore:DEPRECATION::pip._internal.cli.base_command"
}
}
return self._pip_caller.execute(*args, **kwargs)
def _log_message(self, *lines):
self._log(lines, prefix="*", stream="message")
def _log_call(self, *lines):
self._log(lines, prefix=" ", stream="call")
def _log_stdout(self, *lines):
self._log(lines, prefix=">", stream="stdout")
def _log_stderr(self, *lines):
self._log(lines, prefix="!", stream="stderr")
def _log(self, lines, prefix=None, stream=None, strip=True):
if strip:
lines = list(map(lambda x: x.strip(), lines))
self._plugin_manager.send_plugin_message(
self._identifier,
{
"type": "loglines",
"loglines": [{"line": line, "stream": stream} for line in lines],
},
)
for line in lines: # noqa: B007
self._console_logger.debug(f"{prefix} {line}")
def _mark_plugin_enabled(self, plugin, needs_restart=False):
disabled_list = list(
self._settings.global_get(
["plugins", "_disabled"],
validator=lambda x: isinstance(x, list),
fallback=[],
)
)
if plugin.key in disabled_list:
disabled_list.remove(plugin.key)
self._settings.global_set(["plugins", "_disabled"], disabled_list)
self._settings.save(force=True)
if (
not needs_restart
and not plugin.forced_disabled
and not getattr(plugin, "safe_mode_victim", False)
):
self._plugin_manager.enable_plugin(plugin.key)
else:
if plugin.key in self._pending_disable:
self._pending_disable.remove(plugin.key)
elif not plugin.enabled and plugin.key not in self._pending_enable:
self._pending_enable.add(plugin.key)
# noinspection PyUnresolvedReferences
self._event_bus.fire(
Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN,
{"id": plugin.key, "version": plugin.version},
)
def _mark_plugin_disabled(self, plugin, needs_restart=False):
disabled_list = list(
self._settings.global_get(
["plugins", "_disabled"],
validator=lambda x: isinstance(x, list),
fallback=[],
)
)
if plugin.key not in disabled_list:
disabled_list.append(plugin.key)
self._settings.global_set(["plugins", "_disabled"], disabled_list)
self._settings.save(force=True)
if (
not needs_restart
and not plugin.forced_disabled
and not getattr(plugin, "safe_mode_victim", False)
):
self._plugin_manager.disable_plugin(plugin.key)
else:
if plugin.key in self._pending_enable:
self._pending_enable.remove(plugin.key)
elif (
plugin.enabled
or plugin.forced_disabled
or getattr(plugin, "safe_mode_victim", False)
) and plugin.key not in self._pending_disable:
self._pending_disable.add(plugin.key)
# noinspection PyUnresolvedReferences
self._event_bus.fire(
Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN,
{"id": plugin.key, "version": plugin.version},
)
def _fetch_all_data(self, do_async=False):
def run():
self._repository_available = self._fetch_repository_from_disk()
self._notices_available = self._fetch_notices_from_disk()
if do_async:
thread = threading.Thread(target=run)
thread.daemon = True
thread.start()
else:
run()
def _is_repository_cache_valid(self, mtime=None):
import time
if mtime is None:
mtime = self._repository_mtime
if mtime is None:
return False
return mtime + self._repository_cache_ttl >= time.time() > mtime
def _fetch_repository_from_disk(self):
repo_data = None
if os.path.isfile(self._repository_cache_path):
mtime = os.path.getmtime(self._repository_cache_path)
if self._is_repository_cache_valid(mtime=mtime):
try:
import json
with open(self._repository_cache_path, encoding="utf-8") as f:
repo_data = json.load(f)
self._repository_mtime = mtime
self._logger.info(
"Loaded plugin repository data from disk, was still valid"
)
except Exception:
self._logger.exception(
"Error while loading repository data from {}".format(
self._repository_cache_path
)
)
return self._refresh_repository(repo_data=repo_data)
def _fetch_repository_from_url(self):
if not self._connectivity_checker.online:
self._logger.info(
"Looks like we are offline, can't fetch repository from network"
)
return None
repository_url = self._settings.get(["repository"])
try:
r = requests.get(repository_url, timeout=3.05)
r.raise_for_status()
self._logger.info(f"Loaded plugin repository data from {repository_url}")
except Exception as e:
self._logger.exception(
"Could not fetch plugins from repository at {repository_url}: {message}".format(
repository_url=repository_url, message=e
)
)
return None
try:
repo_data = r.json()
except Exception as e:
self._logger.exception(f"Error while reading repository data: {e}")
return None
# validation
if not isinstance(repo_data, (list, tuple)):
self._logger.warning(
f"Invalid repository data: expected a list, got {repo_data!r}"
)
return None
try:
import json
with octoprint.util.atomic_write(self._repository_cache_path, mode="wb") as f:
f.write(to_bytes(json.dumps(repo_data)))
self._repository_mtime = os.path.getmtime(self._repository_cache_path)
except Exception as e:
self._logger.exception(
"Error while saving repository data to {}: {}".format(
self._repository_cache_path, e
)
)
return repo_data
def _refresh_repository(self, repo_data=None):
if repo_data is None:
repo_data = self._fetch_repository_from_url()
if repo_data is None:
return False
self._repository_plugins = list(
filter(lambda x: x is not None, map(map_repository_entry, repo_data))
)
self._repository_plugins_by_id = {x["id"]: x for x in self._repository_plugins}
return True
def _is_notices_cache_valid(self, mtime=None):
import time
if mtime is None:
mtime = self._notices_mtime
if mtime is None:
return False
return mtime + self._notices_cache_ttl >= time.time() > mtime
def _fetch_notices_from_disk(self):
notice_data = None
if os.path.isfile(self._notices_cache_path):
mtime = os.path.getmtime(self._notices_cache_path)
if self._is_notices_cache_valid(mtime=mtime):
try:
import json
with open(self._notices_cache_path, encoding="utf-8") as f:
notice_data = json.load(f)
self._notices_mtime = mtime
self._logger.info("Loaded notice data from disk, was still valid")
except Exception:
self._logger.exception(
"Error while loading notices from {}".format(
self._notices_cache_path
)
)
return self._refresh_notices(notice_data=notice_data)
def _fetch_notices_from_url(self):
if not self._connectivity_checker.online:
self._logger.info(
"Looks like we are offline, can't fetch notices from network"
)
return None
notices_url = self._settings.get(["notices"])
try:
r = requests.get(notices_url, timeout=3.05)
r.raise_for_status()
self._logger.info(f"Loaded plugin notices data from {notices_url}")
except Exception as e:
self._logger.exception(
"Could not fetch notices from {notices_url}: {message}".format(
notices_url=notices_url, message=str(e)
)
)
return None
notice_data = r.json()
try:
import json
with octoprint.util.atomic_write(self._notices_cache_path, mode="wb") as f:
f.write(to_bytes(json.dumps(notice_data)))
self._notices_mtime = os.path.getmtime(self._notices_cache_path)
except Exception as e:
self._logger.exception(
"Error while saving notices to {}: {}".format(
self._notices_cache_path, str(e)
)
)
return notice_data
def _refresh_notices(self, notice_data=None):
if notice_data is None:
notice_data = self._fetch_notices_from_url()
if notice_data is None:
return False
notices = {}
for notice in notice_data:
if "plugin" not in notice or "text" not in notice or "date" not in notice:
continue
key = notice["plugin"]
try:
# Jekyll turns "%Y-%m-%d %H:%M:%SZ" into "%Y-%m-%d %H:%M:%S +0000", so be sure to ignore "+0000"
#
# Being able to use dateutil here would make things way easier but sadly that can no longer get
# installed (from source) under OctoPi 0.14 due to its setuptools-scm dependency, so we have to do
# without it for now until we can drop support for OctoPi 0.14.
parsed_date = datetime.strptime(notice["date"], "%Y-%m-%d %H:%M:%S +0000")
notice["timestamp"] = parsed_date.timetuple()
except Exception as e:
self._logger.warning(
"Error while parsing date {!r} for plugin notice "
"of plugin {}, ignoring notice: {}".format(
notice["date"], key, str(e)
)
)
continue
if key not in notices:
notices[key] = []
notices[key].append(notice)
self._notices = notices
return True
def _get_orphans(self, refresh=False):
from collections import defaultdict
if self._orphans is not None and not refresh:
return self._orphans
installed_keys = self._plugin_manager.plugins.keys()
orphans = defaultdict(
lambda: {"settings": False, "data": False, "disabled": False}
)
# settings
for key in list(self._settings.global_get(["plugins"]).keys()):
if key.startswith("_"):
# internal key, like _disabled
continue
if key not in installed_keys:
orphans[key]["settings"] = True
# data
for entry in os.scandir(self._settings.getBaseFolder("data")):
if not entry.is_dir():
continue
if entry.name not in installed_keys:
orphans[entry.name]["data"] = True
# disabled
disabled = self._settings.global_get(["plugins", "_disabled"])
for key in disabled:
if key not in installed_keys:
orphans[key]["disabled"] = True
self._orphans = dict(**orphans)
return self._orphans
@property
def _reconnect_hooks(self):
reconnect_hooks = self.__class__.RECONNECT_HOOKS
reconnect_hook_provider_hooks = self._plugin_manager.get_hooks(
"octoprint.plugin.pluginmanager.reconnect_hooks"
)
for name, hook in reconnect_hook_provider_hooks.items():
try:
result = hook()
if isinstance(result, (list, tuple)):
reconnect_hooks.extend(filter(lambda x: isinstance(x, str), result))
except Exception:
self._logger.exception(
f"Error while retrieving additional hooks for which a "
f"reconnect is required from plugin {name}",
extra={"plugin": name},
)
return reconnect_hooks
def _get_plugins(self):
plugins = self._plugin_manager.plugins
hidden = self._settings.get(["hidden"])
result = []
for key, plugin in plugins.items():
if key in hidden or (plugin.bundled and plugin.hidden):
continue
result.append(self._to_external_plugin(plugin))
return result
@staticmethod
def generate_plugins_json(
settings,
plugin_manager,
ignore_bundled=True,
ignore_plugins_folder=True,
repo_plugins=None,
):
plugins = []
plugin_folder = settings.getBaseFolder("plugins")
for plugin in plugin_manager.plugins.values():
if (ignore_bundled and plugin.bundled) or (
ignore_plugins_folder
and isinstance(plugin.origin, octoprint.plugin.core.FolderOrigin)
and plugin.origin.folder == plugin_folder
):
# ignore bundled or from the plugins folder already included in the backup
continue
data = {"key": plugin.key, "name": plugin.name, "url": plugin.url}
if repo_plugins and plugin.key in repo_plugins:
data["archive"] = repo_plugins[plugin.key]["archive"]
plugins.append(data)
return plugins
def _to_external_plugin(self, plugin):
return {
"key": plugin.key,
"name": plugin.name,
"description": plugin.description,
"disabling_discouraged": gettext(plugin.disabling_discouraged)
if plugin.disabling_discouraged
else False,
"author": plugin.author,
"version": plugin.version,
"url": plugin.url,
"license": plugin.license,
"privacypolicy": plugin.privacypolicy,
"python": plugin.pythoncompat,
"bundled": plugin.bundled,
"managable": plugin.managable,
"enabled": plugin.enabled,
"blacklisted": plugin.blacklisted,
"forced_disabled": plugin.forced_disabled,
"incompatible": plugin.incompatible,
"safe_mode_victim": getattr(plugin, "safe_mode_victim", False),
"pending_enable": (
not plugin.enabled
and not getattr(plugin, "safe_mode_victim", False)
and plugin.key in self._pending_enable
),
"pending_disable": (
(plugin.enabled or getattr(plugin, "safe_mode_victim", False))
and plugin.key in self._pending_disable
),
"pending_install": (
self._plugin_manager.is_plugin_marked(plugin.key, "installed")
),
"pending_uninstall": (
self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")
),
"origin": plugin.origin.type,
"notifications": self._get_notifications(plugin),
}
def _get_notifications(self, plugin):
key = plugin.key
if not plugin.enabled:
return
if key not in self._notices:
return
octoprint_version = get_octoprint_version(base=True)
plugin_notifications = self._notices.get(key, [])
def map_notification(notification):
return self._to_external_notification(key, notification)
return list(
filter(
lambda x: x is not None,
map(
map_notification,
filter(
lambda n: _filter_relevant_notification(
n, plugin.version, octoprint_version
),
plugin_notifications,
),
),
)
)
def _to_external_notification(self, key, notification):
return {
"key": key,
"date": time.mktime(notification["timestamp"]),
"text": notification["text"],
"link": notification.get("link"),
"versions": notification.get(
"pluginversions", notification.get("versions", [])
),
"important": notification.get("important", False),
}
@pylru.lrudecorator(size=127)
def parse_requirement(line):
return pkg_resources.Requirement.parse(line)
def _filter_relevant_notification(notification, plugin_version, octoprint_version):
if "pluginversions" in notification:
pluginversions = notification["pluginversions"]
is_range = lambda x: "=" in x or ">" in x or "<" in x
version_ranges = list(
map(
lambda x: parse_requirement(notification["plugin"] + x),
filter(is_range, pluginversions),
)
)
versions = list(filter(lambda x: not is_range(x), pluginversions))
elif "versions" in notification:
version_ranges = []
versions = notification["versions"]
else:
version_ranges = versions = None
return (
"text" in notification
and "date" in notification
and (
(version_ranges is None and versions is None)
or (
plugin_version
and version_ranges
and (any(map(lambda v: plugin_version in v, version_ranges)))
)
or (plugin_version and versions and plugin_version in versions)
)
and (
"octoversions" not in notification
or is_octoprint_compatible(
*notification["octoversions"], octoprint_version=octoprint_version
)
)
)
def _register_custom_events(*args, **kwargs):
return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"]
__plugin_name__ = "Plugin Manager"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_hidden__ = True
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = PluginManagerPlugin()
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.systeminfo.additional_bundle_files": __plugin_implementation__.get_additional_bundle_files,
}
global __plugin_helpers__
__plugin_helpers__ = {
"generate_plugins_json": __plugin_implementation__.generate_plugins_json,
}
| 86,845 | Python | .py | 2,076 | 29.129094 | 293 | 0.554466 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,946 | exceptions.py | OctoPrint_OctoPrint/src/octoprint/plugins/pluginmanager/exceptions.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"
class InvalidPackageFormat(Exception):
pass
| 242 | Python | .py | 4 | 58 | 103 | 0.766949 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,947 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/eventmanager/__init__.py | from flask_babel import gettext
import octoprint.events
import octoprint.plugin
from octoprint.access import ADMIN_GROUP
class EventManagerPlugin(
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
):
def on_settings_load(self):
my_settings = {
"availableEvents": octoprint.events.all_events(),
"subscriptions": [],
}
events = self._settings.global_get(["events"])
for event in events.get("subscriptions", []):
if "name" not in event:
event["name"] = event["command"]
if not isinstance(event["event"], list):
event["event"] = [event["event"]]
if events:
my_settings["subscriptions"] = sorted(
events.get("subscriptions", []), key=(lambda x: x["name"])
)
return my_settings
def on_settings_save(self, data):
if type(data.get("subscriptions")) == list:
self._settings.global_set(
["events", "subscriptions"], data.get("subscriptions", [])
)
def get_assets(self):
return {"js": ["js/events.js"]}
def get_template_configs(self):
return [
{
"type": "settings",
"custom_bindings": True,
"name": gettext("Event Manager"),
}
]
def get_additional_permissions(self):
return [
{
"key": "MANAGE",
"name": "Event management",
"description": gettext(
"Allows for the management of event subscriptions."
),
"default_groups": [ADMIN_GROUP],
"roles": ["manage"],
}
]
__plugin_name__ = gettext("Event Manager")
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_author__ = "jneilliii"
__plugin_license__ = "AGPLv3"
__plugin_description__ = gettext(
"Plugin to configure event subscriptions available in config.yaml."
)
__plugin_implementation__ = EventManagerPlugin()
| 2,103 | Python | .py | 60 | 25.5 | 74 | 0.558014 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,948 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/virtual_printer/__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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
class VirtualPrinterPlugin(
octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin
):
def get_template_configs(self):
return [{"type": "settings", "custom_bindings": False}]
def get_settings_defaults(self):
return {
"enabled": False,
"okAfterResend": False,
"forceChecksum": False,
"numExtruders": 1,
"pinnedExtruders": None,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"hasBed": True,
"hasChamber": False,
"repetierStyleTargetTemperature": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"klipperTemperatureReporting": False,
"reprapfwM114": False,
"sdFiles": {"size": True, "longname": False, "longname_quoted": True},
"throttle": 0.01,
"sendWait": True,
"waitInterval": 1.0,
"rxBuffer": 64,
"commandBuffer": 4,
"supportM112": True,
"echoOnM117": True,
"brokenM29": True,
"brokenResend": False,
"supportF": False,
"firmwareName": "Virtual Marlin 1.0",
"sharedNozzle": False,
"sendBusy": False,
"busyInterval": 2.0,
"simulateReset": True,
"resetLines": ["start", "Marlin: Virtual Marlin!", "\x80", "SD card ok"],
"preparedOks": [],
"okFormatString": "ok",
"m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0",
"m115ReportCapabilities": True,
"capabilities": {
"AUTOREPORT_TEMP": True,
"AUTOREPORT_SD_STATUS": True,
"AUTOREPORT_POS": False,
"EMERGENCY_PARSER": True,
"EXTENDED_M20": False,
"LFN_WRITE": False,
},
"m115ReportArea": False,
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}",
"m105NoTargetFormatString": "{heater}:{actual:.2f}",
"ambientTemperature": 21.3,
"errors": {
"checksum_mismatch": "Checksum mismatch",
"checksum_missing": "Missing checksum",
"lineno_mismatch": "expected line {} got {}",
"lineno_missing": "No Line Number with checksum, Last Line: {}",
"maxtemp": "MAXTEMP triggered!",
"mintemp": "MINTEMP triggered!",
"command_unknown": "Unknown command {}",
},
"enable_eeprom": True,
"support_M503": True,
"resend_ratio": 0,
"locked": False,
"passcode": "1234",
"simulated_errors": [
"100:resend",
"105:resend_with_timeout",
"110:missing_lineno",
"115:checksum_mismatch",
],
}
def get_settings_version(self):
return 1
def on_settings_migrate(self, target, current):
if current is None:
config = self._settings.global_get(["devel", "virtualPrinter"])
if config:
self._logger.info(
"Migrating settings from devel.virtualPrinter to plugins.virtual_printer..."
)
self._settings.global_set(
["plugins", "virtual_printer"], config, force=True
)
self._settings.global_remove(["devel", "virtualPrinter"])
def virtual_printer_factory(self, comm_instance, port, baudrate, read_timeout):
if not port == "VIRTUAL":
return None
if not self._settings.get_boolean(["enabled"]):
return None
import logging.handlers
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
seriallog_handler = CleaningTimedRotatingFileHandler(
self._settings.get_plugin_logfile_path(postfix="serial"),
when="D",
backupCount=3,
)
seriallog_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
seriallog_handler.setLevel(logging.DEBUG)
from . import virtual
serial_obj = virtual.VirtualPrinter(
self._settings,
self._printer_profile_manager,
data_folder=self.get_plugin_data_folder(),
seriallog_handler=seriallog_handler,
read_timeout=float(read_timeout),
faked_baudrate=baudrate,
)
return serial_obj
def get_additional_port_names(self, *args, **kwargs):
if self._settings.get_boolean(["enabled"]):
return ["VIRTUAL"]
else:
return []
__plugin_name__ = "Virtual Printer"
__plugin_author__ = "Gina Häußge, based on work by Daid Braam"
__plugin_homepage__ = (
"https://docs.octoprint.org/en/master/development/virtual_printer.html"
)
__plugin_license__ = "AGPLv3"
__plugin_description__ = "Provides a virtual printer via a virtual serial port for development and testing purposes"
__plugin_pythoncompat__ = ">=3.7,<4"
def __plugin_load__():
plugin = VirtualPrinterPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory,
"octoprint.comm.transport.serial.additional_port_names": plugin.get_additional_port_names,
}
| 5,939 | Python | .py | 139 | 31.42446 | 116 | 0.57358 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,949 | virtual.py | OctoPrint_OctoPrint/src/octoprint/plugins/virtual_printer/virtual.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 json
import math
import os
import queue
import re
import threading
import time
from typing import Any, Dict, List, Optional
from serial import SerialTimeoutException
from octoprint.plugin import plugin_manager
from octoprint.util import RepeatedTimer, get_dos_filename, to_bytes, to_unicode
from octoprint.util.files import unix_timestamp_to_m20_timestamp
# noinspection PyBroadException
class VirtualPrinter:
command_regex = re.compile(r"^([GMTF])(\d+)")
sleep_regex = re.compile(r"sleep (\d+)")
sleep_after_regex = re.compile(r"sleep_after ([GMTF]\d+) (\d+)")
sleep_after_next_regex = re.compile(r"sleep_after_next ([GMTF]\d+) (\d+)")
custom_action_regex = re.compile(r"action_custom ([a-zA-Z0-9_]+)(\s+.*)?")
prepare_ok_regex = re.compile(r"prepare_ok (.*)")
send_regex = re.compile(r"send (.*)")
set_ambient_regex = re.compile(r"set_ambient ([-+]?[0-9]*\.?[0-9]+)")
start_sd_regex = re.compile(r"start_sd (.*)")
select_sd_regex = re.compile(r"select_sd (.*)")
resend_ratio_regex = re.compile(r"resend_ratio (\d+)")
def __init__(
self,
settings,
printer_profile_manager,
data_folder,
seriallog_handler=None,
read_timeout=5.0,
write_timeout=10.0,
faked_baudrate=115200,
):
import logging
self._logger = logging.getLogger(
"octoprint.plugins.virtual_printer.VirtualPrinter"
)
self._settings = settings
self._printer_profile_manager = printer_profile_manager
self._faked_baudrate = faked_baudrate
self._plugin_data_folder = data_folder
self._seriallog = logging.getLogger(
"octoprint.plugins.virtual_printer.VirtualPrinter.serial"
)
self._seriallog.setLevel(logging.CRITICAL)
self._seriallog.propagate = False
if seriallog_handler is not None:
import logging.handlers
self._seriallog.addHandler(seriallog_handler)
self._seriallog.setLevel(logging.INFO)
self._seriallog.info("-" * 78)
self._read_timeout = read_timeout
self._write_timeout = write_timeout
self._rx_buffer_size = self._settings.get_int(["rxBuffer"])
self.incoming = CharCountingQueue(self._rx_buffer_size, name="RxBuffer")
self.outgoing = queue.Queue()
self.buffered = queue.Queue(maxsize=self._settings.get_int(["commandBuffer"]))
if self._settings.get_boolean(["simulateReset"]):
for item in self._settings.get(["resetLines"]):
self._send(item + "\n")
self._prepared_oks = []
prepared = self._settings.get(["preparedOks"])
if prepared and isinstance(prepared, list):
for prep in prepared:
self._prepared_oks.append(prep)
self._prepared_errors = []
self._errors = self._settings.get(["errors"], merged=True)
self.currentExtruder = 0
self.extruderCount = self._settings.get_int(["numExtruders"])
self.pinnedExtruders = self._settings.get(["pinnedExtruders"])
if self.pinnedExtruders is None:
self.pinnedExtruders = {}
self.sharedNozzle = self._settings.get_boolean(["sharedNozzle"])
self.temperatureCount = 1 if self.sharedNozzle else self.extruderCount
self._ambient_temperature = self._settings.get_float(["ambientTemperature"])
self.temp = [self._ambient_temperature] * self.temperatureCount
self.targetTemp = [0.0] * self.temperatureCount
self.bedTemp = self._ambient_temperature
self.bedTargetTemp = 0.0
self.chamberTemp = self._ambient_temperature
self.chamberTargetTemp = 0.0
self.lastTempAt = time.monotonic()
self._relative = True
self._lastX = 0.0
self._lastY = 0.0
self._lastZ = 0.0
self._lastE = [0.0] * self.extruderCount
self._lastF = 200
self._unitModifier = 1
self._feedrate_multiplier = 100
self._flowrate_multiplier = 100
self._virtualSd = self._settings.global_get_basefolder("virtualSd")
self._sdCardReady = True
self._sdPrinter = None
self._sdPrintingSemaphore = threading.Event()
self._selectedSdFile = None
self._selectedSdFileSize = None
self._selectedSdFilePos = None
self._writingToSd = False
self._writingToSdHandle = None
self._writingToSdFile = None
self._newSdFilePos = None
self._heatingUp = False
self._virtual_eeprom = (
VirtualEEPROM(self._plugin_data_folder)
if self._settings.get_boolean(["enable_eeprom"])
else None
)
self._support_M503 = self._settings.get_boolean(["support_M503"])
self._okBeforeCommandOutput = self._settings.get_boolean(
["okBeforeCommandOutput"]
)
self._supportM112 = self._settings.get_boolean(["supportM112"])
self._supportF = self._settings.get_boolean(["supportF"])
self._sendWait = self._settings.get_boolean(["sendWait"])
self._sendBusy = self._settings.get_boolean(["sendBusy"])
self._waitInterval = self._settings.get_float(["waitInterval"])
self._busyInterval = self._settings.get_float(["busyInterval"])
self._busy = None
self._busy_loop = None
self._echoOnM117 = self._settings.get_boolean(["echoOnM117"])
self._brokenM29 = self._settings.get_boolean(["brokenM29"])
self._brokenResend = self._settings.get_boolean(["brokenResend"])
self._m115FormatString = self._settings.get(["m115FormatString"])
self._firmwareName = self._settings.get(["firmwareName"])
self._okFormatString = self._settings.get(["okFormatString"])
self._capabilities = self._settings.get(["capabilities"], merged=True)
self._locked = self._settings.get_boolean(["locked"])
self._temperature_reporter = None
self._sdstatus_reporter = None
self._pos_reporter = None
self.current_line = 0
self.lastN = 0
self._incoming_lock = threading.RLock()
self._debug_awol = False
self._debug_sleep = 0
self._sleepAfterNext = {}
self._sleepAfter = {}
self._rerequest_last = False
self._received_lines = 0
self._resend_every_n = 0
self._calculate_resend_every_n(self._settings.get_int(["resend_ratio"]))
self._dont_answer = False
self._broken_klipper_connection = False
self._debug_drop_connection = False
self._action_hooks = plugin_manager().get_hooks(
"octoprint.plugin.virtual_printer.custom_action"
)
self._killed = False
self._simulated_errors = {}
for v in self._settings.get(["simulated_errors"]):
if ":" not in v:
continue
try:
k, v = v.split(":", 1)
k = int(k)
self._simulated_errors[k] = v
except ValueError:
# ignore this, it's not a valid entry
pass
self._already_simulated_errors = set()
readThread = threading.Thread(
target=self._processIncoming,
name="octoprint.plugins.virtual_printer.wait_thread",
)
readThread.start()
bufferThread = threading.Thread(
target=self._processBuffer,
name="octoprint.plugins.virtual_printer.buffer_thread",
)
bufferThread.start()
def __str__(self):
return "VIRTUAL(read_timeout={read_timeout},write_timeout={write_timeout},options={options})".format(
read_timeout=self._read_timeout,
write_timeout=self._write_timeout,
options=self._settings.get([]),
)
def _calculate_resend_every_n(self, resend_ratio):
self._resend_every_n = (100 // resend_ratio) if resend_ratio else 0
def _reset(self):
with self._incoming_lock:
self._relative = True
self._lastX = 0.0
self._lastY = 0.0
self._lastZ = 0.0
self._lastE = [0.0] * self.extruderCount
self._lastF = 200
self._unitModifier = 1
self._feedrate_multiplier = 100
self._flowrate_multiplier = 100
self._sdCardReady = True
self._sdPrinting = False
self._sdCacnelled = False
if self._sdPrinter:
self._sdPrinting = False
self._sdPrintingSemaphore.set()
self._sdPrinter = None
self._selectedSdFile = None
self._selectedSdFileSize = None
self._selectedSdFilePos = None
# read eeprom from disk
if self._virtual_eeprom:
self._virtual_eeprom.read_settings()
if self._writingToSdHandle:
try:
self._writingToSdHandle.close()
except Exception:
pass
self._writingToSd = False
self._writingToSdHandle = None
self._writingToSdFile = None
self._newSdFilePos = None
self._heatingUp = False
self.current_line = 0
self.lastN = 0
self._debug_awol = False
self._debug_sleep = 0
self._sleepAfterNext.clear()
self._sleepAfter.clear()
self._dont_answer = False
self._broken_klipper_connection = False
self._debug_drop_connection = False
self._killed = False
self._already_simulated_errors.clear()
if self._temperature_reporter is not None:
self._temperature_reporter.cancel()
self._temperature_reporter = None
if self._sdstatus_reporter is not None:
self._sdstatus_reporter.cancel()
self._sdstatus_reporter = None
self._clearQueue(self.incoming)
self._clearQueue(self.outgoing)
self._clearQueue(self.buffered)
if self._settings.get_boolean(["simulateReset"]):
for item in self._settings.get(["resetLines"]):
self._send(item + "\n")
self._locked = self._settings.get_boolean(["locked"])
@property
def timeout(self):
return self._read_timeout
@timeout.setter
def timeout(self, value):
self._logger.debug(f"Setting read timeout to {value}s")
self._read_timeout = value
@property
def write_timeout(self):
return self._write_timeout
@write_timeout.setter
def write_timeout(self, value):
self._logger.debug(f"Setting write timeout to {value}s")
self._write_timeout = value
@property
def port(self):
return "VIRTUAL"
@property
def baudrate(self):
return self._faked_baudrate
# noinspection PyMethodMayBeStatic
def _clearQueue(self, q):
try:
while q.get(block=False):
q.task_done()
continue
except queue.Empty:
pass
def _processIncoming(self):
next_wait_timeout = 0
def recalculate_next_wait_timeout():
nonlocal next_wait_timeout
next_wait_timeout = time.monotonic() + self._waitInterval
recalculate_next_wait_timeout()
buf = b""
while self.incoming is not None and not self._killed:
self._simulateTemps()
if self._heatingUp:
time.sleep(1)
continue
try:
data = self.incoming.get(timeout=0.01)
data = to_bytes(data, encoding="ascii", errors="replace")
self.incoming.task_done()
except queue.Empty:
if self._sendWait and time.monotonic() > next_wait_timeout:
self._send("wait")
recalculate_next_wait_timeout()
continue
except Exception:
if self.incoming is None:
# just got closed
break
if data is not None:
buf += data
nl = buf.find(b"\n") + 1
if nl > 0:
data = buf[:nl]
buf = buf[nl:]
else:
continue
recalculate_next_wait_timeout()
if data is None:
continue
if self._dont_answer:
self._dont_answer = False
continue
self._received_lines += 1
# strip checksum
if b"*" in data:
checksum = int(data[data.rfind(b"*") + 1 :])
data = data[: data.rfind(b"*")]
if not checksum == self._calculate_checksum(data):
self._triggerResend(expected=self.current_line + 1)
continue
self.current_line += 1
elif self._settings.get_boolean(["forceChecksum"]):
self._send(self._error("checksum_missing"))
continue
# track N = N + 1
if data.startswith(b"N") and b"M110" in data:
linenumber = int(re.search(b"N([0-9]+)", data).group(1))
self.lastN = linenumber
self.current_line = linenumber
self._sendOk()
self._already_simulated_errors.clear()
continue
elif data.startswith(b"N"):
linenumber = int(re.search(b"N([0-9]+)", data).group(1))
expected = self.lastN + 1
if linenumber != expected:
self._triggerResend(actual=linenumber)
continue
elif (
linenumber in self._simulated_errors
and linenumber not in self._already_simulated_errors
):
action = self._simulated_errors[linenumber]
if action == "resend":
self._triggerResend(expected=linenumber)
self._already_simulated_errors.add(linenumber)
continue
elif action == "resend_with_timeout" and not self._writingToSd:
self._triggerResend(expected=linenumber)
self._dont_answer = True
self.lastN = linenumber
self._already_simulated_errors.add(linenumber)
continue
elif action == "missing_lineno" and not self._writingToSd:
self._send(self._error("lineno_missing", self.lastN))
self._already_simulated_errors.add(linenumber)
continue
elif action == "checksum_mismatch" and not self._writingToSd:
self._triggerResend(checksum=True)
self._already_simulated_errors.add(linenumber)
continue
elif len(self._prepared_errors):
prepared = self._prepared_errors.pop(0)
if callable(prepared):
prepared(linenumber, self.lastN, data)
continue
elif isinstance(prepared, str):
self._send(prepared)
continue
elif self._rerequest_last:
self._triggerResend(actual=linenumber)
continue
else:
self.lastN = linenumber
data = data.split(None, 1)[1].strip()
data += b"\n"
data = to_unicode(data, encoding="ascii", errors="replace").strip()
if data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG":
debug_command = ""
if data.startswith("!!DEBUG:"):
debug_command = data[len("!!DEBUG:") :].strip()
self._debugTrigger(debug_command)
continue
if self._resend_every_n and self._received_lines % self._resend_every_n == 0:
self._triggerResend(checksum=True)
continue
# shortcut for writing to SD
if (
self._writingToSd
and self._writingToSdHandle is not None
and "M29" not in data
):
self._writingToSdHandle.write(data)
self._sendOk()
continue
if data.strip() == "version":
from octoprint import __version__
self._send("OctoPrint VirtualPrinter v" + __version__)
continue
# if we are sending oks before command output, send it now
if len(data.strip()) > 0 and self._okBeforeCommandOutput:
self._sendOk()
# actual command handling
command_match = VirtualPrinter.command_regex.match(data)
if command_match is not None:
if self._broken_klipper_connection:
self._send("!! Lost communication with MCU 'mcu'")
self._sendOk()
continue
command = command_match.group(0)
letter = command_match.group(1)
if self._locked and command != "M511":
self._send("echo:Printer locked! (Unlock with M511 or LCD)")
self._sendOk()
continue
try:
# if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first
letter_handler = f"_gcode_{letter}"
if hasattr(self, letter_handler):
code = command_match.group(2)
handled = getattr(self, letter_handler)(code, data)
if handled:
continue
# then look for a method _gcode_<command> and execute that if it exists
command_handler = f"_gcode_{command}"
if hasattr(self, command_handler):
handled = getattr(self, command_handler)(data)
if handled:
continue
finally:
# recalculate the timeout again, as we might have just run a long
# running command
recalculate_next_wait_timeout()
# make sure that the debug sleepAfter and sleepAfterNext stuff works even
# if we continued above
if len(self._sleepAfter) or len(self._sleepAfterNext):
interval = None
if command in self._sleepAfter:
interval = self._sleepAfter[command]
elif command in self._sleepAfterNext:
interval = self._sleepAfterNext[command]
del self._sleepAfterNext[command]
if interval is not None:
self._send(
"// sleeping for {interval} seconds".format(
interval=interval
)
)
time.sleep(interval)
# if we are sending oks after command output, send it now
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
self._sendOk()
self._logger.info("Closing down read loop")
##~~ command implementations
# noinspection PyUnusedLocal
def _gcode_T(self, code: str, data: str) -> None:
t = int(code)
if 0 <= t < self.extruderCount:
self.currentExtruder = t
self._send("Active Extruder: %d" % self.currentExtruder)
else:
self._send(f"echo:T{t} Invalid extruder ")
# noinspection PyUnusedLocal
def _gcode_F(self, code: str, data: str) -> bool:
if self._supportF:
self._send("echo:changed F value")
return False
else:
self._send(self._error("command_unknown", "F"))
return True
def _gcode_M104(self, data: str) -> None:
self._parseHotendCommand(data)
def _gcode_M109(self, data: str) -> None:
self._parseHotendCommand(data, wait=True, support_r=True)
def _gcode_M140(self, data: str) -> None:
self._parseBedCommand(data)
def _gcode_M190(self, data: str) -> None:
self._parseBedCommand(data, wait=True, support_r=True)
def _gcode_M141(self, data: str) -> None:
self._parseChamberCommand(data)
def _gcode_M191(self, data: str) -> None:
self._parseChamberCommand(data, wait=True, support_r=True)
# noinspection PyUnusedLocal
def _gcode_M105(self, data: str) -> bool:
self._processTemperatureQuery()
return True
# noinspection PyUnusedLocal
def _gcode_M20(self, data: str) -> None:
if self._sdCardReady:
self._listSd(incl_long="L" in data, incl_timestamp="T" in data)
# noinspection PyUnusedLocal
def _gcode_M21(self, data: str) -> None:
self._sdCardReady = True
self._send("SD card ok")
# noinspection PyUnusedLocal
def _gcode_M22(self, data: str) -> None:
self._sdCardReady = False
def _gcode_M23(self, data: str) -> None:
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._selectSdFile(filename)
# noinspection PyUnusedLocal
def _gcode_M24(self, data: str) -> None:
if self._sdCardReady:
self._startSdPrint()
# noinspection PyUnusedLocal
def _gcode_M25(self, data: str) -> None:
if self._sdCardReady:
self._pauseSdPrint()
def _gcode_M26(self, data: str) -> None:
if self._sdCardReady:
pos = int(re.search(r"S([0-9]+)", data).group(1))
self._setSdPos(pos)
def _gcode_M27(self, data: str) -> None:
def report():
if self._sdCardReady:
self._reportSdStatus()
matchS = re.search(r"S([0-9]+)", data)
if matchS:
interval = int(matchS.group(1))
if self._sdstatus_reporter is not None:
self._sdstatus_reporter.cancel()
if interval > 0:
self._sdstatus_reporter = RepeatedTimer(interval, report)
self._sdstatus_reporter.start()
else:
self._sdstatus_reporter = None
report()
def _gcode_M28(self, data: str) -> None:
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._writeSdFile(filename)
# noinspection PyUnusedLocal
def _gcode_M29(self, data: str) -> None:
if self._sdCardReady:
self._finishSdFile()
def _gcode_M30(self, data: str) -> None:
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._deleteSdFile(filename)
def _gcode_M33(self, data: str) -> None:
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
if filename.startswith("/"):
filename = filename[1:]
file = self._getSdFileData(filename)
if file is not None:
self._send(file["name"])
def _gcode_M524(self, data: str) -> None:
if self._sdCardReady:
self._cancelSdPrint()
def _gcode_M113(self, data: str) -> None:
matchS = re.search(r"S([0-9]+)", data)
if matchS is not None:
interval = int(matchS.group(1))
if 0 <= interval <= 60:
self._busyInterval = interval
# noinspection PyUnusedLocal
def _gcode_M114(self, data: str) -> bool:
output = self._generatePositionOutput()
if not self._okBeforeCommandOutput:
ok = self._ok()
if ok:
output = f"{self._ok()} {output}"
self._send(output)
return True
# noinspection PyUnusedLocal
def _gcode_M115(self, data: str) -> None:
output = self._m115FormatString.format(firmware_name=self._firmwareName)
self._send(output)
if self._settings.get_boolean(["m115ReportCapabilities"]):
for cap, value in self._capabilities.items():
self._send("Cap:{}:{}".format(cap.upper(), "1" if value else "0"))
if self._settings.get_boolean(["m115ReportArea"]):
area_report = self._generate_area_report(
self._printer_profile_manager.get_current_or_default()
)
if area_report:
self._send(area_report)
@staticmethod
def _generate_area_report(profile: Dict) -> str:
"""
Generate a string with the area of the printer volume.
See https://marlinfw.org/docs/gcode/M115.html
Example::
>>> VirtualPrinter._generate_area_report({"volume": {"width": 200, "depth": 200, "height": 200, "origin": "lowerleft"}})
'area:{full:{min:{x:0,y:0,z:0},max:{x:200,y:200,z:200}},work:{min:{x:0,y:0,z:0},max:{x:200,y:200,z:200}}}'
>>> VirtualPrinter._generate_area_report({"volume": {"width": 200, "depth": 200, "height": 200, "origin": "center"}})
'area:{full:{min:{x:-100.0,y:-100.0,z:0},max:{x:100.0,y:100.0,z:200}},work:{min:{x:-100.0,y:-100.0,z:0},max:{x:100.0,y:100.0,z:200}}}'
>>> VirtualPrinter._generate_area_report({"volume": {"width": 200, "depth": 200, "height": 200, "custom_box": {"x_min": -3, "y_min": -3, "z_min": 0, "x_max": 200, "y_max": 200, "z_max": 200}, "origin": "lowerleft"}})
'area:{full:{min:{x:-3,y:-3,z:0},max:{x:200,y:200,z:200}},work:{min:{x:0,y:0,z:0},max:{x:200,y:200,z:200}}}'
>>> VirtualPrinter._generate_area_report({})
''
>>> VirtualPrinter._generate_area_report({"foo": "bar"})
''
>>> VirtualPrinter._generate_area_report({"volume": {}})
''
We use printer profile data here, with the full volume being defined by a custom bounding box, if defined.
Based on the docs it's currently unclear on whether this matches the actual behaviour of the implementation
of this part of the M115 command in Marlin, however for testing purposes as part of the virtual printer
it should be sufficient.
"""
if not profile or "volume" not in profile:
return ""
volume = profile["volume"]
if any([x not in volume for x in ["width", "depth", "height", "origin"]]):
return ""
origin_ll = volume["origin"] == "lowerleft"
work_bounds = {
"min": {
"x": 0 if origin_ll else -volume["width"] / 2,
"y": 0 if origin_ll else -volume["depth"] / 2,
"z": 0,
},
"max": {
"x": volume["width"] if origin_ll else volume["width"] / 2,
"y": volume["depth"] if origin_ll else volume["depth"] / 2,
"z": volume["height"],
},
}
full_bounds = work_bounds
custom = volume.get("custom_box")
if custom:
full_bounds = {
"min": {
"x": custom["x_min"],
"y": custom["y_min"],
"z": custom["z_min"],
},
"max": {
"x": custom["x_max"],
"y": custom["y_max"],
"z": custom["z_max"],
},
}
# we'll just use json.dumps to generate the string, and then remove the quotes and spaces
return "area:" + json.dumps({"full": full_bounds, "work": work_bounds}).replace(
'"', ""
).replace(" ", "")
def _gcode_M117(self, data: str) -> None:
# we'll just use this to echo a message, to allow playing around with pause triggers
if self._echoOnM117:
try:
result = re.search(r"M117\s+(.*)", data).group(1)
self._send(f"echo:{result}")
except AttributeError:
self._send("echo:")
def _gcode_M118(self, data: str) -> None:
match = re.search(r"M118 (?:(?P<parameter>A1|E1|Pn[012])\s)?(?P<text>.*)", data)
if not match:
self._send("Unrecognized command parameters for M118")
else:
result = match.groupdict()
text = result["text"]
parameter = result["parameter"]
if parameter == "A1":
self._send(f"//{text}")
elif parameter == "E1":
self._send(f"echo:{text}")
else:
self._send(text)
def _gcode_M154(self, data: str) -> None:
matchS = re.search(r"S([0-9]+)", data)
if matchS is not None:
interval = int(matchS.group(1))
if self._pos_reporter is not None:
self._pos_reporter.cancel()
if interval > 0:
self._pos_reporter = RepeatedTimer(
interval, lambda: self._send(self._generatePositionOutput())
)
self._pos_reporter.start()
else:
self._pos_reporter = None
def _gcode_M155(self, data: str) -> None:
matchS = re.search(r"S([0-9]+)", data)
if matchS is not None:
interval = int(matchS.group(1))
if self._temperature_reporter is not None:
self._temperature_reporter.cancel()
if interval > 0:
self._temperature_reporter = RepeatedTimer(
interval, lambda: self._send(self._generateTemperatureOutput())
)
self._temperature_reporter.start()
else:
self._temperature_reporter = None
def _gcode_M220(self, data: str) -> None:
matchS = re.search(r"S([0-9]+)", data)
if matchS is not None:
self._feedrate_multiplier = float(matchS.group(1))
def _gcode_M221(self, data: str) -> None:
matchS = re.search(r"S([0-9]+)", data)
if matchS is not None:
self._flowrate_multiplier = float(matchS.group(1))
# noinspection PyUnusedLocal
def _gcode_M400(self, data: str) -> None:
self.buffered.join()
# noinspection PyUnusedLocal
def _gcode_M600(self, data: str) -> None:
self._send("//action:paused")
self._showPrompt(
"Heater Timeout",
[
"Reheat",
],
)
self._setBusy("paused for user")
return True # handled as we don't want to send an ok now, only when finishing the busy
# noinspection PyUnusedLocal
def _gcode_M876(self, data: str) -> None:
self._hidePrompt()
if self._busy == "paused for user":
self._busy = None
# noinspection PyUnusedLocal
def _gcode_M999(self, data: str) -> None:
# mirror Marlin behaviour
self._send("Resend: 1")
# noinspection PyUnusedLocal
def _gcode_G20(self, data: str) -> None:
self._unitModifier = 1 / 2.54
if self._lastX is not None:
self._lastX *= 2.54
if self._lastY is not None:
self._lastY *= 2.54
if self._lastZ is not None:
self._lastZ *= 2.54
if self._lastE is not None:
self._lastE = [e * 2.54 if e is not None else None for e in self._lastE]
# noinspection PyUnusedLocal
def _gcode_G21(self, data: str) -> None:
self._unitModifier = 1.0
if self._lastX is not None:
self._lastX /= 2.54
if self._lastY is not None:
self._lastY /= 2.54
if self._lastZ is not None:
self._lastZ /= 2.54
if self._lastE is not None:
self._lastE = [e / 2.54 if e is not None else None for e in self._lastE]
# noinspection PyUnusedLocal
def _gcode_G90(self, data: str) -> None:
self._relative = False
# noinspection PyUnusedLocal
def _gcode_G91(self, data: str) -> None:
self._relative = True
def _gcode_G92(self, data: str) -> None:
self._setPosition(data)
def _gcode_G28(self, data: str) -> None:
self._home(data)
def _gcode_G0(self, data: str) -> None:
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
self.buffered.put(data)
_gcode_G1 = _gcode_G0
_gcode_G2 = _gcode_G0
_gcode_G3 = _gcode_G0
def _gcode_G4(self, data: str) -> None:
matchS = re.search(r"S([0-9]+)", data)
matchP = re.search(r"P([0-9]+)", data)
_timeout = 0
if matchP:
_timeout = float(matchP.group(1)) / 1000
elif matchS:
_timeout = float(matchS.group(1))
if self._sendBusy and self._busyInterval > 0:
until = time.monotonic() + _timeout
while time.monotonic() < until:
time.sleep(self._busyInterval)
self._send("busy:processing")
else:
time.sleep(_timeout)
# noinspection PyUnusedLocal
def _gcode_G33(self, data: str) -> None:
self._send("G33 Auto Calibrate")
self._send("Will take ~60s")
timeout = 60
if self._sendBusy and self._busyInterval > 0:
until = time.monotonic() + timeout
while time.monotonic() < until:
time.sleep(self._busyInterval)
self._send("busy:processing")
else:
time.sleep(timeout)
# Passcode Feature - lock with M510, unlock with M511 P<passcode>.
# https://marlinfw.org/docs/gcode/M510.html / https://marlinfw.org/docs/gcode/M511.html
def _gcode_M510(self, data: str) -> None:
self._locked = True
def _gcode_M511(self, data: str) -> None:
if self._locked:
matchP = re.search(r"P([0-9]+)", data)
if matchP:
passcode = matchP.group(1)
if passcode == self._settings.get(["passcode"]):
self._locked = False
else:
self._send("Incorrect passcode")
# EEPROM management commands
def _gcode_M500(self, data: str) -> None:
# Stores settings to disk
if self._virtual_eeprom:
self._virtual_eeprom.save_settings()
else:
self._send(self._error("command_unknown", "M500"))
def _gcode_M501(self, data: str) -> None:
# Read from EEPROM
if self._virtual_eeprom:
self._virtual_eeprom.read_settings()
for line in self._construct_eeprom_values():
self._send(line)
else:
self._send(self._error("command_unknown", "M501"))
def _gcode_M502(self, data: str) -> None:
# reset to default values
if self._virtual_eeprom:
self._virtual_eeprom.load_defaults()
for line in self._construct_eeprom_values():
self._send(line)
else:
self._send(self._error("command_unknown", "M502"))
def _gcode_M503(self, data: str) -> None:
# echo all eeprom data
if self._virtual_eeprom and self._support_M503:
for line in self._construct_eeprom_values():
self._send(line)
else:
self._send(self._error("command_unknown", "M503"))
def _gcode_M504(self, data: str) -> None:
if self._virtual_eeprom:
self._send("echo:EEPROM OK")
else:
self._send(self._error("command_unknown", "M504"))
# EEPROM settings commands
def _gcode_M92(self, data: str) -> None:
# Steps per unit
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M92"))
return
if not self._check_param_letters("XYZE", data):
# no params, report values
self._send(self._construct_echo_values("steps", "XYZE"))
else:
for key, value in self._parse_eeprom_params("XYZE", data).items():
self._virtual_eeprom.eeprom["steps"]["params"][key] = float(value)
def _gcode_M203(self, data: str) -> None:
# Maximum feedrates (units/s)
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M203"))
return
if not self._check_param_letters("XYZE", data):
# no params, report values
self._send(self._construct_echo_values("feedrate", "XYZE"))
else:
for key, value in self._parse_eeprom_params("XYZE", data).items():
self._virtual_eeprom.eeprom["feedrate"]["params"][key] = float(value)
def _gcode_M201(self, data: str) -> None:
# Maximum Acceleration (units/s2)
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M201"))
return
if not self._check_param_letters("EXYZ", data):
# no params, report values
self._send(self._construct_echo_values("max_accel", "EXYZ"))
else:
for key, value in self._parse_eeprom_params("EXYZ", data).items():
self._virtual_eeprom.eeprom["max_accel"]["params"][key] = float(value)
def _gcode_M204(self, data: str) -> None:
# Starting Acceleration (units/s2)
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M204"))
return
if not self._check_param_letters("PRTS", data):
# no params, report values
self._send(self._construct_echo_values("start_accel", "PRTS"))
else:
for key, value in self._parse_eeprom_params("PRTS", data).items():
self._virtual_eeprom.eeprom["start_accel"]["params"][key] = float(value)
def _gcode_M206(self, data: str) -> None:
# Home offset
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M206"))
return
if not self._check_param_letters("XYZ", data):
# no params, report values
self._send(self._construct_echo_values("home_offset", "XYZ"))
else:
for key, value in self._parse_eeprom_params("XYZ", data).items():
self._virtual_eeprom.eeprom["home_offset"]["params"][key] = float(value)
def _gcode_M851(self, data: str) -> None:
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M851"))
return
if not self._check_param_letters("XYZ", data):
self._send(self._construct_echo_values("probe_offset", "XYZ"))
else:
for key, value in self._parse_eeprom_params("XYZ", data).items():
self._virtual_eeprom.eeprom["probe_offset"]["params"][key] = float(value)
def _gcode_M200(self, data: str) -> None:
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M200"))
return
if not self._check_param_letters("DS", data):
self._send(self._construct_echo_values("filament", "DS"))
else:
for key, value in self._parse_eeprom_params("DS", data).items():
self._virtual_eeprom.eeprom["filament"]["params"][key] = float(value)
def _gcode_M666(self, data: str) -> None:
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M666"))
return
if not self._check_param_letters("XYZ", data):
self._send(self._construct_echo_values("endstop", "XYZ"))
else:
for key, value in self._parse_eeprom_params("XYZ", data).items():
self._virtual_eeprom.eeprom["endstop"]["params"][key] = float(value)
def _gcode_M665(self, data: str) -> None:
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M665"))
return
if not self._check_param_letters("BHLRSXYZ", data):
self._send(self._construct_echo_values("delta", "BHLRSXYZ"))
else:
for key, value in self._parse_eeprom_params("BHLRSXYZ", data).items():
self._virtual_eeprom.eeprom["delta"]["params"][key] = float(value)
def _gcode_M420(self, data: str) -> None:
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M420"))
return
if not self._check_param_letters("SZ", data):
self._send(self._construct_echo_values("auto_level", "SZ"))
else:
for key, value in self._parse_eeprom_params("SZ", data).items():
self._virtual_eeprom.eeprom["auto_level"]["params"][key] = float(value)
def _gcode_M900(self, data: str) -> None:
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M900"))
return
if not self._check_param_letters("K", data):
self._send(self._construct_echo_values("linear_advance", "K"))
else:
for key, value in self._parse_eeprom_params("K", data).items():
self._virtual_eeprom.eeprom["linear_advance"]["params"][key] = float(
value
)
def _gcode_M205(self, data: str) -> None:
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M205"))
return
if not self._check_param_letters("BSTXYZEJ", data):
self._send(self._construct_echo_values("advanced", "BSTXYZEJ"))
else:
for key, value in self._parse_eeprom_params("BSTXYZEJ", data).items():
self._virtual_eeprom.eeprom["advanced"]["params"][key] = float(value)
def _gcode_M145(self, data: str) -> None:
# M145 is a bit special, since it refers to 2 sets of values under the same params
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M145"))
return
if not self._check_param_letters("S", data):
config = self._virtual_eeprom.eeprom["material"]
for material in ["0", "1"]:
line = "echo: " + config["command"] + " S" + material
for param, saved_value in config["params"][material].items():
line = line + " " + param + str(saved_value)
self._send(line)
else:
parsed = self._parse_eeprom_params("SBFH", data)
try:
material_no = parsed["S"]
except KeyError:
self._send("Need to specify a material (S0/S1)")
return
for key, value in parsed.items():
if key == "S":
pass
else:
self._virtual_eeprom.eeprom["material"]["params"][material_no][
key
] = float(value)
def _gcode_M301(self, data: str) -> None:
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M301"))
return
if not self._check_param_letters("PID", data):
self._send(self._construct_echo_values("pid", "PID"))
else:
for key, value in self._parse_eeprom_params("PID", data).items():
self._virtual_eeprom.eeprom["pid"]["params"][key] = float(value)
def _gcode_M304(self, data: str) -> None:
if not self._virtual_eeprom:
self._send(self._error("command_unknown", "M304"))
return
if not self._check_param_letters("PID", data):
self._send(self._construct_echo_values("pid_bed", "PID"))
else:
for key, value in self._parse_eeprom_params("PID", data).items():
self._virtual_eeprom.eeprom["pid_bed"]["params"][key] = float(value)
# EEPROM Helpers
def _construct_eeprom_values(self):
lines = []
# Iterate over the dict, and echo each command/value etc.
for key, value in self._virtual_eeprom.eeprom.items():
# echo, description
lines.append("echo:; " + value["description"])
if key == "material": # material gets special handling...
lines.extend(self._m145_handling())
else:
# echo, command, params
line = "echo: " + value["command"]
for param, saved_value in value["params"].items():
line = line + " " + param + str(saved_value)
lines.append(line)
return lines
def _m145_handling(self):
config = self._virtual_eeprom.eeprom["material"]
lines = []
for material in ["0", "1"]:
line = "echo: " + config["command"] + " S" + material
for param, saved_value in config["params"][material].items():
line = line + " " + param + str(saved_value)
lines.append(line)
return lines
@staticmethod
def _parse_eeprom_params(letters: str, line: str) -> dict:
# letters provided in a string (eg "XYZ") and line (eg. M92 X20 Y20 Z20)
# are parsed into a dict
params = list(letters)
output = {}
for param in params:
match = re.search(param + r"([0-9]+(\.[0-9]{1,2})?)", line)
if match:
output[param] = match.group(1)
return output
def _construct_echo_values(self, name, letters):
# Construct a line like 'echo: M92 X100 Y120 Z130' based on type & letters
config = self._virtual_eeprom.eeprom[name]
line = "echo: " + config["command"]
for param in list(letters):
line = line + " " + param + str(config["params"][param])
return line
@staticmethod
def _check_param_letters(letters, data):
# Checks if any of the params (letters) are included in data
# Purely for saving typing :)
for param in list(letters):
if param in data:
return True
##~~ further helpers
# noinspection PyMethodMayBeStatic
def _calculate_checksum(self, line: bytes) -> int:
checksum = 0
for c in bytearray(line):
checksum ^= c
return checksum
def _kill(self):
if not self._supportM112:
return
self._killed = True
self._send("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
def _triggerResend(
self, expected: int = None, actual: int = None, checksum: int = None
) -> None:
with self._incoming_lock:
if expected is None:
expected = self.lastN + 1
else:
self.lastN = expected - 1
if actual is None:
if checksum:
self._send(self._error("checksum_mismatch"))
else:
self._send(self._error("checksum_missing"))
else:
self._send(self._error("lineno_mismatch", expected, actual))
def request_resend():
self._send("Resend:%d" % expected)
if not self._brokenResend:
self._sendOk()
request_resend()
def _debugTrigger(self, data: str) -> None:
if data == "" or data == "help" or data == "?":
usage = """
OctoPrint Virtual Printer debug commands
help
?
| This help.
# Action Triggers
action_pause
| Sends a "// action:pause" action trigger to the host.
action_resume
| Sends a "// action:resume" action trigger to the host.
action_disconnect
| Sends a "// action:disconnect" action trigger to the
| host.
action_custom <action>[ <parameters>]
| Sends a custom "// action:<action> <parameters>"
| action trigger to the host.
# Communication Errors
dont_answer
| Will not acknowledge the next command.
go_awol
| Will completely stop replying
trigger_resend_lineno
| Triggers a resend error with a line number mismatch
trigger_resend_checksum
| Triggers a resend error with a checksum mismatch
trigger_missing_checksum
| Triggers a resend error with a missing checksum
trigger_missing_lineno
| Triggers a "no line number with checksum" error w/o resend request
trigger_fatal_error_marlin
| Triggers a fatal error/simulated heater fail, Marlin style
trigger_fatal_error_repetier
| Triggers a fatal error/simulated heater fail, Repetier style
drop_connection
| Drops the serial connection
prepare_ok <broken ok>
| Will cause <broken ok> to be enqueued for use,
| will be used instead of actual "ok"
rerequest_last
| Will cause the last line number + 1 to be rerequest add infinitum
resend_ratio <int:percentage>
| Sets the resend ratio to the given percentage, simulating noisy lines.
| Set to 0 to disable noise simulation.
toggle_klipper_connection
| Toggles the Klipper connection state. If disabled, the printer will
| respond to all commands with "!! Lost communication with MCU 'mcu'"
# Reply Timing / Sleeping
sleep <int:seconds>
| Sleep <seconds> s
sleep_after <str:command> <int:seconds>
| Sleeps <seconds> s after each execution of <command>
sleep_after_next <str:command> <int:seconds>
| Sleeps <seconds> s after execution of next <command>
# SD printing
start_sd <str:file>
| Select and start printing file <file> from SD
select_sd <str:file>
| Select file <file> from SD, don't start printing it yet. Use
| start_sd to start the print
cancel_sd
| Cancels an ongoing SD print
# Misc
send <str:message>
| Sends back <message>
reset
| Simulates a reset. Internal state will be lost.
unbusy
| Unsets the busy loop.
"""
for line in usage.split("\n"):
self._send(f"echo: {line.strip()}")
elif data == "action_pause":
self._send("// action:pause")
elif data == "action_resume":
self._send("// action:resume")
elif data == "action_disconnect":
self._send("// action:disconnect")
elif data == "dont_answer":
self._dont_answer = True
elif data == "toggle_klipper_connection":
self._broken_klipper_connection = not self._broken_klipper_connection
elif data == "trigger_resend_lineno":
self._prepared_errors.append(
lambda cur, last, ln: self._triggerResend(expected=last, actual=last + 1)
)
elif data == "trigger_resend_checksum":
self._prepared_errors.append(
lambda cur, last, ln: self._triggerResend(expected=last, checksum=True)
)
elif data == "trigger_missing_checksum":
self._prepared_errors.append(
lambda cur, last, ln: self._triggerResend(expected=last, checksum=False)
)
elif data == "trigger_missing_lineno":
self._prepared_errors.append(
lambda cur, last, ln: self._send(self._error("lineno_missing", last))
)
elif data == "trigger_fatal_error_marlin":
self._send("Error:Thermal Runaway, system stopped! Heater_ID: bed")
self._send("Error:Printer halted. kill() called!")
elif data == "trigger_fatal_error_repetier":
self._send(
"fatal: Heater/sensor error - Printer stopped and heaters disabled due to this error. Fix error and restart with M999."
)
elif data == "drop_connection":
self._debug_drop_connection = True
elif data == "reset":
self._reset()
elif data == "unbusy":
self._setUnbusy()
elif data == "mintemp_error":
self._send(self._error("mintemp"))
elif data == "maxtemp_error":
self._send(self._error("maxtemp"))
elif data == "go_awol":
self._send("// Going AWOL")
self._debug_awol = True
elif data == "rerequest_last":
self._send("// Entering rerequest loop")
self._rerequest_last = True
elif data == "cancel_sd":
if self._sdPrinting and self._sdPrinter:
self._pauseSdPrint()
self._sdPrinting = False
self._sdPrintingSemaphore.set()
self._sdPrinter.join()
self._finishSdPrint()
else:
try:
sleep_match = VirtualPrinter.sleep_regex.match(data)
sleep_after_match = VirtualPrinter.sleep_after_regex.match(data)
sleep_after_next_match = VirtualPrinter.sleep_after_next_regex.match(data)
custom_action_match = VirtualPrinter.custom_action_regex.match(data)
prepare_ok_match = VirtualPrinter.prepare_ok_regex.match(data)
send_match = VirtualPrinter.send_regex.match(data)
set_ambient_match = VirtualPrinter.set_ambient_regex.match(data)
start_sd_match = VirtualPrinter.start_sd_regex.match(data)
select_sd_match = VirtualPrinter.select_sd_regex.match(data)
resend_ratio_match = VirtualPrinter.resend_ratio_regex.match(data)
if sleep_match is not None:
interval = int(sleep_match.group(1))
self._send(f"// sleeping for {interval} seconds")
self._debug_sleep = interval
elif sleep_after_match is not None:
command = sleep_after_match.group(1)
interval = int(sleep_after_match.group(2))
self._sleepAfter[command] = interval
self._send(
f"// going to sleep {interval} seconds after each {command}"
)
elif sleep_after_next_match is not None:
command = sleep_after_next_match.group(1)
interval = int(sleep_after_next_match.group(2))
self._sleepAfterNext[command] = interval
self._send(
f"// going to sleep {interval} seconds after next {command}"
)
elif custom_action_match is not None:
action = custom_action_match.group(1)
params = custom_action_match.group(2)
params = params.strip() if params is not None else ""
self._send(f"// action:{action} {params}".strip())
elif prepare_ok_match is not None:
ok = prepare_ok_match.group(1)
self._prepared_oks.append(ok)
elif send_match is not None:
self._send(send_match.group(1))
elif set_ambient_match is not None:
self._ambient_temperature = float(set_ambient_match.group(1))
self._send(
"// set ambient temperature to {}".format(
self._ambient_temperature
)
)
elif start_sd_match is not None:
self._selectSdFile(start_sd_match.group(1), check_already_open=True)
self._startSdPrint()
elif select_sd_match is not None:
self._selectSdFile(select_sd_match.group(1))
elif resend_ratio_match is not None:
resend_ratio = int(resend_ratio_match.group(1))
if 0 <= resend_ratio <= 100:
self._calculate_resend_every_n(resend_ratio)
except Exception:
self._logger.exception("While handling %r", data)
def _listSd(self, incl_long=False, incl_timestamp=False):
line = "{dosname}"
if self._settings.get_boolean(["sdFiles", "size"]):
line += " {size}"
if self._settings.get_boolean(["sdFiles", "timestamp"]) or incl_timestamp:
line += " {timestamp}"
if self._settings.get_boolean(["sdFiles", "longname"]) or incl_long:
if self._settings.get_boolean(["sdFiles", "longname_quoted"]):
line += ' "{name}"'
else:
line += " {name}"
self._send("Begin file list")
for item in map(lambda x: line.format(**x), self._getSdFiles()):
self._send(item)
self._send("End file list")
def _mappedSdList(self) -> Dict[str, Dict[str, Any]]:
result = {}
for entry in os.scandir(self._virtualSd):
if not entry.is_file():
continue
dosname = get_dos_filename(
entry.name, existing_filenames=list(result.keys())
).lower()
if entry.name.startswith("."):
dosname = "." + dosname
data = {
"name": entry.name,
"path": entry.path,
"dosname": dosname,
"size": entry.stat().st_size,
"timestamp": unix_timestamp_to_m20_timestamp(entry.stat().st_mtime),
}
# index by lower case, we simulate a case insensitive filesystem like FAT,
# which should be closest to what we encounter in reality
result[entry.name.lower()] = data
result[dosname.lower()] = entry.name.lower()
return result
def _getSdFileData(self, filename: str) -> Optional[Dict[str, Any]]:
files = self._mappedSdList()
data = files.get(filename.lower())
if isinstance(data, str):
data = files.get(data.lower())
return data
def _getSdFiles(self) -> List[Dict[str, Any]]:
files = self._mappedSdList()
return [x for x in files.values() if isinstance(x, dict)]
def _selectSdFile(self, filename: str, check_already_open: bool = False) -> None:
if filename.startswith("/"):
filename = filename[1:]
file = self._getSdFileData(filename)
if (
file is None
or not os.path.exists(file["path"])
or not os.path.isfile(file["path"])
):
self._send(f"open failed, File: {file['name']}.")
return
if self._selectedSdFile == file["path"] and check_already_open:
return
self._selectedSdFile = file["path"]
self._selectedSdFileSize = file["size"]
if self._settings.get_boolean(["includeFilenameInOpened"]):
self._send(f"File opened: {file['name']} Size: {self._selectedSdFileSize}")
else:
self._send("File opened")
self._send("File selected")
def _startSdPrint(self):
if self._selectedSdFile is not None:
self._sdPrinting = False
if self._sdPrinter is None:
self._sdCancelled = False
self._sdPrinting = True
self._sdPrinter = threading.Thread(target=self._sdPrintingWorker)
self._sdPrinter.start()
self._sdPrintingSemaphore.set()
def _pauseSdPrint(self):
self._sdPrintingSemaphore.clear()
def _cancelSdPrint(self):
self._sdCancelled = True
self._sdPrinting = False
self._sdPrintingSemaphore.set() # just in case it was cleared before
self._sdPrinter.join()
def _setSdPos(self, pos):
self._newSdFilePos = pos
def _reportSdStatus(self):
if self._sdPrinter is not None:
self._send(
f"SD printing byte {self._selectedSdFilePos}/{self._selectedSdFileSize}"
)
else:
self._send("Not SD printing")
def _generatePositionOutput(self) -> str:
m114FormatString = self._settings.get(["m114FormatString"])
e = {index: value for index, value in enumerate(self._lastE)}
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(
[
f"E{num}:{self._lastE[self.currentExtruder]}"
for num in range(self.extruderCount)
]
)
output = m114FormatString.format(
x=self._lastX,
y=self._lastY,
z=self._lastZ,
e=e,
f=self._lastF,
a=int(self._lastX * 100),
b=int(self._lastY * 100),
c=int(self._lastZ * 100),
)
return output
def _generateTemperatureOutput(self) -> str:
if self._settings.get_boolean(["repetierStyleTargetTemperature"]):
template = self._settings.get(["m105NoTargetFormatString"])
else:
template = self._settings.get(["m105TargetFormatString"])
temps = collections.OrderedDict()
# send simulated temperature data
if self.temperatureCount > 1:
if self._settings.get_boolean(["smoothieTemperatureReporting"]):
temps["T"] = (self.temp[0], self.targetTemp[0])
elif self._settings.get_boolean(["includeCurrentToolInTemps"]):
temps["T"] = (
self.temp[self.currentExtruder],
self.targetTemp[self.currentExtruder],
)
for i in range(len(self.temp)):
if i == 0 and self._settings.get_boolean(
["smoothieTemperatureReporting"]
):
continue
temps[f"T{i}"] = (self.temp[i], self.targetTemp[i])
if self._settings.get_boolean(["hasBed"]):
temps["B"] = (self.bedTemp, self.bedTargetTemp)
if self._settings.get_boolean(["hasChamber"]):
temps["C"] = (self.chamberTemp, self.chamberTargetTemp)
else:
heater = "T"
if self._settings.get_boolean(["klipperTemperatureReporting"]):
heater = "T0"
temps[heater] = (self.temp[0], self.targetTemp[0])
if self._settings.get_boolean(["hasBed"]):
temps["B"] = (self.bedTemp, self.bedTargetTemp)
if self._settings.get_boolean(["hasChamber"]):
temps["C"] = (self.chamberTemp, self.chamberTargetTemp)
output = " ".join(
map(
lambda x: template.format(heater=x[0], actual=x[1][0], target=x[1][1]),
temps.items(),
)
)
output += " @:64\n"
return output
def _processTemperatureQuery(self):
includeOk = not self._okBeforeCommandOutput
output = self._generateTemperatureOutput()
if includeOk:
ok = self._ok()
if ok:
output = f"{ok} {output}"
self._send(output)
def _parseHotendCommand(
self, line: str, wait: bool = False, support_r: bool = False
) -> None:
only_wait_if_higher = True
tool = 0
toolMatch = re.search(r"T([0-9]+)", line)
if toolMatch:
tool = int(toolMatch.group(1))
if tool >= self.temperatureCount:
return
try:
self.targetTemp[tool] = float(re.search(r"S([0-9]+)", line).group(1))
except Exception:
if support_r:
try:
self.targetTemp[tool] = float(re.search(r"R([0-9]+)", line).group(1))
only_wait_if_higher = False
except Exception:
pass
if wait:
self._waitForHeatup("tool%d" % tool, only_wait_if_higher)
if self._settings.get_boolean(["repetierStyleTargetTemperature"]):
self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
def _parseBedCommand(self, line: str, wait: bool = False, support_r: bool = False):
if not self._settings.get_boolean(["hasBed"]):
return
only_wait_if_higher = True
try:
self.bedTargetTemp = float(re.search(r"S([0-9]+)", line).group(1))
except Exception:
if support_r:
try:
self.bedTargetTemp = float(re.search(r"R([0-9]+)", line).group(1))
only_wait_if_higher = False
except Exception:
pass
if wait:
self._waitForHeatup("bed", only_wait_if_higher)
if self._settings.get_boolean(["repetierStyleTargetTemperature"]):
self._send("TargetBed:%d" % self.bedTargetTemp)
def _parseChamberCommand(self, line, wait=False, support_r=False):
if not self._settings.get_boolean(["hasChamber"]):
return
only_wait_if_higher = True
try:
self.chamberTargetTemp = float(re.search("S([0-9]+)", line).group(1))
except Exception:
if support_r:
try:
self.chamberTargetTemp = float(re.search("R([0-9]+)", line).group(1))
only_wait_if_higher = False
except Exception:
pass
if wait:
self._waitForHeatup("chamber", only_wait_if_higher)
def _performMove(self, line: str) -> None:
matchX = re.search(r"X(-?[0-9.]+)", line)
matchY = re.search(r"Y(-?[0-9.]+)", line)
matchZ = re.search(r"Z(-?[0-9.]+)", line)
matchE = re.search(r"E(-?[0-9.]+)", line)
matchF = re.search(r"F([0-9.]+)", line)
duration = 0.0
if matchF is not None:
try:
self._lastF = float(matchF.group(1))
except ValueError:
pass
speedXYZ = self._lastF * (self._feedrate_multiplier / 100)
speedE = self._lastF * (self._flowrate_multiplier / 100)
if speedXYZ == 0:
speedXYZ = 999999999999
if speedE == 0:
speedE = 999999999999
if matchX is not None:
try:
x = float(matchX.group(1))
except ValueError:
pass
else:
if self._relative or self._lastX is None:
duration = max(duration, x * self._unitModifier / speedXYZ * 60)
else:
duration = max(
duration, (x - self._lastX) * self._unitModifier / speedXYZ * 60
)
if self._relative and self._lastX is not None:
self._lastX += x
else:
self._lastX = x
if matchY is not None:
try:
y = float(matchY.group(1))
except ValueError:
pass
else:
if self._relative or self._lastY is None:
duration = max(duration, y * self._unitModifier / speedXYZ * 60)
else:
duration = max(
duration, (y - self._lastY) * self._unitModifier / speedXYZ * 60
)
if self._relative and self._lastY is not None:
self._lastY += y
else:
self._lastY = y
if matchZ is not None:
try:
z = float(matchZ.group(1))
except ValueError:
pass
else:
if self._relative or self._lastZ is None:
duration = max(duration, z * self._unitModifier / speedXYZ * 60)
else:
duration = max(
duration, (z - self._lastZ) * self._unitModifier / speedXYZ * 60
)
if self._relative and self._lastZ is not None:
self._lastZ += z
else:
self._lastZ = z
if matchE is not None:
try:
e = float(matchE.group(1))
except ValueError:
pass
else:
lastE = self._lastE[self.currentExtruder]
if self._relative or lastE is None:
duration = max(duration, e * self._unitModifier / speedE * 60)
else:
duration = max(
duration, (e - lastE) * self._unitModifier / speedE * 60
)
if self._relative and lastE is not None:
self._lastE[self.currentExtruder] += e
else:
self._lastE[self.currentExtruder] = e
if duration:
duration *= 0.1
if duration > self._read_timeout:
slept = 0
while duration - slept > self._read_timeout and not self._killed:
time.sleep(self._read_timeout)
slept += self._read_timeout
else:
time.sleep(duration)
def _setPosition(self, line: str) -> None:
matchX = re.search(r"X(-?[0-9.]+)", line)
matchY = re.search(r"Y(-?[0-9.]+)", line)
matchZ = re.search(r"Z(-?[0-9.]+)", line)
matchE = re.search(r"E(-?[0-9.]+)", line)
if matchX is None and matchY is None and matchZ is None and matchE is None:
self._lastX = self._lastY = self._lastZ = self._lastE[
self.currentExtruder
] = 0
else:
if matchX is not None:
try:
self._lastX = float(matchX.group(1))
except ValueError:
pass
if matchY is not None:
try:
self._lastY = float(matchY.group(1))
except ValueError:
pass
if matchZ is not None:
try:
self._lastZ = float(matchZ.group(1))
except ValueError:
pass
if matchE is not None:
try:
self._lastE[self.currentExtruder] = float(matchE.group(1))
except ValueError:
pass
def _home(self, line):
x = y = z = e = None
if "X" in line:
x = True
if "Y" in line:
y = True
if "Z" in line:
z = True
if "E" in line:
e = True
if x is None and y is None and z is None and e is None:
self._lastX = self._lastY = self._lastZ = self._lastE[
self.currentExtruder
] = 0
else:
if x:
self._lastX = 0
if y:
self._lastY = 0
if z:
self._lastZ = 0
if e:
self._lastE = 0
def _writeSdFile(self, filename: str) -> None:
if filename.startswith("/"):
filename = filename[1:]
file = os.path.join(self._virtualSd, filename)
if os.path.exists(file):
if os.path.isfile(file):
os.remove(file)
else:
self._send("error writing to file")
handle = None
try:
handle = open(file, "w", encoding="utf-8")
except Exception:
self._send("error writing to file")
self._writingToSdHandle = handle
self._writingToSdFile = file
self._writingToSd = True
self._selectedSdFile = file
self._send(f"Writing to file: {filename}")
def _finishSdFile(self):
try:
self._writingToSdHandle.close()
except Exception:
pass
finally:
self._writingToSdHandle = None
self._writingToSd = False
self._selectedSdFile = None
# Most printers don't have RTC and set some ancient date
# by default. Emulate that using 2000-01-01 01:00:00
# (taken from prusa firmware behaviour)
st = os.stat(self._writingToSdFile)
os.utime(self._writingToSdFile, (st.st_atime, 946684800))
self._writingToSdFile = None
self._send("Done saving file")
def _sdPrintingWorker(self):
self._selectedSdFilePos = 0
try:
with open(self._selectedSdFile, encoding="utf-8") as f:
for line in iter(f.readline, ""):
if self._killed or not self._sdPrinting:
break
# reset position if requested by client
if self._newSdFilePos is not None:
f.seek(self._newSdFilePos)
self._newSdFilePos = None
# read current file position
self._selectedSdFilePos = f.tell()
# if we are paused, wait for resuming
self._sdPrintingSemaphore.wait()
if self._killed or not self._sdPrinting:
break
# set target temps
if "M104" in line or "M109" in line:
self._parseHotendCommand(line, wait="M109" in line)
elif "M140" in line or "M190" in line:
self._parseBedCommand(line, wait="M190" in line)
elif (
line.startswith("G0")
or line.startswith("G1")
or line.startswith("G2")
or line.startswith("G3")
):
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
self.buffered.put(line)
except AttributeError:
if self.outgoing is not None:
raise
self._finishSdPrint()
def _finishSdPrint(self):
self._sdPrintingSemaphore.clear()
self._selectedSdFilePos = 0
self._sdPrinting = False
self._sdPrinter = None
if not self._killed and not self._sdCancelled:
self._send("Done printing file")
def _waitForHeatup(self, heater: str, only_wait_if_higher: bool) -> None:
delta = 1
delay = 1
last_busy = time.monotonic()
self._heatingUp = True
try:
if heater.startswith("tool"):
toolNum = int(heater[len("tool") :])
test = lambda: self.temp[toolNum] < self.targetTemp[toolNum] - delta or (
not only_wait_if_higher
and self.temp[toolNum] > self.targetTemp[toolNum] + delta
)
output = lambda: "T:%0.2f" % self.temp[toolNum]
elif heater == "bed":
test = lambda: self.bedTemp < self.bedTargetTemp - delta or (
not only_wait_if_higher and self.bedTemp > self.bedTargetTemp + delta
)
output = lambda: "B:%0.2f" % self.bedTemp
elif heater == "chamber":
test = lambda: self.chamberTemp < self.chamberTargetTemp - delta or (
not only_wait_if_higher
and self.chamberTemp > self.chamberTargetTemp + delta
)
output = lambda: "C:%0.2f" % self.chamberTemp
else:
return
while not self._killed and self._heatingUp and test():
self._simulateTemps(delta=delta)
self._send(output())
if self._sendBusy and time.monotonic() - last_busy >= self._busyInterval:
self._send("echo:busy: processing")
last_busy = time.monotonic()
time.sleep(delay)
except AttributeError:
if self.outgoing is not None:
raise
finally:
self._heatingUp = False
def _deleteSdFile(self, filename: str) -> None:
if filename.startswith("/"):
filename = filename[1:]
file = self._getSdFileData(filename)
if (
file is not None
and os.path.exists(file["path"])
and os.path.isfile(file["path"])
):
os.remove(file["path"])
def _simulateTemps(self, delta=0.5):
timeDiff = self.lastTempAt - time.monotonic()
self.lastTempAt = time.monotonic()
def simulate(actual, target, ambient):
if target > 0:
goal = target
remaining = abs(actual - target)
if remaining > delta:
factor = 10
elif remaining < delta:
factor = remaining
elif not target and abs(actual - ambient) > delta:
goal = ambient
factor = 2
else:
return actual
old = actual
actual += math.copysign(timeDiff * factor, goal - actual)
if math.copysign(1, goal - old) != math.copysign(1, goal - actual):
actual = goal
return actual
for i in range(len(self.temp)):
if i in self.pinnedExtruders:
self.temp[i] = self.pinnedExtruders[i]
continue
self.temp[i] = simulate(
self.temp[i], self.targetTemp[i], self._ambient_temperature
)
self.bedTemp = simulate(
self.bedTemp, self.bedTargetTemp, self._ambient_temperature
)
self.chamberTemp = simulate(
self.chamberTemp, self.chamberTargetTemp, self._ambient_temperature
)
def _processBuffer(self):
while self.buffered is not None:
try:
line = self.buffered.get(timeout=0.5)
except queue.Empty:
continue
if line is None:
continue
self._performMove(line)
self.buffered.task_done()
self._logger.info("Closing down buffer loop")
def _setBusy(self, reason="processing"):
if not self._sendBusy:
return
def loop():
while self._busy:
self._send(f"echo:busy {self._busy}")
time.sleep(self._busyInterval)
self._sendOk()
self._busy = reason
self._busy_loop = threading.Thread(target=loop)
self._busy_loop.daemon = True
self._busy_loop.start()
def _setUnbusy(self):
self._busy = None
def _showPrompt(self, text, choices):
self._hidePrompt()
self._send(f"//action:prompt_begin {text}")
for choice in choices:
self._send(f"//action:prompt_button {choice}")
self._send("//action:prompt_show")
def _hidePrompt(self):
self._send("//action:prompt_end")
def write(self, data: bytes) -> int:
data = to_bytes(data, errors="replace")
u_data = to_unicode(data, errors="replace")
if self._debug_awol:
return len(data)
if self._debug_drop_connection:
self._logger.info(
"Debug drop of connection requested, raising SerialTimeoutException"
)
raise SerialTimeoutException()
with self._incoming_lock:
if self.incoming is None or self.outgoing is None:
return 0
if b"M112" in data and self._supportM112:
self._seriallog.info(f"<<< {u_data}")
self._kill()
return len(data)
try:
written = self.incoming.put(
data, timeout=self._write_timeout, partial=True
)
self._seriallog.info(f"<<< {u_data}")
return written
except queue.Full:
self._logger.info(
"Incoming queue is full, raising SerialTimeoutException"
)
raise SerialTimeoutException()
def readline(self) -> bytes:
if self._debug_awol:
time.sleep(self._read_timeout)
return b""
if self._debug_drop_connection:
raise SerialTimeoutException()
if self._debug_sleep > 0:
# if we are supposed to sleep, we sleep not longer than the read timeout
# (and then on the next call sleep again if there's time to sleep left)
sleep_for = min(self._debug_sleep, self._read_timeout)
self._debug_sleep -= sleep_for
time.sleep(sleep_for)
if self._debug_sleep > 0:
# we slept the full read timeout, return an empty line
return b""
# otherwise our left over timeout is the read timeout minus what we already
# slept for
timeout = self._read_timeout - sleep_for
else:
# use the full read timeout as timeout
timeout = self._read_timeout
try:
# fetch a line from the queue, wait no longer than timeout
line = to_unicode(self.outgoing.get(timeout=timeout), errors="replace")
self._seriallog.info(f">>> {line.strip()}")
self.outgoing.task_done()
return to_bytes(line)
except queue.Empty:
# queue empty? return empty line
return b""
def close(self):
self._killed = True
self.incoming = None
self.outgoing = None
self.buffered = None
def _sendOk(self):
if self.outgoing is None:
return
ok = self._ok()
if ok:
self._send(ok)
def _sendWaitAfterTimeout(self, timeout=5):
time.sleep(timeout)
if self.outgoing is not None:
self._send("wait")
def _send(self, line: str) -> None:
if self.outgoing is not None:
self.outgoing.put(line)
def _ok(self):
ok = self._okFormatString
if self._prepared_oks:
ok = self._prepared_oks.pop(0)
if ok is None:
return ok
return ok.format(
ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize()
)
def _error(self, error: str, *args, **kwargs) -> str:
return f"Error: {self._errors.get(error).format(*args, **kwargs)}"
class VirtualEEPROM:
def __init__(self, data_folder):
self._data_folder = data_folder
self._eeprom_file_path = os.path.join(self._data_folder, "eeprom.json")
self._eeprom = self._initialise_eeprom()
def _initialise_eeprom(self):
if os.path.exists(self._eeprom_file_path):
# file exists, read it
with open(self._eeprom_file_path, encoding="utf-8") as eeprom_file:
data = json.load(eeprom_file)
return data
else:
# no eeprom file, make new one with defaults
data = self.get_default_settings()
with open(self._eeprom_file_path, "w", encoding="utf-8") as eeprom_file:
eeprom_file.write(to_unicode(json.dumps(data)))
return data
@staticmethod
def get_default_settings():
return {
"steps": {
"command": "M92",
"description": "Steps per unit:",
"params": {"X": 80.0, "Y": 80.0, "Z": 800.0, "E": 90.0},
},
"feedrate": {
"command": "M203",
"description": "Maximum feedrates (units/s):",
"params": {"X": 500.0, "Y": 500.0, "Z": 5.0, "E": 25.0},
},
"max_accel": {
"command": "M201",
"description": "Maximum Acceleration (units/s2):",
"params": {"E": 74.0, "X": 2000.0, "Y": 2000.0, "Z": 10.0},
},
"start_accel": {
"command": "M204",
"description": "Acceleration (units/s2): P<print_accel> R<retract_accel>"
" T<travel_accel>",
"params": {"P": 750.0, "R": 1000.0, "T": 300.0, "S": 300.0},
# S is deprecated, use P & T instead
},
"home_offset": {
"command": "M206",
"description": "Home offset:",
"params": {"X": 0.0, "Y": 0.0, "Z": 0.0},
}, # TODO below are not yet implemented in gcode, just settings
"probe_offset": {
"command": "M851",
"description": "Z-Probe Offset (mm):",
"params": {"X": 5.0, "Y": 5.0, "Z": 0.2},
},
"filament": {
"command": "M200",
"description": "Filament settings: Disabled",
"params": {"D": 1.75, "S": 0},
},
"endstop": {
"command": "M666",
"description": "Enstop adjustment:", # TODO description needed
"params": {"X": -1.0, "Y": 0.0, "Z": 0.0},
},
"delta": {
"command": "M665",
"description": "Delta config:", # TODO description
"params": {
"B": 0.0,
"H": 100.0,
"L": 25.0,
"R": 6.5,
"S": 100.0,
"X": 20.0,
"Y": 20.0,
"Z": 20.0,
},
},
"auto_level": {
"command": "M420",
"description": "Bed Levelling:",
"params": {"S": 0, "Z": 0.0},
},
"linear_advance": {
"command": "M900",
"description": "Linear Advance:",
"params": {"K": 0.01},
},
"advanced": {
"command": "M205",
"description": "Advanced: B<min_segment_time_us> S<min_feedrate> "
"T<min_travel_feedrate> X<max_x_jerk> Y<max_y_jerk> "
"Z<max_z_jerk> E<max_e_jerk>",
"params": {
"B": 20000.0,
"S": 0.0,
"T": 0.0,
"X": 10.0,
"Y": 10.0,
"Z": 0.3,
"E": 5.0,
"J": 0.0,
},
},
"material": { # TODO This ones going to need some special handling...
"command": "M145",
"description": "Material heatup parameters:",
"params": {
"0": {"B": 50, "F": 255, "H": "205"},
"1": {"B": 75, "F": 0, "H": 240},
},
},
"pid": {
"command": "M301",
"description": "PID settings:",
"params": {"P": 27.08, "I": 2.51, "D": 73.09},
},
"pid_bed": {
"command": "M304",
"description": "PID settings:",
"params": {"P": 131.06, "I": 11.79, "D": 971.23},
},
}
def save_settings(self):
# M500 behind-the-scenes
with open(self._eeprom_file_path, "w", encoding="utf-8") as eeprom_file:
eeprom_file.write(to_unicode(json.dumps(self._eeprom)))
def read_settings(self):
# M501 - if the file has disappeared, then recreate it
if not os.path.exists(self._eeprom_file_path):
self.load_defaults()
self.save_settings()
with open(self._eeprom_file_path) as eeprom_file:
self._eeprom = json.load(eeprom_file)
def load_defaults(self):
# M502
self._eeprom = self.get_default_settings()
@property
def eeprom(self):
return self._eeprom
# noinspection PyUnresolvedReferences
class CharCountingQueue(queue.Queue):
def __init__(self, maxsize, name=None):
queue.Queue.__init__(self, maxsize=maxsize)
self._size = 0
self._name = name
def clear(self):
with self.mutex:
self.queue.clear()
def put(self, item, block=True, timeout=None, partial=False):
self.not_full.acquire()
try:
if not self._will_it_fit(item) and partial:
space_left = self.maxsize - self._qsize()
if space_left:
item = item[:space_left]
if not block:
if not self._will_it_fit(item):
raise queue.Full
elif timeout is None:
while not self._will_it_fit(item):
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = time.monotonic() + timeout
while not self._will_it_fit(item):
remaining = endtime - time.monotonic()
if remaining <= 0:
raise queue.Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
return self._len(item)
finally:
self.not_full.release()
# noinspection PyMethodMayBeStatic
def _len(self, item):
return len(item)
def _qsize(self, l=len): # noqa: E741
return self._size
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
self._size += self._len(item)
# Get an item from the queue
def _get(self):
item = self.queue.popleft()
self._size -= self._len(item)
return item
def _will_it_fit(self, item):
return self.maxsize - self._qsize() >= self._len(item)
| 90,602 | Python | .py | 2,093 | 30.305781 | 224 | 0.533125 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,950 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/tracking/__init__.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 concurrent.futures
import hashlib
import logging
import time
from urllib.parse import urlencode
import requests
from flask_babel import gettext
import octoprint.plugin
from octoprint.events import Events
from octoprint.util import RepeatedTimer
from octoprint.util.version import get_octoprint_version_string
TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/"
# noinspection PyMissingConstructor
class TrackingPlugin(
octoprint.plugin.SettingsPlugin,
octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.ShutdownPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SimpleApiPlugin,
):
def __init__(self):
self._environment = None
self._throttle_state = None
self._helpers_get_throttle_state = None
self._helpers_get_unlocked_achievements = None
self._printer_connection_parameters = None
self._url = None
self._ping_worker = None
self._pong_worker = None
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
self._record_next_firmware_info = False
self._startup_time = time.monotonic()
def initialize(self):
self._init_id()
##~~ SettingsPlugin
def get_settings_defaults(self):
return {
"enabled": None,
"unique_id": None,
"server": TRACKING_URL,
"ping": 15 * 60,
"pong": 24 * 60 * 60,
"events": {
"pong": True,
"startup": True,
"printjob": True,
"commerror": True,
"plugin": True,
"update": True,
"printer": True,
"printer_safety_check": True,
"throttled": True,
"achievements": True,
"slicing": True,
"webui_load": True,
},
}
def get_settings_restricted_paths(self):
return {
"admin": [["enabled"], ["unique_id"], ["events"]],
"never": [["server"], ["ping"]],
}
def on_settings_save(self, data):
enabled = self._settings.get(["enabled"])
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
if enabled is None and self._settings.get(["enabled"]):
# tracking was just enabled, let's start up tracking
self._start_tracking()
##~~ SimpleApiPlugin
def get_api_commands(self):
return {"track": ["event", "payload"]}
def on_api_command(self, command, data):
if command != "track":
return
event = data.pop("event")
if event == "webui_load":
payload = data.get("payload", {})
browser_name = payload.get("browser_name")
browser_version = payload.get("browser_version")
os_name = payload.get("os_name")
os_version = payload.get("os_version")
if all((browser_name, browser_version, os_name, os_version)):
self._track_webui_load(browser_name, browser_version, os_name, os_version)
##~~ EnvironmentDetectionPlugin
def on_environment_detected(self, environment, *args, **kwargs):
self._environment = environment
##~~ StartupPlugin
def on_after_startup(self):
self._start_tracking()
##~~ ShutdownPlugin
def on_shutdown(self):
if not self._settings.get_boolean(["enabled"]):
return
self._track_shutdown()
self._executor.shutdown(wait=True)
##~~ EventHandlerPlugin
# noinspection PyUnresolvedReferences
def on_event(self, event, payload):
if not self._settings.get_boolean(["enabled"]):
return
if event in (
Events.PRINT_STARTED,
Events.PRINT_DONE,
Events.PRINT_FAILED,
Events.PRINT_CANCELLED,
):
self._track_printjob_event(event, payload)
elif event in (Events.ERROR,):
self._track_commerror_event(event, payload)
elif event in (Events.CONNECTED,):
self._printer_connection_parameters = {
"port": payload["port"],
"baudrate": payload["baudrate"],
}
self._record_next_firmware_info = True
elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info:
self._record_next_firmware_info = False
self._track_printer_event(event, payload)
elif event in (Events.SLICING_STARTED,):
self._track_slicing_event(event, payload)
elif hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN") and event in (
Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN,
):
self._track_plugin_event(event, payload)
elif hasattr(Events, "PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED") and event in (
Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED,
Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED,
):
self._track_update_event(event, payload)
elif hasattr(Events, "PLUGIN_PI_SUPPORT_THROTTLE_STATE") and event in (
Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE,
):
self._throttle_state = payload
self._track_throttle_event(event, payload)
elif hasattr(Events, "PLUGIN_PRINTER_SAFETY_CHECK_WARNING") and event in (
Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING,
):
self._track_printer_safety_event(event, payload)
elif hasattr(Events, "PLUGIN_ACHIEVEMENTS_ACHIEVEMENT_UNLOCKED") and event in (
Events.PLUGIN_ACHIEVEMENTS_ACHIEVEMENT_UNLOCKED,
):
self._track_achievement_unlocked_event(event, payload)
##~~ TemplatePlugin
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Anonymous Usage Tracking"),
"template": "tracking_settings.jinja2",
"custom_bindings": False,
},
{
"type": "wizard",
"name": gettext("Anonymous Usage Tracking"),
"template": "tracking_wizard.jinja2",
"custom_bindings": True,
"mandatory": True,
},
]
##~~ AssetPlugin
def get_assets(self):
return {"js": ["js/usage.js"], "clientjs": ["clientjs/usage.js"]}
##~~ WizardPlugin
def is_wizard_required(self):
return self._settings.get(["enabled"]) is None
##~~ helpers
def _init_id(self):
if not self._settings.get(["unique_id"]):
import uuid
self._settings.set(["unique_id"], str(uuid.uuid4()))
self._settings.save()
def _start_tracking(self):
if not self._settings.get_boolean(["enabled"]):
return
if self._helpers_get_throttle_state is None:
# cautiously look for the get_throttled helper from pi_support
pi_helper = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if pi_helper and "get_throttled" in pi_helper:
self._helpers_get_throttle_state = pi_helper["get_throttled"]
if self._helpers_get_unlocked_achievements is None:
# cautiously look for the get_unlocked_achievements helper from achievements
achievements_helper = self._plugin_manager.get_helpers(
"achievements", "get_unlocked_achievements"
)
if achievements_helper and "get_unlocked_achievements" in achievements_helper:
self._helpers_get_unlocked_achievements = achievements_helper[
"get_unlocked_achievements"
]
if self._ping_worker is None:
ping_interval = self._settings.get_int(["ping"])
if ping_interval:
self._ping_worker = RepeatedTimer(
ping_interval, self._track_ping, run_first=True
)
self._ping_worker.start()
if self._pong_worker is None:
pong_interval = self._settings.get(["pong"])
if pong_interval:
self._pong_worker = RepeatedTimer(
pong_interval, self._track_pong, run_first=True
)
self._pong_worker.start()
# now that we have everything set up, phone home.
self._track_startup()
def _track_ping(self):
if not self._settings.get_boolean(["enabled"]):
return
uptime = int(time.monotonic() - self._startup_time)
printer_state = self._printer.get_state_id()
self._track("ping", octoprint_uptime=uptime, printer_state=printer_state)
def _track_pong(self):
if not self._settings.get_boolean(["events", "pong"]):
return
payload = self._get_environment_payload()
plugins = self._plugin_manager.enabled_plugins
plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled]
payload["plugins"] = ",".join(
map(
lambda x: "{}:{}".format(
x.key.lower(), x.version.lower() if x.version else "?"
),
plugins_thirdparty,
)
)
if self._helpers_get_unlocked_achievements and self._settings.get_boolean(
["events", "achievements"]
):
payload["achievements"] = ",".join(
map(
lambda x: x.key.lower(),
self._helpers_get_unlocked_achievements(),
)
)
self._track("pong", body=True, **payload)
def _track_startup(self):
if not self._settings.get_boolean(["events", "startup"]):
return
payload = self._get_environment_payload()
self._track("startup", **payload)
def _track_shutdown(self):
if not self._settings.get_boolean(["enabled"]):
return
if not self._settings.get_boolean(["events", "startup"]):
return
self._track("shutdown")
def _track_webui_load(self, browser_name, browser_version, os_name, os_version):
if not self._settings.get_boolean(["events", "webui_load"]):
return
self._track(
"webui_load",
browser_name=browser_name,
browser_version=browser_version,
os_name=os_name,
os_version=os_version,
)
def _track_plugin_event(self, event, payload):
if not self._settings.get_boolean(["events", "plugin"]):
return
if event.endswith("_install_plugin"):
self._track(
"install_plugin",
plugin=payload.get("id"),
plugin_version=payload.get("version"),
)
elif event.endswith("_uninstall_plugin"):
self._track(
"uninstall_plugin",
plugin=payload.get("id"),
plugin_version=payload.get("version"),
)
elif event.endswith("_enable_plugin"):
self._track(
"enable_plugin",
plugin=payload.get("id"),
plugin_version=payload.get("version"),
)
elif event.endswith("_disable_plugin"):
self._track(
"disable_plugin",
plugin=payload.get("id"),
plugin_version=payload.get("version"),
)
def _track_update_event(self, event, payload):
if not self._settings.get_boolean(["events", "update"]):
return
if event.endswith("_update_succeeded"):
self._track(
"update_successful",
target=payload.get("target"),
from_version=payload.get("from_version"),
to_version=payload.get("to_version"),
)
elif event.endswith("_update_failed"):
self._track(
"update_failed",
target=payload.get("target"),
from_version=payload.get("from_version"),
to_version=payload.get("to_version"),
)
def _track_throttle_event(self, event, payload):
if not self._settings.get_boolean(["events", "throttled"]):
return
args = {
"throttled_now": payload["current_issue"],
"throttled_past": payload["past_issue"],
"throttled_mask": payload["raw_value"],
"throttled_voltage_now": payload["current_undervoltage"],
"throttled_voltage_past": payload["past_undervoltage"],
"throttled_overheat_now": payload["current_overheat"],
"throttled_overheat_past": payload["past_overheat"],
}
if payload["current_issue"]:
track_event = "system_throttled"
else:
track_event = "system_unthrottled"
if track_event is not None:
self._track(track_event, **args)
def _track_commerror_event(self, event, payload):
if not self._settings.get_boolean(["events", "commerror"]):
return
if "reason" not in payload or "error" not in payload:
return
track_event = "commerror_{}".format(payload["reason"])
args = {"commerror_text": payload["error"]}
if callable(self._helpers_get_throttle_state):
try:
throttle_state = self._helpers_get_throttle_state(run_now=True)
if throttle_state and (
throttle_state.get("current_issue", False)
or throttle_state.get("past_issue", False)
):
args["throttled_now"] = throttle_state["current_issue"]
args["throttled_past"] = throttle_state["past_issue"]
args["throttled_mask"] = throttle_state["raw_value"]
except Exception:
# ignored
pass
self._track(track_event, **args)
def _track_printjob_event(self, event, payload):
if not self._settings.get_boolean(["events", "printjob"]):
return
unique_id = self._settings.get(["unique_id"])
if not unique_id:
return
sha = hashlib.sha1()
sha.update(payload.get("path").encode("utf-8"))
sha.update(unique_id.encode("utf-8"))
track_event = None
args = {"origin": payload.get("origin"), "file": sha.hexdigest()}
if event == Events.PRINT_STARTED:
track_event = "print_started"
elif event == Events.PRINT_DONE:
try:
elapsed = int(payload.get("time", 0))
if elapsed:
args["elapsed"] = elapsed
except (ValueError, TypeError):
pass
track_event = "print_done"
elif event == Events.PRINT_FAILED:
try:
elapsed = int(payload.get("time", 0))
if elapsed:
args["elapsed"] = elapsed
except (ValueError, TypeError):
pass
args["reason"] = payload.get("reason", "unknown")
if "error" in payload and self._settings.get_boolean(["events", "commerror"]):
args["commerror_text"] = payload["error"]
track_event = "print_failed"
elif event == Events.PRINT_CANCELLED:
try:
elapsed = int(payload.get("time", 0))
if elapsed:
args["elapsed"] = elapsed
except (ValueError, TypeError):
pass
track_event = "print_cancelled"
if callable(self._helpers_get_throttle_state):
try:
throttle_state = self._helpers_get_throttle_state(run_now=True)
if throttle_state and (
throttle_state.get("current_issue", False)
or throttle_state.get("past_issue", False)
):
args["throttled_now"] = throttle_state["current_issue"]
args["throttled_past"] = throttle_state["past_issue"]
args["throttled_mask"] = throttle_state["raw_value"]
except Exception:
# ignored
pass
if track_event is not None:
self._track(track_event, **args)
def _track_printer_event(self, event, payload):
if not self._settings.get_boolean(["events", "printer"]):
return
if event in (Events.FIRMWARE_DATA,):
args = {"firmware_name": payload["name"]}
if self._printer_connection_parameters:
args["printer_port"] = self._printer_connection_parameters["port"]
args["printer_baudrate"] = self._printer_connection_parameters["baudrate"]
self._track("printer_connected", **args)
def _track_printer_safety_event(self, event, payload):
if not self._settings.get_boolean(["events", "printer_safety_check"]):
return
self._track(
"printer_safety_warning",
printer_safety_warning_type=payload.get("warning_type", "unknown"),
printer_safety_check_name=payload.get("check_name", "unknown"),
)
def _track_achievement_unlocked_event(self, event, payload):
if not self._settings.get_boolean(["events", "achievements"]):
return
self._track(
"achievement_unlocked",
achievement=payload.get("key", "unknown"),
)
def _track_slicing_event(self, event, payload):
if not self._settings.get_boolean(["events", "slicing"]):
return
self._track("slicing_started", slicer=payload.get(b"slicer", "unknown"))
def _track(self, event, **kwargs):
if not self._settings.get_boolean(["enabled"]):
return
self._executor.submit(self._do_track, event, **kwargs)
def _do_track(self, event, body=False, **kwargs):
if not self._connectivity_checker.online:
return
if not self._settings.get_boolean(["enabled"]):
return
unique_id = self._settings.get(["unique_id"])
if not unique_id:
return
server = self._settings.get(["server"])
url = server.format(id=unique_id, event=event)
# Don't print the URL or UUID! That would expose the UUID in forums/tickets
# if pasted. It's okay for the user to know their uuid, but it shouldn't be shared.
headers = {"User-Agent": f"OctoPrint/{get_octoprint_version_string()}"}
try:
params = urlencode(kwargs, doseq=True).replace("+", "%20")
if body:
requests.post(url, data=params, timeout=3.05, headers=headers)
else:
requests.get(url, params=params, timeout=3.05, headers=headers)
self._logger.info(f"Sent tracking event {event}, payload: {kwargs!r}")
except Exception:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception(
"Error while sending event to anonymous usage tracking"
)
else:
pass
def _get_environment_payload(self):
payload = {
"version": get_octoprint_version_string(),
"os": self._environment["os"]["id"],
"bits": self._environment["os"]["bits"],
"python": self._environment["python"]["version"],
"pip": self._environment["python"]["pip"],
"cores": self._environment["hardware"]["cores"],
"freq": self._environment["hardware"]["freq"],
"ram": self._environment["hardware"]["ram"],
}
if (
"plugins" in self._environment
and "pi_support" in self._environment["plugins"]
):
payload["pi_model"] = self._environment["plugins"]["pi_support"]["model"]
if "octopi_version" in self._environment["plugins"]["pi_support"]:
payload["octopi_version"] = self._environment["plugins"]["pi_support"][
"octopi_version"
]
if "octopiuptodate_build" in self._environment["plugins"]["pi_support"]:
payload["octopiuptodate_build"] = self._environment["plugins"][
"pi_support"
]["octopiuptodate_build"]
return payload
__plugin_name__ = "Anonymous Usage Tracking"
__plugin_description__ = (
"Anonymous version and usage tracking, see homepage for details on what gets tracked"
)
__plugin_url__ = "https://tracking.octoprint.org"
__plugin_author__ = "Gina Häußge"
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = TrackingPlugin()
| 21,424 | Python | .py | 495 | 31.581818 | 103 | 0.571085 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,951 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/classicwebcam/__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"
import threading
import requests
from flask_babel import gettext
import octoprint.plugin
from octoprint.schema.webcam import RatioEnum, Webcam, WebcamCompatibility
from octoprint.webcams import WebcamNotAbleToTakeSnapshotException
class ClassicWebcamPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.WebcamProviderPlugin,
octoprint.plugin.WizardPlugin,
):
def __init__(self):
self._capture_mutex = threading.Lock()
self._webcam_name = "classic"
# ~~ TemplatePlugin API
def get_assets(self):
return {
"js": [
"js/classicwebcam.js",
"js/classicwebcam_settings.js",
"js/classicwebcam_wizard.js",
],
"less": ["less/classicwebcam.less"],
"css": ["css/classicwebcam.css"],
}
def get_template_configs(self):
return [
{
"type": "settings",
"template": "classicwebcam_settings.jinja2",
"custom_bindings": True,
},
{
"type": "webcam",
"name": "Classic Webcam",
"template": "classicwebcam_webcam.jinja2",
"custom_bindings": True,
"suffix": "_real",
},
{
"type": "wizard",
"name": "Classic Webcam Wizard",
"template": "classicwebcam_wizard.jinja2",
"suffix": "_wizard",
},
]
# ~~ WebcamProviderPlugin API
def get_webcam_configurations(self):
streamRatio = self._settings.get(["streamRatio"])
if streamRatio == "4:3":
streamRatio = RatioEnum.four_three
else:
streamRatio = RatioEnum.sixteen_nine
webRtcServers = self._settings.get(["streamWebrtcIceServers"])
cacheBuster = self._settings.get_boolean(["cacheBuster"])
stream = self._get_stream_url()
snapshot = self._get_snapshot_url()
flipH = self._settings.get_boolean(["flipH"])
flipV = self._settings.get_boolean(["flipV"])
rotate90 = self._settings.get_boolean(["rotate90"])
snapshotSslValidation = self._settings.get_boolean(["snapshotSslValidation"])
try:
streamTimeout = int(self._settings.get(["streamTimeout"]))
except Exception:
streamTimeout = 5
try:
snapshotTimeout = int(self._settings.get(["snapshotTimeout"]))
except Exception:
snapshotTimeout = 5
return [
Webcam(
name=self._webcam_name,
displayName="Classic Webcam",
flipH=flipH,
flipV=flipV,
rotate90=rotate90,
snapshotDisplay=snapshot,
canSnapshot=self._can_snapshot(),
compat=WebcamCompatibility(
stream=stream,
streamTimeout=streamTimeout,
streamRatio=streamRatio,
cacheBuster=cacheBuster,
streamWebrtcIceServers=webRtcServers,
snapshot=snapshot,
snapshotTimeout=snapshotTimeout,
snapshotSslValidation=snapshotSslValidation,
),
extras=dict(
stream=stream,
streamTimeout=streamTimeout,
streamRatio=streamRatio,
streamWebrtcIceServers=webRtcServers,
cacheBuster=cacheBuster,
),
),
]
def _get_snapshot_url(self):
return self._settings.get(["snapshot"])
def _get_stream_url(self):
return self._settings.get(["stream"])
def _can_snapshot(self):
snapshot = self._get_snapshot_url()
return snapshot is not None and snapshot.strip() != ""
def take_webcam_snapshot(self, _):
snapshot_url = self._get_snapshot_url()
if not self._can_snapshot():
raise WebcamNotAbleToTakeSnapshotException(self._webcam_name)
with self._capture_mutex:
self._logger.debug(f"Capturing image from {snapshot_url}")
r = requests.get(
snapshot_url,
stream=True,
timeout=self._settings.get_int(["snapshotTimeout"]),
verify=self._settings.get_boolean(["snapshotSslValidation"]),
)
r.raise_for_status()
return r.iter_content(chunk_size=1024)
# ~~ SettingsPlugin API
def get_settings_defaults(self):
return dict(
flipH=False,
flipV=False,
rotate90=False,
stream="",
streamTimeout=5,
streamRatio="16:9",
streamWebrtcIceServers=["stun:stun.l.google.com:19302"],
snapshot="",
cacheBuster=False,
snapshotSslValidation=True,
snapshotTimeout=5,
)
def get_settings_version(self):
return 1
def on_settings_save(self, data):
dirty = False
if "streamTimeout" in data:
self._settings.set_int(["streamTimeout"], data.pop("streamTimeout"))
dirty = True
if "snapshotTimeout" in data:
self._settings.set_int(["snapshotTimeout"], data.pop("snapshotTimeout"))
dirty = True
if dirty:
self._settings.save()
return super().on_settings_save(data)
def on_settings_migrate(self, target, current):
if current is None:
config = self._settings.global_get(["webcam"])
if config:
self._logger.info(
"Migrating settings from webcam to plugins.classicwebcam..."
)
# flipH
self._settings.set_boolean(["flipH"], config.get("flipH", False))
self._settings.global_remove(["webcam", "flipH"])
# flipV
self._settings.set_boolean(["flipV"], config.get("flipV", False))
self._settings.global_remove(["webcam", "flipV"])
# rotate90
self._settings.set_boolean(["rotate90"], config.get("rotate90", False))
self._settings.global_remove(["webcam", "rotate90"])
# stream
self._settings.set(["stream"], config.get("stream", ""))
self._settings.global_remove(["webcam", "stream"])
# streamTimeout
self._settings.set_int(["streamTimeout"], config.get("streamTimeout", 5))
self._settings.global_remove(["webcam", "streamTimeout"])
# streamRatio
self._settings.set(["streamRatio"], config.get("streamRatio", "16:9"))
self._settings.global_remove(["webcam", "streamRatio"])
# streamWebrtcIceServers
self._settings.set(
["streamWebrtcIceServers"],
config.get(
"streamWebrtcIceServers", ["stun:stun.l.google.com:19302"]
),
)
self._settings.global_remove(["webcam", "streamWebrtcIceServers"])
# snapshot
self._settings.set(["snapshot"], config.get("snapshot", ""))
self._settings.global_remove(["webcam", "snapshot"])
# cacheBuster
self._settings.set_boolean(
["cacheBuster"], config.get("cacheBuster", False)
)
self._settings.global_remove(["webcam", "cacheBuster"])
# snapshotTimeout
self._settings.set_int(
["snapshotTimeout"], config.get("snapshotTimeout", 5)
)
self._settings.global_remove(["webcam", "snapshotTimeout"])
# snapshotSslValidation
self._settings.set_boolean(
["snapshotSslValidation"], config.get("snapshotSslValidation", True)
)
self._settings.global_remove(["webcam", "snapshotSslValidation"])
# ~~ WizardPlugin API
def is_wizard_required(self):
required = (
not self._get_stream_url()
or not self._get_snapshot_url()
or not self._settings.global_get(["webcam", "ffmpegPath"])
)
firstrun = self._settings.global_get(["server", "firstRun"])
return required and firstrun
def get_wizard_version(self):
return 1
__plugin_name__ = gettext("Classic Webcam")
__plugin_author__ = "Christian Würthner"
__plugin_description__ = "Provides a simple webcam viewer in OctoPrint's UI, images provided by an MJPEG webcam."
__plugin_disabling_discouraged__ = gettext(
"This plugin provides the standard webcam in OctoPrint. If you do not have any other plugin providing a webcam set up, the webcam section in the control tab will no longer be visible."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = ClassicWebcamPlugin()
| 9,412 | Python | .py | 221 | 30.022624 | 188 | 0.563764 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,952 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/discovery/__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"
"""
The SSDP/UPNP implementations has been largely inspired by https://gist.github.com/schlamar/2428250
For a spec see http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0.pdf
"""
import collections
import platform
import socket
import time
import flask
import zeroconf
from flask_babel import gettext
import octoprint.plugin
import octoprint.util
def __plugin_load__():
plugin = DiscoveryPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_helpers__
__plugin_helpers__ = {
"ssdp_browse": plugin.ssdp_browse,
"zeroconf_browse": plugin.zeroconf_browse,
"zeroconf_register": plugin.zeroconf_register,
"zeroconf_unregister": plugin.zeroconf_unregister,
}
class DiscoveryPlugin(
octoprint.plugin.StartupPlugin,
octoprint.plugin.ShutdownPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SettingsPlugin,
):
ssdp_multicast_addr = "239.255.255.250" # IPv6: ff0X::c
ssdp_multicast_port = 1900
ssdp_server = "{}/{} UPnP/1.0 OctoPrint/{}".format(
platform.system(), platform.version(), octoprint.__version__
)
# noinspection PyMissingConstructor
def __init__(self):
self.host = None
self.port = None
# zeroconf
self._zeroconf = None
self._zeroconf_registrations = collections.defaultdict(list)
# upnp/ssdp
self._ssdp_monitor_active = False
self._ssdp_monitor_thread = None
self._ssdp_notify_timeout = 30
self._ssdp_last_notify = 0
def initialize(self):
self._zeroconf = zeroconf.Zeroconf(interfaces=self.get_interface_addresses())
##~~ SettingsPlugin API
def get_settings_defaults(self):
return {
"publicHost": None,
"publicPort": None,
"pathPrefix": None,
"httpUsername": None,
"httpPassword": None,
"upnpUuid": None,
"zeroConf": [],
"model": {
"name": None,
"description": None,
"number": None,
"url": None,
"serial": None,
"vendor": None,
"vendorUrl": None,
},
"addresses": None,
"ignoredAddresses": None,
"interfaces": None,
"ignoredInterfaces": None,
}
##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML
@octoprint.plugin.BlueprintPlugin.route("/discovery.xml", methods=["GET"])
def discovery(self):
self._logger.debug("Rendering discovery.xml")
modelName = self._settings.get(["model", "name"])
if not modelName:
import octoprint.server
modelName = octoprint.server.DISPLAY_VERSION
vendor = self._settings.get(["model", "vendor"])
vendorUrl = self._settings.get(["model", "vendorUrl"])
if not vendor:
vendor = "The OctoPrint Project"
vendorUrl = "http://www.octoprint.org/"
response = flask.make_response(
flask.render_template(
"discovery.xml.jinja2",
friendlyName=self.get_instance_name(),
manufacturer=vendor,
manufacturerUrl=vendorUrl,
modelName=modelName,
modelDescription=self._settings.get(["model", "description"]),
modelNumber=self._settings.get(["model", "number"]),
modelUrl=self._settings.get(["model", "url"]),
serialNumber=self._settings.get(["model", "serial"]),
uuid=self.get_uuid(),
presentationUrl=flask.url_for("index", _external=True),
)
)
response.headers["Content-Type"] = "application/xml"
return response
def is_blueprint_protected(self):
return False
def is_blueprint_csrf_protected(self):
return True
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
def on_startup(self, host, port):
public_host = self._settings.get(["publicHost"])
if public_host:
host = public_host
public_port = self._settings.get(["publicPort"])
if public_port:
port = public_port
self.host = host
self.port = port
# Zeroconf
instance_name = self.get_instance_name()
self.zeroconf_register(
"_http._tcp", instance_name, txt_record=self._create_http_txt_record_dict()
)
self.zeroconf_register(
"_octoprint._tcp",
instance_name,
txt_record=self._create_octoprint_txt_record_dict(),
)
for zc in self._settings.get(["zeroConf"]):
if "service" in zc:
self.zeroconf_register(
zc["service"],
zc.get("name", instance_name),
port=zc.get("port"),
txt_record=zc.get("txtRecord"),
)
# SSDP
self._ssdp_register()
##~~ ShutdownPlugin API -- used for unregistering OctoPrint's Zeroconf and SSDP service upon application shutdown
def on_shutdown(self):
registrations = list(self._zeroconf_registrations.keys())
for key in registrations:
reg_type, port = key
self.zeroconf_unregister(reg_type, port)
self._ssdp_unregister()
##~~ helpers
# ZeroConf
def _format_zeroconf_service_type(self, service_type):
if not service_type.endswith("."):
service_type += "."
if not service_type.endswith("local."):
service_type += "local."
return service_type
def _format_zeroconf_name(self, name, service_type):
service_type = self._format_zeroconf_service_type(service_type)
return f"{name}.{service_type}"
def _format_zeroconf_txt(self, record):
result = {}
if not record:
return result
for key, value in record.items():
result[octoprint.util.to_bytes(key)] = octoprint.util.to_bytes(value)
return result
def zeroconf_register(self, reg_type, name=None, port=None, txt_record=None):
"""
Registers a new service with Zeroconf/Bonjour/Avahi.
:param reg_type: type of service to register, e.g. "_gntp._tcp"
:param name: displayable name of the service, if not given defaults to the OctoPrint instance name
:param port: port to register for the service, if not given defaults to OctoPrint's (public) port
:param txt_record: optional txt record to attach to the service, dictionary of key-value-pairs
"""
if not name:
name = self.get_instance_name()
if not port:
port = self.port
reg_type = self._format_zeroconf_service_type(reg_type)
name = self._format_zeroconf_name(name, reg_type)
txt_record = self._format_zeroconf_txt(txt_record)
key = (reg_type, port)
addresses = list(
map(lambda x: socket.inet_aton(x), self.get_interface_addresses())
)
try:
info = zeroconf.ServiceInfo(
reg_type,
name,
addresses=addresses,
port=port,
server=f"{socket.gethostname()}.local.",
properties=txt_record,
)
self._zeroconf.register_service(info, allow_name_change=True)
self._zeroconf_registrations[key].append(info)
self._logger.info(f"Registered '{name}' for {reg_type}")
except Exception:
self._logger.exception(
f"Could not register {name} for {reg_type} on port {port}"
)
def zeroconf_unregister(self, reg_type, port=None):
"""
Unregisters a previously registered Zeroconf/Bonjour/Avahi service identified by service and port.
:param reg_type: the type of the service to be unregistered
:param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given
:return:
"""
if not port:
port = self.port
reg_type = self._format_zeroconf_service_type(reg_type)
key = (reg_type, port)
if key not in self._zeroconf_registrations:
return
infos = self._zeroconf_registrations.pop(key)
try:
for info in infos:
self._zeroconf.unregister_service(info)
self._logger.debug(f"Unregistered {reg_type} on port {port}")
except Exception:
self._logger.exception(
f"Could not (fully) unregister {reg_type} on port {port}"
)
def zeroconf_browse(
self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5
):
"""
Browses for services on the local network providing the specified service type. Can be used either blocking or
non-blocking.
The non-blocking version (default behaviour) will not return until the lookup has completed and
return all results that were found.
For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes.
If no callback is provided in non-blocking mode, a ValueError will be raised.
The results are provided as a list of discovered services, with each service being described by a dictionary
with the following keys:
* `name`: display name of the service
* `host`: host name of the service
* `post`: port the service is listening on
* `txt_record`: TXT record of the service as a dictionary, exact contents depend on the service
Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an
example for a valid callback:
def browse_callback(results):
for result in results:
print "Name: {name}, Host: {host}, Port: {port}, TXT: {txt_record!r}".format(**result)
:param service_type: the service type to browse for
:param block: whether to block, defaults to True
:param callback: callback to call once lookup has completed, must be set when `block` is set to `False`
:param browse_timeout: timeout for browsing operation
:param resolve_timeout: timeout for resolving operations for discovered records
:return: if `block` is `True` a list of the discovered services, an empty list otherwise (results will then be
supplied to the callback instead)
"""
import threading
if not block and not callback:
raise ValueError("Non-blocking mode but no callback given")
service_type = self._format_zeroconf_service_type(service_type)
result = []
result_available = threading.Event()
result_available.clear()
class ZeroconfListener:
def __init__(self, logger):
self._logger = logger
def add_service(self, zeroconf, type, name):
self._logger.debug(
"Got a browsing result for Zeroconf resolution of {}, resolving...".format(
type
)
)
info = zeroconf.get_service_info(
type, name, timeout=resolve_timeout * 1000
)
if info:
def to_result(info, address):
n = info.name[: -(len(type) + 1)]
p = info.port
self._logger.debug(
"Resolved a result for Zeroconf resolution of {}: {} @ {}:{}".format(
type, n, address, p
)
)
return {
"name": n,
"host": address,
"port": p,
"txt_record": info.properties,
}
for address in map(lambda x: socket.inet_ntoa(x), info.addresses):
result.append(to_result(info, address))
self._logger.debug(f"Browsing Zeroconf for {service_type}")
def browse():
listener = ZeroconfListener(self._logger)
browser = zeroconf.ServiceBrowser(self._zeroconf, service_type, listener)
time.sleep(browse_timeout)
browser.cancel()
if callback:
callback(result)
result_available.set()
browse_thread = threading.Thread(target=browse)
browse_thread.daemon = True
browse_thread.start()
if block:
result_available.wait()
return result
else:
return []
# SSDP/UPNP
def ssdp_browse(self, query, block=True, callback=None, timeout=1, retries=5):
"""
Browses for UPNP services matching the supplied query. Can be used either blocking or
non-blocking.
The non-blocking version (default behaviour) will not return until the lookup has completed and
return all results that were found.
For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes.
If no callback is provided in non-blocking mode, a ValueError will be raised.
The results are provided as a list of discovered locations of device descriptor files.
Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an
example for a valid callback:
def browse_callback(results):
for result in results:
print("Location: {}".format(result))
:param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices
:param block: whether to block, defaults to True
:param callback: callback to call in non-blocking mode when lookup has finished, must be set if block is False
:param timeout: timeout in seconds to wait for replies to the M-SEARCH query per interface, defaults to 1
:param retries: number of retries to perform the lookup on all interfaces, defaults to 5
:return: if `block` is `True` a list of the discovered devices, an empty list otherwise (results will then be
supplied to the callback instead)
"""
import io
import threading
from http.client import HTTPResponse
class Response(HTTPResponse):
def __init__(self, response_text):
self.fp = io.BytesIO(response_text)
self.debuglevel = 0
self.strict = 0
self.msg = None
self._method = None
self.begin()
result = []
result_available = threading.Event()
result_available.clear()
def browse():
socket.setdefaulttimeout(timeout)
search_message = "".join(
[
"M-SEARCH * HTTP/1.1\r\n",
"ST: {query}\r\n",
"MX: 3\r\n",
'MAN: "ssdp:discovery"\r\n',
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n",
]
)
for _ in range(retries):
for addr in self.get_interface_addresses():
try:
sock = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP
)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.bind((addr, 0))
message = search_message.format(
query=query,
mcast_addr=self.__class__.ssdp_multicast_addr,
mcast_port=self.__class__.ssdp_multicast_port,
)
for _ in range(2):
sock.sendto(
message.encode("utf-8"),
(
self.__class__.ssdp_multicast_addr,
self.__class__.ssdp_multicast_port,
),
)
try:
data = sock.recv(1024)
except socket.timeout:
pass
else:
response = Response(data)
result.append(response.getheader("Location"))
except Exception:
pass
if callback:
callback(result)
result_available.set()
browse_thread = threading.Thread(target=browse)
browse_thread.daemon = True
browse_thread.start()
if block:
result_available.wait()
return result
else:
return []
##~~ internals
# Zeroconf
def _create_http_txt_record_dict(self):
"""
Creates a TXT record for the _http._tcp Zeroconf service supplied by this OctoPrint instance.
Defines the keys for _http._tcp as defined in http://www.dns-sd.org/txtrecords.html
:return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record
"""
# determine path entry
path = "/"
if self._settings.get(["pathPrefix"]):
path = self._settings.get(["pathPrefix"])
else:
prefix = self._settings.global_get(
["server", "reverseProxy", "prefixFallback"]
)
if prefix:
path = prefix
# fetch username and password (if set)
username = self._settings.get(["httpUsername"])
password = self._settings.get(["httpPassword"])
entries = {"path": path}
if username and password:
entries.update({"u": username, "p": password})
return entries
def _create_octoprint_txt_record_dict(self):
"""
Creates a TXT record for the _octoprint._tcp Zeroconf service supplied by this OctoPrint instance.
The following keys are defined:
* `path`: path prefix to actual OctoPrint instance, inherited from _http._tcp
* `u`: username if HTTP Basic Auth is used, optional, inherited from _http._tcp
* `p`: password if HTTP Basic Auth is used, optional, inherited from _http._tcp
* `version`: OctoPrint software version
* `api`: OctoPrint API version
* `model`: Model of the device that is running OctoPrint
* `vendor`: Vendor of the device that is running OctoPrint
:return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record
"""
import octoprint.server
import octoprint.server.api
entries = self._create_http_txt_record_dict()
entries.update(
version=octoprint.server.VERSION,
api=octoprint.server.api.VERSION,
uuid=self.get_uuid(),
)
modelName = self._settings.get(["model", "name"])
if modelName:
entries.update(model=modelName)
vendor = self._settings.get(["model", "vendor"])
if vendor:
entries.update(vendor=vendor)
return entries
# SSDP/UPNP
def _ssdp_register(self):
"""
Registers the OctoPrint instance as basic service with a presentation URL pointing to the web interface
"""
import threading
self._ssdp_monitor_active = True
self._ssdp_monitor_thread = threading.Thread(
target=self._ssdp_monitor, kwargs={"timeout": self._ssdp_notify_timeout}
)
self._ssdp_monitor_thread.daemon = True
self._ssdp_monitor_thread.start()
def _ssdp_unregister(self):
"""
Unregisters the OctoPrint instance again
"""
self._ssdp_monitor_active = False
if self.host and self.port:
for _ in range(2):
self._ssdp_notify(alive=False)
def _ssdp_notify(self, alive=True):
"""
Sends an SSDP notify message across the connected networks.
:param alive: True to send an "ssdp:alive" message, False to send an "ssdp:byebye" message
"""
if (
alive
and self._ssdp_last_notify + self._ssdp_notify_timeout > time.monotonic()
):
# we just sent an alive, no need to send another one now
return
if alive and not self._ssdp_monitor_active:
# the monitor already shut down, alive messages don't make sense anymore as byebye will shortly follow
return
for addr in self.get_interface_addresses():
try:
sock = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP
)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.bind((addr, 0))
location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format(
addr=addr, port=self.port
)
self._logger.debug(
"Sending NOTIFY {} via {}".format(
"alive" if alive else "byebye", addr
)
)
notify_message = "".join(
[
"NOTIFY * HTTP/1.1\r\n",
"Server: {server}\r\n",
"Cache-Control: max-age=900\r\n",
"Location: {location}\r\n",
"NTS: {nts}\r\n",
"NT: {nt}\r\n",
"USN: {usn}\r\n",
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n",
]
)
uuid = self.get_uuid()
for nt, usn in (
("upnp:rootdevice", "uuid:{uuid}::upnp:rootdevice"),
("uuid:{}", "uuid:{uuid}"),
(
"urn:schemas-upnp-org:device:basic:1",
"uuid:{uuid}::url:schemas-upnp-org:device:basic:1",
),
):
message = notify_message.format(
uuid=uuid,
location=location,
nts="ssdp:alive" if alive else "ssdp:byebye",
nt=nt.format(uuid=uuid),
usn=usn.format(uuid=uuid),
server=self.ssdp_server,
mcast_addr=self.ssdp_multicast_addr,
mcast_port=self.ssdp_multicast_port,
)
for _ in range(2):
# send twice, stuff might get lost, it's only UDP
sock.sendto(
message.encode("utf-8"),
(self.ssdp_multicast_addr, self.ssdp_multicast_port),
)
except Exception:
pass
self._ssdp_last_notify = time.monotonic()
def _ssdp_monitor(self, timeout=5):
"""
Monitor thread that listens on the multicast address for M-SEARCH requests and answers them if they are relevant
:param timeout: timeout after which to stop waiting for M-SEARCHs for a short while in order to put out an
alive message
"""
from http.server import BaseHTTPRequestHandler
from io import BytesIO
socket.setdefaulttimeout(timeout)
location_message = "".join(
[
"HTTP/1.1 200 OK\r\n",
"ST: upnp:rootdevice\r\n",
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
"Location: {location}\r\n",
"Cache-Control: max-age=60\r\n\r\n",
]
)
class Request(BaseHTTPRequestHandler):
# noinspection PyMissingConstructor
def __init__(self, request_text):
self.rfile = BytesIO(request_text)
self.raw_requestline = self.rfile.readline()
self.error_code = self.error_message = None
self.parse_request()
def send_error(self, code, message=None):
self.error_code = code
self.error_message = message
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.bind(("", self.__class__.ssdp_multicast_port))
for address in self.get_interface_addresses():
sock.setsockopt(
socket.IPPROTO_IP,
socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(self.__class__.ssdp_multicast_addr)
+ socket.inet_aton(address),
)
self._logger.info(f"Registered {self.get_instance_name()} for SSDP")
self._ssdp_notify(alive=True)
try:
while self._ssdp_monitor_active:
try:
data, address = sock.recvfrom(4096)
request = Request(data)
if (
not request.error_code
and request.command == "M-SEARCH"
and request.path == "*"
and (
request.headers["ST"] == "upnp:rootdevice"
or request.headers["ST"] == "ssdp:all"
)
and request.headers["MAN"] == '"ssdp:discover"'
):
interface_address = octoprint.util.address_for_client(
*address,
addresses=self._settings.get(["addresses"]),
interfaces=self._settings.get(["interfaces"]),
)
if not interface_address:
continue
message = location_message.format(
uuid=self.get_uuid(),
location="http://{host}:{port}/plugin/discovery/discovery.xml".format(
host=interface_address, port=self.port
),
)
sock.sendto(message.encode("utf-8"), address)
self._logger.debug(
"Sent M-SEARCH reply for {path} and {st} to {address!r}".format(
path=request.path,
st=request.headers["ST"],
address=address,
)
)
except socket.timeout:
pass
finally:
self._ssdp_notify(alive=True)
finally:
try:
sock.close()
except Exception:
pass
##~~ helpers
def get_uuid(self):
upnpUuid = self._settings.get(["upnpUuid"])
if upnpUuid is None:
import uuid
upnpUuid = str(uuid.uuid4())
self._settings.set(["upnpUuid"], upnpUuid)
self._settings.save()
return upnpUuid
def get_instance_name(self):
name = self._settings.global_get(["appearance", "name"])
if name:
return f'OctoPrint instance "{name}"'
else:
return f"OctoPrint instance on {socket.gethostname()}"
def get_interface_addresses(self):
addresses = self._settings.get(["addresses"])
if addresses:
return addresses
else:
return list(
octoprint.util.interface_addresses(
interfaces=self._settings.get(["interfaces"]),
ignored=self._settings.get(["ignoredInterfaces"]),
)
)
__plugin_name__ = "Discovery"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/discovery.html"
__plugin_description__ = (
"Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
)
__plugin_disabling_discouraged__ = gettext(
"Without this plugin your OctoPrint instance will no longer be "
"discoverable on the network via Bonjour and uPnP."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
| 29,507 | Python | .py | 661 | 30.963691 | 121 | 0.549991 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,953 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/gcodeviewer/__init__.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 os
import flask
from flask_babel import gettext
import octoprint.plugin
from octoprint.util.files import search_through_file
class GcodeviewerPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
):
def get_assets(self):
js = [
"js/gcodeviewer.js",
"js/viewer/ui.js",
"js/viewer/reader.js",
"js/viewer/renderer.js",
"js/lib/pako.js",
]
return {
"js": js,
"less": ["less/gcodeviewer.less"],
"css": ["css/gcodeviewer.css"],
}
def get_template_configs(self):
return [
{
"type": "tab",
"template": "gcodeviewer_tab.jinja2",
"div": "gcode",
"styles": ["display: none;"],
"data_bind": "visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)",
},
{
"type": "settings",
"name": gettext("GCode Viewer"),
"template": "gcodeviewer_settings.jinja2",
"custom_bindings": True,
},
{"type": "generic", "template": "gcodeviewer_initscript.jinja2"},
]
def get_settings_defaults(self):
return {
"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
"sizeThreshold": 20 * 1024 * 1024, # 20MB
"skipUntilThis": None,
"alwaysCompress": False,
"compressionSizeThreshold": 200 * 1024 * 1024,
}
def get_settings_version(self):
return 1
def on_settings_migrate(self, target, current):
if current is None:
config = self._settings.global_get(["gcodeViewer"])
if config:
self._logger.info(
"Migrating settings from gcodeViewer to plugins.gcodeviewer..."
)
if "mobileSizeThreshold" in config:
self._settings.set_int(
["mobileSizeThreshold"], config["mobileSizeThreshold"]
)
if "sizeThreshold" in config:
self._settings.set_int(["sizeThreshold"], config["sizeThreshold"])
self._settings.global_remove(["gcodeViewer"])
@octoprint.plugin.BlueprintPlugin.route(
"/skipuntilcheck/<string:origin>/<path:filename>", methods=["GET"]
)
def check_skip_until_presence(self, origin, filename):
try:
path = self._file_manager.path_on_disk(origin, filename)
except NotImplementedError:
# storage doesn't support path on disk
flask.abort(404)
if not os.path.exists(path):
# path doesn't exist
flask.abort(404)
skipUntilThis = self._settings.get(["skipUntilThis"])
if not skipUntilThis:
# no skipUntilThis, no need to search, shortcut
return flask.jsonify(present=False)
return flask.jsonify(present=search_through_file(path, skipUntilThis))
def is_blueprint_csrf_protected(self):
return True
__plugin_name__ = gettext("GCode Viewer")
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides a GCODE viewer in OctoPrint's UI."
__plugin_disabling_discouraged__ = gettext(
"Without this plugin the GCode Viewer in OctoPrint will no longer be " "available."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = GcodeviewerPlugin()
# __plugin_hooks__ = {
# "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
# }
| 3,953 | Python | .py | 98 | 30.44898 | 139 | 0.595933 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,954 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/appkeys/__init__.py | import os
import threading
import time
from collections import defaultdict
import flask
from flask_babel import gettext
import octoprint.plugin
from octoprint.access import ADMIN_GROUP, USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.server import NO_CONTENT, current_user
from octoprint.server.util import require_fresh_login_with
from octoprint.server.util.flask import (
add_non_caching_response_headers,
credentials_checked_recently,
ensure_credentials_checked_recently,
no_firstrun_access,
restricted_access,
)
from octoprint.settings import valid_boolean_trues
from octoprint.util import ResettableTimer, atomic_write, generate_api_key, yaml
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
class AppAlreadyExists(Exception):
pass
class PendingDecision:
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
self.created = time.monotonic()
if callable(timeout_callback):
self.poll_timeout = ResettableTimer(
POLL_TIMEOUT, timeout_callback, [user_token]
)
self.poll_timeout.start()
def external(self):
return {
"app_id": self.app_id,
"user_id": self.user_id,
"user_token": self.user_token,
}
def __repr__(self):
return "PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(
self.app_id, self.app_token, self.user_id, self.user_token
)
class ReadyDecision:
def __init__(self, app_id, app_token, user_id):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
@classmethod
def for_pending(cls, pending, user_id):
return cls(pending.app_id, pending.app_token, user_id)
def __repr__(self):
return "ReadyDecision({!r}, {!r}, {!r})".format(
self.app_id, self.app_token, self.user_id
)
class ActiveKey:
def __init__(self, app_id, api_key, user_id):
self.app_id = app_id
self.api_key = api_key
self.user_id = user_id
def external(self, incl_key=False):
result = {"app_id": self.app_id, "user_id": self.user_id}
if incl_key:
result["api_key"] = self.api_key
return result
def internal(self):
return {"app_id": self.app_id, "api_key": self.api_key}
@classmethod
def for_internal(cls, internal, user_id):
return cls(internal["app_id"], internal["api_key"], user_id)
def __repr__(self):
return "ActiveKey({!r}, {!r}, {!r})".format(
self.app_id, self.api_key, self.user_id
)
class AppKeysPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
):
def __init__(self):
self._pending_decisions = []
self._pending_lock = threading.RLock()
self._ready_decisions = []
self._ready_lock = threading.RLock()
self._keys = defaultdict(list)
self._keys_lock = threading.RLock()
self._key_path = None
def initialize(self):
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
self._load_keys()
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "ADMIN",
"name": "Admin access",
"description": gettext("Allows administrating all application keys"),
"roles": ["admin"],
"dangerous": True,
"default_groups": [ADMIN_GROUP],
},
{
"key": "GRANT",
"name": "Grant access",
"description": gettext("Allows to grant app access"),
"roles": ["user"],
"default_groups": [USER_GROUP],
},
]
##~~ TemplatePlugin
def get_template_configs(self):
return [
{"type": "usersettings", "name": gettext("Application Keys")},
{"type": "settings", "name": gettext("Application Keys")},
]
##~~ AssetPlugin
def get_assets(self):
return {
"js": ["js/appkeys.js"],
"clientjs": ["clientjs/appkeys.js"],
"less": ["less/appkeys.less"],
"css": ["css/appkeys.css"],
}
##~~ BlueprintPlugin mixin
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
@no_firstrun_access
def handle_probe(self):
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
@octoprint.plugin.BlueprintPlugin.csrf_exempt()
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if data is None:
flask.abort(400, description="Missing key request")
if "app" not in data:
flask.abort(400, description="No app name provided")
app_name = data["app"]
user_id = None
if "user" in data and data["user"]:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
auth_dialog = flask.url_for(
"plugin.appkeys.handle_auth_dialog", app_token=app_token, _external=True
) + (f"?user={user_id}" if user_id else "")
self._plugin_manager.send_plugin_message(
self._identifier,
{
"type": "request_access",
"app_name": app_name,
"user_token": user_token,
"user_id": user_id,
},
)
response = flask.jsonify(app_token=app_token, auth_dialog=auth_dialog)
response.status_code = 201
response.headers["Location"] = flask.url_for(
".handle_decision_poll", app_token=app_token, _external=True
)
return response
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>", methods=["GET"])
@no_firstrun_access
def handle_decision_poll(self, app_token):
result = self._get_pending_by_app_token(app_token)
if result:
for pending_decision in result:
pending_decision.poll_timeout.reset()
response = flask.jsonify(message="Awaiting decision")
response.status_code = 202
return response
result = self._get_decision(app_token)
if result:
return flask.jsonify(api_key=result)
return flask.abort(404)
@octoprint.plugin.BlueprintPlugin.route("/auth/<app_token>", methods=["GET"])
@no_firstrun_access
def handle_auth_dialog(self, app_token):
from octoprint.server.util.csrf import add_csrf_cookie
user_id = current_user.get_name()
required_user = flask.request.args.get("user", None)
pendings = self._get_pending_by_app_token(app_token)
if not pendings:
return flask.abort(404)
response = require_fresh_login_with(
permissions=[Permissions.PLUGIN_APPKEYS_GRANT], user_id=required_user
)
if response:
return response
pending = None
for p in pendings:
if p.user_id == required_user or (not required_user and p.user_id == user_id):
pending = p
break
else:
return flask.abort(404)
app_id = pending.app_id
user_token = pending.user_token
redirect_url = flask.request.args.get("redirect", "")
response = flask.make_response(
flask.render_template(
"plugin_appkeys/appkeys_authdialog.jinja2",
app=app_id,
user=user_id,
user_token=user_token,
redirect_url=redirect_url,
theming=[],
request_text=gettext(
'"<strong>%(app)s</strong>" has requested access to control OctoPrint through the API.'
).replace("%(app)s", app_id),
)
)
return add_csrf_cookie(add_non_caching_response_headers(response))
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if "decision" not in data:
flask.abort(400, description="No decision provided")
if not Permissions.PLUGIN_APPKEYS_GRANT.can():
flask.abort(403, description="No permission to grant app access")
ensure_credentials_checked_recently()
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
result = self._set_decision(user_token, decision, user_id)
if not result:
return flask.abort(404)
# Close access_request dialog for this request on all open OctoPrint connections
self._plugin_manager.send_plugin_message(
self._identifier, {"type": "end_request", "user_token": user_token}
)
return NO_CONTENT
def is_blueprint_protected(self):
return False # No API key required to request API access
def is_blueprint_csrf_protected(self):
return True # protect anything that isn't explicitly marked as exempt
##~~ SimpleApiPlugin mixin
def get_api_commands(self):
return {"generate": ["app"], "revoke": []}
def on_api_get(self, request):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
# GET ?app_id=...[&user_id=...]
if request.values.get("app"):
app_id = request.values.get("app")
user_id = request.values.get("user", user_id)
if (
user_id != current_user.get_name()
and not Permissions.PLUGIN_APPKEYS_ADMIN.can()
):
return flask.abort(403)
key = self._api_key_for_user_and_app_id(user_id, app_id)
if not key:
return flask.abort(404)
return flask.jsonify(
key=key.external(incl_key=credentials_checked_recently())
)
# GET ?all=true (admin only)
if (
request.values.get("all") in valid_boolean_trues
and Permissions.PLUGIN_APPKEYS_ADMIN.can()
):
keys = self._all_api_keys()
else:
keys = self._api_keys_for_user(user_id)
return flask.jsonify(
keys=list(
map(lambda x: x.external(), keys),
),
pending={
x.user_token: x.external() for x in self._get_pending_by_user_id(user_id)
},
)
def on_api_command(self, command, data):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if command == "revoke":
api_key = data.get("key")
if api_key:
# deprecated key based revoke?
from flask import request
self._logger.warning(
f"Deprecated key based revoke command sent to /api/plugin/appkeys by {request.remote_addr}, should be migrated to use app id/user tuple"
)
else:
# newer app/user based revoke?
user = data.get("user", user_id)
app = data.get("app")
if not app:
return flask.abort(400, description="Need either app or key")
api_key = self._api_key_for_user_and_app_id(user, app)
if not api_key:
return flask.abort(400, description="Need either app or key")
if not Permissions.PLUGIN_APPKEYS_ADMIN.can():
user_for_key = self._user_for_api_key(api_key)
if user_for_key is None or user_for_key.get_id() != user_id:
return flask.abort(403)
ensure_credentials_checked_recently()
self._delete_api_key(api_key)
elif command == "generate":
# manual generateKey
app_name = data.get("app")
if not app_name:
return flask.abort(400)
selected_user_id = data.get("user", user_id)
if selected_user_id != user_id and not Permissions.PLUGIN_APPKEYS_ADMIN.can():
return flask.abort(403)
ensure_credentials_checked_recently()
key = self._add_api_key(selected_user_id, app_name.strip())
return flask.jsonify(user_id=selected_user_id, app_id=app_name, api_key=key)
return NO_CONTENT
##~~ key validator hook
def validate_api_key(self, api_key, *args, **kwargs):
return self._user_for_api_key(api_key)
##~~ Helpers
def _add_pending_decision(self, app_name, user_id=None):
app_token = self._generate_key()
user_token = self._generate_key()
with self._pending_lock:
self._remove_stale_pending()
self._pending_decisions.append(
PendingDecision(
app_name,
app_token,
user_id,
user_token,
timeout_callback=self._expire_pending,
)
)
return app_token, user_token
def _get_pending_by_app_token(self, app_token):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.app_token == app_token:
result.append(data)
return result
def _get_pending_by_user_id(self, user_id):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_id == user_id or data.user_id is None:
result.append(data)
return result
def _expire_pending(self, user_token):
with self._pending_lock:
len_before = len(self._pending_decisions)
self._pending_decisions = list(
filter(lambda x: x.user_token != user_token, self._pending_decisions)
)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._plugin_manager.send_plugin_message(
self._identifier, {"type": "end_request", "user_token": user_token}
)
def _remove_stale_pending(self):
with self._pending_lock:
cutoff = time.monotonic() - CUTOFF_TIME
len_before = len(self._pending_decisions)
self._pending_decisions = list(
filter(lambda x: x.created >= cutoff, self._pending_decisions)
)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._logger.info(
"Deleted {} stale pending authorization requests".format(
len_before - len_after
)
)
def _set_decision(self, user_token, decision, user_id):
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_token == user_token and (
data.user_id == user_id or data.user_id is None
):
pending = data
break
else:
return False # not found
if decision:
with self._ready_lock:
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
with self._pending_lock:
self._pending_decisions = list(
filter(lambda x: x.user_token != user_token, self._pending_decisions)
)
return True
def _get_decision(self, app_token):
self._remove_stale_pending()
with self._ready_lock:
for data in self._ready_decisions:
if data.app_token == app_token:
decision = data
break
else:
return False # not found
api_key = self._add_api_key(decision.user_id, decision.app_id)
with self._ready_lock:
self._ready_decisions = list(
filter(lambda x: x.app_token != app_token, self._ready_decisions)
)
return api_key
def _add_api_key(self, user_id, app_name):
with self._keys_lock:
for key in self._keys[user_id]:
if key.app_id.lower() == app_name.lower():
return key.api_key
key = ActiveKey(app_name, self._generate_key(), user_id)
self._keys[user_id].append(key)
self._save_keys()
return key.api_key
def _delete_api_key(self, api_key):
if isinstance(api_key, ActiveKey):
api_key = api_key.api_key
with self._keys_lock:
for user_id, data in self._keys.items():
self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data))
self._save_keys()
def _user_for_api_key(self, api_key):
if isinstance(api_key, ActiveKey):
api_key = api_key.api_key
with self._keys_lock:
for user_id, data in self._keys.items():
if any(filter(lambda x: x.api_key == api_key, data)):
return self._user_manager.find_user(userid=user_id)
return None
def _api_keys_for_user(self, user_id):
with self._keys_lock:
return self._keys[user_id]
def _all_api_keys(self):
with self._keys_lock:
result = []
for keys in self._keys.values():
result += keys
return result
def _api_key_for_user_and_app_id(self, user_id, app_id):
with self._keys_lock:
if user_id not in self._keys:
return None
for key in self._keys[user_id]:
if key.app_id.lower() == app_id.lower():
return key
return None
def _generate_key(self):
return generate_api_key()
def _load_keys(self):
with self._keys_lock:
if not os.path.exists(self._key_path):
return
try:
persisted = yaml.load_from_file(path=self._key_path)
except Exception:
self._logger.exception(
f"Could not load application keys from {self._key_path}"
)
return
if not isinstance(persisted, dict):
return
keys = defaultdict(list)
for user_id, persisted_keys in persisted.items():
keys[user_id] = [
ActiveKey.for_internal(x, user_id) for x in persisted_keys
]
self._keys = keys
def _save_keys(self):
with self._keys_lock:
to_persist = {}
for user_id, keys in self._keys.items():
to_persist[user_id] = [x.internal() for x in keys]
try:
with atomic_write(self._key_path, mode="wt") as f:
yaml.save_to_file(to_persist, file=f)
except Exception:
self._logger.exception(
f"Could not write application keys to {self._key_path}"
)
__plugin_name__ = "Application Keys Plugin"
__plugin_description__ = (
"Implements a workflow for third party clients to obtain API keys"
)
__plugin_author__ = "Gina Häußge, Aldo Hoeben"
__plugin_disabling_discouraged__ = gettext(
"Without this plugin third party clients will no longer be able to "
"obtain an API key without you manually copy-pasting it."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = AppKeysPlugin()
__plugin_hooks__ = {
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
| 20,416 | Python | .py | 500 | 29.702 | 156 | 0.568289 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,955 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/errortracking/__init__.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 errno
import logging
import requests.exceptions
import serial
import tornado.websocket
from flask import jsonify
from flask_babel import gettext
import octoprint.plugin
from octoprint.util import get_fully_qualified_classname as fqcn # noqa: F401
from octoprint.util.version import (
get_octoprint_version_string,
is_released_octoprint_version,
)
SENTRY_URL_SERVER = (
"https://fc0e29027267843275a25ccb977fd622@o118517.ingest.us.sentry.io/1373987"
)
SENTRY_URL_COREUI = (
"https://abc2a1365195f4eac742746eff1236de@o118517.ingest.us.sentry.io/1374096"
)
SETTINGS_DEFAULTS = {
"enabled": False,
"enabled_unreleased": False,
"unique_id": None,
"url_server": SENTRY_URL_SERVER,
"url_coreui": SENTRY_URL_COREUI,
}
IGNORED_EXCEPTIONS = [
# serial exceptions in octoprint.util.comm
(
serial.SerialException,
lambda exc, logger, plugin, cb: logger == "octoprint.util.comm",
),
# KeyboardInterrupts
KeyboardInterrupt,
# IOErrors of any kind due to a full file system
(
IOError,
lambda exc, logger, plugin, cb: exc.errorgetattr(exc, "errno") # noqa: B009
and exc.errno in (getattr(errno, "ENOSPC"),), # noqa: B009
),
# RequestExceptions of any kind
requests.exceptions.RequestException,
# Tornado WebSocketErrors of any kind
tornado.websocket.WebSocketError,
# Anything triggered by or in third party plugin Astroprint
(
Exception,
lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint")
or plugin == "astroprint"
or cb.startswith("octoprint_astroprint."),
),
]
try:
# noinspection PyUnresolvedReferences
from octoprint.plugins.backup import InsufficientSpace
# if the backup plugin is enabled, ignore InsufficientSpace errors from it as well
IGNORED_EXCEPTIONS.append(InsufficientSpace)
del InsufficientSpace
except ImportError:
pass
class ErrorTrackingPlugin(
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SimpleApiPlugin,
):
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Error Tracking"),
"template": "errortracking_settings.jinja2",
"custom_bindings": False,
},
{"type": "generic", "template": "errortracking_javascripts.jinja2"},
]
def get_template_vars(self):
enabled = self._settings.get_boolean(["enabled"])
enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"])
return {
"enabled": _is_enabled(enabled, enabled_unreleased),
"unique_id": self._settings.get(["unique_id"]),
"url_coreui": self._settings.get(["url_coreui"]),
}
def get_assets(self):
return {"js": ["js/sentry.min.js", "js/errortracking.js"]}
def get_settings_defaults(self):
return SETTINGS_DEFAULTS
def on_settings_save(self, data):
old_enabled = _is_enabled(
self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]),
)
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
enabled = _is_enabled(
self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]),
)
if old_enabled != enabled:
_enable_errortracking()
def on_api_get(self, request):
return jsonify(**self.get_template_vars())
_enabled = False
def _enable_errortracking():
# this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible
# and hence can't wait until our implementation is initialized and injected with settings
from octoprint.settings import settings
global _enabled
if _enabled:
return
version = get_octoprint_version_string()
s = settings()
plugin_defaults = {"plugins": {"errortracking": SETTINGS_DEFAULTS}}
enabled = s.getBoolean(
["plugins", "errortracking", "enabled"], defaults=plugin_defaults
)
enabled_unreleased = s.getBoolean(
["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults
)
url_server = s.get(
["plugins", "errortracking", "url_server"], defaults=plugin_defaults
)
unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults)
if unique_id is None:
import uuid
unique_id = str(uuid.uuid4())
s.set(
["plugins", "errortracking", "unique_id"],
unique_id,
defaults=plugin_defaults,
)
s.save()
if _is_enabled(enabled, enabled_unreleased):
import sentry_sdk
from octoprint.plugin import plugin_manager
def _before_send(event, hint):
if "exc_info" not in hint:
# we only want exceptions
return None
handled = True
logger = event.get("logger", "")
plugin = event.get("extra", {}).get("plugin", None)
callback = event.get("extra", {}).get("callback", None)
for ignore in IGNORED_EXCEPTIONS:
if isinstance(ignore, tuple):
ignored_exc, matcher = ignore
else:
ignored_exc = ignore
matcher = lambda *args: True
exc = hint["exc_info"][1]
if isinstance(exc, ignored_exc) and matcher(
exc, logger, plugin, callback
):
# exception ignored for logger, plugin and/or callback
return None
elif isinstance(ignore, type):
if isinstance(hint["exc_info"][1], ignore):
# exception ignored
return None
if event.get("exception") and event["exception"].get("values"):
handled = not any(
map(
lambda x: x.get("mechanism")
and not x["mechanism"].get("handled", True),
event["exception"]["values"],
)
)
if handled:
# error is handled, restrict further based on logger
if logger != "" and not (
logger.startswith("octoprint.") or logger.startswith("tornado.")
):
# we only want errors logged by loggers octoprint.* or tornado.*
return None
if logger.startswith("octoprint.plugins."):
plugin_id = logger.split(".")[2]
plugin_info = plugin_manager().get_plugin_info(plugin_id)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
if plugin is not None:
plugin_info = plugin_manager().get_plugin_info(plugin)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
return event
sentry_sdk.init(url_server, release=version, before_send=_before_send)
with sentry_sdk.configure_scope() as scope:
scope.user = {"id": unique_id}
logging.getLogger("octoprint.plugins.errortracking").info(
"Initialized error tracking"
)
_enabled = True
def _is_enabled(enabled, enabled_unreleased):
return enabled and (enabled_unreleased or is_released_octoprint_version())
def __plugin_enable__():
_enable_errortracking()
__plugin_name__ = "Error Tracking"
__plugin_author__ = "Gina Häußge"
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = ErrorTrackingPlugin()
| 8,300 | Python | .py | 204 | 30.970588 | 112 | 0.610918 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,956 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/achievements/__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) 2023 The OctoPrint Project - Released under terms of the AGPLv3 License"
import datetime
import json
import os
import threading
from typing import List
from flask import abort, jsonify
from flask_babel import gettext
from pydantic import BaseModel
import octoprint.plugin
import octoprint.util
from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
from octoprint.util.version import get_octoprint_version
from .achievements import Achievement, Achievements
from .data import Data, State, Stats, YearlyStats
class ApiAchievement(Achievement):
logo: str = ""
achieved: int = 0
class ApiTimezoneInfo(BaseModel):
name: str
offset: int
class ApiResponse(BaseModel):
stats: Stats
achievements: List[ApiAchievement]
hidden_achievements: int
current_year: YearlyStats
available_years: List[int]
timezone: ApiTimezoneInfo
class AchievementsPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin,
):
def __init__(self):
super().__init__()
self._data = None
self._data_mutex = threading.Lock()
self._year_data = None
self._year_data_mutex = threading.Lock()
self._get_throttled = lambda: False
self._pause_counter = 0 # not persisted, as it depends on the current print
self._tz = None
def initialize(self):
self._load_data_file()
self._load_current_year_file()
return super().initialize()
def _server_timezone(self):
return (
datetime.datetime.utcnow().astimezone()
) # utcnow still needed while supporting Python 3.7
def _now(self):
if self._tz is None:
import pytz
timezone = self._settings.get(["timezone"])
if timezone:
try:
self._tz = pytz.timezone(timezone)
except Exception:
self._logger.exception(
f"Cannot load timezone {timezone}, falling back to server timezone"
)
return datetime.datetime.now(tz=self._tz)
##~~ Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "VIEW",
"name": "View instance achievements & stats",
"description": gettext(
"Allows to view the instance achievements & stats."
),
"default_groups": [READONLY_GROUP, USER_GROUP, ADMIN_GROUP],
"roles": ["view"],
},
{
"key": "RESET",
"name": "Reset instance achievements & stats",
"description": gettext(
"Allows to reset the instance achievements & stats."
),
"default_groups": [ADMIN_GROUP],
"roles": ["reset"],
},
]
##~~ socket emit hook
def socket_emit_hook(self, socket, user, message, payload, *args, **kwargs):
if (
message != "event"
or payload["type"] != Events.PLUGIN_ACHIEVEMENTS_ACHIEVEMENT_UNLOCKED
):
return True
return user and user.has_permission(Permissions.PLUGIN_ACHIEVEMENTS_VIEW)
##~~ Firmware info hook
def firmware_info_hook(
self, comm_instance, firmware_name, firmware_data, *args, **kwargs
):
if "klipper" in firmware_name.lower():
self._trigger_achievement(Achievements.CROSSOVER_EPISODE)
##~~ StartupPlugin
def on_startup(self, *args, **kwargs):
self._data.stats.server_starts += 1
self._year_data.server_starts += 1
version = get_octoprint_version()
if self._data.stats.last_version != version.base_version:
self._data.stats.seen_versions += 1
self._data.stats.last_version = version.base_version
if self._year_data.last_version != version.base_version:
self._year_data.seen_versions += 1
self._year_data.last_version = version.base_version
self._recheck_plugin_count()
if not self._has_achievement(
Achievements.THE_WIZARD
) and not self._settings.get_boolean(["server", "firstRun"]):
self._trigger_achievement(Achievements.THE_WIZARD, write=False)
self._write_data_file()
self._write_current_year_file()
def on_after_startup(self):
helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if helpers and "get_throttled" in helpers:
self._get_throttled = helpers["get_throttled"]
return super().on_after_startup()
##~~ EventHandlerPlugin
def on_event(self, event, payload, *args, **kwargs):
changed = False
yearly_changed = False
now = self._now()
if event == Events.PRINT_STARTED:
self._pause_counter = 0
self._data.stats.prints_started += 1
self._year_data.prints_started += 1
## specific dates
if now.month == 3 and now.day == 21:
self._trigger_achievement(Achievements.HAPPY_BIRTHDAY_FOOSEL, write=False)
elif now.month == 10 and now.day == 31:
self._trigger_achievement(Achievements.SPOOKY, write=False)
elif now.month == 12 and now.day >= 1 and now.day <= 24:
self._trigger_achievement(Achievements.SANTAS_LITTLE_HELPER, write=False)
elif now.month == 12 and now.day == 25:
self._trigger_achievement(
Achievements.HAPPY_BIRTHDAY_OCTOPRINT, write=False
)
## specific times
if 23 <= now.hour or now.hour < 3:
self._trigger_achievement(Achievements.NIGHT_OWL, write=False)
elif 3 <= now.hour < 7:
self._trigger_achievement(Achievements.EARLY_BIRD, write=False)
## specific weekdays
if now.weekday() == 4: # friday
self._trigger_achievement(Achievements.TGIF, write=False)
if now.weekday() >= 5: # weekend
if self._data.state.date_last_weekend_print:
last_weekend_print = datetime.date.fromisoformat(
self._data.state.date_last_weekend_print
)
last_saturday = now.date() - datetime.timedelta(
days=now.weekday() + 2
)
last_sunday = last_saturday + datetime.timedelta(days=1)
if last_saturday <= last_weekend_print <= last_sunday:
self._data.state.consecutive_weekend_prints += 1
if self._data.state.consecutive_weekend_prints == 4:
self._trigger_achievement(
Achievements.WEEKEND_WARRIOR, write=False
)
self._data.state.date_last_weekend_print = now.date().isoformat()
self._data.stats.prints_started_per_weekday[now.weekday()] = (
self._data.stats.prints_started_per_weekday.get(now.weekday(), 0) + 1
)
self._year_data.prints_started_per_weekday[now.weekday()] = (
self._year_data.prints_started_per_weekday.get(now.weekday(), 0) + 1
)
## other conditions
throttled = self._get_throttled()
if throttled and throttled.get("current_undervoltage"):
self._trigger_achievement(
Achievements.WHAT_COULD_POSSIBLY_GO_WRONG, write=False
)
changed = True
yearly_changed = True
elif event == Events.PRINT_DONE:
self._data.stats.prints_finished += 1
self._data.stats.print_duration_total += payload["time"]
self._data.stats.print_duration_finished += payload["time"]
self._year_data.prints_finished += 1
self._year_data.print_duration_total += payload["time"]
self._year_data.print_duration_finished += payload["time"]
self._data.state.consecutive_prints_cancelled_today = 0
if payload["time"] > self._data.stats.longest_print_duration:
self._data.stats.longest_print_duration = payload["time"]
self._data.stats.longest_print_date = self._now().timestamp()
if payload["time"] > self._year_data.longest_print_duration:
self._year_data.longest_print_duration = payload["time"]
self._year_data.longest_print_date = self._now().timestamp()
self._trigger_achievement(Achievements.ONE_SMALL_STEP_FOR_MAN, write=False)
## print count
if self._data.stats.prints_finished >= 1000:
self._trigger_achievement(Achievements.THE_MANUFACTURER_III)
elif self._data.stats.prints_finished >= 100:
self._trigger_achievement(Achievements.THE_MANUFACTURER_II)
elif self._data.stats.prints_finished >= 10:
self._trigger_achievement(Achievements.THE_MANUFACTURER_I)
## print duration
if payload["time"] > 24 * 60 * 60:
self._trigger_achievement(Achievements.MARATHON, write=False)
if payload["time"] > 12 * 60 * 60:
self._trigger_achievement(Achievements.HALF_MARATHON, write=False)
if payload["time"] < 10 * 60:
self._trigger_achievement(Achievements.SPRINT, write=False)
## prints per day
if now.date().isoformat() != self._data.state.date_last_print:
self._data.state.date_last_print = now.date().isoformat()
self._data.state.prints_today = 0
self._data.state.prints_today += 1
if self._data.state.prints_today >= 10:
self._trigger_achievement(Achievements.CANT_GET_ENOUGH, write=False)
## consecutive prints of same file
lastmodified = self._file_manager.get_lastmodified(
payload.get("origin"), payload.get("path")
)
loc = f"{payload['origin']}:{payload['path']}:{lastmodified}"
if loc == self._data.state.file_last_print:
self._data.state.consecutive_prints_of_same_file += 1
if self._data.state.consecutive_prints_of_same_file >= 5:
self._trigger_achievement(Achievements.MASS_PRODUCTION, write=False)
else:
self._data.state.consecutive_prints_of_same_file = 1
self._data.state.file_last_print = loc
## total finished print duration
if self._data.stats.print_duration_finished >= 404 * 60 * 60:
self._trigger_achievement(Achievements.ACHIEVEMENT_NOT_FOUND)
changed = True
yearly_changed = True
elif event == Events.PRINT_FAILED or event == Events.PRINT_CANCELLED:
self._data.stats.print_duration_total += payload["time"]
self._year_data.print_duration_total += payload["time"]
if Events.PRINT_CANCELLED:
self._trigger_achievement(
Achievements.ALL_BEGINNINGS_ARE_HARD, write=False
)
if payload["progress"] > 95:
self._trigger_achievement(Achievements.SO_CLOSE, write=False)
## cancelled per day
if now.date().isoformat() != self._data.state.date_last_cancelled_print:
self._data.state.date_last_cancelled_print = now.date().isoformat()
self._data.state.prints_cancelled_today = 0
self._data.state.prints_cancelled_today += 1
self._data.state.consecutive_prints_cancelled_today += 1
if self._data.state.consecutive_prints_cancelled_today >= 10:
self._trigger_achievement(Achievements.ONE_OF_THOSE_DAYS, write=False)
changed = True
yearly_changed = True
elif event == Events.PRINT_PAUSED:
self._pause_counter += 1
if self._pause_counter >= 10:
self._trigger_achievement(Achievements.HANG_IN_THERE, write=False)
elif event == Events.FILE_ADDED:
if payload.get("operation") == "add":
self._data.stats.files_uploaded += 1
self._year_data.files_uploaded += 1
if self._data.stats.files_uploaded >= 1000:
self._trigger_achievement(Achievements.THE_COLLECTOR_III)
elif self._data.stats.files_uploaded >= 500:
self._trigger_achievement(Achievements.THE_COLLECTOR_II)
elif self._data.stats.files_uploaded >= 100:
self._trigger_achievement(Achievements.THE_COLLECTOR_I)
size = self._file_manager.get_size(
payload.get("storage"), payload.get("path")
)
if size > 500 * 1024 * 1024:
self._trigger_achievement(Achievements.HEAVY_CHONKER)
changed = yearly_changed = True
elif event == Events.FILE_REMOVED:
if payload.get("operation") == "remove":
self._data.stats.files_deleted += 1
self._year_data.files_deleted += 1
if self._data.stats.files_deleted >= 1000:
self._trigger_achievement(Achievements.CLEAN_HOUSE_III)
elif self._data.stats.files_deleted >= 500:
self._trigger_achievement(Achievements.CLEAN_HOUSE_II)
elif self._data.stats.files_deleted >= 100:
self._trigger_achievement(Achievements.CLEAN_HOUSE_I)
changed = yearly_changed = True
elif event == Events.FOLDER_ADDED:
self._trigger_achievement(Achievements.THE_ORGANIZER)
elif (
hasattr(Events, "PLUGIN_BACKUP_BACKUP_CREATED")
and event == Events.PLUGIN_BACKUP_BACKUP_CREATED
):
self._trigger_achievement(Achievements.BETTER_SAFE_THAN_SORRY)
elif (
hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN")
and event == Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN
):
if payload.get("from_repo"):
self._trigger_achievement(Achievements.ADVENTURER)
else:
self._trigger_achievement(Achievements.TINKERER)
self._data.stats.plugins_installed += 1
self._year_data.plugins_installed += 1
self._recheck_plugin_count()
changed = yearly_changed = True
elif (
hasattr(Events, "PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN")
and event == Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN
):
self._data.stats.plugins_uninstalled += 1
self._year_data.plugins_uninstalled += 1
changed = yearly_changed = True
if changed:
self._write_data_file()
if yearly_changed:
self._write_current_year_file()
##~~ BlueprintPlugin
def is_blueprint_csrf_protected(self):
return True
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@Permissions.PLUGIN_ACHIEVEMENTS_VIEW.require(403)
def get_data(self):
self._now() # make sure self._tz is set, if we have a timezone
achievements = [
ApiAchievement(
achieved=self._data.achievements.get(a.key, 0),
logo=a.icon,
**a.dict(),
)
for a in Achievements.all()
if not a.hidden or self._has_achievement(a)
]
achievements.sort(key=lambda a: a.name)
if self._tz:
timezone_name = self._tz.zone
timezone_offset = (
self._tz.utcoffset(datetime.datetime.now()).total_seconds() // 60
)
else:
server_timezone = self._server_timezone()
timezone_name = server_timezone.tzname()
timezone_offset = server_timezone.utcoffset().total_seconds() // 60
response = ApiResponse(
stats=self._data.stats,
achievements=achievements,
hidden_achievements=len(
[
achievement
for achievement in Achievements.all()
if achievement.hidden and not self._has_achievement(achievement)
]
),
current_year=self._year_data,
available_years=self._available_years(),
timezone=ApiTimezoneInfo(
name=timezone_name,
offset=timezone_offset,
),
)
return jsonify(response.dict())
@octoprint.plugin.BlueprintPlugin.route("/year/<int:year>", methods=["GET"])
@Permissions.PLUGIN_ACHIEVEMENTS_VIEW.require(403)
def get_year_data(self, year):
year_data = self._load_year_file(year=year)
if year_data is None:
if year == self._now().year:
year_data = self._year_data
else:
abort(404)
return jsonify(year_data.dict())
@octoprint.plugin.BlueprintPlugin.route("/reset/achievements", methods=["POST"])
@Permissions.PLUGIN_ACHIEVEMENTS_RESET.require(403)
def reset_achievements(self):
from flask import request
from octoprint.server import NO_CONTENT
data = request.json
if "achievements" not in data or not isinstance(data["achievements"], list):
abort(400, "Need list of achievements to reset")
self._reset_achievements(*data["achievements"])
return NO_CONTENT
##~~ AssetPlugin
def get_assets(self):
return {
"clientjs": ["clientjs/achievements.js"],
"js": ["js/achievements.js"],
"less": ["less/achievements.less"],
"css": ["css/achievements.css"],
}
##~~ SettingsPlugin
def get_settings_defaults(self):
return {
"timezone": "",
}
def on_settings_save(self, data):
super().on_settings_save(data)
if "timezone" in data:
self._tz = None
##~~ TemplatePlugin
def get_template_configs(self):
return [
{
"type": "about",
"name": gettext("Achievements"),
"template": "achievements_about_achievements.jinja2",
"custom_bindings": True,
},
{
"type": "about",
"name": gettext("Instance Stats"),
"template": "achievements_about_stats.jinja2",
"custom_bindings": True,
},
{
"type": "settings",
"name": gettext("Achievements"),
"template": "achievements_settings.jinja2",
"custom_bindings": True,
},
]
def get_template_vars(self):
import pytz
server_timezone = self._server_timezone()
return {
"svgs": self._generate_svg(),
"timezones": pytz.common_timezones,
"server_timezone": server_timezone.tzname(),
}
##~~ External helpers
def get_unlocked_achievements(self):
return list(
filter(
lambda x: x is not None,
[Achievements.get(key) for key in self._data.achievements.keys()],
)
)
##~~ Internal helpers
def _recheck_plugin_count(self):
changed = yearly_changed = False
if len(self._plugin_manager.plugins) > self._data.stats.most_plugins:
self._data.stats.most_plugins = len(self._plugin_manager.plugins)
if len(self._plugin_manager.plugins) > self._year_data.most_plugins:
self._year_data.most_plugins = len(self._plugin_manager.plugins)
return changed, yearly_changed
def _has_achievement(self, achievement):
return achievement.key in self._data.achievements
def _trigger_achievement(self, achievement, write=True):
if self._has_achievement(achievement):
return
self._data.achievements[achievement.key] = int(self._now().timestamp())
if write:
self._write_data_file()
self._year_data.achievements += 1
self._write_current_year_file()
self._logger.info(f"New achievement unlocked: {achievement.name}!")
payload = achievement.dict()
payload["type"] = "achievement"
payload["logo"] = achievement.icon
self._event_bus.fire(Events.PLUGIN_ACHIEVEMENTS_ACHIEVEMENT_UNLOCKED, payload)
def _reset_achievements(self, *achievements, write=True):
for achievement in achievements:
if not Achievements.get(achievement):
self._logger.error(f"Unknown achievement {achievement}")
continue
self._data.achievements.pop(achievement, None)
if write:
self._write_data_file()
def _generate_svg(self):
import os
from xml.dom.minidom import parse
svg = """
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display: none;">
<defs>
"""
for entry in os.scandir(os.path.join(os.path.dirname(__file__), "static", "img")):
if not entry.is_file() or not entry.name.endswith(".svg"):
continue
try:
dom = parse(entry.path)
paths = dom.getElementsByTagName("path")
if len(paths):
svg += (
f"<g id='achievement-logo-{entry.name[:-4]}'>"
+ "".join([path.toxml() for path in paths])
+ "</g>"
)
except Exception:
continue
svg += """
</defs>
</svg>
"""
return svg
@property
def _data_path(self):
return os.path.join(self.get_plugin_data_folder(), "data.json")
def _year_path(self, year=None):
if year is None:
year = self._now().year
return os.path.join(self.get_plugin_data_folder(), f"{year}.json")
def _available_years(self):
years = []
for entry in os.scandir(self.get_plugin_data_folder()):
if not entry.is_file() or not entry.name.endswith(".json"):
continue
try:
years.append(int(entry.name[:-5]))
except Exception:
# not a year file
continue
if not years:
years.append(self._now().year)
return years
def _reset_data(self):
self._data = Data(
stats=Stats(
created=self._now().timestamp(),
created_version=get_octoprint_version().base_version,
),
achievements={},
state=State(),
)
def _load_data_file(self):
path = self._data_path
with self._data_mutex:
if not os.path.exists(path):
self._logger.info("No data file found, starting with empty data")
self._reset_data()
return
try:
with open(path) as f:
self._logger.info(f"Loading data from {path}")
data = json.load(f)
self._data = Data(**data)
except Exception as e:
self._logger.exception(f"Error loading data from {path}: {e}")
self._logger.error("Starting with empty data")
self._reset_data()
def _write_data_file(self):
with self._data_mutex:
self._logger.debug(f"Writing data to {self._data_path}")
with octoprint.util.atomic_write(self._data_path, mode="wb") as f:
f.write(
octoprint.util.to_bytes(
json.dumps(self._data.dict(), indent=2, separators=(",", ": "))
)
)
def _reset_current_year_data(self):
self._year_data = YearlyStats()
def _load_current_year_file(self):
with self._year_data_mutex:
self._year_data = self._load_year_file()
if self._year_data is None:
self._logger.info(
"No data file for the current year found, starting with empty data"
)
self._reset_current_year_data()
def _write_current_year_file(self):
with self._year_data_mutex:
path = self._year_path()
self._logger.debug(f"Writing data to {path}")
with octoprint.util.atomic_write(path, mode="wb") as f:
f.write(
octoprint.util.to_bytes(
json.dumps(
self._year_data.dict(), indent=2, separators=(",", ": ")
)
)
)
def _load_year_file(self, year=None):
path = self._year_path(year=year)
if not os.path.exists(path):
return None
try:
with open(path) as f:
self._logger.info(f"Loading data for {year} from {path}")
data = json.load(f)
return YearlyStats(**data)
except Exception as e:
self._logger.exception(f"Error loading data for year {year} from {path}: {e}")
return None
def _register_custom_events(*args, **kwargs):
return ["achievement_unlocked"]
__plugin_name__ = "Achievements Plugin"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Achievements & stats about your OctoPrint instance"
__plugin_disabling_discouraged__ = gettext(
"Without this plugin you will no longer be able to earn achievements and track stats about your OctoPrint instance."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = AchievementsPlugin()
__plugin_helpers__ = {
"get_unlocked_achievements": __plugin_implementation__.get_unlocked_achievements,
"has_achievement": __plugin_implementation__._has_achievement,
}
__plugin_hooks__ = {
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.comm.protocol.firmware.info": __plugin_implementation__.firmware_info_hook,
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_hook,
}
| 27,188 | Python | .py | 605 | 32.740496 | 120 | 0.577013 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,957 | achievements.py | OctoPrint_OctoPrint/src/octoprint/plugins/achievements/achievements.py | import os
import re
from pydantic import BaseModel
ROMAN_NUMERAL = re.compile(
"^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$", re.IGNORECASE
)
class Achievement(BaseModel):
key: str = ""
name: str = ""
description: str = ""
hidden: bool = False
nag: bool = False
timebased: bool = False
@property
def icon(self):
key = self.key
if "_" in key and ROMAN_NUMERAL.match(key.rsplit("_", 1)[1]):
key = key.rsplit("_", 1)[0]
if os.path.exists(
os.path.join(os.path.dirname(__file__), "static", "img", f"{key}.svg")
):
return f"{key}"
else:
return "trophy"
class AchievementsMetaClass(type):
achievements = {}
key_to_attr = {}
def __new__(mcs, name, bases, args):
cls = type.__new__(mcs, name, bases, args)
for key, value in args.items():
if isinstance(value, Achievement):
value.key = key.lower()
mcs.achievements[key] = value
mcs.key_to_attr[key.lower()] = key
return cls
def all(cls):
return cls.achievements.values()
def get(cls, key):
attr = cls.key_to_attr.get(key)
if not attr:
return None
return cls.achievements.get(attr)
class Achievements(metaclass=AchievementsMetaClass):
## basics
THE_WIZARD = Achievement(
name="The Wizard",
description="Complete the first run setup wizard.",
)
ONE_SMALL_STEP_FOR_MAN = Achievement(
name="That's One Small Step For (A) Man", description="Finish your first print."
)
ADVENTURER = Achievement(
name="The Adventurer",
description="Install a plugin from the repository.",
)
TINKERER = Achievement(
name="The Tinkerer",
description="Install a plugin from a URL.",
)
BETTER_SAFE_THAN_SORRY = Achievement(
name="Better Safe Than Sorry",
description="Create a backup.",
)
## print duration
HALF_MARATHON = Achievement(
name="Half Marathon",
description="Finish a print that took longer than 12 hours.",
nag=True,
)
MARATHON = Achievement(
name="Marathon",
description="Finish a print that took longer than 24 hours.",
nag=True,
)
SPRINT = Achievement(
name="Sprint",
description="Finish a print that took less than 10 minutes.",
)
ACHIEVEMENT_NOT_FOUND = Achievement(
name="Achievement Not Found",
description="Reach a total print duration of 404 hours",
hidden=True,
nag=True,
)
## print count
CANT_GET_ENOUGH = Achievement(
name="Can't Get Enough",
description="Finish 10 prints in one day.",
nag=True,
timebased=True,
)
THE_MANUFACTURER_I = Achievement(
name="The Manufacturer", description="Finish 10 prints.", nag=True
)
THE_MANUFACTURER_II = Achievement(
name="The Manufacturer II",
description="Finish 100 prints.",
hidden=True,
nag=True,
)
THE_MANUFACTURER_III = Achievement(
name="The Manufacturer III",
description="Finish 1000 prints.",
hidden=True,
nag=True,
)
## date or date range specific
HAPPY_BIRTHDAY_FOOSEL = Achievement(
name="Happy Birthday, foosel",
description="Start a print on foosel's birthday, March 21st.",
hidden=True,
timebased=True,
)
HAPPY_BIRTHDAY_OCTOPRINT = Achievement(
name="Happy Birthday, OctoPrint",
description="Start a print on OctoPrint's birthday, December 25th.",
hidden=True,
timebased=True,
)
SPOOKY = Achievement(
name="Spooky",
description="Start a print on Halloween, October 31st.",
hidden=True,
timebased=True,
)
SANTAS_LITTLE_HELPER = Achievement(
name="Santa's Little Helper",
description="Start a print between December 1st and December 24th.",
hidden=True,
timebased=True,
)
## weekday specific
TGIF = Achievement(
name="TGIF",
description="Start a print on a Friday.",
timebased=True,
)
WEEKEND_WARRIOR = Achievement(
name="Weekend Warrior",
description="Start prints on four consecutive weekends.",
timebased=True,
)
## time specific
EARLY_BIRD = Achievement(
name="Early Bird",
description="Start a print between 03:00 and 07:00.",
hidden=True,
timebased=True,
)
NIGHT_OWL = Achievement(
name="Night Owl",
description="Start a print between 23:00 and 03:00.",
hidden=True,
timebased=True,
)
## file management
CLEAN_HOUSE_I = Achievement(
name="Clean House",
description="Delete 100 files.",
hidden=True,
)
CLEAN_HOUSE_II = Achievement(
name="Clean House II",
description="Delete 500 files.",
hidden=True,
)
CLEAN_HOUSE_III = Achievement(
name="Clean House III",
description="Delete 1000 files.",
hidden=True,
)
HEAVY_CHONKER = Achievement(
name="Heavy Chonker",
description="Upload a GCODE file larger than 500MB.",
)
THE_COLLECTOR_I = Achievement(
name="The Collector",
description="Upload 100 files.",
hidden=True,
nag=True,
)
THE_COLLECTOR_II = Achievement(
name="The Collector II",
description="Upload 500 files.",
hidden=True,
nag=True,
)
THE_COLLECTOR_III = Achievement(
name="The Collector III",
description="Upload 1000 files.",
hidden=True,
nag=True,
)
THE_ORGANIZER = Achievement(
name="The Organizer",
description="Create a folder.",
hidden=True,
)
## mishaps
ALL_BEGINNINGS_ARE_HARD = Achievement(
name="All Beginnings Are Hard", description="Cancel your first print."
)
ONE_OF_THOSE_DAYS = Achievement(
name="Must Be One Of Those Days",
description="Cancel ten consecutive prints on the same day.",
hidden=True,
timebased=True,
)
SO_CLOSE = Achievement(
name="So Close",
description="Cancel a print job at 95% progress or more.",
hidden=True,
)
## misc
CROSSOVER_EPISODE = Achievement(
name="What Is This, A Crossover Episode?",
description="Connect to a printer running Klipper.",
hidden=True,
)
HANG_IN_THERE = Achievement(
name="Hang In There!",
description="Pause the same print ten times.",
hidden=True,
)
MASS_PRODUCTION = Achievement(
name="Mass Production",
description="Finish a print of the same file five times in a row.",
hidden=True,
nag=True,
)
WHAT_COULD_POSSIBLY_GO_WRONG = Achievement(
name="What Could Possibly Go Wrong?",
description="Start a print with an active undervoltage issue.",
hidden=True,
)
if __name__ == "__main__":
import json
achievements = Achievements.all()
print("const ACHIEVEMENTS = ", end="")
print(
json.dumps(
{
a.key: {"name": a.name, "hidden": a.hidden}
for a in sorted(achievements, key=lambda x: x.key)
},
indent=2,
)
)
| 7,534 | Python | .py | 248 | 22.717742 | 88 | 0.597618 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,958 | data.py | OctoPrint_OctoPrint/src/octoprint/plugins/achievements/data.py | from typing import Dict
from pydantic import BaseModel
class StatsBase(BaseModel):
last_version: str = ""
"""Version of OctoPrint during last start, used for keeping track of updates."""
seen_versions: int = 0
"""Number of different versions seen."""
server_starts: int = 0
"""Number of times OctoPrint was started."""
prints_started: int = 0
"""Number of prints started."""
prints_cancelled: int = 0
"""Number of prints cancelled."""
prints_errored: int = 0
"""Number of prints errored."""
prints_finished: int = 0
"""Number of prints finished."""
prints_started_per_weekday: Dict[int, int] = {}
"""Number of prints started per weekday."""
print_duration_total: float = 0
"""Total print duration."""
print_duration_cancelled: float = 0
"""Total print duration of cancelled prints."""
print_duration_errored: float = 0
"""Total print duration of errored prints."""
print_duration_finished: float = 0
"""Total print duration of finished prints."""
longest_print_duration: float = 0
"""Duration of longest print."""
longest_print_date: int = 0
"""Timestamp of longest print."""
files_uploaded: int = 0
"""Number of files uploaded."""
files_deleted: int = 0
"""Number of files deleted."""
plugins_installed: int = 0
"""Number of plugins installed."""
plugins_uninstalled: int = 0
"""Number of plugins uninstalled."""
most_plugins: int = 0
"""Most plugins installed at once."""
class Stats(StatsBase):
created: int = 0
"""Timestamp of when stats collection was started."""
created_version: str = ""
"""Version of OctoPrint when stats collection was started."""
class YearlyStats(StatsBase):
achievements: int = 0
"""Number of achievements unlocked."""
class State(BaseModel):
date_last_print: str = ""
"""Date of the last print."""
prints_today: int = 0
"""Number of prints finished today."""
date_last_cancelled_print: str = ""
"""Date of the last cancelled print."""
prints_cancelled_today: int = 0
"""Number of prints cancelled today."""
consecutive_prints_cancelled_today: int = 0
"""Number of consecutive prints cancelled today."""
file_last_print: str = ""
"""Name of the file of the last print."""
consecutive_prints_of_same_file: int = 0
"""Number of consecutive prints of the same file."""
date_last_weekend_print: str = ""
"""Date of last print that was started on a weekend."""
consecutive_weekend_prints: int = 0
"""Number of consecutive prints that were started on a weekend."""
class Data(BaseModel):
stats: Stats
achievements: Dict[str, int]
state: State
| 2,764 | Python | .py | 72 | 33.25 | 84 | 0.667295 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,959 | happy_birthday_octoprint.svg | OctoPrint_OctoPrint/src/octoprint/plugins/achievements/static/img/happy_birthday_octoprint.svg | <svg xmlns="http://www.w3.org/2000/svg" id="mdi-cake-variant" viewBox="0 0 24 24"><path d="M12,6C13.11,6 14,5.1 14,4C14,3.62 13.9,3.27 13.71,2.97L12,0L10.29,2.97C10.1,3.27 10,3.62 10,4A2,2 0 0,0 12,6M16.6,16L15.53,14.92L14.45,16C13.15,17.29 10.87,17.3 9.56,16L8.5,14.92L7.4,16C6.75,16.64 5.88,17 4.96,17C4.23,17 3.56,16.77 3,16.39V21A1,1 0 0,0 4,22H20A1,1 0 0,0 21,21V16.39C20.44,16.77 19.77,17 19.04,17C18.12,17 17.25,16.64 16.6,16M18,9H13V7H11V9H6A3,3 0 0,0 3,12V13.54C3,14.62 3.88,15.5 4.96,15.5C5.5,15.5 6,15.3 6.34,14.93L8.5,12.8L10.61,14.93C11.35,15.67 12.64,15.67 13.38,14.93L15.5,12.8L17.65,14.93C18,15.3 18.5,15.5 19.03,15.5C20.11,15.5 21,14.62 21,13.54V12A3,3 0 0,0 18,9Z" /></svg> | 691 | Python | .py | 1 | 691 | 691 | 0.681621 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,960 | happy_birthday_foosel.svg | OctoPrint_OctoPrint/src/octoprint/plugins/achievements/static/img/happy_birthday_foosel.svg | <svg xmlns="http://www.w3.org/2000/svg" id="mdi-cake" viewBox="0 0 24 24"><path d="M11.5,0.5C12,0.75 13,2.4 13,3.5C13,4.6 12.33,5 11.5,5C10.67,5 10,4.85 10,3.75C10,2.65 11,2 11.5,0.5M18.5,9C21,9 23,11 23,13.5C23,15.06 22.21,16.43 21,17.24V23H12L3,23V17.24C1.79,16.43 1,15.06 1,13.5C1,11 3,9 5.5,9H10V6H13V9H18.5M12,16A2.5,2.5 0 0,0 14.5,13.5H16A2.5,2.5 0 0,0 18.5,16A2.5,2.5 0 0,0 21,13.5A2.5,2.5 0 0,0 18.5,11H5.5A2.5,2.5 0 0,0 3,13.5A2.5,2.5 0 0,0 5.5,16A2.5,2.5 0 0,0 8,13.5H9.5A2.5,2.5 0 0,0 12,16Z" /></svg> | 512 | Python | .py | 1 | 512 | 512 | 0.646484 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,961 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/backup/__init__.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 octoprint.plugin
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
from octoprint.server import NO_CONTENT
from octoprint.server.util.flask import no_firstrun_access
from octoprint.settings import default_settings
from octoprint.util import is_hidden_path, to_bytes, yaml
from octoprint.util.pip import create_pip_caller
from octoprint.util.platform import is_os_compatible
from octoprint.util.version import (
get_comparable_version,
get_octoprint_version,
get_octoprint_version_string,
is_octoprint_compatible,
)
try:
import zlib # check if zlib is available
except ImportError:
zlib = None
import json
import logging
import os
import shutil
import sys
import tempfile
import threading
import time
import traceback
import zipfile
import flask
import requests
import sarge
from flask_babel import gettext
from octoprint.plugins.pluginmanager import DEFAULT_PLUGIN_REPOSITORY
from octoprint.server.util.flask import credentials_checked_recently
from octoprint.settings import valid_boolean_trues
from octoprint.util import get_formatted_size
from octoprint.util.text import sanitize
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
BACKUP_DATE_TIME_FMT = "%Y%m%d-%H%M%S"
MAX_UPLOAD_SIZE = 1024 * 1024 * 1024 # 1GB
class BackupPlugin(
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin,
):
_pip_caller = None
_backup_in_progress = threading.Lock()
_restore_in_progress = threading.Lock()
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "CREATE",
"name": "Create backup",
"description": gettext("Allows to trigger the creation of backups"),
"roles": ["create"],
"default_groups": [ADMIN_GROUP],
},
]
# Socket emit hook
def socket_emit_hook(self, socket, user, message, payload, *args, **kwargs):
if message != "event" or payload["type"] != Events.PLUGIN_BACKUP_BACKUP_CREATED:
return True
return user and user.has_permission(Permissions.PLUGIN_BACKUP_CREATE)
##~~ StartupPlugin
def on_after_startup(self):
self._clean_dir_backup(self._settings._basedir, on_log_progress=self._logger.info)
##~~ SettingsPlugin
def get_settings_defaults(self):
return {"restore_unsupported": False}
##~~ AssetPlugin
def get_assets(self):
return {
"js": ["js/backup.js"],
"clientjs": ["clientjs/backup.js"],
"css": ["css/backup.css"],
"less": ["less/backup.less"],
}
##~~ TemplatePlugin
def get_template_configs(self):
return [
{"type": "settings", "name": gettext("Backup & Restore")},
{"type": "wizard", "name": gettext("Restore Backup?")},
]
def get_template_vars(self):
return {
"max_upload_size": MAX_UPLOAD_SIZE,
"max_upload_size_str": get_formatted_size(MAX_UPLOAD_SIZE),
}
##~~ BlueprintPlugin
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@no_firstrun_access
@Permissions.ADMIN.require(403)
def get_state(self):
backups = self._get_backups()
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(
backups=backups,
backup_in_progress=self._backup_in_progress.locked(),
unknown_plugins=unknown_plugins,
restore_supported=self._restore_supported(self._settings),
max_upload_size=MAX_UPLOAD_SIZE,
)
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
@no_firstrun_access
@Permissions.ADMIN.require(403)
def get_unknown_plugins(self):
# TODO add caching
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(unknown_plugins=unknown_plugins)
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
@no_firstrun_access
@Permissions.ADMIN.require(403)
def delete_unknown_plugins(self):
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
try:
os.remove(data_file)
except Exception:
pass
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
@no_firstrun_access
@Permissions.ADMIN.require(403)
def get_backups(self):
backups = self._get_backups()
return flask.jsonify(backups=backups)
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
@no_firstrun_access
@Permissions.PLUGIN_BACKUP_CREATE.require(403)
def create_backup(self):
data = flask.request.json
exclude = data.get("exclude", [])
filename = self._build_backup_filename(settings=self._settings)
self._start_backup(exclude, filename)
response = flask.jsonify(started=True, name=filename)
response.status_code = 201
return response
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
@no_firstrun_access
@Permissions.ADMIN.require(403)
def delete_backup(self, filename):
self._delete_backup(filename)
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
def perform_restore(self):
if not (
Permissions.ADMIN.can() and credentials_checked_recently()
) and not self._settings.global_get(["server", "firstRun"]):
flask.abort(403)
if not self._restore_supported(self._settings):
flask.abort(
400,
description="Invalid request, the restores are not "
"supported on the underlying operating system",
)
input_name = "file"
input_upload_path = (
input_name
+ "."
+ self._settings.global_get(["server", "uploads", "pathSuffix"])
)
if input_upload_path in flask.request.values:
# file to restore was uploaded
path = flask.request.values[input_upload_path]
elif flask.request.json and "path" in flask.request.json:
# existing backup is supposed to be restored
backup_folder = self.get_plugin_data_folder()
path = os.path.realpath(
os.path.join(backup_folder, flask.request.json["path"])
)
if (
not path.startswith(backup_folder)
or not os.path.exists(path)
or is_hidden_path(path)
):
return flask.abort(404)
else:
flask.abort(
400,
description="Invalid request, neither a file nor a path of a file to "
"restore provided",
)
def on_install_plugins(plugins):
force_user = self._settings.global_get_boolean(
["plugins", "pluginmanager", "pip_force_user"]
)
pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"])
def on_log(line):
self._logger.info(line)
self._send_client_message("logline", {"line": line, "type": "stdout"})
for plugin in plugins:
octoprint_compatible = is_octoprint_compatible(
*plugin["compatibility"]["octoprint"]
)
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
self._logger.warning(
"Cannot install plugin {}, it is incompatible to this version "
"of OctoPrint and the underlying operating system".format(
plugin["id"]
)
)
elif not octoprint_compatible:
self._logger.warning(
"Cannot install plugin {}, it is incompatible to this version "
"of OctoPrint".format(plugin["id"])
)
elif not os_compatible:
self._logger.warning(
"Cannot install plugin {}, it is incompatible to the underlying "
"operating system".format(plugin["id"])
)
self._send_client_message(
"plugin_incompatible",
{
"plugin": plugin["id"],
"octoprint_compatible": octoprint_compatible,
"os_compatible": os_compatible,
},
)
continue
self._logger.info("Installing plugin {}".format(plugin["id"]))
self._send_client_message("installing_plugin", {"plugin": plugin["id"]})
self.__class__._install_plugin(
plugin,
force_user=force_user,
pip_command=self._settings.global_get(
["server", "commands", "localPipCommand"]
),
pip_args=pip_args,
on_log=on_log,
)
def on_report_unknown_plugins(plugins):
self._send_client_message("unknown_plugins", payload={"plugins": plugins})
def on_log_progress(line):
self._logger.info(line)
self._send_client_message(
"logline", payload={"line": line, "stream": "stdout"}
)
def on_log_error(line, exc_info=None):
self._logger.error(line, exc_info=exc_info)
self._send_client_message(
"logline", payload={"line": line, "stream": "stderr"}
)
if exc_info is not None:
exc_type, exc_value, exc_tb = exc_info
output = traceback.format_exception(exc_type, exc_value, exc_tb)
for line in output:
self._send_client_message(
"logline", payload={"line": line.rstrip(), "stream": "stderr"}
)
def on_restore_start(path):
self._send_client_message("restore_started")
def on_restore_done(path):
self._send_client_message("restore_done")
def on_restore_failed(path):
self._send_client_message("restore_failed")
def on_invalid_backup(line):
on_log_error(line)
archive = tempfile.NamedTemporaryFile(delete=False)
archive.close()
shutil.copy(path, archive.name)
path = archive.name
# noinspection PyTypeChecker
thread = threading.Thread(
target=self._restore_backup,
args=(path,),
kwargs={
"settings": self._settings,
"plugin_manager": self._plugin_manager,
"datafolder": self.get_plugin_data_folder(),
"on_install_plugins": on_install_plugins,
"on_report_unknown_plugins": on_report_unknown_plugins,
"on_invalid_backup": on_invalid_backup,
"on_log_progress": on_log_progress,
"on_log_error": on_log_error,
"on_restore_start": on_restore_start,
"on_restore_done": on_restore_done,
"on_restore_failed": on_restore_failed,
},
)
thread.daemon = True
thread.start()
return flask.jsonify(started=True)
def is_blueprint_protected(self):
return False
def is_blueprint_csrf_protected(self):
return True
##~~ WizardPlugin
def is_wizard_required(self):
return self._settings.global_get(["server", "firstRun"]) and is_os_compatible(
["!windows"]
)
def get_wizard_details(self):
return {"required": self.is_wizard_required()}
##~~ tornado hook
def route_hook(self, *args, **kwargs):
from octoprint.server import app
from octoprint.server.util.flask import permission_and_fresh_credentials_validator
from octoprint.server.util.tornado import (
LargeResponseHandler,
access_validation_factory,
path_validation_factory,
)
from octoprint.util import is_hidden_path
plugin_folder = self.get_plugin_data_folder()
def path_check(path):
joined = os.path.join(plugin_folder, path)
return not is_hidden_path(joined) and self._valid_backup(joined)
return [
(
r"/download/(.*)",
LargeResponseHandler,
{
"path": plugin_folder,
"as_attachment": True,
"path_validation": path_validation_factory(
path_check,
status_code=404,
),
"access_validation": access_validation_factory(
app, permission_and_fresh_credentials_validator, Permissions.ADMIN
),
},
)
]
def bodysize_hook(self, current_max_body_sizes, *args, **kwargs):
# max upload size for the restore endpoint
return [("POST", r"/restore", MAX_UPLOAD_SIZE)]
# Exported plugin helpers
def create_backup_helper(self, exclude=None, filename=None):
"""
.. versionadded:: 1.6.0
Create a backup from a plugin or other internal call
This helper is exported as ``create_backup`` and can be used from the plugin
manager's ``get_helpers`` method.
**Example**
The following code snippet can be used from within a plugin, and will create a backup
excluding two folders (``timelapse`` and ``uploads``)
.. code-block:: python
helpers = self._plugin_manager.get_helpers("backup", "create_backup")
if helpers and "create_backup" in helpers:
helpers["create_backup"](exclude=["timelapse", "uploads"])
By using the ``if helpers [...]`` clause, plugins can fall back to other methods
when they are running under versions where these helpers did not exist.
:param list exclude: Names of data folders to exclude, defaults to None
:param str filename: Name of backup to be created, if None (default) the backup
name will be auto-generated. This should use a ``.zip`` extension.
"""
if exclude is None:
exclude = []
if not isinstance(exclude, list):
exclude = list(exclude)
self._start_backup(exclude, filename=filename)
def delete_backup_helper(self, filename):
"""
.. versionadded:: 1.6.0
Delete the specified backup from a plugin or other internal call
This helper is exported as ``delete_backup`` and can be used through the plugin
manager's ``get_helpers`` method.
**Example**
The following code snippet can be used from within a plugin, and will attempt to
delete the backup named ``ExampleBackup.zip``.
.. code-block:: python
helpers = self._plugin_manager.get_helpers("backup", "delete_backup")
if helpers and "delete_backup" in helpers:
helpers["delete_backup"]("ExampleBackup.zip")
By using the ``if helpers [...]`` clause, plugins can fall back to other methods
when they are running under versions where these helpers did not exist.
.. warning::
This method will fail silently if the backup does not exist, and so
it is recommended that you make sure the name comes from a verified source,
for example the name from the events or other helpers.
:param str filename: The name of the backup to delete
"""
self._delete_backup(filename)
##~~ CLI hook
def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs):
import click
@click.command("backup")
@click.option(
"--exclude",
multiple=True,
help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or "
"'timelapse' to exclude timelapses.",
)
@click.option(
"--path",
type=click.Path(),
default=None,
help="Specify full path to backup file to be created",
)
def backup_command(exclude, path):
"""
Creates a new backup.
"""
settings = octoprint.plugin.plugin_settings_for_settings_plugin(
"backup", self, settings=cli_group.settings
)
if path is not None:
datafolder, filename = os.path.split(os.path.abspath(path))
else:
filename = None
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
def on_backup_start(name, temporary_path, exclude):
click.echo(f"Creating backup at {name}, please wait...")
path = self._create_backup(
name=filename,
exclude=exclude,
settings=settings,
plugin_manager=cli_group.plugin_manager,
datafolder=datafolder,
on_backup_start=on_backup_start,
)
click.echo("Done.")
click.echo(f"Backup located at {path}")
@click.command("restore")
@click.argument("path")
def restore_command(path):
"""
Restores an existing backup from the backup zip provided as argument.
OctoPrint does not need to run for this to proceed.
"""
settings = octoprint.plugin.plugin_settings_for_settings_plugin(
"backup", self, settings=cli_group.settings
)
plugin_manager = cli_group.plugin_manager
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
# register plugin manager plugin setting overlays
plugin_info = plugin_manager.get_plugin_info("pluginmanager")
if plugin_info and plugin_info.implementation:
default_settings_overlay = {"plugins": {}}
default_settings_overlay["plugins"][
"pluginmanager"
] = plugin_info.implementation.get_settings_defaults()
settings.add_overlay(default_settings_overlay, at_end=True)
if not os.path.isabs(path):
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
path = os.path.join(datafolder, path)
if not os.path.exists(path):
click.echo(f"Backup {path} does not exist", err=True)
sys.exit(-1)
archive = tempfile.NamedTemporaryFile(delete=False)
archive.close()
shutil.copy(path, archive.name)
path = archive.name
def on_install_plugins(plugins):
if not plugins:
return
force_user = settings.global_get_boolean(
["plugins", "pluginmanager", "pip_force_user"]
)
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
def log(line):
click.echo(f"\t{line}")
for plugin in plugins:
octoprint_compatible = is_octoprint_compatible(
*plugin["compatibility"]["octoprint"]
)
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
click.echo(
"Cannot install plugin {}, it is incompatible to this version of "
"OctoPrint and the underlying operating system".format(
plugin["id"]
)
)
elif not octoprint_compatible:
click.echo(
"Cannot install plugin {}, it is incompatible to this version of "
"OctoPrint".format(plugin["id"])
)
elif not os_compatible:
click.echo(
"Cannot install plugin {}, it is incompatible to the underlying "
"operating system".format(plugin["id"])
)
continue
click.echo("Installing plugin {}".format(plugin["id"]))
self.__class__._install_plugin(
plugin,
force_user=force_user,
pip_command=settings.global_get(
["server", "commands", "localPipCommand"]
),
pip_args=pip_args,
on_log=log,
)
def on_report_unknown_plugins(plugins):
if not plugins:
return
click.echo(
"The following plugins were not found in the plugin repository. You'll need to install them manually."
)
for plugin in plugins:
click.echo(
"\t{} (Homepage: {})".format(
plugin["name"], plugin["url"] if plugin["url"] else "?"
)
)
def on_log_progress(line):
click.echo(line)
def on_log_error(line, exc_info=None):
click.echo(line, err=True)
if exc_info is not None:
exc_type, exc_value, exc_tb = exc_info
output = traceback.format_exception(exc_type, exc_value, exc_tb)
for line in output:
click.echo(line.rstrip(), err=True)
if self._restore_backup(
path,
settings=settings,
plugin_manager=plugin_manager,
datafolder=datafolder,
on_install_plugins=on_install_plugins,
on_report_unknown_plugins=on_report_unknown_plugins,
on_log_progress=on_log_progress,
on_log_error=on_log_error,
on_invalid_backup=on_log_error,
):
click.echo(f"Restored from {path}")
else:
click.echo(f"Restoring from {path} failed", err=True)
return [backup_command, restore_command]
##~~ helpers
def _start_backup(self, exclude, filename=None):
def on_backup_start(name, temporary_path, exclude):
self._logger.info(
"Creating backup zip at {} (excluded: {})...".format(
temporary_path, ",".join(exclude) if len(exclude) else "-"
)
)
self._send_client_message("backup_started", payload={"name": name})
def on_backup_done(name, final_path, exclude):
self._send_client_message("backup_done", payload={"name": name})
self._logger.info("... done creating backup zip.")
self._event_bus.fire(
Events.PLUGIN_BACKUP_BACKUP_CREATED,
{"name": name, "path": final_path, "excludes": exclude},
)
def on_backup_error(name, exc_info):
self._send_client_message(
"backup_error", payload={"name": name, "error": f"{exc_info[1]}"}
)
self._logger.error("Error while creating backup zip", exc_info=exc_info)
thread = threading.Thread(
target=self._create_backup,
kwargs={
"name": filename,
"exclude": exclude,
"settings": self._settings,
"plugin_manager": self._plugin_manager,
"logger": self._logger,
"datafolder": self.get_plugin_data_folder(),
"on_backup_start": on_backup_start,
"on_backup_done": on_backup_done,
"on_backup_error": on_backup_error,
},
)
thread.daemon = True
thread.start()
def _delete_backup(self, filename):
"""
Delete the backup specified
Args:
filename (str): Name of backup to delete
"""
backup_folder = self.get_plugin_data_folder()
full_path = os.path.realpath(os.path.join(backup_folder, filename))
if (
full_path.startswith(backup_folder)
and os.path.exists(full_path)
and not is_hidden_path(full_path)
):
try:
os.remove(full_path)
except Exception:
self._logger.exception(f"Could not delete {filename}")
raise
def _get_backups(self):
backups = []
for entry in os.scandir(self.get_plugin_data_folder()):
if is_hidden_path(entry.path):
continue
if not self._valid_backup(entry.path):
continue
backups.append(
{
"name": entry.name,
"date": entry.stat().st_mtime,
"size": entry.stat().st_size,
"url": flask.url_for("index")
+ "plugin/backup/download/"
+ entry.name,
}
)
return backups
def _get_unknown_plugins(self):
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
if os.path.exists(data_file):
try:
with open(data_file, encoding="utf-8") as f:
unknown_plugins = json.load(f)
assert isinstance(unknown_plugins, list)
assert all(
map(
lambda x: isinstance(x, dict)
and "key" in x
and "name" in x
and "url" in x,
unknown_plugins,
)
)
installed_plugins = self._plugin_manager.plugins
unknown_plugins = list(
filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)
)
if not unknown_plugins:
# no plugins left uninstalled, delete data file
try:
os.remove(data_file)
except Exception:
self._logger.exception(
"Error while deleting list of unknown plugins at {}".format(
data_file
)
)
return unknown_plugins
except Exception:
self._logger.exception(
"Error while reading list of unknown plugins from {}".format(
data_file
)
)
try:
os.remove(data_file)
except Exception:
self._logger.exception(
"Error while deleting list of unknown plugins at {}".format(
data_file
)
)
return []
@classmethod
def _clean_dir_backup(cls, basedir, on_log_progress=None):
basedir_backup = basedir + ".bck"
if os.path.exists(basedir_backup):
def remove_bck():
if callable(on_log_progress):
on_log_progress(
"Found config folder backup from prior restore, deleting it..."
)
shutil.rmtree(basedir_backup)
if callable(on_log_progress):
on_log_progress("... deleted.")
thread = threading.Thread(target=remove_bck)
thread.daemon = True
thread.start()
@classmethod
def _get_disk_size(cls, path, ignored=None):
if ignored is None:
ignored = []
if path in ignored:
return 0
total = 0
for entry in os.scandir(path):
if entry.is_dir():
total += cls._get_disk_size(entry.path, ignored=ignored)
elif entry.is_file():
total += entry.stat().st_size
return total
@classmethod
def _free_space(cls, path, size):
from psutil import disk_usage
return disk_usage(path).free > size
@classmethod
def _get_plugin_repository_data(cls, url, logger=None):
if logger is None:
logger = logging.getLogger(__name__)
try:
r = requests.get(url, timeout=3.05)
r.raise_for_status()
except Exception:
logger.exception(
f"Error while fetching the plugin repository data from {url}"
)
return {}
from octoprint.plugins.pluginmanager import map_repository_entry
return {plugin["id"]: plugin for plugin in map(map_repository_entry, r.json())}
@classmethod
def _install_plugin(
cls, plugin, force_user=False, pip_command=None, pip_args=None, on_log=None
):
if pip_args is None:
pip_args = []
if on_log is None:
on_log = logging.getLogger(__name__).info
# prepare pip caller
def log(prefix, *lines):
for line in lines:
on_log(f"{prefix} {line.rstrip()}")
def log_call(*lines):
log(">", *lines)
def log_stdout(*lines):
log("<", *lines)
def log_stderr(*lines):
log("!", *lines)
if cls._pip_caller is None:
cls._pip_caller = create_pip_caller(
command=pip_command, force_user=force_user
)
cls._pip_caller.on_log_call = log_call
cls._pip_caller.on_log_stdout = log_stdout
cls._pip_caller.on_log_stderr = log_stderr
# install plugin
pip = ["install", sarge.shell_quote(plugin["archive"]), "--no-cache-dir"]
if plugin.get("follow_dependency_links"):
pip.append("--process-dependency-links")
if force_user:
pip.append("--user")
if pip_args:
pip += pip_args
cls._pip_caller.execute(*pip)
@classmethod
def _create_backup(
cls,
name=None,
exclude=None,
settings=None,
plugin_manager=None,
logger=None,
datafolder=None,
on_backup_start=None,
on_backup_done=None,
on_backup_error=None,
):
if logger is None:
logger = logging.getLogger(__name__)
exclude_by_default = (
"generated",
"logs",
"watched",
)
with cls._backup_in_progress:
if name is None:
name = cls._build_backup_filename(settings)
try:
if exclude is None:
exclude = []
if not isinstance(exclude, list):
exclude = list(exclude)
if "timelapse" in exclude:
exclude.append("timelapse_tmp")
current_excludes = list(exclude)
additional_excludes = list()
plugin_data = settings.global_get_basefolder("data")
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.additional_excludes"
).items():
try:
additional = hook(current_excludes)
if isinstance(additional, list):
if "." in additional:
current_excludes.append(os.path.join("data", plugin))
additional_excludes.append(
os.path.join(plugin_data, plugin)
)
else:
current_excludes += map(
lambda x: os.path.join("data", plugin, x), additional
)
additional_excludes += map(
lambda x: os.path.join(plugin_data, plugin, x),
additional,
)
except Exception:
logger.exception(
f"Error while retrieving additional excludes "
f"from plugin {plugin}",
extra={"plugin": plugin},
)
configfile = settings._configfile
basedir = settings._basedir
temporary_path = os.path.join(datafolder, f".{name}")
final_path = os.path.join(datafolder, name)
own_folder = datafolder
defaults = [
os.path.join(basedir, "config.yaml"),
] + [
os.path.join(basedir, folder)
for folder in default_settings["folder"].keys()
]
# check how many bytes we are about to backup
size = os.stat(configfile).st_size
for folder in default_settings["folder"].keys():
if folder in exclude or folder in exclude_by_default:
continue
size += cls._get_disk_size(
settings.global_get_basefolder(folder),
ignored=[
own_folder,
],
)
size += cls._get_disk_size(
basedir,
ignored=defaults
+ [
own_folder,
],
)
# since we can't know the compression ratio beforehand, we assume we need the same amount of space
if not cls._free_space(os.path.dirname(temporary_path), size):
raise InsufficientSpace()
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
backup_error = False
try:
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.before_backup"
).items():
try:
hook()
except Exception:
logger.exception(
f"Error while running before_backup hook from plugin {plugin}",
extra={"plugin": plugin},
)
if callable(on_backup_start):
on_backup_start(name, temporary_path, exclude)
with zipfile.ZipFile(
temporary_path, mode="w", compression=compression, allowZip64=True
) as zip:
def add_to_zip(source, target, ignored=None):
if ignored is None:
ignored = []
if source in ignored:
return
if os.path.isdir(source):
for entry in os.scandir(source):
add_to_zip(
entry.path,
os.path.join(target, entry.name),
ignored=ignored,
)
elif os.path.isfile(source):
zip.write(source, arcname=target)
# add metadata
metadata = {
"version": get_octoprint_version_string(),
"excludes": exclude,
}
zip.writestr("metadata.json", json.dumps(metadata))
# backup current config file
add_to_zip(
configfile,
"basedir/config.yaml",
ignored=[
own_folder,
],
)
# backup configured folder paths
for folder in default_settings["folder"].keys():
if folder in exclude or folder in exclude_by_default:
continue
add_to_zip(
settings.global_get_basefolder(folder),
"basedir/" + folder.replace("_", "/"),
ignored=[
own_folder,
]
+ additional_excludes,
)
# backup anything else that might be lying around in our basedir
add_to_zip(
basedir,
"basedir",
ignored=defaults
+ [
own_folder,
]
+ additional_excludes,
)
# add list of installed plugins
helpers = plugin_manager.get_helpers(
"pluginmanager", "generate_plugins_json"
)
if helpers and "generate_plugins_json" in helpers:
plugins = helpers["generate_plugins_json"](
settings=settings, plugin_manager=plugin_manager
)
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
shutil.move(temporary_path, final_path)
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
return final_path
except Exception:
backup_error = True
raise
finally:
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.after_backup"
).items():
try:
hook(error=backup_error)
except Exception:
logger.exception(
f"Error while running after_backup hook from plugin {plugin}",
extra={"plugin": plugin},
)
except Exception as exc: # noqa: F841
# TODO py3: use the exception, not sys.exc_info()
if callable(on_backup_error):
exc_info = sys.exc_info()
try:
on_backup_error(name, exc_info)
finally:
del exc_info
raise
@classmethod
def _restore_backup(
cls,
path,
settings=None,
plugin_manager=None,
datafolder=None,
on_install_plugins=None,
on_report_unknown_plugins=None,
on_invalid_backup=None,
on_log_progress=None,
on_log_error=None,
on_restore_start=None,
on_restore_done=None,
on_restore_failed=None,
):
if not cls._restore_supported(settings):
if callable(on_log_error):
on_log_error("Restore is not supported on this operating system")
if callable(on_restore_failed):
on_restore_failed(path)
return False
logger = logging.getLogger(__name__)
restart_command = settings.global_get(
["server", "commands", "serverRestartCommand"]
)
basedir = settings._basedir
cls._clean_dir_backup(basedir, on_log_progress=on_log_progress)
repo_url = settings.global_get(["plugins", "pluginmanager", "repository"])
if not repo_url:
repo_url = DEFAULT_PLUGIN_REPOSITORY
plugin_repo = cls._get_plugin_repository_data(repo_url)
with cls._restore_in_progress:
restore_error = False
try:
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.before_restore"
).items():
try:
hook()
except Exception:
logger.exception(
f"Error while running before_restore hook from plugin {plugin}",
extra={"plugin": plugin},
)
if callable(on_restore_start):
on_restore_start(path)
try:
with zipfile.ZipFile(path, "r") as zip:
# read metadata
try:
metadata_zipinfo = zip.getinfo("metadata.json")
except KeyError:
if callable(on_invalid_backup):
on_invalid_backup(
"Not an OctoPrint backup, lacks metadata.json"
)
if callable(on_restore_failed):
on_restore_failed(path)
return False
metadata_bytes = zip.read(metadata_zipinfo)
metadata = json.loads(metadata_bytes)
backup_version = get_comparable_version(
metadata["version"], cut=1
)
if backup_version > get_octoprint_version(cut=1):
if callable(on_invalid_backup):
on_invalid_backup(
"Backup is from a newer version of OctoPrint and cannot be applied"
)
if callable(on_restore_failed):
on_restore_failed(path)
return False
# unzip to temporary folder
temp = tempfile.mkdtemp()
try:
if callable(on_log_progress):
on_log_progress(f"Unpacking backup to {temp}...")
abstemp = os.path.abspath(temp)
dirs = {}
for member in zip.infolist():
abspath = os.path.abspath(
os.path.join(temp, member.filename)
)
if abspath.startswith(abstemp):
date_time = time.mktime(member.date_time + (0, 0, -1))
zip.extract(member, temp)
if os.path.isdir(abspath):
dirs[abspath] = date_time
else:
os.utime(abspath, (date_time, date_time))
# set time on folders
for abspath, date_time in dirs.items():
os.utime(abspath, (date_time, date_time))
# sanity check
configfile = os.path.join(temp, "basedir", "config.yaml")
if not os.path.exists(configfile):
if callable(on_invalid_backup):
on_invalid_backup("Backup lacks config.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
configdata = yaml.load_from_file(path=configfile)
userfile = os.path.join(temp, "basedir", "users.yaml")
if not os.path.exists(userfile):
if callable(on_invalid_backup):
on_invalid_backup("Backup lacks users.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
if callable(on_log_progress):
on_log_progress("Unpacked")
# install available plugins
plugins = []
plugin_list_file = os.path.join(temp, "plugin_list.json")
if os.path.exists(plugin_list_file):
with open(
os.path.join(temp, "plugin_list.json"), "rb"
) as f:
plugins = json.load(f)
known_plugins = []
unknown_plugins = []
if plugins:
if plugin_repo:
for plugin in plugins:
if plugin["key"] in plugin_manager.plugins:
# already installed
continue
if plugin["key"] in plugin_repo:
# not installed, can be installed from repository url
known_plugins.append(
plugin_repo[plugin["key"]]
)
else:
# not installed, not installable
unknown_plugins.append(plugin)
else:
# no repo, all plugins are not installable
unknown_plugins = plugins
if callable(on_log_progress):
if known_plugins:
on_log_progress(
"Known and installable plugins: {}".format(
", ".join(
map(lambda x: x["id"], known_plugins)
)
)
)
if unknown_plugins:
on_log_progress(
"Unknown plugins: {}".format(
", ".join(
map(
lambda x: x["key"],
unknown_plugins,
)
)
)
)
if callable(on_install_plugins):
on_install_plugins(known_plugins)
if callable(on_report_unknown_plugins):
on_report_unknown_plugins(unknown_plugins)
# move config data
basedir_backup = basedir + ".bck"
basedir_extracted = os.path.join(temp, "basedir")
if callable(on_log_progress):
on_log_progress(
f"Renaming {basedir} to {basedir_backup}..."
)
shutil.move(basedir, basedir_backup)
try:
if callable(on_log_progress):
on_log_progress(
f"Moving {basedir_extracted} to {basedir}..."
)
shutil.move(basedir_extracted, basedir)
except Exception:
if callable(on_log_error):
on_log_error(
"Error while restoring config data",
exc_info=sys.exc_info(),
)
on_log_error("Rolling back old config data")
shutil.move(basedir_backup, basedir)
if callable(on_restore_failed):
on_restore_failed(path)
return False
if unknown_plugins:
if callable(on_log_progress):
on_log_progress(
"Writing info file about unknown plugins"
)
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
unknown_plugins_path = os.path.join(
datafolder, UNKNOWN_PLUGINS_FILE
)
try:
with open(unknown_plugins_path, mode="wb") as f:
f.write(to_bytes(json.dumps(unknown_plugins)))
except Exception:
if callable(on_log_error):
on_log_error(
"Could not persist list of unknown plugins to {}".format(
unknown_plugins_path
),
exc_info=sys.exc_info(),
)
finally:
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.before_restore"
).items():
try:
hook(error=restore_error)
except Exception:
logger.exception(
f"Error while running after_restore hook from plugin {plugin}",
extra={"plugin": plugin},
)
if callable(on_log_progress):
on_log_progress("Removing temporary unpacked folder")
shutil.rmtree(temp)
except Exception:
restore_error = True
exc_info = sys.exc_info()
try:
if callable(on_log_error):
on_log_error("Error while running restore", exc_info=exc_info)
if callable(on_restore_failed):
on_restore_failed(path)
finally:
del exc_info
return False
finally:
# remove zip
if callable(on_log_progress):
on_log_progress("Removing temporary zip")
os.remove(path)
finally:
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.after_restore"
).items():
try:
hook(error=restore_error)
except Exception:
logger.exception(
f"Error while running after_restore hook from plugin {plugin}",
extra={"plugin": plugin},
)
# restart server
if not restart_command:
restart_command = (
configdata.get("server", {})
.get("commands", {})
.get("serverRestartCommand")
)
if restart_command:
import sarge
if callable(on_log_progress):
on_log_progress("Restarting...")
if callable(on_restore_done):
on_restore_done(path)
try:
sarge.run(restart_command, close_fds=True, async_=True)
except Exception:
if callable(on_log_error):
on_log_error(
f"Error while restarting via command {restart_command}",
exc_info=sys.exc_info(),
)
on_log_error("Please restart OctoPrint manually")
return False
else:
if callable(on_restore_done):
on_restore_done(path)
if callable(on_log_error):
on_log_error(
"No restart command configured. Please restart OctoPrint manually."
)
return True
@classmethod
def _build_backup_filename(cls, settings):
backup_prefix = cls._get_backup_prefix(settings)
return "{}-backup-{}.zip".format(
backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT)
)
@classmethod
def _get_backup_prefix(cls, settings):
if settings.global_get(["appearance", "name"]) == "":
backup_prefix = "octoprint"
else:
backup_prefix = settings.global_get(["appearance", "name"])
return sanitize(backup_prefix)
@classmethod
def _restore_supported(cls, settings):
return (
is_os_compatible(["!windows"])
and not settings.get_boolean(["restore_unsupported"])
and os.environ.get("OCTOPRINT_BACKUP_RESTORE_UNSUPPORTED", False)
not in valid_boolean_trues
)
@classmethod
def _valid_backup(cls, path):
if not path.endswith(".zip") or not zipfile.is_zipfile(path):
return False
try:
with zipfile.ZipFile(path) as z:
return "metadata.json" in z.namelist()
except Exception:
return False
def _send_client_message(self, message, payload=None):
if payload is None:
payload = {}
payload["type"] = message
self._plugin_manager.send_plugin_message(self._identifier, payload)
class InsufficientSpace(Exception):
pass
def _register_custom_events(*args, **kwargs):
return ["backup_created"]
__plugin_name__ = "Backup & Restore"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Backup & restore your OctoPrint settings and data"
__plugin_disabling_discouraged__ = gettext(
"Without this plugin you will no longer be able to backup "
"& restore your OctoPrint settings and data."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = BackupPlugin()
__plugin_hooks__ = {
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
"octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook,
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_hook,
}
__plugin_helpers__ = {
"create_backup": __plugin_implementation__.create_backup_helper,
"delete_backup": __plugin_implementation__.delete_backup_helper,
}
| 58,534 | Python | .py | 1,277 | 27.740799 | 122 | 0.482468 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,962 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/action_command_notification/__init__.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 re
import time
import flask
from flask_babel import gettext
import octoprint.plugin
from octoprint.access import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
class ActionCommandNotificationPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin,
):
def __init__(self):
self._notifications = []
self._filter = None
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "SHOW",
"name": "Show printer notifications",
"description": gettext("Allows to see printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["show"],
},
{
"key": "CLEAR",
"name": "Clear printer notifications",
"description": gettext("Allows to clear printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["clear"],
},
]
# ~ AssetPlugin
def get_assets(self):
return {
"js": ["js/action_command_notification.js"],
"clientjs": ["clientjs/action_command_notification.js"],
"css": ["css/action_command_notification.css"],
}
# ~ EventHandlerPlugin
def on_event(self, event, payload):
if event == Events.DISCONNECTED:
self._clear_notifications()
# ~ SettingsPlugin
def get_settings_defaults(self):
return {"enable": True, "enable_popups": False, "filter": ""}
def on_settings_initialized(self):
self._set_filter_pattern()
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._set_filter_pattern()
def _set_filter_pattern(self):
pattern = self._settings.get(["filter"])
if pattern:
try:
self._filter = re.compile(pattern)
except re.error:
self._logger.exception("Invalid regular expression in filter, ignoring")
else:
self._filter = None
# ~ SimpleApiPlugin
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can():
return flask.abort(403)
return flask.jsonify(
notifications=[
{"timestamp": notification[0], "message": notification[1]}
for notification in self._notifications
]
)
def get_api_commands(self):
return {"clear": []}
def on_api_command(self, command, data):
if command == "clear":
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR.can():
return flask.abort(403, "Insufficient permissions")
self._clear_notifications()
# ~ TemplatePlugin
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Printer Notifications"),
"custom_bindings": True,
},
{
"type": "sidebar",
"name": gettext("Printer Notifications"),
"icon": "far fa-bell",
"styles_wrapper": ["display: none"],
"template_header": "action_command_notification_sidebar_header.jinja2",
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
" && settings.settings.plugins.action_command_notification.enable()",
},
]
# ~ action command handler
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not self._settings.get_boolean(["enable"]):
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
if action != "notification":
return
message = parameter.strip()
if self._filter and self._filter.search(message):
self._logger.debug(f"Notification matches filter regex: {message}")
return
self._notifications.append((time.time(), message))
self._plugin_manager.send_plugin_message(self._identifier, {"message": message})
self._logger.info(f"Got a notification: {message}")
def _clear_notifications(self):
self._notifications = []
self._plugin_manager.send_plugin_message(self._identifier, {})
self._logger.info("Notifications cleared")
__plugin_name__ = "Action Command Notification Support"
__plugin_description__ = (
"Allows your printer to trigger notifications via action commands on the connection"
)
__plugin_author__ = "Gina Häußge"
__plugin_disabling_discouraged__ = gettext(
"Without this plugin your printer will no longer be able to trigger"
" notifications in OctoPrint"
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = ActionCommandNotificationPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
| 5,675 | Python | .py | 140 | 31.285714 | 126 | 0.615455 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,963 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/announcements/__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) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
import calendar
import logging
import os
import re
import threading
import time
from collections import OrderedDict
import feedparser
import flask
from flask_babel import gettext
import octoprint.plugin
from octoprint import __version__ as OCTOPRINT_VERSION
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
from octoprint.server.util.flask import (
check_etag,
no_firstrun_access,
with_revalidation_checking,
)
from octoprint.util import count, deserialize, serialize, utmify
from octoprint.util.text import sanitize
class AnnouncementPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin,
):
# noinspection PyMissingConstructor
def __init__(self):
self._cached_channel_configs = None
self._cached_channel_configs_mutex = threading.RLock()
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "READ",
"name": "Read announcements",
"description": gettext("Allows to read announcements"),
"default_groups": [ADMIN_GROUP],
"roles": ["read"],
},
{
"key": "MANAGE",
"name": "Manage announcement subscriptions",
"description": gettext(
'Allows to manage announcement subscriptions. Includes "Read announcements" '
"permission"
),
"default_groups": [ADMIN_GROUP],
"roles": ["manage"],
"permissions": ["PLUGIN_ANNOUNCEMENTS_READ"],
},
]
# StartupPlugin
def on_after_startup(self):
# decouple channel fetching from server startup
def fetch_data():
self._fetch_all_channels()
thread = threading.Thread(target=fetch_data)
thread.daemon = True
thread.start()
# SettingsPlugin
def get_settings_defaults(self):
settings = {
"channels": {
"_important": {
"name": "Important Announcements",
"description": "Important announcements about OctoPrint.",
"priority": 1,
"type": "rss",
"url": "https://octoprint.org/feeds/important.xml",
},
"_releases": {
"name": "Release Announcements",
"description": "Announcements of new releases and release candidates of OctoPrint.",
"priority": 2,
"type": "rss",
"url": "https://octoprint.org/feeds/releases.xml",
},
"_blog": {
"name": "On the OctoBlog",
"description": "Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.",
"priority": 2,
"type": "rss",
"url": "https://octoprint.org/feeds/octoblog.xml",
},
"_plugins": {
"name": "New Plugins in the Repository",
"description": "Announcements of new plugins released on the official Plugin Repository.",
"priority": 2,
"type": "rss",
"url": "https://plugins.octoprint.org/feed.xml",
},
"_octopi": {
"name": "OctoPi News",
"description": "News around OctoPi, the Raspberry Pi image including OctoPrint.",
"priority": 2,
"type": "rss",
"url": "https://octoprint.org/feeds/octopi.xml",
},
},
"enabled_channels": [],
"forced_channels": ["_important"],
"channel_order": ["_important", "_releases", "_blog", "_plugins", "_octopi"],
"ttl": 6 * 60,
"display_limit": 3,
"summary_limit": 300,
}
settings["enabled_channels"] = list(settings["channels"].keys())
return settings
def get_settings_version(self):
return 1
def on_settings_migrate(self, target, current):
if current is None:
# first version had different default feeds and only _important enabled by default
channels = self._settings.get(["channels"])
if "_news" in channels:
del channels["_news"]
if "_spotlight" in channels:
del channels["_spotlight"]
self._settings.set(["channels"], channels)
enabled = self._settings.get(["enabled_channels"])
add_blog = False
if "_news" in enabled:
add_blog = True
enabled.remove("_news")
if "_spotlight" in enabled:
add_blog = True
enabled.remove("_spotlight")
if add_blog and "_blog" not in enabled:
enabled.append("_blog")
self._settings.set(["enabled_channels"], enabled)
# AssetPlugin
def get_assets(self):
return {
"js": ["js/announcements.js"],
"less": ["less/announcements.less"],
"css": ["css/announcements.css"],
}
# Template Plugin
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Announcements"),
"template": "announcements_settings.jinja2",
"custom_bindings": True,
},
{
"type": "navbar",
"template": "announcements_navbar.jinja2",
"styles": ["display: none"],
"data_bind": "visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_READ)",
},
]
# Blueprint Plugin
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
def get_channel_data(self):
from octoprint.settings import valid_boolean_trues
result = []
force = flask.request.values.get("force", "false") in valid_boolean_trues
enabled = self._settings.get(["enabled_channels"])
forced = self._settings.get(["forced_channels"])
channel_configs = self._get_channel_configs(force=force)
def view():
channel_data = self._fetch_all_channels(force=force)
for key, data in channel_configs.items():
read_until = channel_configs[key].get("read_until", None)
entries = sorted(
self._to_internal_feed(
channel_data.get(key, []), read_until=read_until
),
key=lambda e: e["published"],
reverse=True,
)
unread = count(filter(lambda e: not e["read"], entries))
if read_until is None and entries:
last = entries[0]["published"]
self._mark_read_until(key, last)
result.append(
{
"key": key,
"channel": data["name"],
"url": data["url"],
"description": data.get("description", ""),
"priority": data.get("priority", 2),
"enabled": key in enabled or key in forced,
"forced": key in forced,
"data": entries,
"unread": unread,
}
)
return flask.jsonify(channels=result)
def etag():
import hashlib
hash = hashlib.sha1()
def hash_update(value):
hash.update(value.encode("utf-8"))
hash_update(repr(sorted(enabled)))
hash_update(repr(sorted(forced)))
hash_update(OCTOPRINT_VERSION)
for channel in sorted(channel_configs.keys()):
hash_update(repr(channel_configs[channel]))
channel_data = self._get_channel_data_from_cache(
channel, channel_configs[channel]
)
hash_update(repr(channel_data))
return hash.hexdigest()
# noinspection PyShadowingNames
def condition(lm, etag):
return check_etag(etag)
return with_revalidation_checking(
etag_factory=lambda *args, **kwargs: etag(),
condition=lambda lm, etag: condition(lm, etag),
unless=lambda: force,
)(view)()
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
@no_firstrun_access
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
def channel_command(self, channel):
from octoprint.server import NO_CONTENT
from octoprint.server.util.flask import get_json_command_from_request
valid_commands = {"read": ["until"], "toggle": []}
command, data, response = get_json_command_from_request(
flask.request, valid_commands=valid_commands
)
if response is not None:
return response
if command == "read":
until = data["until"]
self._mark_read_until(channel, until)
elif command == "toggle":
if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can():
flask.abort(403)
self._toggle(channel)
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["POST"])
@no_firstrun_access
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
def channels_command(self):
from octoprint.server import NO_CONTENT
from octoprint.server.util.flask import get_json_command_from_request
valid_commands = {"read": []}
command, _, response = get_json_command_from_request(
flask.request, valid_commands=valid_commands
)
if response is not None:
return response
if command == "read":
channel_data = self._fetch_all_channels()
for key, entries in channel_data.items():
if not entries:
continue
last = sorted(
self._to_internal_feed(entries),
key=lambda x: x["published"],
reverse=True,
)[0]["published"]
self._mark_read_until(key, last)
return NO_CONTENT
def is_blueprint_protected(self):
return False
def is_blueprint_csrf_protected(self):
return True
##~~ EventHandlerPlugin
def on_event(self, event, payload):
from octoprint.events import Events
if (
event != Events.CONNECTIVITY_CHANGED
or not payload
or not payload.get("new", False)
):
return
self._fetch_all_channels_async()
# Internal Tools
def _mark_read_until(self, channel, until):
"""Set read_until timestamp of a channel."""
current_read_until = None
channel_data = self._settings.get(["channels", channel], merged=True)
if channel_data:
current_read_until = channel_data.get("read_until", None)
defaults = {"plugins": {"announcements": {"channels": {}}}}
defaults["plugins"]["announcements"]["channels"][channel] = {
"read_until": current_read_until
}
with self._cached_channel_configs_mutex:
self._settings.set(
["channels", channel, "read_until"], until, defaults=defaults
)
self._settings.save()
self._cached_channel_configs = None
def _toggle(self, channel):
"""Toggle enable/disabled state of a channel."""
enabled_channels = list(self._settings.get(["enabled_channels"]))
if channel in enabled_channels:
enabled_channels.remove(channel)
else:
enabled_channels.append(channel)
self._settings.set(["enabled_channels"], enabled_channels)
self._settings.save()
def _get_channel_configs(self, force=False):
"""Retrieve all channel configs with sanitized keys."""
with self._cached_channel_configs_mutex:
if self._cached_channel_configs is None or force:
configs = self._settings.get(["channels"], merged=True)
order = self._settings.get(["channel_order"])
all_keys = order + [
key for key in sorted(configs.keys()) if key not in order
]
result = OrderedDict()
for key in all_keys:
config = configs.get(key)
if config is None or "url" not in config or "name" not in config:
# strip invalid entries
continue
result[sanitize(key)] = config
self._cached_channel_configs = result
return self._cached_channel_configs
def _get_channel_config(self, key, force=False):
"""Retrieve specific channel config for channel."""
safe_key = sanitize(key)
return self._get_channel_configs(force=force).get(safe_key)
def _fetch_all_channels_async(self, force=False):
thread = threading.Thread(
target=self._fetch_all_channels, kwargs={"force": force}
)
thread.daemon = True
thread.start()
def _fetch_all_channels(self, force=False):
"""Fetch all channel feeds from cache or network."""
channels = self._get_channel_configs(force=force)
enabled = self._settings.get(["enabled_channels"])
forced = self._settings.get(["forced_channels"])
all_channels = {}
for key, config in channels.items():
if key not in enabled and key not in forced:
continue
if "url" not in config:
continue
data = self._get_channel_data(key, config, force=force)
if data is not None:
all_channels[key] = data
return all_channels
def _get_channel_data(self, key, config, force=False):
"""Fetch individual channel feed from cache/network."""
data = None
if not force:
# we may use the cache, see if we have something in there
data = self._get_channel_data_from_cache(key, config)
if data is None:
# cache not allowed or empty, fetch from network
if self._connectivity_checker.check_immediately():
data = self._get_channel_data_from_network(key, config)
else:
self._logger.info(
"Looks like we are offline, can't fetch announcements for channel {} from network".format(
key
)
)
return data
def _get_channel_data_from_cache(self, key, config):
"""Fetch channel feed from cache."""
channel_path = self._get_channel_cache_path(key)
if os.path.exists(channel_path):
if "ttl" in config and isinstance(config["ttl"], int):
ttl = config["ttl"]
else:
ttl = self._settings.get_int(["ttl"])
ttl *= 60
now = time.time()
if now > os.stat(channel_path).st_mtime + ttl:
return None
try:
d = deserialize(channel_path)
self._logger.debug(f"Loaded channel {key} from cache at {channel_path}")
return d
except Exception:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception(
f"Could not read channel {key} from cache at {channel_path}"
)
try:
os.remove(channel_path)
except OSError:
pass
return None
def _get_channel_data_from_network(self, key, config):
"""Fetch channel feed from network."""
import requests
url = config["url"]
try:
start = time.monotonic()
r = requests.get(url, timeout=3.05)
r.raise_for_status()
self._logger.info(
"Loaded channel {} from {} in {:.2}s".format(
key, config["url"], time.monotonic() - start
)
)
except Exception:
self._logger.exception(
"Could not fetch channel {} from {}".format(key, config["url"])
)
return None
response = feedparser.parse(r.text)
try:
serialize(self._get_channel_cache_path(key), response)
except Exception:
self._logger.exception(f"Failed to cache data for channel {key}")
return response
def _to_internal_feed(self, feed, read_until=None):
"""Convert feed to internal data structure."""
result = []
if "entries" in feed:
for entry in feed["entries"]:
try:
internal_entry = self._to_internal_entry(entry, read_until=read_until)
if internal_entry:
result.append(internal_entry)
except Exception:
self._logger.exception(
"Error while converting entry from feed, skipping it"
)
return result
def _to_internal_entry(self, entry, read_until=None):
"""Convert feed entries to internal data structure."""
timestamp = entry.get("published_parsed", None)
if timestamp is None:
timestamp = entry.get("updated_parsed", None)
if timestamp is None:
return None
published = calendar.timegm(timestamp)
read = True
if read_until is not None:
read = published <= read_until
return {
"title": entry["title"],
"title_without_tags": _strip_tags(entry["title"]),
"summary": _lazy_images(entry["summary"]),
"summary_without_images": _strip_images(entry["summary"]),
"published": published,
"link": utmify(
entry["link"],
source="octoprint",
medium="announcements",
content=OCTOPRINT_VERSION,
),
"read": read,
}
def _get_channel_cache_path(self, key):
"""Retrieve cache path for channel key."""
safe_key = sanitize(key)
return os.path.join(self.get_plugin_data_folder(), f"{safe_key}.cache")
_image_tag_re = re.compile(r"<img.*?/?>")
def _strip_images(text):
"""
>>> _strip_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
"<a href='test.html'>I'm a link</a> and this is an image: "
>>> _strip_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">")
'One and two and three and four '
>>> _strip_images("No images here")
'No images here'
"""
return _image_tag_re.sub("", text)
def _replace_images(text, callback):
"""
>>> callback = lambda img: "foobar"
>>> _replace_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback)
"<a href='test.html'>I'm a link</a> and this is an image: foobar"
>>> _replace_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback)
'One foobar and two foobar and three foobar and four foobar'
"""
result = text
for match in _image_tag_re.finditer(text):
tag = match.group(0)
replaced = callback(tag)
result = result.replace(tag, replaced)
return result
_image_src_re = re.compile(r'src=(?P<quote>[\'"]*)(?P<src>.*?)(?P=quote)(?=\s+|>)')
def _lazy_images(text, placeholder=None):
"""
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png")
'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="ph.png" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png")
'One <img src="ph.png" data-src="one.jpg"> and two <img src="ph.png" data-src=\\'two.jpg\\' > and three <img src="ph.png" data-src=three.jpg> and four <img src="ph.png" data-src="four.png" alt="four">'
>>> _lazy_images("No images here")
'No images here'
"""
if placeholder is None:
# 1px transparent gif
placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
def callback(img_tag):
match = _image_src_re.search(img_tag)
if match is not None:
src = match.group("src")
quote = match.group("quote")
quoted_src = quote + src + quote
img_tag = img_tag.replace(
match.group(0), f'src="{placeholder}" data-src={quoted_src}'
)
return img_tag
return _replace_images(text, callback)
def _strip_tags(text):
"""
>>> _strip_tags("<a href='test.html'>Hello world</a><img src='foo.jpg'>")
"Hello world<img src='foo.jpg'>"
>>> _strip_tags("> > Foo")
'> > Foo'
"""
from html.parser import HTMLParser
class TagStripper(HTMLParser):
def __init__(self, **kw):
HTMLParser.__init__(self, **kw)
self._fed = []
def handle_data(self, data):
self._fed.append(data)
def handle_entityref(self, ref):
self._fed.append(f"&{ref};")
def handle_charref(self, ref):
self._fed.append(f"&#{ref};")
def get_data(self):
return "".join(self._fed)
tag_stripper = TagStripper(convert_charrefs=False)
tag_stripper.feed(text)
return tag_stripper.get_data()
__plugin_name__ = "Announcement Plugin"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Announcements all around OctoPrint"
__plugin_disabling_discouraged__ = gettext(
"Without this plugin you might miss important announcements "
"regarding security or other critical issues concerning OctoPrint."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = AnnouncementPlugin()
__plugin_hooks__ = {
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
| 23,797 | Python | .py | 547 | 31.734918 | 205 | 0.559529 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,964 | __init__.py | OctoPrint_OctoPrint/src/octoprint/plugins/action_command_prompt/__init__.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 flask
from flask_babel import gettext
import octoprint.plugin
from octoprint.access import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
class Prompt:
def __init__(self, text):
self.text = text
self.choices = []
self._active = False
@property
def active(self):
return self._active
def add_choice(self, text):
self.choices.append(text)
def activate(self):
self._active = True
def validate_choice(self, choice):
return 0 <= choice < len(self.choices)
class ActionCommandPromptPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
):
COMMAND = "M876"
CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT"
# noinspection PyMissingConstructor
def __init__(self):
self._prompt = None
self._enable = "detected"
self._command = None
self._enable_emergency_sending = True
self._enable_signal_support = True
self._cap_prompt_support = False
def initialize(self):
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(
["enable_emergency_sending"]
)
self._enable_signal_support = self._settings.get_boolean(
["enable_signal_support"]
)
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "INTERACT",
"name": "Interact with printer prompts",
"description": gettext("Allows to see and interact with printer prompts"),
"default_groups": [USER_GROUP],
"roles": ["interact"],
}
]
# ~ AssetPlugin
def get_assets(self):
return {
"js": ["js/action_command_prompt.js"],
"clientjs": ["clientjs/action_command_prompt.js"],
}
# ~ EventHandlerPlugin
def on_event(self, event, payload):
if (
event == Events.CONNECTED
and self._enable == "always"
and self._enable_signal_support
):
self._printer.commands([f"{self._command} P1"])
elif event == Events.DISCONNECTED:
self._close_prompt()
# ~ SettingsPlugin
def get_settings_defaults(self):
return {
"enable": "detected",
"command": self.COMMAND,
"enable_emergency_sending": True,
"enable_signal_support": True,
}
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(
["enable_emergency_sending"]
)
self._enable_signal_support = self._settings.get_boolean(
["enable_signal_support"]
)
# ~ SimpleApiPlugin
def get_api_commands(self):
return {"select": ["choice"]}
def on_api_command(self, command, data):
if command == "select":
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403)
if self._prompt is None:
return flask.abort(409, description="No active prompt")
choice = data["choice"]
if not isinstance(choice, int) or not self._prompt.validate_choice(choice):
return flask.abort(400, f"{choice!r} is not a valid value for choice")
self._answer_prompt(choice)
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403)
if self._prompt is None:
return flask.jsonify()
else:
return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices)
# ~ TemplatePlugin
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Printer Dialogs"),
"custom_bindings": False,
}
]
# ~ action command handler
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not action.startswith("prompt_"):
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
if action == "prompt_begin":
if self._prompt is not None and self._prompt.active:
self._logger.warning("Prompt is already defined")
return
self._prompt = Prompt(parameter.strip())
elif action == "prompt_choice" or action == "prompt_button":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._prompt.add_choice(parameter.strip())
elif action == "prompt_show":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._show_prompt()
elif action == "prompt_end":
if self._prompt is None:
return
self._close_prompt()
self._prompt = None
# ~ queuing handling
def gcode_queuing_handler(
self,
comm_instance,
phase,
cmd,
cmd_type,
gcode,
subcode=None,
tags=None,
*args,
**kwargs,
):
if gcode != self._command:
return
if (
self._enable == "never"
or (self._enable == "detected" and not self._cap_prompt_support)
or not self._enable_emergency_sending
):
return
if "S" not in cmd:
# we only force-send M876 Sx
return
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(
cmd, f"Force-sending {self._command} to the printer", gcode=gcode
)
# ~ capability reporting
def firmware_capability_handler(
self, comm_instance, capability, enabled, already_defined, *args, **kwargs
):
if capability == self.CAP_PROMPT_SUPPORT and enabled:
self._cap_prompt_support = True
if self._enable == "detected" and self._enable_signal_support:
self._printer.commands([f"{self._command} P1"])
# ~ prompt handling
def _show_prompt(self):
if self._enable == "never" or (
self._enable == "detected" and not self._cap_prompt_support
):
return
self._prompt.activate()
self._plugin_manager.send_plugin_message(
self._identifier,
{
"action": "show",
"text": self._prompt.text,
"choices": self._prompt.choices,
},
)
def _close_prompt(self):
if self._enable == "never" or (
self._enable == "detected" and not self._cap_prompt_support
):
return
self._prompt = None
self._plugin_manager.send_plugin_message(self._identifier, {"action": "close"})
def _answer_prompt(self, choice):
if self._enable == "never" or (
self._enable == "detected" and not self._cap_prompt_support
):
return
self._close_prompt()
if "{choice}" in self._command:
self._printer.commands([self._command.format(choice=choice)], force=True)
else:
self._printer.commands(
[f"{self._command} S{choice}"],
force=True,
)
__plugin_name__ = "Action Command Prompt Support"
__plugin_description__ = (
"Allows your printer to trigger prompts via action commands on the connection"
)
__plugin_author__ = "Gina Häußge"
__plugin_disabling_discouraged__ = gettext(
"Without this plugin your printer will no longer be able to trigger"
" confirmation or selection prompts in OctoPrint"
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = ActionCommandPromptPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
| 9,223 | Python | .py | 245 | 28.057143 | 107 | 0.590338 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,965 | with_attrs_docs.py | OctoPrint_OctoPrint/src/octoprint/vendor/with_attrs_docs.py | # Based on pydantic-settings version 0.2.5 by Daniel Daniels, licensed under MIT
#
# https://github.com/danields761/pydantic-settings
from typing import Type
from class_doc import extract_docs_from_cls_obj
from pydantic import BaseModel
def apply_attributes_docs(
model: Type[BaseModel], override_existing: bool = True
) -> None:
"""
Apply model attributes documentation in-place. Resulted docs are placed
inside :code:`field.schema.description` for *pydantic* model field.
:param model: any pydantic model
:param override_existing: override existing descriptions
"""
docs = extract_docs_from_cls_obj(model)
for field in model.__fields__.values():
if field.field_info.description and not override_existing:
continue
try:
field.field_info.description = '\n'.join(docs[field.name])
except KeyError:
pass
def with_attrs_docs(
model_cls: Type[BaseModel]
) -> Type[BaseModel]:
"""
Applies :py:func:`.apply_attributes_docs`.
"""
def decorator(maybe_model_cls: Type[BaseModel]) -> Type[BaseModel]:
apply_attributes_docs(
maybe_model_cls
)
return maybe_model_cls
return decorator(model_cls)
| 1,249 | Python | .py | 35 | 29.942857 | 80 | 0.69186 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,966 | flask_principal.py | OctoPrint_OctoPrint/src/octoprint/vendor/flask_principal.py | # -*- coding: utf-8 -*-
"""
flask_principal
~~~~~~~~~~~~~~~
Identity management for Flask.
:copyright: (c) 2012 by Ali Afshar.
:license: MIT, see LICENSE for more details.
"""
from __future__ import with_statement
__version__ = '0.4.0'
import sys
from collections import deque, namedtuple
from functools import partial, wraps
from flask import abort, current_app, g, request, session
from flask.signals import Namespace
PY3 = sys.version_info[0] == 3
signals = Namespace()
identity_changed = signals.signal('identity-changed', doc="""
Signal sent when the identity for a request has been changed.
Actual name: ``identity-changed``
Authentication providers should send this signal when authentication has been
successfully performed. Flask-Principal connects to this signal and
causes the identity to be saved in the session.
For example::
from flaskext.principal import Identity, identity_changed
def login_view(req):
username = req.form.get('username')
# check the credentials
identity_changed.send(app, identity=Identity(username))
""")
identity_loaded = signals.signal('identity-loaded', doc="""
Signal sent when the identity has been initialised for a request.
Actual name: ``identity-loaded``
Identity information providers should connect to this signal to perform two
major activities:
1. Populate the identity object with the necessary authorization provisions.
2. Load any additional user information.
For example::
from flaskext.principal import identity_loaded, RoleNeed, UserNeed
@identity_loaded.connect
def on_identity_loaded(sender, identity):
# Get the user information from the db
user = db.get(identity.name)
# Update the roles that a user can provide
for role in user.roles:
identity.provides.add(RoleNeed(role.name))
# Save the user somewhere so we only look it up once
identity.user = user
""")
Need = namedtuple('Need', ['method', 'value'])
"""A required need
This is just a named tuple, and practically any tuple will do.
The ``method`` attribute can be used to look up element 0, and the ``value``
attribute can be used to look up element 1.
"""
UserNeed = partial(Need, 'id')
UserNeed.__doc__ = """A need with the method preset to `"id"`."""
RoleNeed = partial(Need, 'role')
RoleNeed.__doc__ = """A need with the method preset to `"role"`."""
TypeNeed = partial(Need, 'type')
TypeNeed.__doc__ = """A need with the method preset to `"type"`."""
ActionNeed = partial(Need, 'action')
TypeNeed.__doc__ = """A need with the method preset to `"action"`."""
ItemNeed = namedtuple('ItemNeed', ['method', 'value', 'type'])
"""A required item need
An item need is just a named tuple, and practically any tuple will do. In
addition to other Needs, there is a type, for example this could be specified
as::
ItemNeed('update', 27, 'posts')
('update', 27, 'posts') # or like this
And that might describe the permission to update a particular blog post. In
reality, the developer is free to choose whatever convention the permissions
are.
"""
class PermissionDenied(RuntimeError):
"""Permission denied to the resource"""
class Identity(object):
"""Represent the user's identity.
:param id: The user id
:param auth_type: The authentication type used to confirm the user's
identity.
The identity is used to represent the user's identity in the system. This
object is created on login, or on the start of the request as loaded from
the user's session.
Once loaded it is sent using the `identity-loaded` signal, and should be
populated with additional required information.
Needs that are provided by this identity should be added to the `provides`
set after loading.
"""
def __init__(self, id, auth_type=None):
self.id = id
self.auth_type = auth_type
self.provides = set()
def can(self, permission):
"""Whether the identity has access to the permission.
:param permission: The permission to test provision for.
"""
return permission.allows(self)
def __repr__(self):
return '<{0} id="{1}" auth_type="{2}" provides={3}>'.format(
self.__class__.__name__, self.id, self.auth_type, self.provides
)
class AnonymousIdentity(Identity):
"""An anonymous identity"""
def __init__(self):
Identity.__init__(self, None)
class IdentityContext(object):
"""The context of an identity for a permission.
.. note:: The principal is usually created by the flaskext.Permission.require method
call for normal use-cases.
The principal behaves as either a context manager or a decorator. The
permission is checked for provision in the identity, and if available the
flow is continued (context manager) or the function is executed (decorator).
"""
def __init__(self, permission, http_exception=None):
self.permission = permission
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
"""
return self.identity.can(self.permission)
def __call__(self, f):
@wraps(f)
def _decorated(*args, **kw):
with self:
rv = f(*args, **kw)
return rv
return _decorated
def __enter__(self):
# check the permission here
if not self.can():
if self.http_exception:
abort(self.http_exception)
raise PermissionDenied(self.permission)
def __exit__(self, *args):
return False
class Permission(object):
"""Represents needs, any of which must be present to access a resource
:param needs: The needs for this permission
"""
def __init__(self, *needs):
"""A set of needs, any of which must be present in an identity to have
access.
"""
self.needs = set(needs)
self.excludes = set()
def _bool(self):
return bool(self.can())
def __nonzero__(self):
"""Equivalent to ``self.can()``.
"""
return self._bool()
def __bool__(self):
"""Equivalent to ``self.can()``.
"""
return self._bool()
def __and__(self, other):
"""Does the same thing as ``self.union(other)``
"""
return self.union(other)
def __or__(self, other):
"""Does the same thing as ``self.difference(other)``
"""
return self.difference(other)
def __contains__(self, other):
"""Does the same thing as ``other.issubset(self)``.
"""
return other.issubset(self)
def __repr__(self):
return '<{0} needs={1} excludes={2}>'.format(
self.__class__.__name__, self.needs, self.excludes
)
def require(self, http_exception=None):
"""Create a principal for this permission.
The principal may be used as a context manager, or a decroator.
If ``http_exception`` is passed then ``abort()`` will be called
with the HTTP exception code. Otherwise a ``PermissionDenied``
exception will be raised if the identity does not meet the
requirements.
:param http_exception: the HTTP exception code (403, 401 etc)
"""
return IdentityContext(self, http_exception)
def test(self, http_exception=None):
"""
Checks if permission available and raises relevant exception
if not. This is useful if you just want to check permission
without wrapping everything in a require() block.
This is equivalent to::
with permission.require():
pass
"""
with self.require(http_exception):
pass
def reverse(self):
"""
Returns reverse of current state (needs->excludes, excludes->needs)
"""
p = Permission()
p.needs.update(self.excludes)
p.excludes.update(self.needs)
return p
def union(self, other):
"""Create a new permission with the requirements of the union of this
and other.
:param other: The other permission
"""
p = Permission(*self.needs.union(other.needs))
p.excludes.update(self.excludes.union(other.excludes))
return p
def difference(self, other):
"""Create a new permission consisting of requirements in this
permission and not in the other.
"""
p = Permission(*self.needs.difference(other.needs))
p.excludes.update(self.excludes.difference(other.excludes))
return p
def issubset(self, other):
"""Whether this permission needs are a subset of another
:param other: The other permission
"""
return (
self.needs.issubset(other.needs) and
self.excludes.issubset(other.excludes)
)
def allows(self, identity):
"""Whether the identity can access this permission.
:param identity: The identity
"""
if self.needs and not self.needs.intersection(identity.provides):
return False
if self.excludes and self.excludes.intersection(identity.provides):
return False
return True
def can(self):
"""Whether the required context for this permission has access
This creates an identity context and tests whether it can access this
permission
"""
return self.require().can()
class Denial(Permission):
"""
Shortcut class for passing excluded needs.
"""
def __init__(self, *excludes):
self.excludes = set(excludes)
self.needs = set()
def session_identity_loader():
if 'identity.id' in session and 'identity.auth_type' in session:
identity = Identity(session['identity.id'],
session['identity.auth_type'])
return identity
def session_identity_saver(identity):
session['identity.id'] = identity.id
session['identity.auth_type'] = identity.auth_type
session.modified = True
class Principal(object):
"""Principal extension
:param app: The flask application to extend
:param use_sessions: Whether to use sessions to extract and store
identification.
:param skip_static: Whether to ignore static endpoints.
"""
def __init__(self, app=None, use_sessions=True, skip_static=False, anonymous_identity=AnonymousIdentity):
self.identity_loaders = deque()
self.identity_savers = deque()
self.anonymous_identity = anonymous_identity
# XXX This will probably vanish for a better API
self.use_sessions = use_sessions
self.skip_static = skip_static
if app is not None:
self.init_app(app)
def _init_app(self, app):
from warnings import warn
warn(DeprecationWarning(
'_init_app is deprecated, use the new init_app '
'method instead.'), stacklevel=1
)
self.init_app(app)
def init_app(self, app):
if hasattr(app, 'static_url_path'):
self._static_path = app.static_url_path
else:
self._static_path = app.static_path
app.before_request(self._on_before_request)
identity_changed.connect(self._on_identity_changed, app)
if self.use_sessions:
self.identity_loader(session_identity_loader)
self.identity_saver(session_identity_saver)
def set_identity(self, identity):
"""Set the current identity.
:param identity: The identity to set
"""
self._set_thread_identity(identity)
for saver in self.identity_savers:
saver(identity)
def identity_loader(self, f):
"""Decorator to define a function as an identity loader.
An identity loader function is called before request to find any
provided identities. The first found identity is used to load from.
For example::
app = Flask(__name__)
principals = Principal(app)
@principals.identity_loader
def load_identity_from_weird_usecase():
return Identity('ali')
"""
self.identity_loaders.appendleft(f)
return f
def identity_saver(self, f):
"""Decorator to define a function as an identity saver.
An identity loader saver is called when the identity is set to persist
it for the next request.
For example::
app = Flask(__name__)
principals = Principal(app)
@principals.identity_saver
def save_identity_to_weird_usecase(identity):
my_special_cookie['identity'] = identity
"""
self.identity_savers.appendleft(f)
return f
def _set_thread_identity(self, identity):
g.identity = identity
identity_loaded.send(current_app._get_current_object(),
identity=identity)
def _on_identity_changed(self, app, identity):
if self._is_static_route():
return
self.set_identity(identity)
def _on_before_request(self):
if self._is_static_route():
return
g.identity = self.anonymous_identity()
for loader in self.identity_loaders:
identity = loader()
if identity is not None:
self.set_identity(identity)
return
def _is_static_route(self):
return (
self.skip_static and
request.path.startswith(self._static_path)
)
| 13,915 | Python | .py | 350 | 31.922857 | 109 | 0.643288 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,967 | __init__.py | OctoPrint_OctoPrint/src/octoprint/vendor/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals | 106 | Python | .py | 2 | 52.5 | 82 | 0.72381 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,968 | imp.py | OctoPrint_OctoPrint/src/octoprint/vendor/imp.py | """This module provides the components needed to build your own __import__
function. Undocumented functions are obsolete.
In most cases it is preferred you consider using the importlib module's
functionality over this module.
Taken from CPython 3.7.0 and vendored to still have it when it gets
completely removed.
Licensed under the PSF LICENSE AGREEMENT <https://docs.python.org/3/license.html>
"""
# (Probably) need to stay in _imp
# noinspection PyCompatibility
from _imp import (lock_held, acquire_lock, release_lock,
get_frozen_object, is_frozen_package,
init_frozen, is_builtin, is_frozen,
_fix_co_filename)
try:
# noinspection PyCompatibility
from _imp import create_dynamic
except ImportError:
# Platform doesn't support dynamic loading.
create_dynamic = None
# noinspection PyCompatibility,PyProtectedMember
from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
# noinspection PyCompatibility,PyProtectedMember
from importlib._bootstrap_external import SourcelessFileLoader
# noinspection PyCompatibility
from importlib import machinery
# noinspection PyCompatibility
from importlib import util
import importlib
import os
import sys
import tokenize
import types
import warnings
SEARCH_ERROR = 0
PY_SOURCE = 1
PY_COMPILED = 2
C_EXTENSION = 3
PY_RESOURCE = 4
PKG_DIRECTORY = 5
C_BUILTIN = 6
PY_FROZEN = 7
PY_CODERESOURCE = 8
IMP_HOOK = 9
def new_module(name):
"""Create a new module.
The module is not entered into sys.modules.
"""
# noinspection PyUnresolvedReferences
return types.ModuleType(name)
def get_magic():
"""Return the magic number for .pyc files.
"""
return util.MAGIC_NUMBER
def get_tag():
"""Return the magic tag for .pyc files."""
return sys.implementation.cache_tag
def cache_from_source(path, debug_override=None):
"""Given the path to a .py file, return the path to its .pyc file.
The .py file does not need to exist; this simply returns the path to the
.pyc file calculated as if the .py file were imported.
If debug_override is not None, then it must be a boolean and is used in
place of sys.flags.optimize.
If sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return util.cache_from_source(path, debug_override)
def source_from_cache(path):
"""Given the path to a .pyc. file, return the path to its .py file.
The .pyc file does not need to exist; this simply returns the path to
the .py file calculated to correspond to the .pyc file. If path does
not conform to PEP 3147 format, ValueError will be raised. If
sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
return util.source_from_cache(path)
def get_suffixes():
extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
return extensions + source + bytecode
class NullImporter:
"""Null import object."""
def __init__(self, path):
if path == '':
raise ImportError('empty pathname', path='')
elif os.path.isdir(path):
raise ImportError('existing directory', path=path)
def find_module(self, fullname):
"""Always returns None."""
return None
# noinspection PyCompatibility,PyUnresolvedReferences
class _HackedGetData:
"""Compatibility support for 'file' arguments of various load_*()
functions."""
def __init__(self, fullname, path, file=None):
super().__init__(fullname, path)
self.file = file
def get_data(self, path):
"""Gross hack to contort loader to deal w/ load_*()'s bad API."""
if self.file and path == self.path:
if not self.file.closed:
file = self.file
else:
self.file = file = open(self.path, 'r')
with file:
# Technically should be returning bytes, but
# SourceLoader.get_code() just passed what is returned to
# compile() which can handle str. And converting to bytes would
# require figuring out the encoding to decode to and
# tokenize.detect_encoding() only accepts bytes.
return file.read()
else:
return super().get_data(path)
class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
"""Compatibility support for implementing load_source()."""
def load_source(name, pathname, file=None):
loader = _LoadSourceCompatibility(name, pathname, file)
spec = util.spec_from_file_location(name, pathname, loader=loader)
if name in sys.modules:
module = _exec(spec, sys.modules[name])
else:
module = _load(spec)
# To allow reloading to potentially work, use a non-hacked loader which
# won't rely on a now-closed file object.
module.__loader__ = machinery.SourceFileLoader(name, pathname)
module.__spec__.loader = module.__loader__
return module
class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
"""Compatibility support for implementing load_compiled()."""
def load_compiled(name, pathname, file=None):
"""**DEPRECATED**"""
loader = _LoadCompiledCompatibility(name, pathname, file)
spec = util.spec_from_file_location(name, pathname, loader=loader)
if name in sys.modules:
module = _exec(spec, sys.modules[name])
else:
module = _load(spec)
# To allow reloading to potentially work, use a non-hacked loader which
# won't rely on a now-closed file object.
module.__loader__ = SourcelessFileLoader(name, pathname)
module.__spec__.loader = module.__loader__
return module
def load_package(name, path):
if os.path.isdir(path):
extensions = (machinery.SOURCE_SUFFIXES[:] +
machinery.BYTECODE_SUFFIXES[:])
for extension in extensions:
init_path = os.path.join(path, '__init__' + extension)
if os.path.exists(init_path):
path = init_path
break
else:
raise ValueError('{!r} is not a package'.format(path))
spec = util.spec_from_file_location(name, path,
submodule_search_locations=[])
if name in sys.modules:
return _exec(spec, sys.modules[name])
else:
return _load(spec)
def load_module(name, file, filename, details):
"""Load a module, given information returned by find_module().
The module name must include the full package name, if any.
"""
suffix, mode, type_ = details
if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
raise ValueError('invalid file open mode {!r}'.format(mode))
elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
msg = 'file object required for import (type code {})'.format(type_)
raise ValueError(msg)
elif type_ == PY_SOURCE:
return load_source(name, filename, file)
elif type_ == PY_COMPILED:
return load_compiled(name, filename, file)
elif type_ == C_EXTENSION and load_dynamic is not None:
if file is None:
with open(filename, 'rb') as opened_file:
return load_dynamic(name, filename, opened_file)
else:
return load_dynamic(name, filename, file)
elif type_ == PKG_DIRECTORY:
return load_package(name, filename)
elif type_ == C_BUILTIN:
return init_builtin(name)
elif type_ == PY_FROZEN:
return init_frozen(name)
else:
msg = "Don't know how to import {} (type code {})".format(name, type_)
raise ImportError(msg, name=name)
def find_module(name, path=None):
"""Search for a module.
If path is omitted or None, search for a built-in, frozen or special
module and continue search in sys.path. The module name cannot
contain '.'; to search for a submodule of a package, pass the
submodule name and the package's __path__.
"""
if not isinstance(name, str):
raise TypeError("'name' must be a str, not {}".format(type(name)))
elif not isinstance(path, (type(None), list)):
# Backwards-compatibility
raise RuntimeError("'path' must be None or a list, "
"not {}".format(type(path)))
if path is None:
if is_builtin(name):
return None, None, ('', '', C_BUILTIN)
elif is_frozen(name):
return None, None, ('', '', PY_FROZEN)
else:
path = sys.path
for entry in path:
package_directory = os.path.join(entry, name)
for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
package_file_name = '__init__' + suffix
file_path = os.path.join(package_directory, package_file_name)
if os.path.isfile(file_path):
return None, package_directory, ('', '', PKG_DIRECTORY)
for suffix, mode, type_ in get_suffixes():
file_name = name + suffix
file_path = os.path.join(entry, file_name)
if os.path.isfile(file_path):
break
else:
continue
break # Break out of outer loop when breaking out of inner loop.
else:
raise ImportError(_ERR_MSG.format(name), name=name)
encoding = None
if 'b' not in mode:
with open(file_path, 'rb') as file:
encoding = tokenize.detect_encoding(file.readline)[0]
file = open(file_path, mode, encoding=encoding)
return file, file_path, (suffix, mode, type_)
def reload(module):
"""Reload the module and return it.
The module must have been successfully imported before.
"""
return importlib.reload(module)
def init_builtin(name):
"""Load and return a built-in module by name, or None is such module doesn't exist"""
try:
return _builtin_from_name(name)
except ImportError:
return None
if create_dynamic:
def load_dynamic(name, path, file=None):
"""Load an extension module."""
import importlib.machinery
loader = importlib.machinery.ExtensionFileLoader(name, path)
# Issue #24748: Skip the sys.modules check in _load_module_shim;
# always load new extension
spec = importlib.machinery.ModuleSpec(
name=name, loader=loader, origin=path)
return _load(spec)
else:
load_dynamic = None
| 10,684 | Python | .py | 255 | 34.858824 | 89 | 0.660873 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,969 | alt_translates.py | OctoPrint_OctoPrint/src/octoprint/vendor/awesome_slugify/alt_translates.py | # coding=utf8
CYRILLIC = { # instead of:
u'ё': u'e', # io / yo
u'у': u'y', # u
u'х': u'h', # kh
u'щ': u'sch', # shch
u'ю': u'u', # iu / yu
u'я': u'ya', # ia
}
GERMAN = { # instead of:
u'ä': u'ae', # a
u'ö': u'oe', # o
u'ü': u'ue', # u
}
GREEK = { # instead of:
u'Ξ': u'X', # Ks
u'χ': u'ch', # kh
u'ϒ': u'Y', # U
u'υ': u'y', # u
u'ύ': u'y', # ...
u'ϋ': u'y',
u'ΰ': u'y',
}
| 514 | Python | .py | 23 | 17.695652 | 32 | 0.324841 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,970 | __init__.py | OctoPrint_OctoPrint/src/octoprint/vendor/awesome_slugify/__init__.py |
from .main import Slugify, UniqueSlugify
from .alt_translates import *
slugify = Slugify()
unique_slugify = UniqueSlugify()
slugify_unicode = Slugify(translate=None)
slugify_url = Slugify()
slugify_url.to_lower = True
slugify_url.stop_words = ('a', 'an', 'the')
slugify_url.max_length = 200
slugify_filename = Slugify()
slugify_filename.separator = '_'
slugify_filename.safe_chars = '-.'
slugify_filename.max_length = 255
slugify_ru = Slugify(pretranslate=CYRILLIC)
slugify_de = Slugify(pretranslate=GERMAN)
slugify_el = Slugify(pretranslate=GREEK)
# Legacy code
def deprecate_init(Klass):
class NewKlass(Klass):
def __init__(self, *args, **kwargs):
import warnings
warnings.simplefilter('once')
warnings.warn("'slugify.get_slugify' is deprecated; use 'slugify.Slugify' instead.",
DeprecationWarning, stacklevel=2)
super(NewKlass, self).__init__(*args, **kwargs)
return NewKlass
# get_slugify was deprecated in 2014, march 31
get_slugify = deprecate_init(Slugify)
| 1,063 | Python | .py | 28 | 33.428571 | 96 | 0.710526 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,971 | main.py | OctoPrint_OctoPrint/src/octoprint/vendor/awesome_slugify/main.py | # coding=utf8
import sys
from unidecode import unidecode
import regex as re
# Don't set regex.DEFAULT_VERSION to regex.VERSION1 cause
# this option will influence on 3rd party libs. E.g. `mailgun` and `flanker`.
# Use regex.VERSION1 regex flag.
# re.VERSION1 - New enhanced behaviour with nested sets and set operations
if sys.version_info[0] == 2:
str_type = unicode # Python 2
else:
str_type = str # Python 3
def join_words(words, separator, max_length=None):
"""
words - iterator or list
"""
if not max_length:
return separator.join(words)
words = iter(words) # List to Generator
try:
text = next(words)
except StopIteration:
return u''
for word in words:
if len(text + separator + word) <= max_length:
text += separator + word
return text[:max_length]
# uppercase letters to translate to uppercase letters, NOT camelcase
UPPER_TO_UPPER_LETTERS_RE = \
r'''
(
\p{Uppercase_Letter} {2,} # 2 or more adjacent letters - UP always
|
\p{Uppercase_Letter} # target one uppercase letter, then
(?=
[^\p{Lowercase_Letter}…\p{Term}--,،﹐,]+ # not chars breaks possible UP (…abc.?!:;)
\p{Uppercase_Letter} {2} # and 2 uppercase letters
)
|
(?<=
\p{Uppercase_Letter} {2} # 2 uppercase letters
[^\p{Lowercase_Letter}…\p{Term}--,،﹐,]+ # not chars breaks possible UP (…abc.?!:;), then
)
\p{Uppercase_Letter} # target one uppercase letter, then
(?!
\p{Lowercase_Letter} # not lowercase letter
|
[…\p{Term}--,،﹐,]\p{Uppercase_Letter} # and not dot (.?…!:;) with uppercase letter
)
)
'''
class Slugify(object):
upper_to_upper_letters_re = re.compile(UPPER_TO_UPPER_LETTERS_RE, re.VERBOSE | re.VERSION1)
_safe_chars = ''
_stop_words = ()
def __init__(self, pretranslate=None, translate=unidecode, safe_chars='', stop_words=(),
to_lower=False, max_length=None, separator=u'-', capitalize=False,
fold_abbrs=False):
self.pretranslate = pretranslate
self.translate = translate
self.safe_chars = safe_chars
self.stop_words = stop_words
self.to_lower = to_lower
self.max_length = max_length
self.separator = separator
self.capitalize = capitalize
self.fold_abbrs = fold_abbrs
def pretranslate_dict_to_function(self, convert_dict):
# add uppercase letters
for letter, translation in list(convert_dict.items()):
letter_upper = letter.upper()
if letter_upper != letter and letter_upper not in convert_dict:
convert_dict[letter_upper] = translation.capitalize()
self.convert_dict = convert_dict
PRETRANSLATE = re.compile(r'(\L<options>)', options=convert_dict)
# translate some letters before translating
return lambda text: PRETRANSLATE.sub(lambda m: convert_dict[m.group(1)], text)
def set_pretranslate(self, pretranslate):
if isinstance(pretranslate, dict):
pretranslate = self.pretranslate_dict_to_function(pretranslate)
elif pretranslate is None:
pretranslate = lambda text: text
elif not callable(pretranslate):
error_message = u"Keyword argument 'pretranslate' must be dict, None or callable. Not {0.__class__.__name__}".format(pretranslate)
raise ValueError(error_message)
self._pretranslate = pretranslate
pretranslate = property(fset=set_pretranslate)
def set_translate(self, func):
if func:
self._translate = func
else:
self._translate = lambda text: text
translate = property(fset=set_translate)
def set_safe_chars(self, safe_chars):
self._safe_chars = safe_chars
self.apostrophe_is_not_safe = "'" not in safe_chars
self.calc_unwanted_chars_re()
safe_chars = property(fset=set_safe_chars)
def set_stop_words(self, stop_words):
self._stop_words = tuple(stop_words)
self.calc_unwanted_chars_re()
stop_words = property(fset=set_stop_words)
def calc_unwanted_chars_re(self):
unwanted_chars_re = r'[^\p{{AlNum}}{safe_chars}]+'.format(safe_chars=re.escape(self._safe_chars or ''))
self.unwanted_chars_re = re.compile(unwanted_chars_re, re.IGNORECASE)
if self._stop_words:
unwanted_chars_and_words_re = unwanted_chars_re + r'|(?<!\p{AlNum})(?:\L<stop_words>)(?!\p{AlNum})'
self.unwanted_chars_and_words_re = re.compile(unwanted_chars_and_words_re, re.IGNORECASE, stop_words=self._stop_words)
else:
self.unwanted_chars_and_words_re = None
def sanitize(self, text):
if self.apostrophe_is_not_safe:
text = text.replace("'", '').strip() # remove '
if self.unwanted_chars_and_words_re:
words = [word for word in self.unwanted_chars_and_words_re.split(text) if word]
if words:
return words
words = filter(None, self.unwanted_chars_re.split(text))
return words
def __call__(self, text, **kwargs):
max_length = kwargs.get('max_length', self.max_length)
separator = kwargs.get('separator', self.separator)
if not isinstance(text, str_type):
text = text.decode('utf8', 'ignore')
if kwargs.get('fold_abbrs', self.fold_abbrs):
text = re.sub(r'(?<![\p{Letter}.])((?:\p{Letter}\.){2,})', lambda x: x.group(0).replace('.', ''), text)
if kwargs.get('to_lower', self.to_lower):
text = self._pretranslate(text)
text = self._translate(text)
text = text.lower()
else:
text_parts = self.upper_to_upper_letters_re.split(text)
for position, text_part in enumerate(text_parts):
text_part = self._pretranslate(text_part)
text_part = self._translate(text_part)
if position % 2:
text_part = text_part.upper()
text_parts[position] = text_part
text = u''.join(text_parts)
words = self.sanitize(text)
text = join_words(words, separator, max_length)
if text and kwargs.get('capitalize', self.capitalize):
text = text[0].upper() + text[1:]
return text
class UniqueSlugify(Slugify):
"""
Manage unique slugified ids
"""
def __init__(self, *args, **kwargs):
# don't declare uids in args to avoid problem if someone uses positional arguments on initialization
self.uids = kwargs.pop('uids', set())
if isinstance(self.uids, list):
self.uids = set(self.uids)
self.unique_check = kwargs.pop(
"unique_check",
lambda text, uids: self.default_unique_check(text, uids)
)
super(UniqueSlugify, self).__init__(*args, **kwargs)
def __call__(self, text, **kwargs):
# get slugified text
text = super(UniqueSlugify, self).__call__(text, **kwargs)
count = 0
newtext = text
separator = kwargs.get('separator', self.separator)
while not self.unique_check(newtext, self.uids):
count += 1
newtext = "%s%s%d" % (text, separator, count)
self.uids.add(newtext)
return newtext
def default_unique_check(self, text, uids):
return text not in uids
# \p{SB=AT} = '.․﹒.'
# \p{SB=ST} = '!?՜՞։؟۔܀܁܂߹।॥၊။።፧፨᙮᜵᜶‼‽⁇⁈⁉⸮。꓿꘎꘏꤯﹖﹗!?。'
# \p{Term} = '!,.:;?;·։׃،؛؟۔܀܁܂܃܄܅܆܇܈܉܊܌߸߹।॥๚๛༈།༎༏༐༑༒၊။፡።፣፤፥፦፧፨᙭᙮᛫᛬᛭។៕៖៚‼‽⁇⁈⁉⸮、。꓾꓿꘍꘎꘏꤯﹐﹑﹒﹔﹕﹖﹗!,.:;?。、'
# \p{Sterm} = '! . ?՜՞։؟܀ ܁ ܂߹।॥၊။ ።፧፨ ᙮᜵᜶ ‼‽⁇⁈⁉⸮ 。 ꓿ ꘎꘏꤯﹒ ﹖﹗!. ?。'
# \p{SB=AT} = .
# \p{SB=ST} = ! ?
# \p{Term} = . ! ? , : ;
# \p{Sterm} = . ! ?
# \u002c - Latin comma
# \u060c - Arabic comma
# \ufe50 - Small comma
# \uff0c - Fullwidth comma
# […\p{Term}--,،﹐,] - ellipsis + Terms - commas
| 8,614 | Python | .py | 184 | 36.168478 | 142 | 0.570986 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,972 | __init__.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
| 270 | Python | .py | 7 | 36.571429 | 82 | 0.698473 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,973 | periodic.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/periodic.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.periodic
~~~~~~~~~~~~~~~~~~~~~~~
This module implements customized PeriodicCallback from tornado with
support of the sliding window.
"""
import time
import logging
LOG = logging.getLogger("tornado.general")
class Callback(object):
"""Custom implementation of the Tornado.Callback with support
of callback timeout delays.
"""
def __init__(self, callback, callback_time, io_loop):
"""Constructor.
`callback`
Callback function
`callback_time`
Callback timeout value (in milliseconds)
`io_loop`
io_loop instance
"""
self.callback = callback
self.callback_time = callback_time
self.io_loop = io_loop
self._running = False
self.next_run = None
def calculate_next_run(self):
"""Caltulate next scheduled run"""
return time.time() + self.callback_time / 1000
def start(self, timeout=None):
"""Start callbacks"""
self._running = True
if timeout is None:
timeout = self.calculate_next_run()
self.io_loop.add_timeout(timeout, self._run)
def stop(self):
"""Stop callbacks"""
self._running = False
def delay(self):
"""Delay callback"""
self.next_run = self.calculate_next_run()
def _run(self):
if not self._running:
return
# Support for shifting callback window
if self.next_run is not None and time.time() < self.next_run:
self.start(self.next_run)
self.next_run = None
return
next_call = None
try:
next_call = self.callback()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
LOG.error("Error in periodic callback", exc_info=True)
if self._running:
self.start(next_call)
| 2,036 | Python | .py | 61 | 25.213115 | 82 | 0.602656 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,974 | util.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/util.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import functools
import sys
PY3 = sys.version_info[0] == 3
from past.builtins import unicode
if PY3:
MAXSIZE = sys.maxsize
def bytes_to_str(b):
if isinstance(b, bytes):
return b.decode('utf8')
return b
def str_to_bytes(s):
if isinstance(s, bytes):
return s
return s.encode('utf8')
import urllib.parse
unquote_plus = urllib.parse.unquote_plus
else:
if sys.platform == "java":
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31
try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1)
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1)
del X
def bytes_to_str(s):
if isinstance(s, bytes):
return s.decode('utf-8')
return s
def str_to_bytes(s):
if isinstance(s, unicode):
return s.encode('utf8')
return s
import urllib
unquote_plus = urllib.unquote_plus
def no_auto_finish(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
self._auto_finish = False
return method(self, *args, **kwargs)
return wrapper
def get_current_ioloop():
import asyncio
from tornado.ioloop import IOLoop
try:
loop = asyncio.get_running_loop()
return IOLoop._ioloop_for_asyncio.get(loop)
except RuntimeError:
# no current loop
return None
| 1,771 | Python | .py | 61 | 21.42623 | 82 | 0.577581 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,975 | sessioncontainer.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/sessioncontainer.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.sessioncontainer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simple heapq-based session implementation with sliding expiration window
support.
"""
from heapq import heappush, heappop
from time import time
from hashlib import md5
from random import random
def _random_key():
"""Return random session key"""
i = md5()
i.update('%s%s' % (random(), time()))
return i.hexdigest()
class SessionMixin(object):
"""Represents one session object stored in the session container.
Derive from this object to store additional data.
"""
def __init__(self, session_id=None, expiry=None):
"""Constructor.
``session_id``
Optional session id. If not provided, will generate
new session id.
``expiry``
Expiration time. If not provided, will never expire.
"""
self.session_id = session_id or _random_key()
self.promoted = None
self.expiry = expiry
if self.expiry is not None:
self.expiry_date = time() + self.expiry
def is_alive(self):
"""Check if session is still alive"""
return self.expiry_date > time()
def promote(self):
"""Mark object as alive, so it won't be collected during next
run of the garbage collector.
"""
if self.expiry is not None:
self.promoted = time() + self.expiry
def on_delete(self, forced):
"""Triggered when object was expired or deleted."""
pass
def __lt__(self, other):
return self.expiry_date < other.expiry_date
__cmp__ = __lt__
def __repr__(self):
return '%f %s %d' % (getattr(self, 'expiry_date', -1),
self.session_id,
self.promoted or 0)
class SessionContainer(object):
"""Session container object.
If we will implement sessions with Tornado timeouts, for polling transports
it will be nightmare - if load will be high, number of discarded timeouts
will be huge and will be huge performance hit, as Tornado will have to
clean them up all the time.
"""
def __init__(self):
self._items = {}
self._queue = []
def add(self, session):
"""Add session to the container.
`session`
Session object
"""
self._items[session.session_id] = session
if session.expiry is not None:
heappush(self._queue, session)
def get(self, session_id):
"""Return session object or None if it is not available
`session_id`
Session identifier
"""
return self._items.get(session_id, None)
def remove(self, session_id):
"""Remove session object from the container
`session_id`
Session identifier
"""
session = self._items.get(session_id, None)
if session is not None:
session.promoted = -1
session.on_delete(True)
del self._items[session_id]
return True
return False
def expire(self, current_time=None):
"""Expire any old entries
`current_time`
Optional time to be used to clean up queue (can be used in unit tests)
"""
if not self._queue:
return
if current_time is None:
current_time = time()
while self._queue:
# Get top most item
top = self._queue[0]
# Early exit if item was not promoted and its expiration time
# is greater than now.
if top.promoted is None and top.expiry_date > current_time:
break
# Pop item from the stack
top = heappop(self._queue)
need_reschedule = (top.promoted is not None
and top.promoted > current_time)
# Give chance to reschedule
if not need_reschedule:
top.promoted = None
top.on_delete(False)
need_reschedule = (top.promoted is not None
and top.promoted > current_time)
# If item is promoted and expiration time somewhere in future
# just reschedule it
if need_reschedule:
top.expiry_date = top.promoted
top.promoted = None
heappush(self._queue, top)
else:
del self._items[top.session_id]
| 4,616 | Python | .py | 123 | 27.601626 | 82 | 0.578522 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,976 | basehandler.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/basehandler.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.basehandler
~~~~~~~~~~~~~~~~~~~~~~~~~~
Various base http handlers
"""
import datetime
import socket
import logging
from tornado.web import RequestHandler
from tornado.gen import coroutine
from urllib.parse import urlparse
CACHE_TIME = 31536000
LOG = logging.getLogger("tornado.general")
class BaseHandler(RequestHandler):
"""Base request handler with set of helpers."""
def initialize(self, server):
"""Initialize request
`server`
SockJSRouter instance.
"""
self.server = server
self.logged = False
# Statistics
def prepare(self):
"""Increment connection count"""
self.logged = True
self.server.stats.on_conn_opened()
def _log_disconnect(self):
"""Decrement connection count"""
if self.logged:
self.server.stats.on_conn_closed()
self.logged = False
def finish(self, chunk=None):
"""Tornado `finish` handler"""
self._log_disconnect()
super(BaseHandler, self).finish(chunk)
def on_connection_close(self):
"""Tornado `on_connection_close` handler"""
self._log_disconnect()
# Various helpers
def enable_cache(self):
"""Enable client-side caching for the current request"""
self.set_header('Cache-Control', 'max-age=%d, public' % CACHE_TIME)
d = datetime.datetime.now() + datetime.timedelta(seconds=CACHE_TIME)
self.set_header('Expires', d.strftime('%a, %d %b %Y %H:%M:%S'))
self.set_header('access-control-max-age', CACHE_TIME)
def disable_cache(self):
"""Disable client-side cache for the current request"""
self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
def handle_session_cookie(self):
"""Handle JSESSIONID cookie logic"""
# If JSESSIONID support is disabled in the settings, ignore cookie logic
if not self.server.settings['jsessionid']:
return
cookie = self.cookies.get('JSESSIONID')
if not cookie:
cv = 'dummy'
else:
cv = cookie.value
self.set_cookie('JSESSIONID', cv)
def safe_finish(self):
"""Finish session. If it will blow up - connection was set to Keep-Alive and
client dropped connection, ignore any IOError or socket error."""
try:
self.finish()
except (socket.error, IOError):
# We don't want to raise IOError exception if finish() call fails.
# It can happen if connection is set to Keep-Alive, but client
# closes connection after receiving response.
LOG.debug('Ignoring IOError in safe_finish()')
pass
class PreflightHandler(BaseHandler):
"""CORS preflight handler"""
@coroutine
def options(self, *args, **kwargs):
"""XHR cross-domain OPTIONS handler"""
self.enable_cache()
self.handle_session_cookie()
self.preflight()
if self.verify_origin():
allowed_methods = getattr(self, 'access_methods', 'OPTIONS, POST')
self.set_header('Access-Control-Allow-Methods', allowed_methods)
self.set_header('Allow', allowed_methods)
self.set_status(204)
else:
# Set forbidden
self.set_status(403)
self.finish()
def preflight(self):
"""Handles request authentication"""
origin = self.request.headers.get('Origin', '*')
self.set_header('Access-Control-Allow-Origin', origin)
headers = self.request.headers.get('Access-Control-Request-Headers')
if headers:
self.set_header('Access-Control-Allow-Headers', headers)
self.set_header('Access-Control-Allow-Credentials', 'true')
def verify_origin(self):
"""Verify if request can be served"""
# adapted from sockjs.tornado.websocket.SockJSWebSocketHandler
origin = self.request.headers.get('Origin', '*')
# first check if connection from the same domain
same_domain = self.check_origin(origin)
if same_domain:
return True
# this is cross-origin connection - check using SockJS server settings
allow_origin = self.server.settings.get("websocket_allow_origin", "*")
if allow_origin == "":
return False
elif allow_origin == "*":
return True
else:
parsed_origin = urlparse(origin)
origin = parsed_origin.netloc
origin = origin.lower()
return origin in allow_origin
def check_origin(self, origin):
# adapted from tornado.websocket.WebSocketHandler
parsed_origin = urlparse(origin)
origin = parsed_origin.netloc
origin = origin.lower()
host = self.request.headers.get("Host")
# Check to see that origin matches host directly, including ports
return origin == host
| 5,110 | Python | .py | 125 | 32.288 | 90 | 0.632079 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,977 | router.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/router.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.router
~~~~~~~~~~~~~~~~~~~~~
SockJS protocol router implementation.
"""
from tornado import ioloop, version_info
from octoprint.vendor.sockjs.tornado import transports, session, sessioncontainer, static, stats, proto
DEFAULT_SETTINGS = {
# Sessions check interval in seconds
'session_check_interval': 1,
# Session expiration in seconds
'disconnect_delay': 5,
# Heartbeat time in seconds. Do not change this value unless
# you absolutely sure that new value will work.
'heartbeat_delay': 25,
# Enabled protocols
'disabled_transports': [],
# SockJS location
'sockjs_url': 'https://cdn.jsdelivr.net/sockjs/0.3/sockjs.min.js',
# Max response body size
'response_limit': 128 * 1024,
# Enable or disable JSESSIONID cookie handling
'jsessionid': True,
# Should sockjs-tornado flush messages immediately or queue then and
# flush on next ioloop tick
'immediate_flush': True,
# Enable or disable Nagle for persistent transports
'disable_nagle': True,
# Enable IP checks for polling transports. If enabled, all subsequent
# polling calls should be from the same IP address.
'verify_ip': True,
# list of allowed origins for websocket connections
# or "*" - accept all websocket connections
'websocket_allow_origin': "*"
}
GLOBAL_HANDLERS = [
('xhr_send', transports.XhrSendHandler),
('jsonp_send', transports.JSONPSendHandler)
]
TRANSPORTS = {
'websocket': transports.WebSocketTransport,
'xhr': transports.XhrPollingTransport,
'xhr_streaming': transports.XhrStreamingTransport,
'jsonp': transports.JSONPTransport,
'eventsource': transports.EventSourceTransport,
'htmlfile': transports.HtmlFileTransport
}
STATIC_HANDLERS = {
'/chunking_test': static.ChunkingTestHandler,
'/info': static.InfoHandler,
'/iframe[0-9-.a-z_]*.html': static.IFrameHandler,
'/websocket': transports.RawWebSocketTransport,
'/?': static.GreetingsHandler
}
class SockJSRouter(object):
"""SockJS protocol router"""
def __init__(self,
connection,
prefix='',
user_settings={},
io_loop=None,
session_kls=None):
"""Constructor.
`connection`
SockJSConnection class
`prefix`
Connection prefix
`user_settings`
Settings dictionary
`io_loop`
Optional IOLoop instance
"""
# TODO: Version check
if version_info[0] < 2:
raise Exception('sockjs-tornado requires Tornado 2.0 or higher.')
# Store connection class
self._connection = connection
# Initialize io_loop
self.io_loop = io_loop or ioloop.IOLoop.instance()
# Settings
self.settings = DEFAULT_SETTINGS.copy()
if user_settings:
self.settings.update(user_settings)
self.websockets_enabled = 'websocket' not in self.settings['disabled_transports']
self.cookie_needed = self.settings['jsessionid']
# Sessions
self._session_kls = session_kls if session_kls else session.Session
self._sessions = sessioncontainer.SessionContainer()
check_interval = self.settings['session_check_interval'] * 1000
self._sessions_cleanup = ioloop.PeriodicCallback(self._sessions.expire,
check_interval)
self._sessions_cleanup.start()
# Stats
self.stats = stats.StatsCollector()
# Initialize URLs
base = prefix + r'/[^/.]+/(?P<session_id>[^/.]+)'
# Generate global handler URLs
self._transport_urls = [('%s/%s$' % (base, p[0]), p[1], {"server": self})
for p in GLOBAL_HANDLERS]
for k, v in TRANSPORTS.items():
if k in self.settings['disabled_transports']:
continue
# Only version 1 is supported
self._transport_urls.append(
(r'%s/%s$' % (base, k),
v,
{"server": self})
)
# Generate static URLs
self._transport_urls.extend([('%s%s' % (prefix, k), v, {"server": self})
for k, v in STATIC_HANDLERS.items()])
@property
def urls(self):
"""List of the URLs to be added to the Tornado application"""
return self._transport_urls
def apply_routes(self, routes):
"""Feed list of the URLs to the routes list. Returns list"""
routes.extend(self._transport_urls)
return routes
def create_session(self, session_id, register=True):
"""Creates new session object and returns it.
`request`
Request that created the session. Will be used to get query string
parameters and cookies
`register`
Should be session registered in a storage. Websockets don't
need it.
"""
# TODO: Possible optimization here for settings.get
s = self._session_kls(self._connection,
self,
session_id,
self.settings.get('disconnect_delay')
)
if register:
self._sessions.add(s)
return s
def get_session(self, session_id):
"""Get session by session id
`session_id`
Session id
"""
return self._sessions.get(session_id)
def get_connection_class(self):
"""Return associated connection class"""
return self._connection
# Broadcast helper
def broadcast(self, clients, msg):
"""Optimized `broadcast` implementation. Depending on type of the session, will json-encode
message once and will call either `send_message` or `send_jsonifed`.
`clients`
Clients iterable
`msg`
Message to send
"""
json_msg = None
count = 0
for c in clients:
sess = c.session
if not sess.is_closed:
if sess.send_expects_json:
if json_msg is None:
json_msg = proto.json_encode(msg)
sess.send_jsonified(json_msg, False)
else:
sess.send_message(msg, stats=False)
count += 1
self.stats.on_pack_sent(count)
| 6,624 | Python | .py | 170 | 29.158824 | 103 | 0.598534 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,978 | conn.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/conn.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.conn
~~~~~~~~~~~~~~~~~~~
SockJS connection interface
"""
class SockJSConnection(object):
def __init__(self, session):
"""Connection constructor.
`session`
Associated session
"""
self.session = session
# Public API
def on_open(self, request):
"""Default on_open() handler.
Override when you need to do some initialization or request validation.
If you return False, connection will be rejected.
You can also throw Tornado HTTPError to close connection.
`request`
``ConnectionInfo`` object which contains caller IP address, query string
parameters and cookies associated with this request (if any).
"""
pass
def on_message(self, message):
"""Default on_message handler. Must be overridden in your application"""
raise NotImplementedError()
def on_close(self):
"""Default on_close handler."""
pass
def send(self, message, binary=False):
"""Send message to the client.
`message`
Message to send.
"""
if not self.is_closed:
self.session.send_message(message, binary=binary)
def broadcast(self, clients, message):
"""Broadcast message to the one or more clients.
Use this method if you want to send same message to lots of clients, as
it contains several optimizations and will work fast than just having loop
in your code.
`clients`
Clients iterable
`message`
Message to send.
"""
self.session.broadcast(clients, message)
def close(self):
self.session.close()
@property
def is_closed(self):
"""Check if connection was closed"""
return self.session.is_closed
| 1,972 | Python | .py | 55 | 27.709091 | 84 | 0.625263 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,979 | __init__.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from .router import SockJSRouter
from .conn import SockJSConnection
| 176 | Python | .py | 4 | 42.75 | 82 | 0.783626 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,980 | websocket.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/websocket.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import tornado
from tornado import escape, gen, websocket
from urllib.parse import urlparse
class SockJSWebSocketHandler(websocket.WebSocketHandler):
if tornado.version_info[0] == 4 and tornado.version_info[1] > 1:
def get_compression_options(self):
# let tornado use compression when Sec-WebSocket-Extensions:permessage-deflate is provided
return {}
SUPPORTED_METHODS = ('GET',)
def check_origin(self, origin):
# let tornado first check if connection from the same domain
same_domain = super(SockJSWebSocketHandler, self).check_origin(origin)
if same_domain:
return True
# this is cross-origin connection - check using SockJS server settings
allow_origin = self.server.settings.get("websocket_allow_origin", "*")
if allow_origin == "":
return False
elif allow_origin == "*":
return True
else:
parsed_origin = urlparse(origin)
origin = parsed_origin.netloc
origin = origin.lower()
return origin in allow_origin
def abort_connection(self):
if self.ws_connection:
self.ws_connection._abort()
def send_complete(self, f=None):
try:
f.result()
except (IOError, websocket.WebSocketError):
self.on_close()
| 1,475 | Python | .py | 35 | 33.457143 | 102 | 0.649196 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,981 | migrate.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/migrate.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.migrate
~~~~~~~~~~~~~~~~~~~~~~
`tornado.websocket` to `sockjs.tornado` migration helper.
"""
from octoprint.vendor.sockjs.tornado import conn
class WebsocketHandler(conn.SockJSConnection):
"""If you already use Tornado websockets for your application and
want try sockjs-tornado, change your handlers to derive from this
WebsocketHandler class. There are some limitations, for example
only self.request only contains remote_ip, cookies and arguments
collection"""
def open(self):
"""open handler"""
pass
def on_open(self, info):
"""sockjs-tornado on_open handler"""
# Store some properties
self.ip = info.ip
# Create fake request object
self.request = info
# Call open
self.open()
def write_message(self, msg):
self.send(msg)
| 985 | Python | .py | 27 | 30.555556 | 82 | 0.671233 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,982 | static.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/static.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.static
~~~~~~~~~~~~~~~~~~~~~
Various static handlers required for SockJS to function properly.
"""
import time
import hashlib
import random
import sys
from tornado.gen import coroutine
from octoprint.vendor.sockjs.tornado.basehandler import BaseHandler, PreflightHandler
from octoprint.vendor.sockjs.tornado.proto import json_encode
from octoprint.vendor.sockjs.tornado.util import MAXSIZE, str_to_bytes
IFRAME_TEXT = '''<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
document.domain = document.domain;
_sockjs_onload = function(){SockJS.bootstrap_iframe();};
</script>
<script src="%s"></script>
</head>
<body>
<h2>Don't panic!</h2>
<p>This is a SockJS hidden iframe. It's used for cross domain magic.</p>
</body>
</html>'''.strip()
class IFrameHandler(BaseHandler):
"""SockJS IFrame page handler"""
def get(self):
data = str_to_bytes(IFRAME_TEXT % self.server.settings['sockjs_url'])
hsh = hashlib.md5(data).hexdigest()
value = self.request.headers.get('If-None-Match')
if value:
if value.find(hsh) != -1:
# TODO: Fix me? Right now it is a hack to remove content-type
# header
self.clear()
del self._headers['Content-Type']
self.set_status(304)
return
self.enable_cache()
self.set_header('Etag', hsh)
self.write(data)
class GreetingsHandler(BaseHandler):
"""SockJS greetings page handler"""
def initialize(self, server):
self.server = server
def get(self):
self.enable_cache()
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
self.write('Welcome to SockJS!\n')
class ChunkingTestHandler(PreflightHandler):
"""SockJS chunking test handler"""
# Step timeouts according to sockjs documentation
steps = [0.005, 0.025, 0.125, 0.625, 3.125]
def initialize(self, server):
self.server = server
self.step = 0
self.io_loop = server.io_loop
@coroutine
def post(self):
self.preflight()
self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
# Send one 'h' immediately
self.write('h\n')
self.flush()
# Send 2048 spaces followed by 'h'
self.write(' ' * 2048 + 'h\n')
self.flush()
# Send 'h' with different timeouts
def run_step():
try:
self.write('h\n')
self.flush()
self.step += 1
if self.step < len(self.steps):
self.io_loop.add_timeout(time.time() + self.steps[self.step],
run_step)
else:
self.finish()
except IOError:
pass
self.io_loop.add_timeout(time.time() + self.steps[0], run_step)
class InfoHandler(PreflightHandler):
"""SockJS 0.2+ /info handler"""
def initialize(self, server):
self.server = server
self.access_methods = 'OPTIONS, GET'
def get(self):
self.preflight()
self.disable_cache()
self.set_header('Content-Type', 'application/json; charset=UTF-8')
options = {"websocket": self.server.websockets_enabled,
"cookie_needed": self.server.cookie_needed,
"origins": ['*:*'],
"entropy": random.randint(0, MAXSIZE)}
self.write(json_encode(options))
| 3,771 | Python | .py | 102 | 28.627451 | 85 | 0.604785 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,983 | stats.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/stats.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import deque
from tornado import ioloop
class MovingAverage(object):
"""Moving average class implementation"""
def __init__(self, period=10):
"""Constructor.
`period`
Moving window size. Average will be calculated
from the data in the window.
"""
self.period = period
self.stream = deque()
self.sum = 0
self.accumulator = 0
self.last_average = 0
def add(self, n):
"""Add value to the current accumulator
`n`
Value to add
"""
self.accumulator += n
def flush(self):
"""Add accumulator to the moving average queue
and reset it. For example, called by the StatsCollector
once per second to calculate per-second average.
"""
n = self.accumulator
self.accumulator = 0
stream = self.stream
stream.append(n)
self.sum += n
streamlen = len(stream)
if streamlen > self.period:
self.sum -= stream.popleft()
streamlen -= 1
if streamlen == 0:
self.last_average = 0
else:
self.last_average = self.sum / streamlen
class StatsCollector(object):
def __init__(self):
# Sessions
self.sess_active = 0
# Avoid circular reference
self.sess_transports = {}
# Connections
self.conn_active = 0
self.conn_ps = MovingAverage()
# Packets
self.pack_sent_ps = MovingAverage()
self.pack_recv_ps = MovingAverage()
self._callback = ioloop.PeriodicCallback(self._update,
1000)
self._callback.start()
def _update(self):
self.conn_ps.flush()
self.pack_sent_ps.flush()
self.pack_recv_ps.flush()
def dump(self):
"""Return dictionary with current statistical information"""
data = {"sessions_active": self.sess_active,
# Connections
"connections_active": self.conn_active,
"connections_ps": self.conn_ps.last_average,
# Packets
"packets_sent_ps": self.pack_sent_ps.last_average,
"packets_recv_ps": self.pack_recv_ps.last_average}
for k, v in self.sess_transports.items():
data['transp_' + k] = v
return data
# Various event callbacks
def on_sess_opened(self, transport):
self.sess_active += 1
if transport not in self.sess_transports:
self.sess_transports[transport] = 0
self.sess_transports[transport] += 1
def on_sess_closed(self, transport):
self.sess_active -= 1
self.sess_transports[transport] -= 1
def on_conn_opened(self):
self.conn_active += 1
self.conn_ps.add(1)
def on_conn_closed(self):
self.conn_active -= 1
def on_pack_sent(self, num):
self.pack_sent_ps.add(num)
def on_pack_recv(self, num):
self.pack_recv_ps.add(num)
| 3,150 | Python | .py | 90 | 25.844444 | 82 | 0.589032 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,984 | proto.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/proto.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.proto
~~~~~~~~~~~~~~~~~~~~
SockJS protocol related functions
"""
import logging
LOG = logging.getLogger("tornado.general")
# TODO: Add support for ujson module once they can accept unicode strings
# Try to find best json encoder available
try:
# Check for simplejson
import simplejson
json_encode = lambda data: simplejson.dumps(data, separators=(',', ':'))
json_decode = lambda data: simplejson.loads(data)
JSONDecodeError = ValueError
LOG.debug('sockjs.tornado will use simplejson module')
except ImportError:
# Use slow json
import json
LOG.debug('sockjs.tornado will use json module')
json_encode = lambda data: json.dumps(data, separators=(',', ':'))
json_decode = lambda data: json.loads(data)
JSONDecodeError = ValueError
# Protocol handlers
CONNECT = 'o'
DISCONNECT = 'c'
MESSAGE = 'm'
HEARTBEAT = 'h'
# Various protocol helpers
def disconnect(code, reason):
"""Return SockJS packet with code and close reason
`code`
Closing code
`reason`
Closing reason
"""
return 'c[%d,"%s"]' % (code, reason)
| 1,238 | Python | .py | 39 | 27.948718 | 82 | 0.694772 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,985 | session.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/session.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.session
~~~~~~~~~~~~~~~~~~~~~~
SockJS session implementation.
"""
import asyncio
import functools
import logging
from octoprint.vendor.sockjs.tornado import periodic, proto, sessioncontainer
from octoprint.vendor.sockjs.tornado.util import bytes_to_str, get_current_ioloop
LOG = logging.getLogger("tornado.general")
def ensure_io_loop(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if get_current_ioloop():
method(self, *args, **kwargs)
else:
def run():
method(self, *args, **kwargs)
self.server.io_loop.add_callback(run)
return wrapper
class ConnectionInfo(object):
"""Connection information object.
Will be passed to the ``on_open`` handler of your connection class.
Has few properties:
`ip`
Caller IP address
`cookies`
Collection of cookies
`arguments`
Collection of the query string arguments
`headers`
Collection of headers sent by the browser that established this
connection
`path`
Request uri path
"""
def __init__(self, ip, cookies, arguments, headers, path):
self.ip = ip
self.cookies = cookies
self.arguments = arguments
self.headers = headers
self.path = path
def get_argument(self, name):
"""Return single argument by name"""
val = self.arguments.get(name)
if val:
return val[0]
return None
def get_cookie(self, name):
"""Return single cookie by its name"""
return self.cookies.get(name)
def get_header(self, name):
"""Return single header by its name"""
return self.headers.get(name)
# Session states
CONNECTING = 0
OPEN = 1
CLOSING = 2
CLOSED = 3
class BaseSession(object):
"""Base session implementation class"""
def __init__(self, conn, server):
"""Base constructor.
`conn`
Connection class
`server`
SockJSRouter instance
"""
self.server = server
self.stats = server.stats
self.send_expects_json = False
self.handler = None
self.state = CONNECTING
self.conn_info = None
self.conn = conn(self)
self.close_reason = None
def set_handler(self, handler):
"""Set transport handler
``handler``
Handler, should derive from the `sockjs.tornado.transports.base.BaseTransportMixin`.
"""
if self.handler is not None:
raise Exception('Attempted to overwrite BaseSession handler')
self.handler = handler
self.transport_name = self.handler.name
if self.conn_info is None:
self.conn_info = handler.get_conn_info()
self.stats.on_sess_opened(self.transport_name)
return True
def verify_state(self):
"""Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
if self.state == CONNECTING:
self.state = OPEN
self.conn.on_open(self.conn_info)
def remove_handler(self, handler):
"""Remove active handler from the session
`handler`
Handler to remove
"""
# Attempt to remove another handler
if self.handler != handler:
raise Exception('Attempted to remove invalid handler')
self.handler = None
def close(self, code=3000, message='Go away!'):
"""Close session or endpoint connection.
`code`
Closing code
`message`
Close message
"""
if self.state != CLOSED:
try:
self.conn.on_close()
except Exception:
LOG.debug("Failed to call on_close().", exc_info=True)
finally:
self.state = CLOSED
self.close_reason = (code, message)
self.conn = None
# Bump stats
self.stats.on_sess_closed(self.transport_name)
# If we have active handler, notify that session was closed
if self.handler is not None:
self.handler.session_closed()
def delayed_close(self):
"""Delayed close - won't close immediately, but on next ioloop tick."""
self.state = CLOSING
self.server.io_loop.add_callback(self.close)
def get_close_reason(self):
"""Return last close reason tuple.
For example:
if self.session.is_closed:
code, reason = self.session.get_close_reason()
"""
if self.close_reason:
return self.close_reason
return (3000, 'Go away!')
@property
def is_closed(self):
"""Check if session was closed."""
return self.state == CLOSED or self.state == CLOSING
def send_message(self, msg, stats=True, binary=False):
"""Send or queue outgoing message
`msg`
Message to send
`stats`
If set to True, will update statistics after operation completes
"""
raise NotImplementedError()
def send_jsonified(self, msg, stats=True):
"""Send or queue outgoing message which was json-encoded before. Used by the `broadcast`
method.
`msg`
JSON-encoded message to send
`stats`
If set to True, will update statistics after operation completes
"""
raise NotImplementedError()
def broadcast(self, clients, msg):
"""Optimized `broadcast` implementation. Depending on type of the session, will json-encode
message once and will call either `send_message` or `send_jsonifed`.
`clients`
Clients iterable
`msg`
Message to send
"""
self.server.broadcast(clients, msg)
class Session(BaseSession, sessioncontainer.SessionMixin):
"""SockJS session implementation.
"""
def __init__(self, conn, server, session_id, expiry=None):
"""Session constructor.
`conn`
Default connection class
`server`
`SockJSRouter` instance
`session_id`
Session id
`expiry`
Session expiry time
"""
# Initialize session
sessioncontainer.SessionMixin.__init__(self, session_id, expiry)
BaseSession.__init__(self, conn, server)
self.send_queue = ''
self.send_expects_json = True
# Heartbeat related stuff
self._heartbeat_timer = None
self._heartbeat_interval = self.server.settings['heartbeat_delay'] * 1000
self._immediate_flush = self.server.settings['immediate_flush']
self._pending_flush = False
self._verify_ip = self.server.settings['verify_ip']
# Session callbacks
def on_delete(self, forced):
"""Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False.
"""
# Do not remove connection if it was not forced and there's running connection
if not forced and self.handler is not None and not self.is_closed:
self.promote()
else:
self.close()
# Add session
def set_handler(self, handler, start_heartbeat=True):
"""Set active handler for the session
`handler`
Associate active Tornado handler with the session
`start_heartbeat`
Should session start heartbeat immediately
"""
# Check if session already has associated handler
if self.handler is not None:
handler.send_pack(proto.disconnect(2010, "Another connection still open"))
return False
if self._verify_ip and self.conn_info is not None:
# If IP address doesn't match - refuse connection
if handler.request.remote_ip != self.conn_info.ip:
LOG.error('Attempted to attach to session %s (%s) from different IP (%s)' % (
self.session_id,
self.conn_info.ip,
handler.request.remote_ip
))
handler.send_pack(proto.disconnect(2010, "Attempted to connect to session from different IP"))
return False
if (self.state == CLOSING or self.state == CLOSED) and not self.send_queue:
handler.send_pack(proto.disconnect(*self.get_close_reason()))
return False
# Associate handler and promote session
super(Session, self).set_handler(handler)
self.promote()
if start_heartbeat:
self.start_heartbeat()
return True
@ensure_io_loop
def verify_state(self):
"""Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
# If we're in CONNECTING state - send 'o' message to the client
if self.state == CONNECTING:
self.handler.send_pack(proto.CONNECT)
# Call parent implementation
super(Session, self).verify_state()
def remove_handler(self, handler):
"""Detach active handler from the session
`handler`
Handler to remove
"""
super(Session, self).remove_handler(handler)
self.promote()
self.stop_heartbeat()
def send_message(self, msg, stats=True, binary=False):
"""Send or queue outgoing message
`msg`
Message to send
`stats`
If set to True, will update statistics after operation completes
"""
self.send_jsonified(proto.json_encode(bytes_to_str(msg)), stats)
@ensure_io_loop
def send_jsonified(self, msg, stats=True):
"""Send JSON-encoded message
`msg`
JSON encoded string to send
`stats`
If set to True, will update statistics after operation completes
"""
msg = bytes_to_str(msg)
if self._immediate_flush:
if self.handler and self.handler.active and not self.send_queue:
# Send message right away
self.handler.send_pack('a[%s]' % msg)
else:
if self.send_queue:
self.send_queue += ','
self.send_queue += msg
self.flush()
else:
if self.send_queue:
self.send_queue += ','
self.send_queue += msg
if not self._pending_flush:
self.server.io_loop.add_callback(self.flush)
self._pending_flush = True
if stats:
self.stats.on_pack_sent(1)
@ensure_io_loop
def flush(self):
"""Flush message queue if there's an active connection running"""
self._pending_flush = False
if self.handler is None or not self.handler.active or not self.send_queue:
return
self.handler.send_pack('a[%s]' % self.send_queue)
self.send_queue = ''
@ensure_io_loop
def close(self, code=3000, message='Go away!'):
"""Close session.
`code`
Closing code
`message`
Closing message
"""
if self.state != CLOSED:
# Notify handler
if self.handler is not None:
self.handler.send_pack(proto.disconnect(code, message))
super(Session, self).close(code, message)
# Heartbeats
def start_heartbeat(self):
"""Reset hearbeat timer"""
self.stop_heartbeat()
self._heartbeat_timer = periodic.Callback(self._heartbeat,
self._heartbeat_interval,
self.server.io_loop)
self._heartbeat_timer.start()
def stop_heartbeat(self):
"""Stop active heartbeat"""
if self._heartbeat_timer is not None:
self._heartbeat_timer.stop()
self._heartbeat_timer = None
def delay_heartbeat(self):
"""Delay active heartbeat"""
if self._heartbeat_timer is not None:
self._heartbeat_timer.delay()
@ensure_io_loop
def _heartbeat(self):
"""Heartbeat callback"""
if self.handler is not None:
self.handler.send_pack(proto.HEARTBEAT)
else:
self.stop_heartbeat()
def on_messages(self, msg_list):
"""Handle incoming messages
`msg_list`
Message list to process
"""
self.stats.on_pack_recv(len(msg_list))
for msg in msg_list:
if self.state == OPEN:
self.conn.on_message(msg)
| 12,913 | Python | .py | 343 | 27.594752 | 110 | 0.592319 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,986 | htmlfile.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/htmlfile.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.transports.htmlfile
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HtmlFile transport implementation.
"""
import re
from octoprint.vendor.sockjs.tornado import proto
from octoprint.vendor.sockjs.tornado.transports import streamingbase
from octoprint.vendor.sockjs.tornado.util import no_auto_finish
try:
# noinspection PyCompatibility
from html import escape
except:
# noinspection PyDeprecation
from cgi import escape
RE = re.compile(r'[\W_]+')
# HTMLFILE template
HTMLFILE_HEAD = r'''
<!doctype html>
<html><head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head><body><h2>Don't panic!</h2>
<script>
document.domain = document.domain;
var c = parent.%s;
c.start();
function p(d) {c.message(d);};
window.onload = function() {c.stop();};
</script>
'''.strip()
HTMLFILE_HEAD += ' ' * (1024 - len(HTMLFILE_HEAD) + 14)
HTMLFILE_HEAD += '\r\n\r\n'
class HtmlFileTransport(streamingbase.StreamingTransportBase):
name = 'htmlfile'
def initialize(self, server):
super(HtmlFileTransport, self).initialize(server)
@no_auto_finish
def get(self, session_id):
# Start response
self.preflight()
self.handle_session_cookie()
self.disable_cache()
self.set_header('Content-Type', 'text/html; charset=UTF-8')
# Grab callback parameter
callback = self.get_argument('c', None)
if not callback:
self.write('"callback" parameter required')
self.set_status(500)
self.finish()
return
# TODO: Fix me - use parameter
self.write(HTMLFILE_HEAD % escape(RE.sub('', callback)))
self.flush()
# Now try to attach to session
if not self._attach_session(session_id):
self.finish()
return
# Flush any pending messages
if self.session:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for HtmlFileTransport')
# TODO: Just do escaping
msg = '<script>\np(%s);\n</script>\r\n' % proto.json_encode(message)
self.active = False
try:
self.notify_sent(len(message))
self.write(msg)
self.flush().add_done_callback(self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
self._detach()
| 2,771 | Python | .py | 78 | 28.730769 | 82 | 0.63599 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,987 | streamingbase.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/streamingbase.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from octoprint.vendor.sockjs.tornado.transports import pollingbase
class StreamingTransportBase(pollingbase.PollingTransportBase):
def initialize(self, server):
super(StreamingTransportBase, self).initialize(server)
self.amount_limit = self.server.settings['response_limit']
# HTTP 1.0 client might send keep-alive
if hasattr(self.request, 'connection') and not self.request.version == 'HTTP/1.1':
self.request.connection.no_keep_alive = True
def notify_sent(self, data_len):
"""
Update amount of data sent
"""
self.amount_limit -= data_len
def should_finish(self):
"""
Check if transport should close long running connection after
sending X bytes to the client.
`data_len`
Amount of data that was sent
"""
if self.amount_limit <= 0:
return True
return False
def send_complete(self, f=None):
"""
Verify if connection should be closed based on amount of data that was sent.
"""
self.active = True
if self.should_finish():
self._detach()
# Avoid race condition when waiting for write callback and session getting closed in between
if not self._finished:
self.safe_finish()
else:
if self.session:
self.session.flush()
| 1,558 | Python | .py | 38 | 31.157895 | 104 | 0.621353 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,988 | pollingbase.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/pollingbase.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.transports.pollingbase
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Polling transports base
"""
from octoprint.vendor.sockjs.tornado import basehandler
from octoprint.vendor.sockjs.tornado.transports import base
class PollingTransportBase(basehandler.PreflightHandler, base.BaseTransportMixin):
"""Polling transport handler base class"""
def initialize(self, server):
super(PollingTransportBase, self).initialize(server)
self.session = None
self.active = True
def _get_session(self, session_id):
return self.server.get_session(session_id)
def _attach_session(self, session_id, start_heartbeat=False):
session = self._get_session(session_id)
if session is None:
session = self.server.create_session(session_id)
# Try to attach to the session
if not session.set_handler(self, start_heartbeat):
return False
self.session = session
# Verify if session is properly opened
session.verify_state()
return True
def _detach(self):
"""Detach from the session"""
if self.session:
self.session.remove_handler(self)
self.session = None
def check_xsrf_cookie(self):
pass
def send_message(self, message, binary=False):
"""Called by the session when some data is available"""
raise NotImplementedError()
def session_closed(self):
"""Called by the session when it was closed"""
self._detach()
self.safe_finish()
def on_connection_close(self):
# If connection was dropped by the client, close session.
# In all other cases, connection will be closed by the server.
if self.session is not None:
self.session.close(1002, 'Connection interrupted')
super(PollingTransportBase, self).on_connection_close()
def send_complete(self, f=None):
self._detach()
# Avoid race condition when waiting for write callback and session getting closed in between
if not self._finished:
self.safe_finish()
| 2,245 | Python | .py | 53 | 34.54717 | 100 | 0.663289 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,989 | xhrstreaming.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/xhrstreaming.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.transports.xhrstreaming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xhr-Streaming transport implementation
"""
from octoprint.vendor.sockjs.tornado.transports import streamingbase
from octoprint.vendor.sockjs.tornado.util import no_auto_finish
class XhrStreamingTransport(streamingbase.StreamingTransportBase):
name = 'xhr_streaming'
@no_auto_finish
def post(self, session_id):
# Handle cookie
self.preflight()
self.handle_session_cookie()
self.disable_cache()
self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
# Send prelude and flush any pending messages
self.write('h' * 2048 + '\n')
self.flush()
if not self._attach_session(session_id, False):
self.finish()
return
if self.session:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for XhrStreamingTransport')
self.active = False
try:
self.notify_sent(len(message))
self.write(message + '\n')
self.flush().add_done_callback(self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
self._detach()
| 1,556 | Python | .py | 39 | 31.589744 | 82 | 0.636303 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,990 | jsonp.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/jsonp.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.transports.jsonp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
JSONP transport implementation.
"""
import logging
from octoprint.vendor.sockjs.tornado import proto
from octoprint.vendor.sockjs.tornado.transports import pollingbase
from octoprint.vendor.sockjs.tornado.util import bytes_to_str, unquote_plus
from octoprint.vendor.sockjs.tornado.util import no_auto_finish
LOG = logging.getLogger("tornado.general")
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@no_auto_finish
def get(self, session_id):
# Start response
self.handle_session_cookie()
self.disable_cache()
# Grab callback parameter
self.callback = self.get_argument('c', None)
if not self.callback:
self.write('"callback" parameter required')
self.set_status(500)
self.finish()
return
# Get or create session without starting heartbeat
if not self._attach_session(session_id, False):
return
# Might get already detached because connection was closed in on_open
if not self.session:
return
if not self.session.send_queue:
self.session.start_heartbeat()
else:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for JSONPTransport')
self.active = False
try:
# TODO: Just escape
msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message))
self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
self.set_header('Content-Length', len(msg))
# TODO: Fix me
self.set_header('Etag', 'dummy')
self.write(msg)
self.flush().add_done_callback(self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
class JSONPSendHandler(pollingbase.PollingTransportBase):
def post(self, session_id):
self.preflight()
self.handle_session_cookie()
self.disable_cache()
session = self._get_session(session_id)
if session is None or session.is_closed:
self.set_status(404)
return
data = bytes_to_str(self.request.body)
ctype = self.request.headers.get('Content-Type', '').lower()
if ctype == 'application/x-www-form-urlencoded':
if not data.startswith('d='):
LOG.exception('jsonp_send: Invalid payload.')
self.write("Payload expected.")
self.set_status(500)
return
data = unquote_plus(data[2:])
if not data:
LOG.debug('jsonp_send: Payload expected.')
self.write("Payload expected.")
self.set_status(500)
return
try:
messages = proto.json_decode(data)
except Exception:
# TODO: Proper error handling
LOG.debug('jsonp_send: Invalid json encoding')
self.write("Broken JSON encoding.")
self.set_status(500)
return
try:
session.on_messages(messages)
except Exception:
LOG.exception('jsonp_send: on_message() failed')
session.close()
self.write('Message handler failed.')
self.set_status(500)
return
self.write('ok')
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
self.set_status(200)
| 3,826 | Python | .py | 96 | 29.854167 | 84 | 0.608437 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,991 | __init__.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import octoprint.vendor.sockjs.tornado.transports.pollingbase
from .xhr import XhrPollingTransport, XhrSendHandler
from .jsonp import JSONPTransport, JSONPSendHandler
from .websocket import WebSocketTransport
from .xhrstreaming import XhrStreamingTransport
from .eventsource import EventSourceTransport
from .htmlfile import HtmlFileTransport
from .rawwebsocket import RawWebSocketTransport
| 500 | Python | .py | 10 | 48.8 | 82 | 0.862705 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,992 | websocket.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/websocket.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.transports.websocket
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Websocket transport implementation
"""
import logging
from tornado.websocket import WebSocketError
from octoprint.vendor.sockjs.tornado import proto, websocket
from octoprint.vendor.sockjs.tornado.transports import base
from octoprint.vendor.sockjs.tornado.util import bytes_to_str, get_current_ioloop
LOG = logging.getLogger("tornado.general")
class WebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin):
"""Websocket transport"""
name = 'websocket'
def initialize(self, server):
self.server = server
self.session = None
self.active = True
def open(self, session_id):
# Stats
self.server.stats.on_conn_opened()
# Disable nagle
if self.server.settings['disable_nagle']:
if hasattr(self, 'ws_connection'):
self.ws_connection.stream.set_nodelay(True)
else:
self.stream.set_nodelay(True)
# Handle session
self.session = self.server.create_session(session_id, register=False)
if not self.session.set_handler(self):
self.close()
return
self.session.verify_state()
if self.session:
self.session.flush()
def _detach(self):
if self.session is not None:
self.session.remove_handler(self)
self.session = None
def on_message(self, message):
# SockJS requires that empty messages should be ignored
if not message or not self.session:
return
try:
msg = proto.json_decode(bytes_to_str(message))
if isinstance(msg, list):
self.session.on_messages(msg)
else:
self.session.on_messages((msg,))
except Exception:
LOG.exception('WebSocket')
# Close session on exception
#self.session.close()
# Close running connection
self.abort_connection()
def on_close(self):
# Close session if websocket connection was closed
if self.session is not None:
# Stats
self.server.stats.on_conn_closed()
# Detach before closing session
session = self.session
self._detach()
session.close()
def send_pack(self, message, binary=False):
if get_current_ioloop() == self.server.io_loop:
# Running in Main Thread
# Send message
try:
self.write_message(message, binary).add_done_callback(self.send_complete)
except (IOError, WebSocketError):
self.server.io_loop.add_callback(self.on_close)
else:
# Not running in Main Thread so use proper thread to send message
self.server.io_loop.add_callback(lambda: self.send_pack(message, binary))
def session_closed(self):
# If session was closed by the application, terminate websocket
# connection as well.
try:
self.close()
except IOError:
pass
finally:
self._detach()
# Websocket overrides
def allow_draft76(self):
return True
def auto_decode(self):
return False
| 3,445 | Python | .py | 91 | 28.318681 | 89 | 0.616702 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,993 | base.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/base.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from octoprint.vendor.sockjs.tornado import session
class BaseTransportMixin(object):
"""Base transport.
Implements few methods that session expects to see in each transport.
"""
name = 'override_me_please'
def get_conn_info(self):
"""Return `ConnectionInfo` object from current transport"""
return session.ConnectionInfo(self.request.remote_ip,
self.request.cookies,
self.request.arguments,
self.request.headers,
self.request.path)
def session_closed(self):
"""Called by the session, when it gets closed"""
pass
| 835 | Python | .py | 18 | 33.444444 | 82 | 0.592593 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,994 | xhr.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/xhr.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.transports.xhr
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xhr-Polling transport implementation
"""
import logging
from octoprint.vendor.sockjs.tornado import proto
from octoprint.vendor.sockjs.tornado.transports import pollingbase
from octoprint.vendor.sockjs.tornado.util import bytes_to_str, no_auto_finish
LOG = logging.getLogger("tornado.general")
class XhrPollingTransport(pollingbase.PollingTransportBase):
"""xhr-polling transport implementation"""
name = 'xhr'
@no_auto_finish
def post(self, session_id):
# Start response
self.preflight()
self.handle_session_cookie()
self.disable_cache()
# Get or create session without starting heartbeat
if not self._attach_session(session_id, False):
return
# Might get already detached because connection was closed in on_open
if not self.session:
return
if not self.session.send_queue:
self.session.start_heartbeat()
else:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for XhrPollingTransport')
self.active = False
try:
self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
self.set_header('Content-Length', len(message) + 1)
self.write(message + '\n')
self.flush().add_done_callback(self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
class XhrSendHandler(pollingbase.PollingTransportBase):
def post(self, session_id):
self.preflight()
self.handle_session_cookie()
self.disable_cache()
session = self._get_session(session_id)
if session is None or session.is_closed:
self.set_status(404)
return
data = self.request.body
if not data:
self.write("Payload expected.")
self.set_status(500)
return
try:
messages = proto.json_decode(bytes_to_str(data))
except Exception:
# TODO: Proper error handling
self.write("Broken JSON encoding.")
self.set_status(500)
return
try:
session.on_messages(messages)
except Exception:
LOG.exception('XHR incoming')
session.close()
self.set_status(500)
return
self.set_status(204)
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
| 2,831 | Python | .py | 74 | 29.189189 | 84 | 0.62902 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,995 | rawwebsocket.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.transports.rawwebsocket
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Raw websocket transport implementation
"""
import logging
from tornado.websocket import WebSocketError
from octoprint.vendor.sockjs.tornado import session, websocket
from octoprint.vendor.sockjs.tornado.transports import base
from octoprint.vendor.sockjs.tornado.util import get_current_ioloop
LOG = logging.getLogger("tornado.general")
class RawSession(session.BaseSession):
"""Raw session without any sockjs protocol encoding/decoding. Simply
works as a proxy between `SockJSConnection` class and `RawWebSocketTransport`."""
def send_message(self, msg, stats=True, binary=False):
self.handler.send_pack(msg, binary)
def on_message(self, msg):
self.conn.on_message(msg)
class RawWebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin):
"""Raw Websocket transport"""
name = 'rawwebsocket'
def initialize(self, server):
self.server = server
self.session = None
self.active = True
def open(self):
# Stats
self.server.stats.on_conn_opened()
# Disable nagle if needed
if self.server.settings['disable_nagle']:
self.set_nodelay(True)
# Create and attach to session
self.session = RawSession(self.server.get_connection_class(), self.server)
self.session.set_handler(self)
self.session.verify_state()
def _detach(self):
if self.session is not None:
self.session.remove_handler(self)
self.session = None
def on_message(self, message):
# SockJS requires that empty messages should be ignored
if not message or not self.session:
return
try:
self.session.on_message(message)
except Exception:
LOG.exception('RawWebSocket')
# Close running connection
self.abort_connection()
def on_close(self):
# Close session if websocket connection was closed
if self.session is not None:
# Stats
self.server.stats.on_conn_closed()
session = self.session
self._detach()
session.close()
def send_pack(self, message, binary=False):
if get_current_ioloop() == self.server.io_loop:
# Running in Main Thread
# Send message
try:
self.write_message(message, binary).add_done_callback(self.send_complete)
except (IOError, WebSocketError):
self.server.io_loop.add_callback(self.on_close)
else:
# Not running in Main Thread so use proper thread to send message
self.server.io_loop.add_callback(lambda: self.send_pack(message, binary))
def session_closed(self):
try:
self.close(*self.session.get_close_reason())
except IOError:
pass
finally:
self._detach()
# Websocket overrides
def allow_draft76(self):
return True
| 3,188 | Python | .py | 80 | 31.375 | 89 | 0.64906 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,996 | eventsource.py | OctoPrint_OctoPrint/src/octoprint/vendor/sockjs/tornado/transports/eventsource.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
sockjs.tornado.transports.eventsource
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EventSource transport implementation.
"""
from octoprint.vendor.sockjs.tornado.transports import streamingbase
from octoprint.vendor.sockjs.tornado.util import no_auto_finish
class EventSourceTransport(streamingbase.StreamingTransportBase):
name = 'eventsource'
@no_auto_finish
def get(self, session_id):
# Start response
self.preflight()
self.handle_session_cookie()
self.disable_cache()
self.set_header('Content-Type', 'text/event-stream; charset=UTF-8')
self.write('\r\n')
self.flush()
if not self._attach_session(session_id):
self.finish()
return
if self.session:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for EventSourceTransport')
msg = 'data: %s\r\n\r\n' % message
self.active = False
try:
self.notify_sent(len(msg))
self.write(msg)
self.flush().add_done_callback(self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
self._detach()
| 1,501 | Python | .py | 39 | 30.153846 | 82 | 0.628453 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,997 | analysis.py | OctoPrint_OctoPrint/src/octoprint/filemanager/analysis.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 collections
import copy
import logging
import os
import queue
import threading
import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import dict_merge
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import yaml
from octoprint.util.platform import CLOSE_FDS
EMPTY_RESULT = {
"_empty": True,
"printingArea": {
"minX": 0,
"maxX": 0,
"minY": 0,
"maxY": 0,
"minZ": 0,
"maxZ": 0,
},
"travelArea": {
"minX": 0,
"maxX": 0,
"minY": 0,
"maxY": 0,
"minZ": 0,
"maxZ": 0,
},
"dimensions": {"width": 0, "height": 0, "depth": 0},
"travelDimensions": {"width": 0, "height": 0, "depth": 0},
"filament": {},
}
class QueueEntry(
collections.namedtuple(
"QueueEntry",
"name, path, type, location, absolute_path, printer_profile, analysis",
)
):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
Arguments:
name (str): Name of the file to analyze.
path (str): Storage location specific path to the file to analyze.
type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class.
At the moment, only ``gcode`` is supported here.
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
def __str__(self):
return f"{self.location}:{self.path}"
class AnalysisAborted(Exception):
def __init__(self, reenqueue=True, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.reenqueue = reenqueue
class AnalysisQueue:
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
:meth:`unregister_finish_callback`.
:meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown
(no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the
entry will be enqueued with the type specific analysis queue.
"""
def __init__(self, queue_factories):
self._logger = logging.getLogger(__name__)
self._callbacks = []
self._queues = {}
for key, queue_factory in queue_factories.items():
self._queues[key] = queue_factory(self._analysis_finished)
def register_finish_callback(self, callback):
self._callbacks.append(callback)
def unregister_finish_callback(self, callback):
self._callbacks.remove(callback)
def enqueue(self, entry, high_priority=False):
if entry is None:
return False
if entry.type not in self._queues:
return False
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
def dequeue(self, entry):
if entry is None:
return False
if entry.type not in self._queues:
return False
self._queues[entry.type].dequeue(entry.location, entry.path)
def dequeue_folder(self, destination, path):
for q in self._queues.values():
q.dequeue_folder(destination, path)
def pause(self):
for q in self._queues.values():
q.pause()
def resume(self):
for q in self._queues.values():
q.resume()
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
try:
callback(entry, result)
except Exception:
self._logger.exception(
f"Error while pushing analysis data to callback {callback}",
extra={"callback": fqcn(callback)},
)
eventManager().fire(
Events.METADATA_ANALYSIS_FINISHED,
{
"name": entry.name,
"path": entry.path,
"origin": entry.location,
"result": result,
},
)
class AbstractAnalysisQueue:
"""
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
processing.
Arguments:
finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue.
The callback will be called with the analyzed entry as the first argument and the analysis result as
returned from the queue implementation as the second parameter.
.. automethod:: _do_analysis
.. automethod:: _do_abort
"""
LOW_PRIO = 100
LOW_PRIO_ABORTED = 75
HIGH_PRIO = 50
HIGH_PRIO_ABORTED = 0
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
self._finished_callback = finished_callback
self._active = threading.Event()
self._active.set()
self._done = threading.Event()
self._done.clear()
self._currentFile = None
self._currentProgress = None
self._queue = queue.PriorityQueue()
self._current = None
self._current_highprio = False
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def enqueue(self, entry, high_priority=False):
"""
Enqueues an ``entry`` for analysis by the queue.
If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before
other entries in the queue with normal priority.
Arguments:
entry (QueueEntry): The :class:`QueueEntry` to analyze.
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
(False, default)
"""
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug(f"Ignoring entry {entry} for analysis queue")
return
elif high_priority:
self._logger.debug(
"Adding entry {entry} to analysis queue with high priority".format(
entry=entry
)
)
prio = self.__class__.HIGH_PRIO
else:
self._logger.debug(
"Adding entry {entry} to analysis queue with low priority".format(
entry=entry
)
)
prio = self.__class__.LOW_PRIO
self._queue.put((prio, entry, high_priority))
if high_priority and self._current is not None and not self._current_highprio:
self._logger.debug("Aborting current analysis in favor of high priority one")
self._do_abort()
def dequeue(self, location, path):
if (
self._current is not None
and self._current.location == location
and self._current.path == path
):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue_folder(self, location, path):
if (
self._current is not None
and self._current.location == location
and self._current.path.startswith(path + "/")
):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def pause(self):
"""
Pauses processing of the queue, e.g. when a print is active.
"""
self._logger.debug("Pausing analysis")
self._active.clear()
if self._current is not None:
self._logger.debug(
"Aborting running analysis, will restart when analyzer is resumed"
)
self._do_abort()
def resume(self):
"""
Resumes processing of the queue, e.g. when a print has finished.
"""
self._logger.debug("Resuming analyzer")
self._active.set()
def _work(self):
while True:
(priority, entry, high_priority) = self._queue.get()
self._logger.debug(
f"Processing entry {entry} from queue (priority {priority})"
)
self._active.wait()
try:
self._analyze(entry, high_priority=high_priority)
self._queue.task_done()
self._done.set()
except AnalysisAborted as ex:
if ex.reenqueue:
self._queue.put(
(
self.__class__.HIGH_PRIO_ABORTED
if high_priority
else self.__class__.LOW_PRIO_ABORTED,
entry,
high_priority,
)
)
self._logger.debug(f"Running analysis of entry {entry} aborted")
self._queue.task_done()
self._done.set()
else:
time.sleep(1.0)
def _analyze(self, entry, high_priority=False):
path = entry.absolute_path
if path is None or not os.path.exists(path):
return
self._current = entry
self._current_highprio = high_priority
self._current_progress = 0
try:
start_time = time.monotonic()
self._logger.info(f"Starting analysis of {entry}")
eventManager().fire(
Events.METADATA_ANALYSIS_STARTED,
{
"name": entry.name,
"path": entry.path,
"origin": entry.location,
"type": entry.type,
},
)
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.info(
"Analysis of entry {} finished, needed {:.2f}s".format(
entry, time.monotonic() - start_time
)
)
self._finished_callback(self._current, result)
except RuntimeError as exc:
self._logger.error(f"Analysis for {self._current} ran into error: {exc}")
finally:
self._current = None
self._current_progress = None
def _do_analysis(self, high_priority=False):
"""
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
overridden by sub classes.
Arguments:
high_priority (bool): Whether the current entry has high priority or not.
Returns:
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
construction.
"""
return None
def _do_abort(self, reenqueue=True):
"""
Aborts analysis of the current entry. Needs to be overridden by sub classes.
"""
pass
class GcodeAnalysisQueue(AbstractAnalysisQueue):
"""
A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows:
.. list-table::
:widths: 25 70
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in seconds
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
- * ``filament.toolX.length``
* The extruded length in mm
- * ``filament.toolX.volume``
* The extruded volume in cm³
- * ``printingArea``
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
- * ``printingArea.minX``
* Minimum X coordinate of the printed object
- * ``printingArea.maxX``
* Maximum X coordinate of the printed object
- * ``printingArea.minY``
* Minimum Y coordinate of the printed object
- * ``printingArea.maxY``
* Maximum Y coordinate of the printed object
- * ``printingArea.minZ``
* Minimum Z coordinate of the printed object
- * ``printingArea.maxZ``
* Maximum Z coordinate of the printed object
- * ``dimensions``
* Dimensions of the printed object in X, Y, Z
- * ``dimensions.width``
* Width of the printed model along the X axis, in mm
- * ``dimensions.depth``
* Depth of the printed model along the Y axis, in mm
- * ``dimensions.height``
* Height of the printed model along the Z axis, in mm
- * ``travelArea``
* Bounding box of all machine movements (minimum and maximum coordinates)
- * ``travelArea.minX``
* Minimum X coordinate of the machine movement
- * ``travelArea.maxX``
* Maximum X coordinate of the machine movement
- * ``travelArea.minY``
* Minimum Y coordinate of the machine movement
- * ``travelArea.maxY``
* Maximum Y coordinate of the machine movement
- * ``travelArea.minZ``
* Minimum Z coordinate of the machine movement
- * ``travelArea.maxZ``
* Maximum Z coordinate of the machine movement
- * ``travelDimensions``
* Dimensions of the travel area in X, Y, Z
- * ``travelDimensions.width``
* Width of the travel area along the X axis, in mm
- * ``travelDimensions.depth``
* Depth of the travel area along the Y axis, in mm
- * ``travelDimensions.height``
* Height of the travel area along the Z axis, in mm
"""
def __init__(self, finished_callback):
AbstractAnalysisQueue.__init__(self, finished_callback)
self._aborted = False
self._reenqueue = False
self._command = None
def _do_analysis(self, high_priority=False):
import sys
import sarge
if self._current.analysis and all(
map(
lambda x: x in self._current.analysis,
(
"printingArea",
"dimensions",
"travelArea",
"travelDimensions",
"estimatedPrintTime",
"filament",
),
)
):
return self._current.analysis
try:
throttle = (
settings().getFloat(["gcodeAnalysis", "throttle_highprio"])
if high_priority
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
)
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
bed_z = settings().getFloat(["gcodeAnalysis", "bedZ"])
speedx = self._current.printer_profile["axes"]["x"]["speed"]
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
command = [
sys.executable,
"-m",
"octoprint",
"analysis",
"gcode",
f"--speed-x={speedx}",
f"--speed-y={speedy}",
f"--max-t={max_extruders}",
f"--throttle={throttle}",
f"--throttle-lines={throttle_lines}",
f"--bed-z={bed_z}",
]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
self._logger.info(f"Invoking analysis command: {' '.join(command)}")
self._aborted = False
p = sarge.run(
command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture()
)
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
try:
# by now we should have a command, let's wait for its
# process to have been prepared
self._command = p.commands[0]
self._command.process_ready.wait()
if not self._command.process:
# the process might have been set to None in case of any exception
raise RuntimeError(
"Error while trying to run command {}".format(" ".join(command))
)
try:
# let's wait for stuff to finish
self._command.wait()
if self._aborted:
raise AnalysisAborted(reenqueue=self._reenqueue)
finally:
p.close()
finally:
self._command = None
output = p.stdout.text
self._logger.debug(f"Got output: {output!r}")
result = {}
if "ERROR:" in output:
_, error = output.split("ERROR:")
raise RuntimeError(error.strip())
elif "EMPTY:" in output:
self._logger.info("Result is empty, no extrusions found")
result = copy.deepcopy(EMPTY_RESULT)
elif "RESULTS:" not in output:
raise RuntimeError("No analysis result found")
else:
_, output = output.split("RESULTS:")
analysis = yaml.load_from_file(file=output)
result["printingArea"] = analysis["printing_area"]
result["dimensions"] = analysis["dimensions"]
result["travelArea"] = analysis["travel_area"]
result["travelDimensions"] = analysis["travel_dimensions"]
if analysis["total_time"]:
result["estimatedPrintTime"] = analysis["total_time"] * 60
if analysis["extrusion_length"]:
result["filament"] = {}
for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
"length": analysis["extrusion_length"][i],
"volume": analysis["extrusion_volume"][i],
}
if self._current.analysis and isinstance(self._current.analysis, dict):
return dict_merge(result, self._current.analysis)
else:
return result
finally:
self._gcode = None
def _do_abort(self, reenqueue=True):
self._aborted = True
self._reenqueue = reenqueue
if self._command:
self._logger.info(f"Terminating analysis subprocess for {self._current}...")
self._command.terminate()
| 20,460 | Python | .py | 482 | 30.917012 | 120 | 0.570229 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,998 | util.py | OctoPrint_OctoPrint/src/octoprint/filemanager/util.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 io
import os
from octoprint import UMASK
from octoprint.util import atomic_write
class AbstractFileWrapper:
"""
Wrapper for file representations to save to storages.
Arguments:
filename (str): The file's name
"""
DEFAULT_PERMISSIONS = 0o664
def __init__(self, filename):
self.filename = filename
def save(self, path, permissions=None):
"""
Saves the file's content to the given absolute path.
Arguments:
path (str): The absolute path to where to save the file
permissions (int): The permissions to set on the file
"""
raise NotImplementedError()
def stream(self):
"""
Returns a Python stream object (subclass of io.IOBase) representing the file's contents.
Returns:
io.IOBase: The file's contents as a stream.
"""
raise NotImplementedError()
class DiskFileWrapper(AbstractFileWrapper):
"""
An implementation of :class:`.AbstractFileWrapper` that wraps an actual file on disk. The `save` implementations
will either copy the file to the new path (preserving file attributes) or -- if `move` is `True` (the default) --
move the file.
Arguments:
filename (str): The file's name
path (str): The file's absolute path
move (boolean): Whether to move the file upon saving (True, default) or copying.
"""
def __init__(self, filename, path, move=True):
AbstractFileWrapper.__init__(self, filename)
self.path = path
self.move = move
def save(self, path, permissions=None):
import shutil
if self.move:
shutil.move(self.path, path)
else:
shutil.copy2(self.path, path)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
def stream(self):
return open(self.path, "rb")
class StreamWrapper(AbstractFileWrapper):
"""
A wrapper allowing processing of one or more consecutive streams.
Arguments:
*streams: One or more :py:class:`io.IOBase` streams to process one after another to save to storage.
"""
def __init__(self, filename, *streams):
if not len(streams) > 0:
raise ValueError("Need at least one stream to wrap")
AbstractFileWrapper.__init__(self, filename)
self.streams = streams
def save(self, path, permissions=None):
"""
Will dump the contents of all streams provided during construction into the target file, in the order they were
provided.
"""
import shutil
with atomic_write(path, mode="wb") as dest:
for source in self.streams:
shutil.copyfileobj(source, dest)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
def stream(self):
"""
If more than one stream was provided to the constructor, will return a :class:`.MultiStream` wrapping all
provided streams in the order they were provided, else the first and only stream is returned directly.
"""
if len(self.streams) > 1:
return MultiStream(*self.streams)
else:
return self.streams[0]
class MultiStream(io.RawIOBase):
"""
A stream implementation which when read reads from multiple streams, one after the other, basically concatenating
their contents in the order they are provided to the constructor.
Arguments:
*streams: One or more :py:class:`io.IOBase` streams to concatenate.
"""
def __init__(self, *streams):
super().__init__()
self.streams = streams
self.current_stream = 0
def read(self, n=-1):
if n == 0:
return b""
if len(self.streams) == 0:
return b""
while self.current_stream < len(self.streams):
stream = self.streams[self.current_stream]
result = stream.read(n)
if result is None or len(result) != 0:
return result
else:
self.current_stream += 1
return b""
def readinto(self, b):
n = len(b)
read = self.read(n)
b[: len(read)] = read
return len(read)
def close(self):
for stream in self.streams:
try:
stream.close()
except Exception:
pass
def readable(self, *args, **kwargs):
return True
def seekable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
class LineProcessorStream(io.RawIOBase):
"""
While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method
:meth:`.process_line` for each read line.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that
``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need
to do the decoding yourself.
Arguments:
input_stream (io.RawIOBase): The stream to process on the fly.
"""
def __init__(self, input_stream):
super().__init__()
self.input_stream = io.BufferedReader(input_stream)
self.leftover = bytearray()
def read(self, n=-1):
if n == 0:
return b""
result = bytearray()
while len(result) < n or n == -1:
# add left over from previous loop
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(self.leftover):
# only s
result += self.leftover[:bytes_left]
self.leftover = self.leftover[bytes_left:]
break
else:
result += self.leftover
self.leftover = bytearray()
# read one line from the underlying stream
processed_line = None
while processed_line is None:
line = self.input_stream.readline()
if not line:
break
processed_line = self.process_line(line)
if processed_line is None:
break
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(processed_line):
result += processed_line[:bytes_left]
self.leftover = processed_line[bytes_left:]
break
else:
result += processed_line
return bytes(result)
def readinto(self, b):
n = len(b)
read = self.read(n)
b[: len(read)] = read
return len(read)
def process_line(self, line):
"""
Called from the `read` Method of this stream with each line read from `self.input_stream`.
By returning ``None`` the line will not be returned from the read stream, effectively being stripped from the
wrapper `input_stream`.
Arguments:
line (bytes): The line as read from `self.input_stream` in byte representation
Returns:
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
stripped from the processed stream.
"""
return line
def close(self):
self.input_stream.close()
def readable(self, *args, **kwargs):
return True
def seekable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
| 7,995 | Python | .py | 200 | 30.665 | 121 | 0.60869 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |
21,999 | destinations.py | OctoPrint_OctoPrint/src/octoprint/filemanager/destinations.py | __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
class FileDestinations:
SDCARD = "sdcard"
LOCAL = "local"
| 156 | Python | .py | 4 | 35.5 | 87 | 0.72 | OctoPrint/OctoPrint | 8,222 | 1,667 | 264 | AGPL-3.0 | 9/5/2024, 5:13:10 PM (Europe/Amsterdam) |