Merge branch 'maintenance' into devel

This commit is contained in:
Gina Häußge committed 2023-01-26 09:23:25 +01:00
commit 63ec0d5bca
56 files changed
+652 -3359

No files matched your search

+6 -7
View File
@@ -55,24 +55,23 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- name: 👀 Determine latest release
id: latest
uses: foosel/github-action-get-latest-release@master
with:
repository: "OctoPrint/OctoPrint"
run: |
OCTOPRINT_VERSION=$(curl -i https://github.com/OctoPrint/OctoPrint/releases/latest | grep -i location: | head -n1 | awk -F/ '{print $NF}' | tr -d '\r')
echo "OCTOPRINT_VERSION=$OCTOPRINT_VERSION" >> $GITHUB_ENV
- name: 🐍 Set up Python ${{ matrix.python }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python }}
- name: 👷 Build and install latest release
run: |
pip install https://github.com/OctoPrint/OctoPrint/archive/${{ steps.latest.outputs.release }}.zip
pip install https://github.com/OctoPrint/OctoPrint/archive/${{ env.OCTOPRINT_VERSION }}.zip
- name: 📧 Discord success notification
continue-on-error: true
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful"
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ env.OCTOPRINT_VERSION }}` was successful"
- name: 📧 Discord failure notification
continue-on-error: true
if: failure()
@@ -80,4 +79,4 @@ jobs:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed"
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ env.OCTOPRINT_VERSION }}` failed"
+1
View File
@@ -176,6 +176,7 @@ date of first contribution):
* [Frederik Kemner](https://github.com/040medien)
* [Moiz Rasheed](https://github.com/msrasheed)
* [Scott Martin](https://github.com/smartin015)
* [Shyam Sunder](https://github.com/sgsunder)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+1 -1
View File
@@ -44,7 +44,7 @@
* [emoji](https://github.com/carpedm20/emoji/): BSD
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
* [filetype](https://h2non.github.io/filetype.py/): MIT
* [Flask](http://flask.pocoo.org/): BSD
* [Flask](https://flask.palletsprojects.com/): BSD
* [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD
* [Flask-Babel](http://github.com/mitsuhiko/flask-babel): BSD
* [Flask-Login](https://github.com/maxcountryman/flask-login): MIT
+3 -8
View File
@@ -473,7 +473,7 @@ Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
OctoPrint injects the template variables that your plugin defines prefixed with ``plugin_<plugin identifier>_`` into
the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple
`Jinja2 Variable <http://jinja.octoprint.org/templates.html#variables>`_ in your plugin's template.
`Jinja2 Variable <https://jinja.palletsprojects.com/templates.html#variables>`_ in your plugin's template.
Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should
still work and point to the URL we defined as default.
@@ -1041,10 +1041,9 @@ might show what's possible with a few lines of code already. Finally, just take
.. seealso::
`Jinja Template Designer Documentation <http://jinja.octoprint.org/templates.html>`_
`Jinja Template Designer Documentation <https://jinja.palletsprojects.com/templates.html>`_
Jinja's Template Designer Documentation describes the syntax and semantics of the template language used
by OctoPrint's frontend. Linked here are the docs for Jinja 2.8.1, which OctoPrint still
relies on for backwards compatibility reasons [#f3]_.
by OctoPrint's frontend.
.. rubric:: Footnotes
@@ -1057,7 +1056,3 @@ might show what's possible with a few lines of code already. Finally, just take
.. [#f2] Refer to the `LESS documentation <http://lesscss.org/#using-less>`_ on how to do that. If you are developing
your plugin under Windows you might also want to give `WinLESS <http://winless.org/>`_ a look which will run
in the background and keep your CSS files up to date with your various project's LESS files automatically.
.. [#f3] Please always consult the Jinja documentation at `jinja.octoprint.org <http://jinja.octoprint.org>`_ instead of
the current stable documentation available at Jinja's project page. The reason for that is that for backwards
compatibility reasons OctoPrint currently sadly has to rely on an older version of Jinja. The documentation
available at `jinja.octoprint.org <http://jinja.octoprint.org>`_ matches that older version.
+35 -1
View File
@@ -264,6 +264,7 @@ def init_logging(
# default logging configuration
if default_config is None:
simple_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"
default_config = {
"version": 1,
"formatters": {
@@ -280,6 +281,13 @@ def init_logging(
},
},
"serial": {"format": "%(asctime)s - %(message)s"},
"tornado": {
"()": "tornado.log.LogFormatter",
"color": False,
"format": simple_format,
"datefmt": date_format,
},
"auth": {"format": "%(asctime)s - %(message)s"},
"timings": {"format": "%(asctime)s - %(message)s"},
"timingscsv": {"format": "%(asctime)s;%(func)s;%(timing)f"},
},
@@ -310,6 +318,22 @@ def init_logging(
),
"delay": True,
},
"tornadoFile": {
"class": "octoprint.logging.handlers.TornadoLogHandler",
"level": "DEBUG",
"formatter": "tornado",
"backupCount": 1,
"filename": os.path.join(
settings.getBaseFolder("logs"), "tornado.log"
),
},
"authFile": {
"class": "octoprint.logging.handlers.AuthLogHandler",
"level": "DEBUG",
"formatter": "auth",
"backupCount": 1,
"filename": os.path.join(settings.getBaseFolder("logs"), "auth.log"),
},
"pluginTimingsFile": {
"class": "octoprint.logging.handlers.PluginTimingsLogHandler",
"level": "DEBUG",
@@ -337,12 +361,22 @@ def init_logging(
"handlers": ["serialFile"],
"propagate": False,
},
"AUTH": {
"level": "INFO",
"handlers": ["authFile"],
"propagate": False,
},
"PLUGIN_TIMINGS": {
"level": "INFO",
"handlers": ["pluginTimingsFile", "pluginTimingsCsvFile"],
"propagate": False,
},
"PLUGIN_TIMINGS.octoprint.plugin": {"level": "INFO"},
"tornado.access": {
"level": "INFO",
"handlers": ["tornadoFile"],
"propagate": False,
},
"octoprint": {"level": "INFO"},
"octoprint.util": {"level": "INFO"},
"octoprint.plugins": {"level": "INFO"},
@@ -826,7 +860,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
if isinstance(result, list):
return result
def fetch_blacklist_from_url(url, timeout=3, cache=None):
def fetch_blacklist_from_url(url, timeout=3.05, cache=None):
result = []
try:
r = requests.get(url, timeout=timeout)
+15
View File
@@ -1,4 +1,19 @@
import logging
ADMIN_GROUP = "admins"
USER_GROUP = "users"
GUEST_GROUP = "guests"
READONLY_GROUP = "readonly"
def auth_log(message):
logging.getLogger("AUTH").info(message)
login_mechanisms = login_mechanism_lut = {
"http": "credentials",
"autologin": "autologin",
"remember_me": "Remember Me cookie",
"basic_auth": "Basic Authorization header",
"remote_user": "Remote User header",
}
+20 -6
View File
@@ -259,7 +259,10 @@ class OctoPrintDevelCommands(click.MultiCommand):
)
@click.option("--all", "all_files", is_flag=True, help="Build all less files")
@click.option(
"--list", "list_files", is_flag=True, help="List all available files and exit"
"--list",
"list_files",
is_flag=True,
help="List all available files and exit",
)
def command(files, all_files, list_files):
import shutil
@@ -312,12 +315,24 @@ class OctoPrintDevelCommands(click.MultiCommand):
# Check that lessc is installed
less = shutil.which("lessc")
if not less:
# Check that less-plugin-clean-css is installed
if less:
_, _, stderr = self.command_caller.call(
[less, "--clean-css"], logged=False
)
clean_css = not any(
map(lambda x: "Unable to load plugin clean-css" in x, stderr)
)
else:
clean_css = False
if not less or not clean_css:
click.echo(
"lessc is not installed/not available, please install it first"
"lessc or less-plugin-clean-css is not installed/not available, please install it first"
)
click.echo(
"Try `npm i -g less` to install it (NOT lessc in this command!)"
"Try `npm i -g less less-plugin-clean-css` to install both (note that it does NOT say 'lessc' in this command!)"
)
sys.exit(1)
@@ -327,10 +342,9 @@ class OctoPrintDevelCommands(click.MultiCommand):
sys.exit(1)
# Build command line, with necessary options
# TODO -x is deprecated, find replacement?
less_command = [
less,
"-x",
"--clean-css=--s1 --advanced --compatibility=ie8",
available_files[less_file]["source"],
available_files[less_file]["output"],
]
+1
View File
@@ -92,6 +92,7 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None
for log in (
"octoprint.log",
"serial.log",
"tornado.log",
):
logpath = os.path.join(logbase, log)
if os.path.exists(logpath):
+5 -5
View File
@@ -181,19 +181,19 @@ def get_content_type_mapping_for_extension(extension, subtree=None):
return None
def valid_extension(extension, type=None):
def valid_extension(extension, type=None, tree=None):
if not type:
return extension in get_all_extensions()
return extension in get_all_extensions(subtree=tree)
else:
extensions = get_extensions(type)
extensions = get_extensions(type, subtree=tree)
if extensions:
return extension in extensions
def valid_file_type(filename, type=None):
def valid_file_type(filename, type=None, tree=None):
_, extension = os.path.splitext(filename)
extension = extension[1:].lower()
return valid_extension(extension, type=type)
return valid_extension(extension, type=type, tree=tree)
def get_file_type(filename):
+8
View File
@@ -137,6 +137,14 @@ class PluginTimingsLogHandler(TriggeredRolloverLogHandler):
pass
class TornadoLogHandler(CleaningTimedRotatingFileHandler):
pass
class AuthLogHandler(CleaningTimedRotatingFileHandler):
pass
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, *args, **kwargs):
super().__init__(*args, **kwargs)
+11 -11
View File
@@ -600,7 +600,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
OctoPrint will query whether your mixin implementation will handle a
provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask
`Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object as
`Request <https://flask.palletsprojects.com/api/#flask.Request>`_ object as
parameter. If you plugin returns `True` here, OctoPrint will next call
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like
- again - the Flask Request object and the render keyword arguments as
@@ -676,7 +676,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
``UiPlugin.will_handle_ui``.
Arguments:
request (flask.Request): A Flask `Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_
request (flask.Request): A Flask `Request <https://flask.palletsprojects.com/api/#flask.Request>`_
object.
Returns:
@@ -761,12 +761,12 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
now (datetime.datetime): The datetime instance representing "now"
for this request, in case your plugin implementation needs this
information.
request (flask.Request): A Flask `Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object.
request (flask.Request): A Flask `Request <https://flask.palletsprojects.com/api/#flask.Request>`_ object.
render_kwargs (dict): The (cached) render keyword arguments that
would usually be provided to the core UI render function.
Returns:
flask.Response: Should return a Flask `Response <http://flask.pocoo.org/docs/0.10/api/#flask.Response>`_
flask.Response: Should return a Flask `Response <https://flask.palletsprojects.com/api/#flask.Response>`_
object that can be served to the requesting client directly. May be
created with ``flask.make_response`` combined with something like
``flask.render_template``.
@@ -1173,7 +1173,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
"""
Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one
resource accepting JSON commands POSTed to it. This is the easy alternative for plugin's which don't need the
full power of a `Flask Blueprint <http://flask.pocoo.org/docs/0.10/blueprints/>`_ that the :class:`BlueprintPlugin`
full power of a `Flask Blueprint <https://flask.palletsprojects.com/blueprints/>`_ that the :class:`BlueprintPlugin`
mixin offers.
Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend
@@ -1298,7 +1298,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
def on_api_get(self, request):
"""
Called by OctoPrint upon a GET request to ``/api/plugin/<plugin identifier>``. ``request`` will contain the
received `Flask request object <http://flask.pocoo.org/docs/0.9/api/#flask.Request>`_ which you may evaluate
received `Flask request object <https://flask.palletsprojects.com/api/#flask.Request>`_ which you may evaluate
for additional arguments supplied with the request.
If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content``
@@ -1317,7 +1317,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose,
be it a more sophisticated API than what is possible via the :class:`SimpleApiPlugin` or a custom web frontend.
The mechanism at work here is `Flask's <http://flask.pocoo.org/>`_ own `Blueprint mechanism <http://flask.pocoo.org/docs/0.10/blueprints/>`_.
The mechanism at work here is `Flask's <https://flask.palletsprojects.com/>`_ own `Blueprint mechanism <https://flask.palletsprojects.com/blueprints/>`_.
The mixin automatically creates a blueprint for you that will be registered under ``/plugin/<plugin identifier>/``.
All you need to do is decorate all of your view functions with the :func:`route` decorator,
@@ -1389,8 +1389,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
A decorator to mark view methods in your BlueprintPlugin subclass. Works just the same as Flask's
own ``route`` decorator available on blueprints.
See `the documentation for flask.Blueprint.route <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.route>`_
and `the documentation for flask.Flask.route <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.route>`_ for more
See `the documentation for flask.Blueprint.route <https://flask.palletsprojects.com/api/#flask.Blueprint.route>`_
and `the documentation for flask.Flask.route <https://flask.palletsprojects.com/api/#flask.Flask.route>`_ for more
information.
"""
@@ -1413,8 +1413,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's
own ``errorhandler`` decorator available on blueprints.
See `the documentation for flask.Blueprint.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.errorhandler>`_
and `the documentation for flask.Flask.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.errorhandler>`_ for more
See `the documentation for flask.Blueprint.errorhandler <https://flask.palletsprojects.com/api/#flask.Blueprint.errorhandler>`_
and `the documentation for flask.Flask.errorhandler <https://flask.palletsprojects.com/api/#flask.Flask.errorhandler>`_ for more
information.
.. versionadded:: 1.3.0
@@ -437,7 +437,7 @@ class AnnouncementPlugin(
if data is None:
# cache not allowed or empty, fetch from network
if self._connectivity_checker.online:
if self._connectivity_checker.check_immediately():
data = self._get_channel_data_from_network(key, config)
else:
self._logger.info(
@@ -488,7 +488,7 @@ class AnnouncementPlugin(
url = config["url"]
try:
start = time.monotonic()
r = requests.get(url, timeout=30)
r = requests.get(url, timeout=3.05)
r.raise_for_status()
self._logger.info(
"Loaded channel {} from {} in {:.2}s".format(
@@ -1 +1 @@
table th.settings_plugin_announcements_channels_name,table td.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_announcements_channels_actions,table td.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table th.settings_plugin_announcements_channels_actions a,table td.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table th.settings_plugin_announcements_channels_actions a.disabled,table td.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:bold}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:black}#plugin_announcements_dialog .modal-footer .configurelink{float:left}
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}#plugin_announcements_dialog .modal-footer .configurelink{float:left}
@@ -1 +1 @@
#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a{color:black}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type="checkbox"],#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type="checkbox"]{margin-top:0}#plugin_appkeys_keygenerated .control-text{display:inline-block}
#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}#plugin_appkeys_keygenerated .control-text{display:inline-block}
@@ -1 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}#auth-choice,#auth-done,#auth-error,#auth-offline{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05);text-align:center}.form-auth-heading{margin-bottom:10px}
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}#auth-choice,#auth-done,#auth-error,#auth-offline{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05);text-align:center}.form-auth-heading{margin-bottom:10px}
+1 -1
View File
@@ -840,7 +840,7 @@ class BackupPlugin(
logger = logging.getLogger(__name__)
try:
r = requests.get(url, timeout=30)
r = requests.get(url, timeout=3.05)
r.raise_for_status()
except Exception:
logger.exception(
@@ -1 +1 @@
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:black}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type="checkbox"]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:bold}#settings_plugin_backup_restoredialog_output .error{font-weight:bold;color:#990000}#settings_plugin_backup_restoredialog_output .stdout{color:#333333}#settings_plugin_backup_restoredialog_output .stderr{color:#990000}#settings_plugin_backup_restoredialog_output .call{color:#000099}
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009}
@@ -1,148 +1 @@
#webcam_video_container {
width: 100%;
position: relative;
outline: none;
}
#webcam_video_container .video-controls {
position: absolute;
bottom: 0px;
right: 8px;
z-index: 10;
opacity: 0.4;
}
#webcam_video_container:hover .video-controls {
opacity: 1;
}
#webcam_video_container #webcam_hls,
#webcam_video_container #webcam_rtsp {
width: 100%;
height: 100%;
}
#webcam_video_container .webcam_rotated {
position: relative;
width: 100%;
padding-bottom: 56.25%;
display: flex;
justify-content: center;
align-items: center;
margin: auto;
}
#webcam_video_container .webcam_rotated .rotation_target {
position: absolute;
transform: rotate(-90deg);
width: 100%;
}
#webcam_video_container .webcam_rotated .rotation_target div {
width: 100%;
height: 100%;
}
#webcam_video_container .webcam_unrotated {
position: relative;
width: 100%;
}
#webcam_img_container {
width: 100%;
position: relative;
outline: none;
background-color: black;
}
#webcam_img_container .keycontrol_overlay {
position: absolute;
left: 10px;
right: 10px;
bottom: 10px;
background: rgba(0, 0, 0, 0.5);
font-size: 85%;
color: white;
padding: 0;
}
#webcam_img_container .keycontrol_overlay kbd {
border: 1px solid #eeeeee;
border-radius: 3px;
margin-left: 2px;
margin-right: 2px;
font-size: 90%;
padding: 2px;
min-width: 1em;
}
#webcam_img_container .keycontrol_overlay .keycontrol_overlay_heading {
position: relative;
padding: 10px;
font-weight: bold;
}
#webcam_img_container .keycontrol_overlay .keycontrol_overlay_column {
position: relative;
width: 45%;
padding: 10px;
float: left;
}
#webcam_img_container .nowebcam {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
#webcam_img_container .nowebcam .text {
color: white;
text-align: center;
position: relative;
margin: auto;
width: 80%;
top: 50%;
transform: translateY(-50%);
display: block;
}
#webcam_img_container .nowebcam .text.webcam_loading {
animation: pulsate 3s ease-out;
animation-iteration-count: infinite;
}
#webcam_img_container .webcam_rotated {
position: relative;
width: 100%;
padding-bottom: 100%;
pointer-events: none;
}
#webcam_img_container .webcam_rotated .webcam_fixed_ratio {
position: absolute;
transform: rotate(-90deg);
top: 0;
bottom: 0;
pointer-events: none;
}
#webcam_img_container .webcam_rotated .webcam_fixed_ratio .webcam_fixed_ratio_inner {
width: 100%;
height: 100%;
pointer-events: none;
}
#webcam_img_container .webcam_unrotated .webcam_fixed_ratio {
width: 100%;
pointer-events: none;
padding-bottom: 100%;
position: relative;
}
#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio43 {
padding-bottom: 75%;
}
#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio169 {
padding-bottom: 56.25%;
}
#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio1610 {
padding-bottom: 62.5%;
}
#webcam_img_container .webcam_unrotated .webcam_fixed_ratio .webcam_fixed_ratio_inner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
pointer-events: none;
}
#webcam_img_container img {
width: 100%;
height: 100%;
object-fit: contain;
}
#webcamTestContainer {
min-height: 384px;
}
#webcam_video_container{width:100%;position:relative;outline:0}#webcam_video_container .video-controls{position:absolute;bottom:0;right:8px;z-index:10;opacity:.4}#webcam_video_container:hover .video-controls{opacity:1}#webcam_video_container #webcam_hls,#webcam_video_container #webcam_rtsp{width:100%;height:100%}#webcam_video_container .webcam_rotated{position:relative;width:100%;padding-bottom:56.25%;display:flex;justify-content:center;align-items:center;margin:auto}#webcam_video_container .webcam_rotated .rotation_target{position:absolute;transform:rotate(-90deg);width:100%}#webcam_img_container,#webcam_video_container .webcam_unrotated{width:100%;position:relative}#webcam_video_container .webcam_rotated .rotation_target div{width:100%;height:100%}#webcam_img_container{outline:0;background-color:#000}#webcam_img_container .keycontrol_overlay{position:absolute;left:10px;right:10px;bottom:10px;background:rgba(0,0,0,.5);font-size:85%;color:#fff;padding:0}#webcam_img_container .keycontrol_overlay kbd{border:1px solid #eee;border-radius:3px;margin-left:2px;margin-right:2px;font-size:90%;padding:2px;min-width:1em}#webcam_img_container .keycontrol_overlay .keycontrol_overlay_heading{position:relative;padding:10px;font-weight:700}#webcam_img_container .keycontrol_overlay .keycontrol_overlay_column{position:relative;width:45%;padding:10px;float:left}#webcam_img_container .nowebcam{position:absolute;top:0;left:0;right:0;bottom:0}#webcam_img_container .nowebcam .text{color:#fff;text-align:center;position:relative;margin:auto;width:80%;top:50%;transform:translateY(-50%);display:block}#webcam_img_container .nowebcam .text.webcam_loading{animation:pulsate 3s ease-out;animation-iteration-count:infinite}#webcam_img_container .webcam_rotated{position:relative;width:100%;padding-bottom:100%;pointer-events:none}#webcam_img_container .webcam_rotated .webcam_fixed_ratio{position:absolute;transform:rotate(-90deg);top:0;bottom:0;pointer-events:none}#webcam_img_container .webcam_rotated .webcam_fixed_ratio .webcam_fixed_ratio_inner{width:100%;height:100%;pointer-events:none}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio{width:100%;pointer-events:none;padding-bottom:100%;position:relative}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio43{padding-bottom:75%}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio169{padding-bottom:56.25%}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio1610{padding-bottom:62.5%}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio .webcam_fixed_ratio_inner{position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none}#webcam_img_container img{width:100%;height:100%;object-fit:contain}#webcamTestContainer{min-height:384px}
@@ -37,25 +37,6 @@ class ServerCommandsSubwizard:
return gettext("Server Commands")
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class WebcamSubwizard:
def _is_webcam_wizard_firstrunonly(self):
return True
def _is_webcam_wizard_required(self):
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
def _get_webcam_wizard_details(self):
return {"required": self._is_webcam_wizard_required()}
def _get_webcam_wizard_name(self):
return gettext("Webcam & Timelapse")
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class AclSubwizard:
def _is_acl_wizard_firstrunonly(self):
@@ -1,42 +0,0 @@
<h3>{{ _('Webcam &amp; Timelapse Recordings') }}</h3>
{% trans %}<p>
If you have a webcam, you may now configure it here.
</p>{% endtrans %}
<h4>{{ _('Webcam') }}</h4>
{% trans %}<p>
The <strong>Stream URL</strong> is the URL OctoPrint uses to embed the
actual webcam stream (which should be an MJPG stream) into the web
interface. This needs to be reachable <strong>from your browser</strong>.
</p><p>
It may be
<ul>
<li>a fully qualified URL (<code>http://host:port/path</code>),</li>
<li>a URL defaulting to the protocol used for accessing the web
interface (e.g. <code>//host:port/path</code>),</li>
<li>an absolute path on the same host as OctoPrint (e.g. <code>/absolute/path</code>) or</li>
<li>a relative path on the same host as OctoPrint (e.g. <code>relative/path</code>)</li>
</ul>
</p><p>
The <strong>Snapshot URL</strong> is the URL OctoPrint uses to fetch single
images from the webcam for creating timelapse recordings. This needs to be
a fully qualified URL reachable <strong>from the OctoPrint server</strong>.
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel" onsubmit="return false;">
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
</form>
<h4>{{ _('Timelapse Recordings') }}</h4>
{% trans %}<p>
To render the snapshots into timelapse recordings, OctoPrint also needs to
know the correct <strong>path to FFMPEG</strong>.
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel" onsubmit="return false;">
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
</form>
@@ -1 +1 @@
#gcode .progress{width:588px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode .canvas_container{position:relative}#gcode .canvas_container:hover,#gcode .canvas_container:active{outline:0}#gcode .layer-buttons{padding-top:5px;padding-bottom:7px}#gcode #gcode_layer_slider{position:absolute;right:0;top:0;height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}
#gcode .progress{width:588px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode .canvas_container{position:relative}#gcode .canvas_container:active,#gcode .canvas_container:hover{outline:0}#gcode .layer-buttons{padding-top:5px;padding-bottom:7px}#gcode #gcode_layer_slider{position:absolute;right:0;top:0;height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}
@@ -1 +1 @@
table th.settings_logs_checkbox,table td.settings_logs_checkbox{text-align:center;width:10px}table th.settings_logs_checkbox input[type="checkbox"],table td.settings_logs_checkbox input[type="checkbox"]{margin-top:0}table th.settings_logs_name,table td.settings_logs_name{text-overflow:ellipsis;text-align:left}table th.settings_logs_size,table td.settings_logs_size{text-align:right;width:70px}table th.settings_logs_date,table td.settings_logs_date{text-align:left;width:130px}table th.settings_logs_action,table td.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table th.settings_logs_action a,table td.settings_logs_action a{text-decoration:none;color:#000}table th.settings_logs_action a.disabled,table td.settings_logs_action a.disabled{color:#ccc;cursor:default}
table td.settings_logs_checkbox,table th.settings_logs_checkbox{text-align:center;width:10px}table td.settings_logs_checkbox input[type=checkbox],table th.settings_logs_checkbox input[type=checkbox]{margin-top:0}table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
+170 -36
View File
@@ -105,12 +105,6 @@ def map_repository_entry(entry):
return result
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
success_string = "Successfully installed"
failure_string = "Could not install"
python_mismatch_string = "requires a different Python:"
class PluginManagerPlugin(
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
@@ -123,6 +117,7 @@ class PluginManagerPlugin(
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 = (
@@ -174,6 +169,7 @@ class PluginManagerPlugin(
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
@@ -192,6 +188,7 @@ class PluginManagerPlugin(
self._install_task = None
self._install_lock = threading.RLock()
self._jsoninstall_lock = threading.Lock()
self._queued_installs = []
self._queued_installs_abort_timer = None
@@ -348,7 +345,9 @@ class PluginManagerPlugin(
return {
"all": plugins,
"thirdparty": list(filter(lambda p: not p["bundled"], plugins)),
"file_extensions": self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS,
"file_extensions": self.ARCHIVE_EXTENSIONS
+ self.PYTHON_EXTENSIONS
+ self.JSON_EXTENSIONS,
}
def get_template_types(self, template_sorting, template_rules, *args, **kwargs):
@@ -391,7 +390,7 @@ class PluginManagerPlugin(
exts = list(
filter(
lambda x: upload_name.lower().endswith(x),
self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS,
self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS + self.JSON_EXTENSIONS,
)
)
if not len(exts):
@@ -445,11 +444,15 @@ class PluginManagerPlugin(
def export_plugin_list(self):
import json
plugins = self.generate_plugins_json(self._settings, self._plugin_manager)
plugins = self.generate_plugins_json(
self._settings,
self._plugin_manager,
repo_plugins=self._repository_plugins_by_id,
)
return Response(
json.dumps(plugins),
mimetype="text/plain",
mimetype="application/json",
headers={"Content-Disposition": 'attachment; filename="plugin_list.json"'},
)
@@ -472,6 +475,7 @@ class PluginManagerPlugin(
"supported_extensions": {
"archive": self.ARCHIVE_EXTENSIONS,
"python": self.PYTHON_EXTENSIONS,
"json": self.JSON_EXTENSIONS,
},
}
@@ -877,6 +881,18 @@ class PluginManagerPlugin(
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,
@@ -885,6 +901,7 @@ class PluginManagerPlugin(
force=False,
reinstall=None,
dependency_links=False,
partial=False,
):
folder = None
@@ -909,11 +926,25 @@ class PluginManagerPlugin(
force=force,
reinstall=reinstall,
dependency_links=dependency_links,
partial=partial,
)
elif self._is_pythonfile(path):
result = self._command_install_pythonfile(
path, source=source, source_type=source_type, name=name
path,
source=source,
source_type=source_type,
name=name,
partial=partial,
)
elif self._is_jsonfile(path):
result = self._command_install_jsonfile(
path,
source=source,
source_type=source_type,
name=name,
partial=partial,
)
else:
@@ -927,7 +958,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": f"Could not fetch plugin from server, got {e}",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
except exceptions.InvalidPackageFormat:
self._logger.error(
@@ -942,7 +973,7 @@ class PluginManagerPlugin(
"reason": "Could not install plugin from {}, was neither "
"a plugin archive nor a single file plugin".format(source),
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
except Exception:
error_msg = (
@@ -957,7 +988,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": error_msg,
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
finally:
if folder is not None:
@@ -975,6 +1006,7 @@ class PluginManagerPlugin(
force=False,
reinstall=None,
dependency_links=False,
partial=False,
):
throttled = self._get_throttled()
if (
@@ -995,7 +1027,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": error_msg,
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
from urllib.parse import quote as url_quote
@@ -1049,11 +1081,11 @@ class PluginManagerPlugin(
source
),
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
if is_python_mismatch(stderr):
return self.handle_python_mismatch(source, source_type)
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
@@ -1072,7 +1104,7 @@ class PluginManagerPlugin(
source
),
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
if is_python_mismatch(stderr):
@@ -1091,7 +1123,7 @@ class PluginManagerPlugin(
"reason": "Could not parse output from pip, see plugin_pluginmanager_console.log "
"for generated output",
}
self._send_result_notification("install", result)
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
@@ -1118,7 +1150,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": "Pip did not report successful installation",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
installed = list(
@@ -1145,7 +1177,7 @@ class PluginManagerPlugin(
"was_reinstalled": False,
"plugin": "unknown",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
self._plugin_manager.reload_plugins()
@@ -1201,10 +1233,10 @@ class PluginManagerPlugin(
or reinstall is not None,
"plugin": self._to_external_plugin(new_plugin),
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
def _handle_python_mismatch(self, source, source_type):
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
@@ -1217,11 +1249,13 @@ class PluginManagerPlugin(
"reason": "Pip reported a Python version mismatch",
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
}
self._send_result_notification("install", result)
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):
def _command_install_pythonfile(
self, path, source=None, source_type=None, name=None, partial=False
):
if name is None:
name = os.path.basename(path)
@@ -1250,7 +1284,7 @@ class PluginManagerPlugin(
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
pythoncompat = metadata.get(
@@ -1264,7 +1298,7 @@ class PluginManagerPlugin(
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
# copy plugin
@@ -1279,7 +1313,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": "Plugin could not be copied",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
plugins = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False)
@@ -1299,7 +1333,7 @@ class PluginManagerPlugin(
"was_reinstalled": False,
"plugin": "unknown",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
self._plugin_manager.reload_plugins()
@@ -1343,7 +1377,96 @@ class PluginManagerPlugin(
"was_reinstalled": new_plugin.key in all_plugins_before,
"plugin": self._to_external_plugin(new_plugin),
}
self._send_result_notification("install", result)
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
):
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
)
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):
@@ -1680,8 +1803,11 @@ class PluginManagerPlugin(
return None
def _send_result_notification(self, action, result):
notification = {"type": "result", "action": action}
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)
@@ -1864,7 +1990,7 @@ class PluginManagerPlugin(
repository_url = self._settings.get(["repository"])
try:
r = requests.get(repository_url, timeout=30)
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:
@@ -1912,6 +2038,7 @@ class PluginManagerPlugin(
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):
@@ -1953,7 +2080,7 @@ class PluginManagerPlugin(
notices_url = self._settings.get(["notices"])
try:
r = requests.get(notices_url, timeout=30)
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:
@@ -2089,7 +2216,11 @@ class PluginManagerPlugin(
@staticmethod
def generate_plugins_json(
settings, plugin_manager, ignore_bundled=True, ignore_plugins_folder=True
settings,
plugin_manager,
ignore_bundled=True,
ignore_plugins_folder=True,
repo_plugins=None,
):
plugins = []
plugin_folder = settings.getBaseFolder("plugins")
@@ -2102,7 +2233,10 @@ class PluginManagerPlugin(
# ignore bundled or from the plugins folder already included in the backup
continue
plugins.append({"key": plugin.key, "name": plugin.name, "url": plugin.url})
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):
@@ -1 +1 @@
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox{text-align:center;width:10px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox input[type="checkbox"],#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox input[type="checkbox"]{margin-top:0}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px !important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px;padding-right:10px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty{overflow:hidden;width:100%;height:400px;background-image:url("../img/repo_unavailable.png");text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:bold}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:bold;color:#990000}#settings_plugin_pluLine truncated
#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox],#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox],#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{color:#000;text-decoration:none}#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox{text-align:center;width:10px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output{font-size:.8em}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugLine truncated
@@ -212,6 +212,7 @@ $(function () {
self.online = ko.observable();
self.supportedArchiveExtensions = ko.observableArray([]);
self.supportedPythonExtensions = ko.observableArray([]);
self.supportedJsonExtensions = ko.observableArray([]);
var createExtensionsHelp = function (extensions) {
return _.reduce(
@@ -235,15 +236,21 @@ $(function () {
self.supportedExtensionsHelp = ko.pureComputed(function () {
var archiveExts = createExtensionsHelp(self.supportedArchiveExtensions());
var pythonExts = createExtensionsHelp(self.supportedPythonExtensions());
var jsonExts = createExtensionsHelp(self.supportedJsonExtensions());
return _.sprintf(
gettext(
"This does not look like a valid plugin. Valid plugins should be " +
"either archives installable via <code>pip</code> that " +
"have the extension %(archiveExtensions)s, or single file python " +
"plugins with the extension %(pythonExtensions)s."
"plugins with the extension %(pythonExtensions)s, or a plugin list " +
"export with the extension %(jsonExtensions)s."
),
{archiveExtensions: archiveExts, pythonExtensions: pythonExts}
{
archiveExtensions: archiveExts,
pythonExtensions: pythonExts,
jsonExtensions: jsonExts
}
);
});
@@ -429,21 +436,19 @@ $(function () {
);
});
self.hasExtension = function (name, extensions) {
const lowerName = name.toLocaleLowerCase();
return extensions.some((ext) => lowerName.endsWith(ext));
};
self.invalidFile = ko.pureComputed(function () {
var allowedFileExtensions = self
.supportedArchiveExtensions()
.concat(self.supportedPythonExtensions());
.concat(self.supportedPythonExtensions())
.concat(self.supportedJsonExtensions());
var name = self.uploadFilename();
var lowerName = name !== undefined ? name.toLocaleLowerCase() : undefined;
var lowerNameHasExtension = function (extension) {
return _.endsWith(lowerName, extension);
};
return (
name !== undefined && !_.any(allowedFileExtensions, lowerNameHasExtension)
);
return name !== undefined && !self.hasExtension(name, allowedFileExtensions);
});
self.enableFileInstall = ko.pureComputed(function () {
@@ -468,18 +473,44 @@ $(function () {
return false;
}
self.uploadFilename(data.files[0].name);
var name = data.files[0].name;
self.uploadFilename(name);
var isJsonFile =
name !== undefined &&
self.hasExtension(name, self.supportedJsonExtensions());
self.uploadButton.unbind("click");
self.uploadButton.bind("click", function () {
self._markWorking(
gettext("Installing plugin..."),
gettext("Installing plugin from uploaded file...")
);
data.formData = {
dependency_links: self.followDependencyLinks()
const proceed = () => {
self._markWorking(
isJsonFile
? gettext("Installing plugins...")
: gettext("Installing plugin..."),
isJsonFile
? gettext("Installing plugins from uploaded file...")
: gettext("Installing plugin from uploaded file...")
);
data.formData = {
dependency_links: self.followDependencyLinks()
};
data.submit();
};
data.submit();
if (isJsonFile) {
showConfirmationDialog({
title: gettext("Confirm installation of multiple plugins"),
message: gettext(
"Please confirm you want to perform all plugins specified in the json file."
),
cancel: gettext("Cancel"),
proceed: gettext("Install"),
proceedClass: "primary",
onproceed: proceed
});
} else {
proceed();
}
return false;
});
},
@@ -736,6 +767,7 @@ $(function () {
if (!data) return;
self.supportedArchiveExtensions(data.archive || []);
self.supportedPythonExtensions(data.python || []);
self.supportedJsonExtensions(data.json || []);
};
self.dataPluginsDeferred = undefined;
@@ -1617,35 +1649,77 @@ $(function () {
};
self._processPluginManagementResult = function (response, action, plugin) {
if (response.result) {
if (self.queuedInstalls().length > 0 && action === "install") {
var plugin_dequeue = ko.utils.arrayFirst(
self.queuedInstalls(),
function (item) {
return item.url === response.source;
}
);
if (plugin_dequeue) {
self.queuedInstalls.remove(plugin_dequeue);
if (response.type == "partial_result") {
if (!response.result) {
self.loglines.push({line: gettext("Error!"), stream: "error"});
self.loglines.push({line: response.reason, stream: "error"});
if (response.faq) {
self.loglines.push({
line: _.sprintf(
gettext(
"You can find more info on this issue in the FAQ at %(url)s"
),
{url: faq}
),
stream: "error"
});
}
if (self.queuedInstalls().length === 0) {
self.multiInstallRunning(false);
}
self.loglines.push({line: "", stream: "separator"});
self.loglines.push({
line: _.repeat("+", 50),
stream: "separator"
});
self.loglines.push({line: "", stream: "separator"});
} else {
if (response.result) {
if (self.queuedInstalls().length > 0 && action === "install") {
var plugin_dequeue = ko.utils.arrayFirst(
self.queuedInstalls(),
function (item) {
return item.url === response.source;
}
);
if (plugin_dequeue) {
self.queuedInstalls.remove(plugin_dequeue);
}
if (self.queuedInstalls().length === 0) {
self.multiInstallRunning(false);
self._markDone();
}
} else if (self.multiInstallRunning() && action === "install") {
// A MultiInstall job has finished
self.alertMultiInstallJobDone(response);
} else {
self._markDone();
}
} else if (self.multiInstallRunning() && action === "install") {
// A MultiInstall job has finished
self.alertMultiInstallJobDone(response);
} else {
self._markDone();
self._markDone(response.reason, response.faq);
}
} else {
self._markDone(response.reason, response.faq);
}
self._displayPluginManagementNotification(response, action, plugin);
self._addPluginManagementLog(response, action, plugin);
self._displayPluginManagementNotification();
};
self._displayPluginManagementNotification = function (response, action, plugin) {
self._extractActionAndNameFromResult = function (result) {
var action = result.action;
var name = "Unknown";
if (result.hasOwnProperty("plugin")) {
if (result.plugin !== "unknown") {
if (_.isPlainObject(result.plugin)) {
name = result.plugin.name;
} else {
name = result.plugin;
}
}
}
return {action: action, name: name};
};
self._addPluginManagementLog = function (response, action, plugin) {
self.logContents.action.restart =
self.logContents.action.restart || response.needs_restart;
self.logContents.action.refresh =
@@ -1658,7 +1732,9 @@ $(function () {
result: response.result,
faq: response.faq
});
};
self._displayPluginManagementNotification = function () {
var title = gettext("Plugin management log");
var text = "<p><ul>";
@@ -1737,7 +1813,11 @@ $(function () {
"</p>";
type = "warning";
if (self.restartCommandSpec && !self.multiInstallRunning()) {
if (
self.restartCommandSpec &&
!self.multiInstallRunning() &&
!self.working()
) {
var restartClicked = false;
confirm = {
confirm: true,
@@ -1792,7 +1872,7 @@ $(function () {
"</p>";
type = "warning";
if (!self.multiInstallRunning()) {
if (!self.multiInstallRunning() && !self.working()) {
var refreshClicked = false;
confirm = {
confirm: true,
@@ -2240,21 +2320,13 @@ $(function () {
self.loglines.push(self._preprocessLine(line));
});
self._scrollWorkingOutputToEnd();
} else if (messageType === "result") {
var action = data.action;
var name = "Unknown";
if (data.hasOwnProperty("plugin")) {
if (data.plugin !== "unknown") {
if (_.isPlainObject(data.plugin)) {
name = data.plugin.name;
} else {
name = data.plugin;
}
}
}
} else if (messageType === "result" || messageType === "partial_result") {
var {action, name} = self._extractActionAndNameFromResult(data);
self._processPluginManagementResult(data, action, name);
self.requestPluginData();
if (messageType === "result") {
self._displayPluginManagementNotification();
self.requestPluginData();
}
} else if (messageType === "queued_installs") {
if (data.hasOwnProperty("queued")) {
self.queuedInstalls(data.queued);
@@ -161,10 +161,17 @@
}
#settings_plugin_pluginmanager_workingdialog_output {
font-size: 0.8em;
.message {
font-weight: bold;
}
.separator {
font-weight: bold;
color: #666666;
}
.error {
font-weight: bold;
color: #990000;
@@ -211,7 +211,7 @@
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line + '\n', css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
@@ -423,7 +423,7 @@ class SoftwareUpdatePlugin(
def _get_check_overlay(self, url):
self._logger.info(f"Fetching check overlays from {url}")
try:
r = requests.get(url, timeout=3.1)
r = requests.get(url, timeout=3.05)
r.raise_for_status()
data = r.json()
except Exception as exc:
@@ -1147,7 +1147,7 @@ class SoftwareUpdatePlugin(
)
def view():
self._environment_ready.wait(timeout=30.0)
self._environment_ready.wait(timeout=10.0)
try:
(
@@ -1765,9 +1765,9 @@ class SoftwareUpdatePlugin(
self._save_version_cache()
self._get_versions_data = information, update_available, update_possible
self._get_versions_data_ready.set()
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()
@@ -2118,7 +2118,7 @@ class SoftwareUpdatePlugin(
self._send_client_message("success", {"results": target_results})
def _perform_update(self, target, check, force, credentials=None):
online = self._connectivity_checker.online
online = self._connectivity_checker.check_immediately()
information, update_available, update_possible, _, _ = self._get_current_version(
target, check, online=online, credentials=credentials
@@ -1 +1 @@
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#990000}#settings_plugin_softwareupdate_workingdialog_output .call{color:#000099}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#990000}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}.progress-softwareupdate.progress{position:relative;display:flex;overflow:hidden;height:25px;font-size:12px}.progress-softwareupdate.progress .bar{display:flex;justify-content:center;align-items:center;width:100%;color:white;height:25px;font-size:12px}.progress-softwareupdate.progress .progress-text{position:absolute;display:flex;justify-content:center;align-items:center;left:0;right:0;top:0;bottom:0;background:white;transition:clip-path 1s linear;height:25px;font-size:12px}
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}.progress-softwareupdate.progress{position:relative;display:flex;overflow:hidden;height:25px;font-size:12px}.progress-softwareupdate.progress .bar{display:flex;justify-content:center;align-items:center;width:100%;color:#fff;height:25px;font-size:12px}.progress-softwareupdate.progress .progress-text{position:absolute;display:flex;justify-content:center;align-items:center;left:0;right:0;top:0;bottom:0;background:#fff;transition:clip-path 1s linear;height:25px;font-size:12px}
@@ -212,7 +212,7 @@
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px; display: none" data-bind="visible: $root.updateAccess(), foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px; display: none" data-bind="visible: $root.updateAccess(), foreach: loglines"><span data-bind="text: line + '\n', css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
<p style="display: none" data-bind="visible: !$root.updateAccess() && $root.working()"><i class="fas fa-spinner fa-spin"></i> {{ _('Update in progress, please wait.') }}</p>
<p style="display: none" data-bind="visible: !$root.updateAccess() && !$root.working()">{{ _('Update done, please close this window.') }}</p>
</div>
@@ -49,7 +49,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
headers["authorization"] = f"Basic {auth_value}"
try:
r = requests.get(url, headers=headers, timeout=(3.05, 30))
r = requests.get(url, headers=headers, timeout=(3.05, 7))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
@@ -21,7 +21,7 @@ def get_latest(target, check, online=True, *args, **kwargs):
raise ConfigurationInvalid("jsondata version check needs jsondata set")
try:
with requests.get(url, timeout=(3.05, 30)) as r:
with requests.get(url, timeout=(3.05, 7)) as r:
data = r.json()
except Exception as exc:
raise NetworkError(cause=exc)
@@ -67,7 +67,7 @@ def _get_latest_release(package, include_prerelease):
from ..exceptions import NetworkError
try:
r = requests.get(INFO_URL.format(package=package), timeout=(3.05, 30))
r = requests.get(INFO_URL.format(package=package), timeout=(3.05, 7))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
+2 -2
View File
@@ -518,9 +518,9 @@ class TrackingPlugin(
params = urlencode(kwargs, doseq=True).replace("+", "%20")
if body:
requests.post(url, data=params, timeout=3.1, headers=headers)
requests.post(url, data=params, timeout=3.05, headers=headers)
else:
requests.get(url, params=params, timeout=3.1, headers=headers)
requests.get(url, params=params, timeout=3.05, headers=headers)
self._logger.info(f"Sent tracking event {event}, payload: {kwargs!r}")
except Exception:
+5 -2
View File
@@ -102,8 +102,8 @@ class PluginBlacklistConfig(BaseModel):
ttl: int = CONST_15MIN
"""Time to live of the cached blacklist, in seconds (default: 15 minutes)."""
timeout: float = 3.1
"""Timeout for fetching the blacklist, in seconds (default: 3.1 seconds)."""
timeout: float = 3.05
"""Timeout for fetching the blacklist, in seconds (default: 3.05 seconds)."""
@with_attrs_docs
@@ -207,3 +207,6 @@ class ServerConfig(BaseModel):
cookies: CookiesConfig = CookiesConfig()
"""Settings for further configuration of the cookies that OctoPrint sets (login, remember me, ...)."""
allowedLoginRedirectPaths: List[str] = []
"""List of paths that are allowed to be used as redirect targets for the login page, in addition to the default ones (`/`, `/recovery/` and `/plugin/appkeys/auth/`)"""
+7
View File
@@ -34,6 +34,7 @@ from flask_login import ( # noqa: F401
LoginManager,
current_user,
session_protected,
user_loaded_from_cookie,
user_logged_out,
)
from watchdog.observers import Observer
@@ -191,6 +192,12 @@ def on_user_logged_out(sender, user=None):
_clear_identity(sender)
@user_loaded_from_cookie.connect_via(app)
def on_user_loaded_from_cookie(sender, user=None):
if user:
session["login_mechanism"] = "remember_me"
def load_user(id):
if id is None:
return None
+16 -1
View File
@@ -22,6 +22,7 @@ import octoprint.access.users
import octoprint.plugin
import octoprint.server
import octoprint.util.net as util_net
from octoprint.access import auth_log
from octoprint.access.permissions import Permissions
from octoprint.events import Events, eventManager
from octoprint.server import NO_CONTENT
@@ -298,6 +299,7 @@ def login():
if "user" in data and "pass" in data:
username = data["user"]
password = data["pass"]
remote_addr = get_remote_address(request)
if "remember" in data and data["remember"] in valid_boolean_trues:
remember = True
@@ -311,6 +313,9 @@ def login():
if user is not None:
if octoprint.server.userManager.check_password(username, password):
if not user.is_active:
auth_log(
f"Failed login attempt for user {username} from {remote_addr}, user is deactivated"
)
abort(403)
user = octoprint.server.userManager.login_user(user)
@@ -326,7 +331,6 @@ def login():
)
session["login_mechanism"] = "http"
remote_addr = get_remote_address(request)
logging.getLogger(__name__).info(
"Actively logging in user {} from {}".format(
user.get_id(), remote_addr
@@ -348,9 +352,19 @@ def login():
eventManager().fire(
Events.USER_LOGGED_IN, payload={"username": user.get_id()}
)
auth_log(f"Logging in user {username} from {remote_addr} via credentials")
return r
else:
auth_log(
f"Failed login attempt for user {username} from {remote_addr}, wrong password"
)
else:
auth_log(
f"Failed login attempt for user {username} from {remote_addr}, user is unknown"
)
abort(403)
elif "passive" in data:
@@ -377,6 +391,7 @@ def logout():
if username:
eventManager().fire(Events.USER_LOGGED_OUT, payload={"username": username})
auth_log(f"Logging out user {username} from {get_remote_address(request)}")
return r
+6 -3
View File
@@ -335,10 +335,13 @@ def _getFileList(
file.update({"date": f["date"]})
files.append(file)
else:
# PERF: Only retrieve the extension tree once
extension_tree = octoprint.filemanager.full_extension_tree()
filter_func = None
if filter:
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(
entry, type=filter
entry, type=filter, tree=extension_tree
)
with _file_cache_mutex:
@@ -396,7 +399,7 @@ def _getFileList(
if (
"analysis" in file_or_folder
and octoprint.filemanager.valid_file_type(
file_or_folder["name"], type="gcode"
file_or_folder["name"], type="gcode", tree=extension_tree
)
):
file_or_folder["gcodeAnalysis"] = file_or_folder["analysis"]
@@ -405,7 +408,7 @@ def _getFileList(
if (
"history" in file_or_folder
and octoprint.filemanager.valid_file_type(
file_or_folder["name"], type="gcode"
file_or_folder["name"], type="gcode", tree=extension_tree
)
):
# convert print log
+17 -2
View File
@@ -268,6 +268,8 @@ def get_user_for_remote_user_header(request):
)
user = octoprint.server.userManager.findUser(userid=header)
if user:
_flask.session["login_mechanism"] = "remote_user"
return user
@@ -299,6 +301,8 @@ def get_user_for_authorization_header(header):
# password check enabled and password don't match
return None
if user:
_flask.session["login_mechanism"] = "basic_auth"
return user
@@ -459,7 +463,7 @@ def validate_local_redirect(url, allowed_paths):
Args:
url (str): URL to validate
allowed_paths (List[str]): List of allowed paths, only paths contained
will be considered valid.
or prefixed (if allowed path ends with "*") will be considered valid.
Returns:
bool: Whether the `url` passed validation or not.
@@ -467,4 +471,15 @@ def validate_local_redirect(url, allowed_paths):
from urllib.parse import urlparse
parsed = urlparse(url)
return parsed.scheme == "" and parsed.netloc == "" and parsed.path in allowed_paths
return (
parsed.scheme == ""
and parsed.netloc == ""
and any(
map(
lambda x: parsed.path.startswith(x[:-1])
if x.endswith("*")
else parsed.path == x,
allowed_paths,
)
)
)
+11 -3
View File
@@ -36,6 +36,7 @@ import octoprint.access.users
import octoprint.plugin
import octoprint.server
import octoprint.vendor.flask_principal as flask_principal
from octoprint.access import auth_log, login_mechanisms
from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import DefaultOrderedDict, deprecated, yaml
@@ -677,7 +678,16 @@ def passive_login():
def login(u):
# login known user
if not u.is_anonymous:
if not flask.g.identity or not flask.g.identity.id:
# the user was just now found
login_mechanism = login_mechanisms.get(
flask.session.get("login_mechanism", "unknown"), "unknown mechanism"
)
auth_log(
f"Logging in user {u.get_id()} from {remote_address} via {login_mechanism}"
)
u = octoprint.server.userManager.login_user(u)
flask_login.login_user(u)
flask_principal.identity_changed.send(
flask.current_app._get_current_object(),
@@ -720,9 +730,7 @@ def passive_login():
autologin_user = octoprint.server.userManager.find_user(autologin_as)
if autologin_user is not None and autologin_user.is_active:
logger.info(
"Passively logging in user {} from {} via autologin".format(
autologin_as, remote_address
)
f"Logging in user {autologin_as} from {remote_address} via autologin"
)
flask.session["login_mechanism"] = "autologin"
return autologin_user
+17 -2
View File
@@ -179,9 +179,24 @@ def _locale_str(locale):
def login():
from flask_login import current_user
default_redirect_url = request.script_root + url_for("index")
default_redirect_url = url_for("index")
redirect_url = request.args.get("redirect", default_redirect_url)
allowed_paths = [url_for("index"), url_for("recovery")]
configured_allowed_paths = settings().get(["server", "allowedLoginRedirectPaths"])
if configured_allowed_paths is None or not isinstance(configured_allowed_paths, list):
configured_allowed_paths = []
configured_allowed_paths = list(
filter(
lambda x: isinstance(x, str),
configured_allowed_paths,
)
)
allowed_paths = [
url_for("index"),
url_for("recovery"),
url_for("plugin.appkeys.handle_auth_dialog", app_token="*"),
] + configured_allowed_paths
if not validate_local_redirect(redirect_url, allowed_paths):
_logger.warning(
+1 -1
View File
@@ -1 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type="text"],.form-signin input[type="password"]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error-credentials,#login-error-rate,#login-offline{display:none}#login-error-credentials.in,#login-error-rate.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:white}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#ffffff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center}
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .checkbox,.form-signin .form-signin-heading{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error-credentials,#login-error-rate,#login-offline{display:none}#login-error-credentials.in,#login-error-rate.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#fff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
#workdialog .pre-output span{display:block}#workdialog .pre-output .message{font-weight:bold}#workdialog .pre-output .error{font-weight:bold;color:#990000}#workdialog .pre-output .stdout{color:#333333}#workdialog .pre-output .stderr{color:#990000}#workdialog .pre-output .call{color:#000099}
#workdialog .pre-output span{display:block}#workdialog .pre-output .message{font-weight:700}#workdialog .pre-output .error{font-weight:700;color:#900}#workdialog .pre-output .stdout{color:#333}#workdialog .pre-output .stderr{color:#900}#workdialog .pre-output .call{color:#009}
@@ -89,7 +89,7 @@ $(function () {
self.moveDestinationFilename = ko.observable(undefined);
self.moveDestinationFullpath = ko.pureComputed(function () {
// Join the paths for renaming
if (self.moveSourceFilename() != self.moveDestinationFilename()) {
if (self.moveSourceFilename() !== self.moveDestinationFilename()) {
if (self.moveDestination() === "/") {
return self.moveDestination() + self.moveDestinationFilename();
} else {
@@ -100,6 +100,16 @@ $(function () {
}
});
self.moveError = ko.observable("");
self.moveButtonText = ko.pureComputed(function () {
if (self.moveSource() === self.moveDestination()) {
return gettext("Rename");
} else {
// Moving, but maybe also renaming
if (self.moveSourceFilename() !== self.moveDestinationFilename()) {
return gettext("Move & Rename");
} else return gettext("Move");
}
});
self.folderList = ko.observableArray(["/"]);
self.addFolderDialog = undefined;
+11 -5
View File
@@ -23,7 +23,7 @@
<div id="move_file_or_folder_dialog" class="modal hide fade-in">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Move File or Folder') }}</h3>
<h3>{{ _('Move or Rename ') }}<span data-bind="text: moveEntry().type === 'folder' ? gettext('Folder') : gettext('File')"></span></h3>
</div>
<div class="modal-body">
<form class="form-vertical" action="javascript:void(0)">
@@ -33,18 +33,24 @@
<select class="input-block-level" data-bind="value: moveDestination, options: folderList"></select>
<span class="help-block"><small class="text-error" data-bind="text: moveError, visible: moveError().length > 0" style="display: none"></small></span>
</div>
<label class="control-label">{{ _('Set destination filename ') }} ({{ _('Currently:') }} <span data-bind="text: moveSourceFilename()"></span>)</label>
<label class="control-label">{{ _('Set destination name ') }} ({{ _('Currently:') }} <span data-bind="text: moveSourceFilename()"></span>)</label>
<div class="controls">
<input class="input-block-level" data-bind="value: moveDestinationFilename" />
<input type="text" class="input-block-level" data-bind="value: moveDestinationFilename" />
</div>
<p> {{ _('File/Folder will be moved to: ') }} <span data-bind="text: moveDestinationFullpath()"></span></p>
<p data-bind="visible: moveSource() !== moveDestination() || moveSourceFilename() !== moveDestinationFilename()">
<span data-bind="text: moveEntry().type === 'folder' ? gettext('Folder') : gettext('File')"></span>{{ _(' will be moved to: ') }} <span data-bind="text: moveDestinationFullpath()"></span>
</p>
</div>
</form>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="#" class="btn btn-primary" data-bind="click: function() { if ((moveSource() !== moveDestination() || moveSourceFilename() !== moveDestinationFilename()) && !movingFileOrFolder()) { $root.moveFileOrFolder(moveEntry().path, moveDestinationFullpath()) } else {} }, css: {disabled: (moveSource() === moveDestination() && moveSourceFilename() === moveDestinationFilename()) || movingFileOrFolder()}"><i class="fas fa-spinner fa-spin" data-bind="visible: movingFileOrFolder"></i> {{ _('Move') }}</a>
<a href="#" class="btn btn-primary"
data-bind="click: function() { if ((moveSource() !== moveDestination() || moveSourceFilename() !== moveDestinationFilename()) && !movingFileOrFolder()) { $root.moveFileOrFolder(moveEntry().path, moveDestinationFullpath()) } else {} },
css: {disabled: (moveSource() === moveDestination() && moveSourceFilename() === moveDestinationFilename()) || movingFileOrFolder()},
text: moveButtonText">
<i class="fas fa-spinner fa-spin" data-bind="visible: movingFileOrFolder"></i></a>
</div>
</div>
+1 -1
View File
@@ -24,7 +24,7 @@
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
<div class="btn-group action-buttons">
<a class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_DOWNLOAD), attr: {href: $root.downloadLink($data)}, css: {disabled: !$root.downloadLink($data)}" title="{{ _('Download')|edq }}" aria-label="{{ _('Download')|edq }}"><i class="fas fa-download"></i></a>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasAllPermissionsKo($root.access.permissions.FILES_UPLOAD, $root.access.permissions.FILES_DELETE), click: function(data, event) { if ($root.enableMove($data)) { $root.showMoveDialog($data, event); } else { return; } }, css: {disabled: !$root.enableMove($data)}" title="{{ _('Move')|edq }}" aria-label="{{ _('Move')|edq }}" role="link"><i class="fas fa-cut"></i></div>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasAllPermissionsKo($root.access.permissions.FILES_UPLOAD, $root.access.permissions.FILES_DELETE), click: function(data, event) { if ($root.enableMove($data)) { $root.showMoveDialog($data, event); } else { return; } }, css: {disabled: !$root.enableMove($data)}" title="{{ _('Move or Rename')|edq }}" aria-label="{{ _('Move or Rename')|edq }}" role="link"><i class="fas fa-cut"></i></div>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_DELETE), click: function(data, event) { if ($root.enableRemove($data)) { $root.removeFile($data, event); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove')|edq }}" aria-label="{{ _('Remove')|edq }}" role="link"><i class="far fa-trash-alt"></i></div>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_SELECT), click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load')|edq }}" aria-label="{{ _('Load')|edq }}" role="link"><i class="fas fa-folder-open"></i></div>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.PRINT), click: function() { if ($root.enableSelectAndPrint($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelectAndPrint($data)}" title="{{ _('Load and Print')|edq }}" aria-label="{{ _('Load and Print')|edq }}" role="link"><i class="fas fa-print"></i></div>
+8 -3
View File
@@ -161,6 +161,7 @@ class CommandlineCaller:
command: Union[str, List[str], Tuple[str]],
delimiter: bytes = b"\n",
buffer_size: int = -1,
logged: bool = True,
**kwargs,
) -> Tuple[Optional[int], List[str], List[str]]:
"""
@@ -176,7 +177,7 @@ class CommandlineCaller:
"""
p = self.non_blocking_call(
command, delimiter=delimiter, buffer_size=buffer_size, **kwargs
command, delimiter=delimiter, buffer_size=buffer_size, logged=logged, **kwargs
)
if p is None:
return None, [], []
@@ -190,7 +191,8 @@ class CommandlineCaller:
processed = self._preprocess_lines(
*map(lambda x: to_unicode(x, errors="replace"), lines)
)
logger(*processed)
if logged:
logger(*processed)
return list(processed)
def process_stdout(lines):
@@ -218,6 +220,7 @@ class CommandlineCaller:
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)):
@@ -225,7 +228,9 @@ class CommandlineCaller:
else:
joined_command = command
self._logger.debug(f"Calling: {joined_command}")
self.on_log_call(joined_command)
if logged:
self.on_log_call(joined_command)
kwargs.update(
{
+26 -23
View File
@@ -122,44 +122,27 @@ class ConnectivityChecker:
return self.online
def log_full_report(self):
from octoprint.util import map_boolean
with self._check_mutex:
self._logger.info(
"Connectivity state is currently: {}".format(
map_boolean(self.online, "online", "offline")
self._map_online(self.online)
)
)
self.log_details()
def log_change_report(self, old_value, new_value, include_details=False):
from octoprint.util import map_boolean
with self._check_mutex:
self._logger.info(
"Connectivity changed from {} to {}".format(
map_boolean(old_value, "online", "offline"),
map_boolean(new_value, "online", "offline"),
)
)
if include_details:
self.log_details()
def log_details(self):
from octoprint.util import map_boolean
self._logger.info(
"Connecting to {}:{} is {}".format(
self._host,
self._port,
map_boolean(self._connection_working, "working", "not working"),
self._map_working(self._connection_working),
)
)
if self._name:
self._logger.info(
"Resolving {} is {}".format(
self._name,
map_boolean(self._resolution_working, "working", "not working"),
self._map_working(self._resolution_working),
)
)
@@ -220,14 +203,18 @@ class ConnectivityChecker:
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 != self._online:
self._trigger_change(old_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)
self._log_change_report(old_value, new_value, include_details=not new_value)
if callable(self._on_change):
self._on_change(
old_value,
@@ -235,3 +222,19 @@ class ConnectivityChecker:
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"
+2 -2
View File
@@ -257,8 +257,8 @@ def resolve_host(host):
return []
def download_file(url, folder, max_length=None):
with requests.get(url, stream=True, timeout=(3.05, 30)) as r:
def download_file(url, folder, max_length=None, connect_timeout=3.05, read_timeout=7):
with requests.get(url, stream=True, timeout=(connect_timeout, read_timeout)) as r:
r.raise_for_status()
filename = None
+8 -3
View File
@@ -27,6 +27,9 @@ OUTPUT_SUCCESS = "Successfully installed"
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"""
@@ -58,8 +61,10 @@ def is_already_installed(lines):
bool: True if detected, False otherwise
"""
result_line = get_result_line(lines) # neither success nor failure reported
return not result_line and any(
line.strip().startswith(OUTPUT_ALREADY_INSTALLED) for line in lines
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)
)
@@ -114,7 +119,7 @@ def get_result_line(lines):
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 installed".
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.
+8
View File
@@ -44,6 +44,14 @@ def _save_to_file_base(data, file=None, path=None, pretty=False, **kwargs):
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)
+17
View File
@@ -108,6 +108,23 @@ class FilemanagerMethodTest(unittest.TestCase):
self.assertTrue(octoprint.filemanager.valid_file_type("foo.mime_detect_yes"))
self.assertFalse(octoprint.filemanager.valid_file_type("foo.unknown"))
extension_tree = {
"machinecode": {
"gcode": octoprint.filemanager.ContentTypeMapping(
["gcode", "gco", "g"], "text/plain"
),
"foo": ["foo", "f"],
}
}
# With cached extension tree
self.assertTrue(
octoprint.filemanager.valid_file_type("foo.foo", tree=extension_tree)
)
self.assertFalse(
octoprint.filemanager.valid_file_type("foo.amf", tree=extension_tree)
)
def test_get_file_type(self):
self.assertEqual(
["machinecode", "gcode"], octoprint.filemanager.get_file_type("foo.gcode")
+25 -17
View File
@@ -3,31 +3,39 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms
import pytest
DEFAULT_ALLOWED_PATHS = ["/", "/recovery/", "/plugin/appkeys/auth/*"]
PREFIXED_ALLOWED_PATHS = list(map(lambda x: "/octoprint" + x, DEFAULT_ALLOWED_PATHS))
@pytest.mark.parametrize(
"url,paths,expected",
[
# various default UI URLs
("/", ["/", "/recovery/"], True),
("/?", ["/", "/recovery/"], True),
("/?l10n=de", ["/", "/recovery/"], True),
("/?l10n=de&", ["/", "/recovery/"], True),
("/octoprint/", ["/octoprint/", "/octoprint/recovery/"], True),
("/", DEFAULT_ALLOWED_PATHS, True),
("/?", DEFAULT_ALLOWED_PATHS, True),
("/?l10n=de", DEFAULT_ALLOWED_PATHS, True),
("/?l10n=de&", DEFAULT_ALLOWED_PATHS, True),
("/octoprint/", PREFIXED_ALLOWED_PATHS, True),
# various recovery URLs
("/recovery/", ["/", "/recovery/"], True),
("/recovery/?", ["/", "/recovery/"], True),
("/recovery/?l10n=de", ["/", "/recovery/"], True),
("/octoprint/recovery/?l10n=de", ["/octoprint/", "/octoprint/recovery/"], True),
("/recovery/", DEFAULT_ALLOWED_PATHS, True),
("/recovery/?", DEFAULT_ALLOWED_PATHS, True),
("/recovery/?l10n=de", DEFAULT_ALLOWED_PATHS, True),
("/octoprint/recovery/?l10n=de", PREFIXED_ALLOWED_PATHS, True),
# various appkeys URLs
("/plugin/appkeys/auth/1234567890", DEFAULT_ALLOWED_PATHS, True),
("/plugin/appkeys/auth/1234567890?", DEFAULT_ALLOWED_PATHS, True),
("/plugin/appkeys/auth/1234567890?l10n=de", DEFAULT_ALLOWED_PATHS, True),
("/octoprint/plugin/appkeys/auth/1234567890", PREFIXED_ALLOWED_PATHS, True),
# various external URLs
("http://example.com", ["/", "/recovery/"], False),
("https://example.com", ["/", "/recovery/"], False),
("//example.com", ["/", "/recovery/"], False),
("/\\/\\example.com", ["/", "/recovery/"], False),
(" /\\/\\example.com", ["/", "/recovery/"], False),
("\\/\\/example.com", ["/", "/recovery/"], False),
(" \\/\\/example.com", ["/", "/recovery/"], False),
("http://example.com", DEFAULT_ALLOWED_PATHS, False),
("https://example.com", DEFAULT_ALLOWED_PATHS, False),
("//example.com", DEFAULT_ALLOWED_PATHS, False),
("/\\/\\example.com", DEFAULT_ALLOWED_PATHS, False),
(" /\\/\\example.com", DEFAULT_ALLOWED_PATHS, False),
("\\/\\/example.com", DEFAULT_ALLOWED_PATHS, False),
(" \\/\\/example.com", DEFAULT_ALLOWED_PATHS, False),
# other stuff
("javascript:alert(document.cookie)", ["/", "/recovery/"], False),
("javascript:alert(document.cookie)", DEFAULT_ALLOWED_PATHS, False),
],
)
def test_validate_local_redirect(url, paths, expected):
@@ -0,0 +1,18 @@
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Processing /tmp/tmprvq8z421.zip
Preparing metadata (setup.py): started
Preparing metadata (setup.py): finished with status 'done'
Requirement already satisfied: OctoPrint in /home/pi/oprint/lib/python3.9/site-packages (from OctoEverywhere==1.11.2) (1.8.6)
Requirement already satisfied: certifi in /home/pi/oprint/lib/python3.9/site-packages (from OctoEverywhere==1.11.2) (2022.9.24)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x75453a30>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x754a4a18>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x754a4568>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x754a4028>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x754a4be0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x75453c40>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x75453d90>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x75453e80>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x75453f70>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x75453fe8>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/dnspython/
ERROR: Could not find a version that satisfies the requirement dnspython (from octoeverywhere) (from versions: none)
ERROR: No matching distribution found for dnspython
+1
View File
@@ -165,6 +165,7 @@ class PipUtilTest(unittest.TestCase):
("already_installed_1.txt", True),
("already_installed_2.txt", True),
("successful_install_1.txt", False),
("dependency_error.txt", False),
)
@ddt.unpack
def test_is_already_installed(self, file, expected):