Merge branch 'maintenance' of https://github.com/OctoPrint/OctoPrint into maintenance
This commit is contained in:
commit
8793495edd
88 files changed
+1092
-475
No files matched your search
@@ -1,10 +1,10 @@
|
||||
name: "Issue Labeler"
|
||||
on:
|
||||
issues:
|
||||
types: [opened, edited]
|
||||
types: [opened, edited, closed, reopened]
|
||||
|
||||
jobs:
|
||||
apply-label:
|
||||
label-opened-and-edited:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v2
|
||||
@@ -12,19 +12,50 @@ jobs:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
let labels = [];
|
||||
let setLabels = false;
|
||||
context.payload.issue.labels.forEach(label => { labels.push(label.name) });
|
||||
|
||||
if (context.payload.issue.title.match(/\[request\]|feature request/i)) {
|
||||
labels.push('type:request');
|
||||
}
|
||||
if (context.payload.issue.title.match(/\[brainstorming\]/i)) {
|
||||
labels.push('type:brainstorming');
|
||||
}
|
||||
if (context.payload.issue.title.match(/\[rc feedback\]/i)) {
|
||||
labels.push('type:rc feedback');
|
||||
switch (context.payload.action) {
|
||||
|
||||
case 'opened':
|
||||
case 'edited': {
|
||||
if (context.payload.issue.title.match(/\[request\]|feature request/i)) {
|
||||
labels.push('request');
|
||||
labels = labels.filter(label => label !== 'triage');
|
||||
setLabels = true;
|
||||
}
|
||||
if (context.payload.issue.title.match(/\[rc feedback\]/i)) {
|
||||
labels.push('rc feedback');
|
||||
labels = labels.filter(label => label !== 'triage');
|
||||
setLabels = true;
|
||||
}
|
||||
|
||||
if (labels.length === 0) {
|
||||
labels.push('triage');
|
||||
setLabels = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'closed': {
|
||||
if (labels.includes('bug') || labels.includes('request') || labels.includes('improvement')) {
|
||||
labels.push('done');
|
||||
setLabels = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'reopened': {
|
||||
if (labels.includes('done')) {
|
||||
labels = labels.filter(label => label !== 'done');
|
||||
setLabels = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (labels.length > 0) {
|
||||
github.issues.addLabels({
|
||||
if (setLabels) {
|
||||
github.issues.setLabels({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
|
||||
@@ -5,8 +5,12 @@ repos:
|
||||
hooks:
|
||||
- id: end-of-file-fixer
|
||||
- id: trailing-whitespace
|
||||
- id: check-case-conflict
|
||||
- id: check-json
|
||||
- id: check-yaml
|
||||
- id: check-toml
|
||||
- id: check-merge-conflict
|
||||
- id: fix-encoding-pragma
|
||||
- repo: https://github.com/OctoPrint/codemods
|
||||
rev: main
|
||||
hooks:
|
||||
@@ -32,6 +36,8 @@ repos:
|
||||
rev: 3.8.1
|
||||
hooks:
|
||||
- id: flake8
|
||||
additional_dependencies:
|
||||
- flake8-bugbear
|
||||
- repo: https://github.com/prettier/prettier
|
||||
rev: master
|
||||
hooks:
|
||||
|
||||
@@ -128,6 +128,7 @@ date of first contribution):
|
||||
* [Charlie Powell](https://github.com/cp2004)
|
||||
* [Ollis Git](https://github.com/OllisGit)
|
||||
* [Sophist](https://github.com/Sophist-UK)
|
||||
* [Manuel McLure](https://github.com/ManuelMcLure)
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
OctoPrint's Code of Conduct can be found at [octoprint.org/conduct/](https://octoprint.org/conduct/).
|
||||
+1
-2
@@ -360,8 +360,7 @@ and branching strategy.
|
||||
An [automatic build workflow](https://github.com/OctoPrint/OctoPrint/actions?query=workflow%3ABuild)
|
||||
is in place that will run these checks - if they fail your PR will be marked accordingly.
|
||||
10. **Test your changes thoroughly**. That also means testing with usage
|
||||
scenarios you don't normally use, e.g. if you only use access control, test
|
||||
without and vice versa. If you only test with your printer, test with the
|
||||
scenarios you don't normally use. If you only test with your printer, test with the
|
||||
virtual printer and vice versa. State in your pull request how you tested
|
||||
your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
|
||||
department, but we are trying to change that, so any new code already covered
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
# OctoPrint
|
||||
<p align="center"><img src="https://octoprint.org/assets/img/logo.png" alt="OctoPrint's logo" /></p>
|
||||
|
||||

|
||||

|
||||
[](https://pypi.python.org/pypi/octoprint/)
|
||||

|
||||
[](https://community.octoprint.org)
|
||||
[](https://discord.octoprint.org)
|
||||
[](https://twitter.com/OctoPrint3d)
|
||||
[](https://github.com/psf/black)
|
||||
[](https://github.com/prettier/prettier)
|
||||
[](https://pycqa.github.io/isort/)
|
||||
[](https://github.com/pre-commit/pre-commit)
|
||||
<h1 align="center">OctoPrint</h1>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/github/v/release/OctoPrint/OctoPrint?logo=github&logoColor=white" alt="GitHub release"/>
|
||||
<img src="https://img.shields.io/pypi/v/OctoPrint?logo=python&logoColor=white" alt="PyPI"/>
|
||||
<img src="https://img.shields.io/github/workflow/status/OctoPrint/OctoPrint/Build" alt="Build status"/>
|
||||
<a href="https://community.octoprint.org"><img src="https://img.shields.io/discourse/users?logo=discourse&logoColor=white&server=https%3A%2F%2Fcommunity.octoprint.org" alt="Community Forum"/></a>
|
||||
<a href="https://discord.octoprint.org"><img src="https://img.shields.io/discord/704958479194128507?label=discord&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://twitter.com/OctoPrint3d"><img src="https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow" alt="Twitter Follow"/></a>
|
||||
<a href="https://octoprint.org/conduct/"><img src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg" alt="Contributor Covenant"/></a>
|
||||
<a href="https://github.com/psf/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code style: black"/></a>
|
||||
<a href="https://github.com/prettier/prettier"><img src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square" alt="Code style: prettier"/></a>
|
||||
<a href="https://pycqa.github.io/isort/"><img src="https://img.shields.io/badge/%20imports-isort-%231674b1" alt="Imports: isort"/></a>
|
||||
<a href="https://github.com/pre-commit/pre-commit"><img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white" alt="pre-commit"/></a>
|
||||
</p>
|
||||
|
||||
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
|
||||
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
|
||||
@@ -31,7 +34,7 @@ The official plugin repository can be reached at [plugins.octoprint.org](https:/
|
||||
**OctoPrint's development wouldn't be possible without the [financial support by its community](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
|
||||
If you enjoy OctoPrint, please consider becoming a regular supporter!**
|
||||
|
||||

|
||||

|
||||
|
||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
||||
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
||||
|
||||
@@ -28,7 +28,7 @@ Settings Dialog, navigate to the Software Update section therein and once you ar
|
||||
wrench icon in the upper right corner.
|
||||
|
||||
.. _fig-bundledplugins-softwareupdate-plugin-configuration:
|
||||
.. figure:: ../images/bundledplugins-softwareupdate-plugin-configuration.png
|
||||
.. figure:: ../images/bundledplugins-softwareupdate-configuration.png
|
||||
:align: center
|
||||
:alt: Software Update plugin configuration dialog
|
||||
|
||||
@@ -38,21 +38,25 @@ There you can adjust the following settings:
|
||||
|
||||
* **OctoPrint version tracking**: Whether you want to track OctoPrint *releases* or every *commit*. Usually you want to
|
||||
select "Release" here which is also the default, unless you are a developer.
|
||||
* **OctoPrint Release Channel** (if tracking releases): The release channel of OctoPrint to track for updates. If you only want stable versions,
|
||||
select "Stable" here which is also the default. "Maintenance RCs" will also allow you to update to maintenance release
|
||||
candidates, "Devel RCs" will also allow you to update to development release candidates. If in doubt, leave it at
|
||||
"Stable". `Read more about Release Channels here <https://community.octoprint.org/t/how-to-use-the-release-channels-to-help-test-release-candidates/402>`_.
|
||||
* **OctoPrint checkout folder** (if tracking git commits): This must be the path to OctoPrint's git checkout folder
|
||||
* **Tracked branch** (if tracking is set to "Github Commit"): The branch that will be tracked if you set version tracking to "Github Commit".
|
||||
* **OctoPrint ``pip`` target** (if tracking is set to "Release" or "Github Commit"): The argument that will be provided to ``pip`` when updating OctoPrint.
|
||||
Usually you don't want to change this from its default value of ``https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip``.
|
||||
* **OctoPrint checkout folder** (if tracking is set to "Local checkout"): This must be the path to OctoPrint's git checkout folder
|
||||
(``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide <https://community.octoprint.org/t/setting-up-octoprint-on-a-raspberry-pi-running-raspbian/2337/>`_).
|
||||
Note that since OctoPrint 1.3.6 you will no longer need to set this to be able to update to releases, only if you
|
||||
want to be able to update against some bleeding edge git branch.
|
||||
* **Enable ``pip`` update checks**: Whether to have OctoPrint automatically check for updates of
|
||||
the ``pip`` tool that is used for updating most components.
|
||||
* **Version cache TTL**: The "time to live" of the cache OctoPrint will use to temporarily persist the version information
|
||||
for the various components registered with the plugin, so that they don't have to be queried from the internet every time
|
||||
you load the page. Defaults to 24h, you usually shouldn't need to change that value.
|
||||
* **Show notifications to users**: Whether to display update notifications (without "Update now" button) to users that cannot
|
||||
apply updates.
|
||||
* **Minimum free disk space**: The minimum amount of free disk space needed in order to allow software updates to be run.
|
||||
|
||||
More settings are available by :ref:`editing the corresponding section in config.yaml <sec-bundledplugins-softwareupdate-configuration>`.
|
||||
|
||||
That restart commands for OctoPrint and the whole server can be configured under Settings > Server.
|
||||
Restart commands for OctoPrint and the whole server can be configured under Settings > Server.
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-cli:
|
||||
|
||||
@@ -123,9 +127,6 @@ Configuring the Plugin
|
||||
|
||||
plugins:
|
||||
softwareupdate:
|
||||
# the time-to-live of the version cache, in minutes
|
||||
cache_ttl: 60
|
||||
|
||||
# configured version check and update methods
|
||||
checks:
|
||||
# "octoprint" is reserved for OctoPrint
|
||||
@@ -145,6 +146,41 @@ Configuring the Plugin
|
||||
# used - should normally NOT be necessary and hence set
|
||||
pip_command: /path/to/pip
|
||||
|
||||
# the time-to-live of the version cache, in minutes, defaults to 24h
|
||||
cache_ttl: 1440
|
||||
|
||||
# whether to show update notifications to users that cannot apply updates
|
||||
notify_users: true
|
||||
|
||||
# whether to ignore the system throttled state reported by the pisupport plugin and
|
||||
# allow updating even when the system is not running stable - really not recommended
|
||||
ignore_throttled: false
|
||||
|
||||
# minimum free storage in MB for updates to be enabled
|
||||
minimum_free_storage: 150
|
||||
|
||||
# URL from which to fetch check overlays
|
||||
check_overlay_url: https://plugins.octoprint.org/update_check_overlay.json
|
||||
|
||||
# time to live of the overlay cache, defaults to 6h
|
||||
check_overlay_ttl: 360
|
||||
|
||||
# global credentials to provide to version checks
|
||||
credentials:
|
||||
|
||||
# GitHub API token to use for the github_release and github_commit version checks.
|
||||
# Helpful if you regularly run into rate limit issues with the GitHub API using
|
||||
# the default anonymous access. Use a personal access token:
|
||||
# https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token
|
||||
# Unset by default
|
||||
github:
|
||||
|
||||
# Bitbucket user name and password, used by the bitbucket_commit version check if
|
||||
# provided, but only if the check doesn't specify credentials on its own.
|
||||
# Unset by default
|
||||
bitbucket_user:
|
||||
bitbucket_password:
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-configuration-versionchecks:
|
||||
|
||||
Version checks
|
||||
@@ -501,6 +537,28 @@ commit identifier. E.g. ``https://gist.githubusercontent.com/<user>/<gistid>/raw
|
||||
``https://gist.githubusercontent.com/<user>/<gistid>/raw/<commit>/my_plugin.py``. Note that these URLs will
|
||||
be cached by Github for a bit, so an update will not be immediately picked up.
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-configuration-credentials:
|
||||
|
||||
Global credentials
|
||||
++++++++++++++++++
|
||||
|
||||
.. versionadded:: 1.5.0
|
||||
|
||||
Starting with OctoPrint 1.5.0, the Software Update Plugin supports supplyting a GitHub
|
||||
API token to use for the ``github_release`` and ``github_commit`` version check types,
|
||||
to work around possible rate limit problems if a lot of checks are to be made from a single
|
||||
external IP. You may create a `personal access token <https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token>`_
|
||||
and configure that as ``plugins.softwareupdate.credentials.github`` via
|
||||
:ref:`config.yaml <sec-configuration-config_yaml>` in order to get a higher rate limit than with purely anonymous access.
|
||||
|
||||
Additionally, the username and password to use with the ``bitbucket_commit`` version check
|
||||
type may also be configured via ``plugins.softwareupdate.credentials.bitbucket_user`` and
|
||||
``plugins.softwareupdate.credentials.bitbucket_password`` respectively.
|
||||
|
||||
None of these configuration options are currently exposed on the UI and can only be used
|
||||
via :ref:`config.yaml <sec-configuration-config_yaml>` or the
|
||||
:ref:`config command line interface <sec-configuration-cli>`.
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-events:
|
||||
|
||||
Events
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
.. _sec-configuration-cli:
|
||||
|
||||
CLI
|
||||
===
|
||||
|
||||
.. versionadded:: 1.3.0
|
||||
|
||||
OctoPrint provides a basic command line interface for manipulation of :ref:`config.yaml <sec-configuration-config_yaml>`:
|
||||
|
||||
.. code-block::
|
||||
|
||||
$ octoprint config --help
|
||||
Usage: octoprint config [OPTIONS] COMMAND [ARGS]...
|
||||
|
||||
Basic config manipulation.
|
||||
|
||||
Options:
|
||||
--help Show this message and exit.
|
||||
|
||||
Commands:
|
||||
append_value Appends value to list behind config path.
|
||||
effective Retrieves the full effective config.
|
||||
get Retrieves value from config path.
|
||||
insert_value Inserts value at index of list behind config key.
|
||||
remove Removes a config path.
|
||||
remove_value Removes value from list at config path.
|
||||
set Sets a config path to the provided value.
|
||||
|
||||
.. code-block::
|
||||
|
||||
$ octoprint config append_value --help
|
||||
Usage: octoprint config append_value [OPTIONS] PATH VALUE
|
||||
|
||||
Appends value to list behind config path.
|
||||
|
||||
Options:
|
||||
--json
|
||||
--help Show this message and exit.
|
||||
|
||||
.. code-block::
|
||||
|
||||
$ octoprint config effective --help
|
||||
Usage: octoprint config effective [OPTIONS]
|
||||
|
||||
Retrieves the full effective config.
|
||||
|
||||
Options:
|
||||
--json Output value formatted as JSON
|
||||
--yaml Output value formatted as YAML
|
||||
--raw Output value as raw string representation
|
||||
--help Show this message and exit.
|
||||
|
||||
.. code-block::
|
||||
|
||||
$ octoprint config get --help
|
||||
Usage: octoprint config get [OPTIONS] PATH
|
||||
|
||||
Retrieves value from config path.
|
||||
|
||||
Options:
|
||||
--json Output value formatted as JSON
|
||||
--yaml Output value formatted as YAML
|
||||
--raw Output value as raw string representation
|
||||
--help Show this message and exit.
|
||||
|
||||
.. code-block::
|
||||
|
||||
$ octoprint config insert_value --help
|
||||
Usage: octoprint config insert_value [OPTIONS] PATH INDEX VALUE
|
||||
|
||||
Inserts value at index of list behind config key.
|
||||
|
||||
Options:
|
||||
--json
|
||||
--help Show this message and exit.
|
||||
|
||||
.. code-block::
|
||||
|
||||
$ octoprint config remove --help
|
||||
Usage: octoprint config remove [OPTIONS] PATH
|
||||
|
||||
Removes a config path.
|
||||
|
||||
Options:
|
||||
--help Show this message and exit.
|
||||
|
||||
.. code-block::
|
||||
|
||||
$ octoprint config remove_value --help
|
||||
Usage: octoprint config remove_value [OPTIONS] PATH VALUE
|
||||
|
||||
Removes value from list at config path.
|
||||
|
||||
Options:
|
||||
--json
|
||||
--help Show this message and exit.
|
||||
|
||||
.. code-block::
|
||||
|
||||
$ octoprint config set --help
|
||||
Usage: octoprint config set [OPTIONS] PATH VALUE
|
||||
|
||||
Sets a config path to the provided value.
|
||||
|
||||
Options:
|
||||
--bool Interpret value as bool
|
||||
--float Interpret value as float
|
||||
--int Interpret value as int
|
||||
--json Parse value from json
|
||||
--help Show this message and exit.
|
||||
@@ -10,6 +10,7 @@ you can just create it - it will only get created by OctoPrint once you save set
|
||||
settings.
|
||||
|
||||
Note that many of these settings are available from the "Settings" menu in OctoPrint itself.
|
||||
They can also be configured via :ref:`config command line interface <sec-configuration-cli>`.
|
||||
|
||||
.. contents::
|
||||
|
||||
|
||||
@@ -10,3 +10,4 @@ Configuration
|
||||
yaml.rst
|
||||
config_yaml.rst
|
||||
logging_yaml.rst
|
||||
cli.rst
|
||||
@@ -606,6 +606,32 @@ ToolChange
|
||||
|
||||
.. versionadded:: 1.3.5
|
||||
|
||||
CommandSuppressed
|
||||
A command was suppressed by OctoPrint due to according configuration and will not be
|
||||
sent to the printer.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``command``: the command that was suppressed
|
||||
* ``message``: a message containing an explanation of the command suppression
|
||||
* ``severity``: a severity level, either ``warn`` or ``info`` - ``warn`` indicates
|
||||
that the command was suppressed probably due to a misconfiguration either inside
|
||||
OctoPrint or the firmware and that it should be investigated by the user
|
||||
|
||||
.. versionadded:: 1.5.0
|
||||
|
||||
InvalidToolReported
|
||||
The firmware reported a tool as invalid upon trying to select it. It has thus been marked
|
||||
as invalid and further attempts to select said tool will result in the tool command
|
||||
to get suppressed (and ``SuppressedCommand`` to be generated).
|
||||
|
||||
Payload:
|
||||
|
||||
* ``tool``: the tool number that was reported as invalid by the firmware
|
||||
* ``fallback``: the tool number that OctoPrint will revert to
|
||||
|
||||
.. versionadded:: 1.5.0
|
||||
|
||||
.. _sec-events-available_events-timelapses:
|
||||
|
||||
Timelapses
|
||||
|
||||
@@ -172,9 +172,10 @@ Controls
|
||||
turn the button red.
|
||||
* - ``enabled``
|
||||
- (Optional) A JavaScript snippet returning either ``true`` or ``false`` determining whether the control
|
||||
should be enabled or not. This allow to override the default logic for this (disabled if printer is offline
|
||||
or currently printing). The JavaScript snippet is ``eval``'d and processed in a context where the control
|
||||
it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``.
|
||||
should be enabled or not. This allows to override the default logic for the enable state
|
||||
of the control (disabled if printer is offline). The JavaScript snippet is ``eval``'d and processed
|
||||
in a context where the control it is part of is provided as local variable ``data`` and the
|
||||
``ControlViewModel`` is available as ``self``.
|
||||
* - ``input``
|
||||
- (Optional) A list of definitions of input parameters for a ``command`` or ``commands``, to be rendered as
|
||||
additional input fields. ``command``/``commands`` may contain placeholders to be replaced by the values obtained
|
||||
@@ -213,17 +214,28 @@ Controls
|
||||
- (Optional) A :ref:`regular expression <re-syntax>` to
|
||||
match against lines received from the printer to retrieve information from it (e.g. specific output). Together
|
||||
with ``template`` this allows rendition of received data from the printer within the UI.
|
||||
|
||||
**Please also read the note below**.
|
||||
* - ``template``
|
||||
- (Optional) A template to use for rendering the match of ``regex``. May contain placeholders in
|
||||
:ref:`Python Format String Syntax <formatstrings>` for either named
|
||||
groups within the regex (e.g. ``Temperature: {temperature}`` for a regex ``T:\s*(?P<temperature>\d+(\.\d*)``)
|
||||
or positional groups within the regex (e.g. ``Position: X={0}, Y={1}, Z={2}, E={3}`` for a regex
|
||||
``X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)``).
|
||||
|
||||
**Please also read the note below**.
|
||||
* - ``confirm``
|
||||
- (Optional) A text to display to the user to confirm his button press. Can be used with sensitive custom controls
|
||||
like changing EEPROM values in order to prevent accidental clicks. The text will be displayed in a confirmation
|
||||
dialog like in :numref:`fig-configuration-customcontrols-confirm`.
|
||||
|
||||
.. note::
|
||||
|
||||
``regex`` and ``template`` are only supported for controls that are defined through
|
||||
``config.yaml``. These control properties aren't supported for controls added only in
|
||||
the frontend by the :ref:`getAdditionalControls <sec-plugins-viewmodels-callbacks>`
|
||||
view model callback.
|
||||
|
||||
.. _fig-configuration-customcontrols-confirm:
|
||||
.. figure:: ../images/features-custom_controls-confirm.png
|
||||
:align: center
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 35 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 24 KiB |
@@ -238,6 +238,11 @@ getAdditionalControls()
|
||||
Your view model may return additional custom control definitions for inclusion on the "Control" tab of OctoPrint's
|
||||
interface. See :ref:`the custom control feature<sec-features-custom_controls>`.
|
||||
|
||||
.. note::
|
||||
|
||||
Controls injected from a view model do not support feedback controls (as defined by
|
||||
``regex`` and ``template``).
|
||||
|
||||
onSettingsShown()
|
||||
Called when the settings dialog is shown.
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python2
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -228,12 +228,7 @@ def init_settings(basedir, configfile):
|
||||
try:
|
||||
return settings(init=True, basedir=basedir, configfile=configfile)
|
||||
except InvalidSettings as e:
|
||||
message = "Error parsing the configuration file, it appears to be invalid YAML."
|
||||
if e.line is not None and e.column is not None:
|
||||
message += " The parser reported an error on line {}, column {}.".format(
|
||||
e.line, e.column
|
||||
)
|
||||
raise FatalStartupError(message)
|
||||
raise FatalStartupError(str(e))
|
||||
|
||||
|
||||
def preinit_logging(
|
||||
@@ -468,7 +463,7 @@ def init_pluginsystem(
|
||||
|
||||
def validator(phase, plugin_info):
|
||||
if phase in ("before_import", "before_load", "before_enable"):
|
||||
setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled)
|
||||
plugin_info.safe_mode_victim = not plugin_info.bundled
|
||||
if not plugin_info.bundled:
|
||||
return False
|
||||
return True
|
||||
@@ -497,7 +492,7 @@ def init_pluginsystem(
|
||||
plugin.needs_restart = True
|
||||
|
||||
# plugin has a settings overlay, inject it
|
||||
overlay_definition = getattr(plugin.instance, "__plugin_settings_overlay__")
|
||||
overlay_definition = plugin.instance.__plugin_settings_overlay__
|
||||
if isinstance(overlay_definition, (tuple, list)):
|
||||
overlay_definition, order = overlay_definition
|
||||
else:
|
||||
|
||||
@@ -687,7 +687,7 @@ def get_versions():
|
||||
# versionfile_source is the relative path from the top of the source
|
||||
# tree (where the .git directory might live) to this file. Invert
|
||||
# this to find the root from __file__.
|
||||
for i in cfg.versionfile_source.split("/"):
|
||||
for _ in cfg.versionfile_source.split("/"):
|
||||
root = os.path.dirname(root)
|
||||
except NameError:
|
||||
return {
|
||||
|
||||
@@ -35,7 +35,6 @@ class UserManager(GroupChangeListener, object):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._session_users_by_session = {}
|
||||
self._sessionids_by_userid = {}
|
||||
self._enabled = True
|
||||
|
||||
if settings is None:
|
||||
settings = s()
|
||||
@@ -50,29 +49,14 @@ class UserManager(GroupChangeListener, object):
|
||||
self._login_status_listeners.remove(listener)
|
||||
|
||||
def anonymous_user_factory(self):
|
||||
if self.enabled:
|
||||
return AnonymousUser([self._group_manager.guest_group])
|
||||
else:
|
||||
return AdminUser(
|
||||
[self._group_manager.admin_group, self._group_manager.user_group]
|
||||
)
|
||||
return AnonymousUser([self._group_manager.guest_group])
|
||||
|
||||
def api_user_factory(self):
|
||||
return ApiUser([self._group_manager.admin_group, self._group_manager.user_group])
|
||||
|
||||
@property
|
||||
def enabled(self):
|
||||
return self._enabled
|
||||
|
||||
@enabled.setter
|
||||
def enabled(self, value):
|
||||
self._enabled = value
|
||||
|
||||
def enable(self):
|
||||
self._enabled = True
|
||||
|
||||
def disable(self):
|
||||
self._enabled = False
|
||||
return True
|
||||
|
||||
def login_user(self, user):
|
||||
self._cleanup_sessions()
|
||||
@@ -112,7 +96,7 @@ class UserManager(GroupChangeListener, object):
|
||||
return user
|
||||
|
||||
def logout_user(self, user, stale=False):
|
||||
if user is None or user.is_anonymous or isinstance(user, AdminUser):
|
||||
if user is None or user.is_anonymous:
|
||||
return
|
||||
|
||||
if isinstance(user, LocalProxy):
|
||||
@@ -1444,11 +1428,3 @@ class SessionUser(wrapt.ObjectProxy):
|
||||
class ApiUser(User):
|
||||
def __init__(self, groups):
|
||||
User.__init__(self, "_api", "", True, [], groups)
|
||||
|
||||
|
||||
##~~ User object to use when access control is disabled
|
||||
|
||||
|
||||
class AdminUser(User):
|
||||
def __init__(self, groups):
|
||||
User.__init__(self, "_admin", "", True, [], groups)
|
||||
@@ -106,7 +106,7 @@ def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||
)
|
||||
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo(str(e), err=True)
|
||||
click.echo("There was a fatal error initializing the client.", err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ def config(ctx):
|
||||
get_ctx_obj_option(ctx, "configfile", None),
|
||||
)
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo(str(e), err=True)
|
||||
click.echo("There was a fatal error initializing the settings manager.", err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
@@ -87,7 +87,7 @@ def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except Exception as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo(str(e), err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
data_type = None
|
||||
@@ -124,7 +124,7 @@ def append_value_command(ctx, path, value, as_json=False):
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except Exception as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo(str(e), err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
current = ctx.obj.settings.get(path)
|
||||
@@ -153,7 +153,7 @@ def insert_value_command(ctx, path, index, value, as_json=False):
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except Exception as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo(str(e), err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
current = ctx.obj.settings.get(path)
|
||||
@@ -181,7 +181,7 @@ def remove_value_command(ctx, path, value, as_json=False):
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except Exception as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo(str(e), err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
current = ctx.obj.settings.get(path)
|
||||
|
||||
@@ -89,7 +89,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False)
|
||||
)
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo(str(e), err=True)
|
||||
click.echo(
|
||||
"There was a fatal error initializing the settings or the plugin system.",
|
||||
err=True,
|
||||
|
||||
@@ -262,7 +262,7 @@ def enable_safemode(ctx, **kwargs):
|
||||
get_ctx_obj_option(ctx, "configfile", None),
|
||||
)
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo(str(e), err=True)
|
||||
click.echo("There was a fatal error initializing the settings manager.", err=True)
|
||||
ctx.exit(-1)
|
||||
else:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
@@ -71,8 +71,6 @@ def user(ctx):
|
||||
err=True,
|
||||
)
|
||||
user_manager = FilebasedUserManager(group_manager, settings=settings)
|
||||
finally:
|
||||
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
|
||||
|
||||
ctx.obj.user_manager = user_manager
|
||||
|
||||
|
||||
@@ -104,6 +104,8 @@ class Events(object):
|
||||
FIRMWARE_DATA = "FirmwareData"
|
||||
TOOL_CHANGE = "ToolChange"
|
||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||
COMMAND_SUPPRESSED = "CommandSuppressed"
|
||||
INVALID_TOOL_REPORTED = "InvalidToolReported"
|
||||
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
|
||||
@@ -129,7 +129,7 @@ def get_all_extensions(subtree=None):
|
||||
|
||||
result = []
|
||||
if isinstance(subtree, dict):
|
||||
for key, value in subtree.items():
|
||||
for value in subtree.values():
|
||||
if isinstance(value, dict):
|
||||
result += get_all_extensions(value)
|
||||
elif isinstance(value, (ContentTypeMapping, ContentTypeDetector)):
|
||||
@@ -167,7 +167,7 @@ def get_content_type_mapping_for_extension(extension, subtree=None):
|
||||
if subtree is None:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
for value in subtree.values():
|
||||
content_extension_matches = (
|
||||
isinstance(value, (ContentTypeMapping, ContentTypeDetector))
|
||||
and extension in value.extensions
|
||||
@@ -313,7 +313,7 @@ class FileManager(object):
|
||||
if root is not None:
|
||||
backlog_generator = storage_manager.analysis_backlog_for_path(path=root)
|
||||
|
||||
for entry, path, printer_profile in backlog_generator:
|
||||
for entry, path, _ in backlog_generator:
|
||||
file_type = get_file_type(path)[-1]
|
||||
file_name = storage_manager.split_path(path)
|
||||
|
||||
|
||||
@@ -1712,7 +1712,7 @@ class PluginManager(object):
|
||||
)
|
||||
|
||||
self.plugin_implementations[name] = plugin.implementation
|
||||
setattr(plugin.implementation, "__timing_wrapped", True)
|
||||
plugin.implementation.__timing_wrapped = True
|
||||
|
||||
def _deactivate_plugin(self, name, plugin):
|
||||
for hook, definition in plugin.hooks.items():
|
||||
@@ -2354,7 +2354,7 @@ class EntryPointMetadata(pkginfo.Distribution):
|
||||
for metadata_file in metadata_files:
|
||||
try:
|
||||
return self.entry_point.dist.get_metadata(metadata_file)
|
||||
except (IOError, OSError):
|
||||
except (IOError, OSError): # noqa: B014
|
||||
# file not found, metadata file might be missing, ignore
|
||||
# IOError: file not found in Py2
|
||||
# OSError (specifically FileNotFoundError): file not found in Py3
|
||||
|
||||
@@ -100,6 +100,7 @@ class ActionCommandNotificationPlugin(
|
||||
"name": gettext("Printer Notifications"),
|
||||
"icon": "bell-o",
|
||||
"styles_wrapper": ["display: none"],
|
||||
"template_header": "action_command_notification_sidebar_header.jinja2",
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
|
||||
" && settings.settings.plugins.action_command_notification.enable()",
|
||||
},
|
||||
|
||||
+28
-1
@@ -7,6 +7,10 @@ $(function () {
|
||||
self.settings = parameters[2];
|
||||
|
||||
self.notifications = ko.observableArray([]);
|
||||
self.sortDesc = ko.observable(false);
|
||||
self.sortDesc.subscribe(function () {
|
||||
self._toLocalStorage();
|
||||
});
|
||||
|
||||
self.toDateTimeString = function (timestamp) {
|
||||
return formatDate(timestamp);
|
||||
@@ -24,7 +28,11 @@ $(function () {
|
||||
};
|
||||
|
||||
self.fromResponse = function (response) {
|
||||
self.notifications(response.notifications);
|
||||
var notifications = response.notifications;
|
||||
if (self.sortDesc()) {
|
||||
notifications.reverse();
|
||||
}
|
||||
self.notifications(notifications);
|
||||
};
|
||||
|
||||
self.clear = function () {
|
||||
@@ -38,6 +46,11 @@ $(function () {
|
||||
OctoPrint.plugins.action_command_notification.clear();
|
||||
};
|
||||
|
||||
self.toggleSorting = function () {
|
||||
self.sortDesc(!self.sortDesc());
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
self.requestData();
|
||||
};
|
||||
@@ -71,6 +84,20 @@ $(function () {
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
var optionsLocalStorageKey = "core.gcodeviewer.options";
|
||||
self._toLocalStorage = function () {
|
||||
saveToLocalStorage(optionsLocalStorageKey, {sortDesc: self.sortDesc()});
|
||||
};
|
||||
|
||||
self._fromLocalStorage = function () {
|
||||
var data = loadFromLocalStorage(optionsLocalStorageKey);
|
||||
if (data["sortDesc"] !== undefined) {
|
||||
self.sortDesc(!!data["sortDesc"]);
|
||||
}
|
||||
};
|
||||
|
||||
self._fromLocalStorage();
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
<div class="sidebar_plugin_action_command_notification_entry_message" data-bind="text: message"></div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn btn-block" data-bind="click: clear, visible: loginState.hasPermission(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR)">{{ _('Clear notifications') }}</button>
|
||||
<button class="btn btn-block" data-bind="click: clear, visible: loginState.hasPermission(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR)"><i class="fa fa-trash-o"></i> {{ _('Clear notifications') }}</button>
|
||||
</div>
|
||||
<div style="display: none" data-bind="visible: notifications().length == 0">
|
||||
{{ _('There are currently no notifications from your printer.') }}
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
<div class="accordion-heading-button btn-group" data-bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR) && notifications().length > 0">
|
||||
<a href="javascript:void(0)" data-bind="click: clear" title="{{ _('Clear notifications')|edq }}">
|
||||
<i class="fa fa-trash-o"></i>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="accordion-heading-button btn-group" data-bind="visible: notifications().length > 0">
|
||||
<a href="javascript:void(0)" data-bind="click: toggleSorting" title="{{ _('Change sorting')|edq }}">
|
||||
<i class="fa" data-bind="css: {'fa-sort-amount-desc': sortDesc, 'fa-sort-amount-asc': !sortDesc()}"></i>
|
||||
</a>
|
||||
</div>
|
||||
@@ -419,11 +419,7 @@ class AppKeysPlugin(
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
if any(filter(lambda x: x.api_key == api_key, data)):
|
||||
if self._user_manager.enabled:
|
||||
return self._user_manager.find_user(userid=user_id)
|
||||
elif user_id == "_admin" or user_id == "dummy":
|
||||
# dummy = backwards compatible
|
||||
return self._user_manager.anonymous_user_factory()
|
||||
return self._user_manager.find_user(userid=user_id)
|
||||
return None
|
||||
|
||||
def _api_keys_for_user(self, user_id):
|
||||
@@ -433,7 +429,7 @@ class AppKeysPlugin(
|
||||
def _all_api_keys(self):
|
||||
with self._keys_lock:
|
||||
result = []
|
||||
for user_id, keys in self._keys.items():
|
||||
for keys in self._keys.values():
|
||||
result += keys
|
||||
return result
|
||||
|
||||
|
||||
@@ -969,7 +969,7 @@ class BackupPlugin(
|
||||
# add list of installed plugins
|
||||
plugins = []
|
||||
plugin_folder = settings.global_get_basefolder("plugins")
|
||||
for key, plugin in plugin_manager.plugins.items():
|
||||
for plugin in plugin_manager.plugins.values():
|
||||
if plugin.bundled or (
|
||||
isinstance(plugin.origin, FolderOrigin)
|
||||
and plugin.origin.folder == plugin_folder
|
||||
@@ -1101,14 +1101,13 @@ class BackupPlugin(
|
||||
with io.open(configfile, "rt", encoding="utf-8") as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
|
||||
if configdata.get("accessControl", {}).get("enabled", True):
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup("Backup lacks users.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
if callable(on_invalid_backup):
|
||||
on_invalid_backup("Backup lacks users.yaml")
|
||||
if callable(on_restore_failed):
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress("Unpacked")
|
||||
|
||||
@@ -105,7 +105,7 @@ class CoreWizardPlugin(
|
||||
return result
|
||||
|
||||
def get_wizard_version(self):
|
||||
return 3
|
||||
return 4
|
||||
|
||||
# ~~ helpers
|
||||
|
||||
|
||||
@@ -9,20 +9,19 @@ $(function () {
|
||||
self.confirmedPassword = ko.observable(undefined);
|
||||
|
||||
self.setup = ko.observable(false);
|
||||
self.decision = ko.observable();
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.passwordMismatch = ko.pureComputed(function () {
|
||||
return self.password() != self.confirmedPassword();
|
||||
return self.password() !== self.confirmedPassword();
|
||||
});
|
||||
|
||||
self.validUsername = ko.pureComputed(function () {
|
||||
return self.username() && self.username().trim() != "";
|
||||
return self.username() && self.username().trim() !== "";
|
||||
});
|
||||
|
||||
self.validPassword = ko.pureComputed(function () {
|
||||
return self.password() && self.password().trim() != "";
|
||||
return self.password() && self.password().trim() !== "";
|
||||
});
|
||||
|
||||
self.validData = ko.pureComputed(function () {
|
||||
@@ -31,11 +30,10 @@ $(function () {
|
||||
);
|
||||
});
|
||||
|
||||
self.keepAccessControl = function () {
|
||||
self.createAccount = function () {
|
||||
if (!self.validData()) return;
|
||||
|
||||
var data = {
|
||||
ac: true,
|
||||
user: self.username(),
|
||||
pass1: self.password(),
|
||||
pass2: self.confirmedPassword()
|
||||
@@ -43,35 +41,27 @@ $(function () {
|
||||
self._sendData(data);
|
||||
};
|
||||
|
||||
self.disableAccessControl = function () {
|
||||
var message = gettext(
|
||||
"If you disable Access Control <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>"
|
||||
);
|
||||
showConfirmationDialog({
|
||||
message: message,
|
||||
onproceed: function (e) {
|
||||
var data = {
|
||||
ac: false
|
||||
};
|
||||
self._sendData(data);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self._sendData = function (data, callback) {
|
||||
OctoPrint.postJson("plugin/corewizard/acl", data).done(function () {
|
||||
self.setup(true);
|
||||
self.decision(data.ac);
|
||||
if (data.ac) {
|
||||
// we now log the user in
|
||||
var user = data.user;
|
||||
var pass = data.pass1;
|
||||
self.loginStateViewModel.login(user, pass, true).done(function () {
|
||||
if (callback) callback();
|
||||
});
|
||||
} else {
|
||||
|
||||
// we now log the user in
|
||||
var user = data.user;
|
||||
var pass = data.pass1;
|
||||
self.loginStateViewModel.login(user, pass, true).done(function () {
|
||||
if (callback) callback();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
self._showDecisionNeededDialog = function () {
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up Access Control"),
|
||||
message: gettext(
|
||||
"You haven't yet set up access control. You need to setup a " +
|
||||
'username and password and click "Create Account" before ' +
|
||||
"continuing."
|
||||
)
|
||||
});
|
||||
};
|
||||
|
||||
@@ -85,12 +75,17 @@ $(function () {
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up Access Control"),
|
||||
message: gettext(
|
||||
'You haven\'t yet set up access control. You need to either setup a username and password and click "Keep Access Control Enabled" or click "Disable Access Control" before continuing'
|
||||
)
|
||||
});
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onBeforeWizardFinish = function () {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (self.setup()) return true;
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -102,14 +97,6 @@ $(function () {
|
||||
response.corewizard.details.acl &&
|
||||
response.corewizard.details.acl.required;
|
||||
};
|
||||
|
||||
self.onWizardFinish = function () {
|
||||
if (!self.required) return;
|
||||
|
||||
if (!self.decision()) {
|
||||
return "reload";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function CoreWizardWebcamViewModel(parameters) {
|
||||
|
||||
@@ -63,10 +63,10 @@ class WebcamSubwizard(object):
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
class AclSubwizard(object):
|
||||
def _is_acl_wizard_firstrunonly(self):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _is_acl_wizard_required(self):
|
||||
return self._user_manager.enabled and not self._user_manager.has_been_customized()
|
||||
return not self._user_manager.has_been_customized()
|
||||
|
||||
def _get_acl_wizard_details(self):
|
||||
return {"required": self._is_acl_wizard_required()}
|
||||
@@ -81,11 +81,11 @@ class AclSubwizard(object):
|
||||
def acl_wizard_api(self):
|
||||
from flask import abort, request
|
||||
|
||||
from octoprint.server.api import NO_CONTENT, valid_boolean_trues
|
||||
from octoprint.server.api import NO_CONTENT
|
||||
|
||||
if (
|
||||
not self._settings.global_get(["server", "firstRun"])
|
||||
or self._user_manager.has_been_customized()
|
||||
and self._user_manager.has_been_customized()
|
||||
):
|
||||
abort(404)
|
||||
|
||||
@@ -94,17 +94,12 @@ class AclSubwizard(object):
|
||||
data = request.values
|
||||
|
||||
if (
|
||||
"ac" in data
|
||||
and data["ac"] in valid_boolean_trues
|
||||
and "user" in data
|
||||
"user" in data
|
||||
and "pass1" in data
|
||||
and "pass2" in data
|
||||
and data["pass1"] == data["pass2"]
|
||||
):
|
||||
# configure access control
|
||||
self._settings.global_set_boolean(["accessControl", "enabled"], True)
|
||||
self._user_manager.enable()
|
||||
|
||||
self._user_manager.add_user(
|
||||
data["user"],
|
||||
data["pass1"],
|
||||
@@ -113,10 +108,6 @@ class AclSubwizard(object):
|
||||
[USER_GROUP, ADMIN_GROUP],
|
||||
overwrite=True,
|
||||
)
|
||||
elif "ac" in data and data["ac"] not in valid_boolean_trues:
|
||||
# disable access control
|
||||
self._settings.global_set_boolean(["accessControl", "enabled"], False)
|
||||
self._user_manager.disable()
|
||||
self._settings.save()
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@@ -1,26 +1,10 @@
|
||||
<h3>{{ _('Access Control') }}</h3>
|
||||
|
||||
{% trans safe_remote_url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %}<p>
|
||||
<strong>Please read the following, it is very important for your printer's health!</strong>
|
||||
</p>
|
||||
<p>
|
||||
OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
|
||||
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
|
||||
malicious intent - to gain access to your printer</strong> via an untrustworthy network
|
||||
and using it in such a way that it is damaged or worse (i.e. causes a fire).
|
||||
</p>
|
||||
<p>
|
||||
If you plan on accessing OctoPrint remotely over the internet, <strong>you should not only rely on the built-in
|
||||
Access Control mechanisms</strong> however -
|
||||
<a href="{{ safe_remote_url }}" target="_blank" rel="noopener noreferrer">take additional precautions</a>.
|
||||
Your OctoPrint enabled printer is a critical home appliance you really should not give anyone who happens to be
|
||||
connected to the internet access to - even read-only! <strong>An instance available publicly on the internet
|
||||
will be found, and people will try to break it open.</strong>
|
||||
</p>
|
||||
<p>
|
||||
It looks like you haven't configured access control yet. Please <strong>set up a username and password</strong> for the
|
||||
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
|
||||
on "Keep Access Control Enabled":
|
||||
{% trans %}<p>
|
||||
It looks like you haven't configured access control yet, which is now mandatory.
|
||||
Please <strong>set up a username and password</strong> for the
|
||||
initial administrator account who will have full access to both the printer and
|
||||
OctoPrint's settings:
|
||||
</p>{% endtrans %}
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
<div class="control-group" data-bind="css: {success: validUsername()}">
|
||||
@@ -42,26 +26,7 @@
|
||||
<span class="help-inline" data-bind="visible: passwordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<a href="#" class="btn btn-primary" data-bind="click: function() { if(!setup()){createAccount()}}, enable: !setup() && validData(), css: {disabled: !validData() || setup()}">{{ _('Create Account') }}</a>
|
||||
</div>
|
||||
</form>
|
||||
{% trans %}<p>
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy local network and you don't
|
||||
need Access Control for other reasons, you may alternatively disable Access Control. You should only
|
||||
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Do NOT underestimate the risk of access from the internet to your printer and OctoPrint instance!</strong>
|
||||
</p>{% endtrans %}
|
||||
|
||||
<div class="row-fluid">
|
||||
<a href="#" class="btn btn-danger span6" data-bind="click: function() { if(!setup()){disableAccessControl()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Access Control') }}</a>
|
||||
<a href="#" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){keepAccessControl()}}, enable: !setup() && validData(), css: {disabled: !validData() || setup()}">{{ _('Keep Access Control Enabled') }}</a>
|
||||
</div>
|
||||
|
||||
<div class="acl_decision" style="display: none" data-bind="visible: setup()">
|
||||
<div class="text-center" style="display: none" data-bind="visible: decision()">{% trans %}
|
||||
Access control is <strong class="text-success">enabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
<div class="text-center" style="display: none" data-bind="visible: !decision()">{% trans %}
|
||||
Access control is <strong class="text-danger">disabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
</div>
|
||||
@@ -1,4 +1,4 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
@@ -46,8 +46,8 @@ IGNORED_EXCEPTIONS = [
|
||||
# IOErrors of any kind due to a full file system
|
||||
(
|
||||
IOError,
|
||||
lambda exc, logger, plugin, cb: getattr(exc, "errno")
|
||||
and exc.errno in (getattr(errno, "ENOSPC"),),
|
||||
lambda exc, logger, plugin, cb: exc.errorgetattr(exc, "errno") # noqa: B009
|
||||
and exc.errno in (getattr(errno, "ENOSPC"),), # noqa: B009
|
||||
),
|
||||
# RequestExceptions of any kind
|
||||
requests.exceptions.RequestException,
|
||||
|
||||
@@ -860,41 +860,25 @@ $(function () {
|
||||
|
||||
var optionsLocalStorageKey = "core.gcodeviewer.options";
|
||||
self._toLocalStorage = function () {
|
||||
if (!Modernizr.localstorage) return;
|
||||
|
||||
var current = {};
|
||||
current["centerViewport"] = self.renderer_centerViewport();
|
||||
current["zoomOnModel"] = self.renderer_zoomOnModel();
|
||||
current["showMoves"] = self.renderer_showMoves();
|
||||
current["showRetracts"] = self.renderer_showRetracts();
|
||||
current["showPrinthead"] = self.renderer_showPrinthead();
|
||||
current["showPrevious"] = self.renderer_showPrevious();
|
||||
current["showCurrent"] = self.renderer_showCurrent();
|
||||
current["showNext"] = self.renderer_showNext();
|
||||
current["showFullsize"] = self.renderer_showFullSize();
|
||||
current["showBoundingBox"] = self.renderer_showBoundingBox();
|
||||
current["hideEmptyLayers"] = self.reader_hideEmptyLayers();
|
||||
current["sortLayers"] = self.reader_sortLayers();
|
||||
|
||||
localStorage[optionsLocalStorageKey] = JSON.stringify(current);
|
||||
saveToLocalStorage(optionsLocalStorageKey, {
|
||||
centerViewPort: self.renderer_centerViewport(),
|
||||
zoomOnModel: self.renderer_zoomOnModel(),
|
||||
showMoves: self.renderer_showMoves(),
|
||||
showRetracts: self.renderer_showRetracts(),
|
||||
showPrinthead: self.renderer_showPrinthead(),
|
||||
showPrevious: self.renderer_showPrevious(),
|
||||
showCurrent: self.renderer_showCurrent(),
|
||||
showNext: self.renderer_showNext(),
|
||||
showFullsize: self.renderer_showFullSize(),
|
||||
showBoundingBox: self.renderer_showBoundingBox(),
|
||||
hideEmptyLayers: self.reader_hideEmptyLayers(),
|
||||
sortLayers: self.reader_sortLayers()
|
||||
});
|
||||
};
|
||||
self._fromLocalStorage = function () {
|
||||
self.resetOptions();
|
||||
|
||||
if (!Modernizr.localstorage) return;
|
||||
|
||||
var currentString = localStorage[optionsLocalStorageKey];
|
||||
var current;
|
||||
if (currentString === undefined) {
|
||||
current = {};
|
||||
} else {
|
||||
try {
|
||||
current = JSON.parse(currentString);
|
||||
} catch (ex) {
|
||||
current = {};
|
||||
}
|
||||
}
|
||||
|
||||
var current = loadFromLocalStorage(optionsLocalStorageKey);
|
||||
if (current["centerViewport"] !== undefined)
|
||||
self.renderer_centerViewport(current["centerViewport"]);
|
||||
if (current["zoomOnModel"] !== undefined)
|
||||
|
||||
@@ -252,8 +252,14 @@ class PiSupportPlugin(
|
||||
def on_api_get(self, request):
|
||||
if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can():
|
||||
return flask.abort(403)
|
||||
result = {"throttle_state": self._throttle_state.as_dict()}
|
||||
result.update(self.get_additional_environment())
|
||||
|
||||
environment = self.get_additional_environment()
|
||||
|
||||
result = {
|
||||
"throttle_state": self._throttle_state.as_dict(),
|
||||
"model_unrecommended": "zero" in environment.get("model").lower(),
|
||||
}
|
||||
result.update(environment)
|
||||
return flask.jsonify(**result)
|
||||
|
||||
# ~~ AssetPlugin
|
||||
@@ -309,6 +315,7 @@ class PiSupportPlugin(
|
||||
return {
|
||||
"vcgencmd_throttle_check_enabled": True,
|
||||
"vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE,
|
||||
"ignore_unrecommended_model": False,
|
||||
}
|
||||
|
||||
def get_settings_restricted_paths(self):
|
||||
|
||||
@@ -4,6 +4,7 @@ $(function () {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[1];
|
||||
self.settings = parameters[2];
|
||||
|
||||
self.model = ko.observable();
|
||||
|
||||
@@ -27,6 +28,42 @@ $(function () {
|
||||
// Raspberry Pi model
|
||||
self.model(response.model);
|
||||
|
||||
// Unrecommended model
|
||||
if (
|
||||
response.model_unrecommended &&
|
||||
!self.settings.settings.plugins.pi_support.ignore_unrecommended_model()
|
||||
) {
|
||||
var warning = gettext(
|
||||
"OctoPrint does not and never has supported the " +
|
||||
"RPi Zero or Zero W. Use at least a Raspberry Pi 3, or " +
|
||||
"risk bad performance and failed prints."
|
||||
);
|
||||
var faq = gettext(
|
||||
"" +
|
||||
'You can read more <a href="%(url)s" target="_blank">in the FAQ</a>.'
|
||||
);
|
||||
var remove = gettext(
|
||||
"You can disable this message via Settings > " +
|
||||
"Pi Support > Ignore warning on unsupported hardware"
|
||||
);
|
||||
new PNotify({
|
||||
title: gettext("Unsupported hardware detected"),
|
||||
text:
|
||||
"<p>" +
|
||||
warning +
|
||||
"</p><p>" +
|
||||
_.sprintf(faq, {
|
||||
url: "https://faq.octoprint.org/recommended-hardware"
|
||||
}) +
|
||||
"</p><p>" +
|
||||
"<small>" +
|
||||
remove +
|
||||
"</small></p>",
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
|
||||
// Throttle state
|
||||
self.fromThrottleState(response.throttle_state);
|
||||
|
||||
@@ -130,6 +167,6 @@ $(function () {
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PiSupportViewModel,
|
||||
elements: ["#navbar_plugin_pi_support"],
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"]
|
||||
dependencies: ["loginStateViewModel", "accessViewModel", "settingsViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,15 @@
|
||||
<p>{{ _('Please restart OctoPrint after changing any of this plugin\'s settings.') }}</p>
|
||||
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.pi_support.ignore_unrecommended_model"> {{ _('Disable warning about unsupported hardware') }} <label class="label label-important">{{ _('Warning') }}</label>
|
||||
</label>
|
||||
<span class="help-block">{{ _('If you check this, you will no longer get warned if you run OctoPrint on Raspberry Pi models that are not officially supported due to bad performance that can lead to failed prints. Do so at your own risk.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
|
||||
@@ -1312,7 +1312,7 @@ class PluginManagerPlugin(
|
||||
existing={}, ignore_uninstalled=False
|
||||
)
|
||||
|
||||
for key, plugin in plugins.items():
|
||||
for plugin in plugins.values():
|
||||
if plugin.origin is None or plugin.origin.type != "entry_point":
|
||||
continue
|
||||
|
||||
@@ -1400,7 +1400,7 @@ class PluginManagerPlugin(
|
||||
"loglines": [{"line": line, "stream": stream} for line in lines],
|
||||
},
|
||||
)
|
||||
for line in lines:
|
||||
for line in lines: # noqa: B007
|
||||
self._console_logger.debug("{prefix} {line}".format(**locals()))
|
||||
|
||||
def _mark_plugin_enabled(self, plugin, needs_restart=False):
|
||||
|
||||
@@ -222,7 +222,7 @@ class SoftwareUpdatePlugin(
|
||||
check_providers[key] = name
|
||||
|
||||
yaml_config = {}
|
||||
effective_config = default_config
|
||||
effective_config = copy.deepcopy(default_config)
|
||||
|
||||
if key in overlays:
|
||||
effective_config = dict_merge(
|
||||
@@ -534,6 +534,11 @@ class SoftwareUpdatePlugin(
|
||||
"minimum_free_storage": 150,
|
||||
"check_overlay_url": "https://plugins.octoprint.org/update_check_overlay.json",
|
||||
"check_overlay_ttl": 6 * 60,
|
||||
"credentials": {
|
||||
"github": None,
|
||||
"bitbucket_user": None,
|
||||
"bitbucket_password": None,
|
||||
},
|
||||
}
|
||||
|
||||
def on_settings_load(self):
|
||||
@@ -591,6 +596,9 @@ class SoftwareUpdatePlugin(
|
||||
|
||||
return data
|
||||
|
||||
def get_settings_restricted_paths(self):
|
||||
return {"never": [["credentials"]]}
|
||||
|
||||
def on_settings_save(self, data):
|
||||
# ~~ plugin settings
|
||||
|
||||
@@ -874,7 +882,7 @@ class SoftwareUpdatePlugin(
|
||||
if delete is None:
|
||||
delete = []
|
||||
|
||||
for k, v in data.items():
|
||||
for k in data:
|
||||
if k in defaults and defaults[k] == data[k]:
|
||||
delete.append(k)
|
||||
|
||||
@@ -1247,6 +1255,8 @@ class SoftwareUpdatePlugin(
|
||||
update_possible = False
|
||||
information = {}
|
||||
|
||||
credentials = self._settings.get(["credentials"], merged=True)
|
||||
|
||||
# we don't want to do the same work twice, so let's use a lock
|
||||
if self._get_versions_mutex.acquire(False):
|
||||
self._get_versions_data_ready.clear()
|
||||
@@ -1272,6 +1282,7 @@ class SoftwareUpdatePlugin(
|
||||
target,
|
||||
populated_check,
|
||||
force=force,
|
||||
credentials=credentials,
|
||||
)
|
||||
futures_to_result[future] = (target, populated_check)
|
||||
except exceptions.UnknownCheckType:
|
||||
@@ -1445,7 +1456,9 @@ class SoftwareUpdatePlugin(
|
||||
hash_update(dict_to_sorted_repr(check))
|
||||
return hash.hexdigest()
|
||||
|
||||
def _get_current_version(self, target, check, force=False, online=None):
|
||||
def _get_current_version(
|
||||
self, target, check, force=False, online=None, credentials=None
|
||||
):
|
||||
"""
|
||||
Determines the current version information for one target based on its check configuration.
|
||||
"""
|
||||
@@ -1478,7 +1491,7 @@ class SoftwareUpdatePlugin(
|
||||
try:
|
||||
version_checker = self._get_version_checker(target, check)
|
||||
information, is_current = version_checker.get_latest(
|
||||
target, check, online=online
|
||||
target, check, online=online, credentials=credentials
|
||||
)
|
||||
if information is not None:
|
||||
if (
|
||||
@@ -1497,17 +1510,33 @@ class SoftwareUpdatePlugin(
|
||||
update_possible = False
|
||||
information["needs_online"] = True
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warning("Unknown check type %s for %s" % (check["type"], target))
|
||||
self._logger.warning(
|
||||
"Unknown check type {} for {}".format(check["type"], target)
|
||||
)
|
||||
update_possible = False
|
||||
error = "unknown_check"
|
||||
except exceptions.NetworkError:
|
||||
self._logger.warning(
|
||||
"Could not check %s for updates due to a network error" % target
|
||||
"Could not check {} for updates due to a network error".format(target)
|
||||
)
|
||||
update_possible = False
|
||||
error = "network"
|
||||
except exceptions.RateLimitCheckError as exc:
|
||||
self._logger.warning(
|
||||
"Could not check {} for updates due to running into a rate limit: {}".format(
|
||||
target, exc
|
||||
)
|
||||
)
|
||||
update_possible = False
|
||||
error = "ratelimit"
|
||||
except exceptions.CheckError:
|
||||
self._logger.warning(
|
||||
"Could not check {} for updates due to a check error".format(target)
|
||||
)
|
||||
update_possible = False
|
||||
error = "check"
|
||||
except Exception:
|
||||
self._logger.exception("Could not check %s for updates" % target)
|
||||
self._logger.exception("Could not check {} for updates".format(target))
|
||||
update_possible = False
|
||||
error = "unknown"
|
||||
else:
|
||||
@@ -1597,6 +1626,8 @@ class SoftwareUpdatePlugin(
|
||||
|
||||
restart_type = None
|
||||
|
||||
credentials = self._settings.get(["credentials"], merged=True)
|
||||
|
||||
try:
|
||||
self._update_in_progress = True
|
||||
|
||||
@@ -1616,7 +1647,9 @@ class SoftwareUpdatePlugin(
|
||||
if target not in check_targets:
|
||||
continue
|
||||
|
||||
target_error, target_result = self._perform_update(target, check, force)
|
||||
target_error, target_result = self._perform_update(
|
||||
target, check, force, credentials=credentials
|
||||
)
|
||||
error = error or target_error
|
||||
if target_result is not None:
|
||||
target_results[target] = target_result
|
||||
@@ -1689,11 +1722,11 @@ class SoftwareUpdatePlugin(
|
||||
else:
|
||||
self._send_client_message("success", {"results": target_results})
|
||||
|
||||
def _perform_update(self, target, check, force):
|
||||
def _perform_update(self, target, check, force, credentials=None):
|
||||
online = self._connectivity_checker.online
|
||||
|
||||
information, update_available, update_possible, _, _ = self._get_current_version(
|
||||
target, check, online=online
|
||||
target, check, online=online, credentials=credentials
|
||||
)
|
||||
|
||||
if not update_available and not force:
|
||||
|
||||
@@ -37,11 +37,30 @@ class NetworkError(Exception):
|
||||
return "NetworkError"
|
||||
|
||||
|
||||
class CheckError(Exception):
|
||||
def __init__(self, message):
|
||||
self.message = message
|
||||
|
||||
def __str__(self):
|
||||
return self.message
|
||||
|
||||
|
||||
class RateLimitCheckError(CheckError):
|
||||
def __init__(self, message, remaining=None, limit=None, reset=None):
|
||||
super(RateLimitCheckError, self).__init__(message)
|
||||
self.remaining = remaining
|
||||
self.limit = limit
|
||||
self.reset = reset
|
||||
|
||||
|
||||
class UpdateError(Exception):
|
||||
def __init__(self, message, data):
|
||||
self.message = message
|
||||
self.data = data
|
||||
|
||||
def __str__(self):
|
||||
return self.message
|
||||
|
||||
|
||||
class ScriptError(Exception):
|
||||
def __init__(self, returncode, stdout, stderr):
|
||||
|
||||
@@ -577,6 +577,14 @@ $(function () {
|
||||
case "network": {
|
||||
return gettext("Network error while checking for update");
|
||||
}
|
||||
case "ratelimit": {
|
||||
return gettext(
|
||||
"Rate limit exceeded while checking for update, please try again later"
|
||||
);
|
||||
}
|
||||
case "check": {
|
||||
return gettext("Check internal error while checking for update");
|
||||
}
|
||||
case "unknown": {
|
||||
return gettext(
|
||||
"Unknown error while checking for update, please check the logs"
|
||||
|
||||
@@ -5,6 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from ..exceptions import RateLimitCheckError
|
||||
from . import ( # noqa: F401
|
||||
always_current,
|
||||
bitbucket_commit,
|
||||
@@ -20,21 +21,43 @@ from . import ( # noqa: F401
|
||||
)
|
||||
|
||||
|
||||
class GithubRateLimitCheckError(RateLimitCheckError):
|
||||
def __init__(self, remaining, ratelimit, reset):
|
||||
if reset:
|
||||
message = "Github rate limit exceeded, reset at {}".format(reset)
|
||||
else:
|
||||
message = "Github rate limit exceeded"
|
||||
super(GithubRateLimitCheckError, self).__init__(
|
||||
message, remaining=remaining, limit=ratelimit, reset=reset
|
||||
)
|
||||
|
||||
|
||||
def log_github_ratelimit(logger, r):
|
||||
ratelimit = (
|
||||
r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?"
|
||||
)
|
||||
remaining = (
|
||||
r.headers["X-RateLimit-Remaining"]
|
||||
if "X-RateLimit-Remaining" in r.headers
|
||||
else "?"
|
||||
)
|
||||
try:
|
||||
ratelimit = int(r.headers.get("X-RateLimit-Limit", None))
|
||||
except ValueError:
|
||||
ratelimit = None
|
||||
|
||||
try:
|
||||
remaining = int(r.headers.get("X-RateLimit-Remaining", None))
|
||||
except ValueError:
|
||||
remaining = None
|
||||
|
||||
reset = r.headers["X-RateLimit-Reset"] if "X-RateLimit-Reset" in r.headers else None
|
||||
try:
|
||||
import time
|
||||
|
||||
reset = time.strftime("%Y-%m-%d %H:%M", time.gmtime(int(reset)))
|
||||
except Exception:
|
||||
reset = "?"
|
||||
reset = None
|
||||
|
||||
logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset))
|
||||
logger.debug(
|
||||
"Github rate limit: {}/{}, reset at {}".format(
|
||||
remaining if remaining is not None else "?",
|
||||
ratelimit if ratelimit is not None else "?",
|
||||
reset if reset is not None else "?",
|
||||
)
|
||||
)
|
||||
|
||||
if remaining == 0:
|
||||
raise GithubRateLimitCheckError(remaining, ratelimit, reset)
|
||||
@@ -5,7 +5,7 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
def get_latest(target, check, online=True, *args, **kwargs):
|
||||
current_version = check.get("current_version", "1.0.0")
|
||||
|
||||
information = {
|
||||
|
||||
@@ -44,7 +44,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
|
||||
return reference["hash"]
|
||||
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
if "user" not in check or "repo" not in check:
|
||||
@@ -60,6 +60,10 @@ def get_latest(target, check, online=True):
|
||||
api_user = check.get("api_user")
|
||||
api_password = check.get("api_password")
|
||||
|
||||
if api_user is None and api_password is None and credentials:
|
||||
api_user = credentials.get("bitbucket_user")
|
||||
api_password = credentials.get("bitbucket_password")
|
||||
|
||||
current = check.get("current")
|
||||
|
||||
information = {
|
||||
|
||||
@@ -12,7 +12,7 @@ from ..exceptions import CannotCheckOffline, ConfigurationInvalid
|
||||
from ..util import execute
|
||||
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
def get_latest(target, check, online=True, *args, **kwargs):
|
||||
command = check.get("command")
|
||||
if command is None:
|
||||
raise ConfigurationInvalid(
|
||||
|
||||
@@ -51,7 +51,7 @@ def _git(args, cwd, hide_stderr=False):
|
||||
return p.returncode, stdout
|
||||
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
def get_latest(target, check, online=True, *args, **kwargs):
|
||||
checkout_folder = check.get("checkout_folder")
|
||||
if checkout_folder is None:
|
||||
raise ConfigurationInvalid(
|
||||
|
||||
@@ -16,13 +16,19 @@ logger = logging.getLogger(
|
||||
)
|
||||
|
||||
|
||||
def _get_latest_commit(user, repo, branch):
|
||||
def _get_latest_commit(user, repo, branch, apikey=None):
|
||||
from ..exceptions import NetworkError
|
||||
|
||||
headers = {}
|
||||
if apikey:
|
||||
auth = "token " + apikey
|
||||
headers = {"Authorization": auth}
|
||||
|
||||
try:
|
||||
r = requests.get(
|
||||
BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch),
|
||||
timeout=(3.05, 30),
|
||||
headers=headers,
|
||||
)
|
||||
except requests.ConnectionError as exc:
|
||||
raise NetworkError(cause=exc)
|
||||
@@ -41,7 +47,7 @@ def _get_latest_commit(user, repo, branch):
|
||||
return reference["object"]["sha"]
|
||||
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
user = check.get("user")
|
||||
@@ -73,7 +79,13 @@ def get_latest(target, check, online=True):
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
|
||||
apikey = None
|
||||
if credentials:
|
||||
apikey = credentials.get("github")
|
||||
|
||||
remote_commit = _get_latest_commit(
|
||||
check["user"], check["repo"], branch, apikey=apikey
|
||||
)
|
||||
remote_name = (
|
||||
"Commit {commit}".format(commit=remote_commit)
|
||||
if remote_commit is not None
|
||||
|
||||
@@ -100,14 +100,27 @@ def _filter_out_latest(releases, sort_key=None, include_prerelease=False, commit
|
||||
|
||||
|
||||
def _get_latest_release(
|
||||
user, repo, compare_type, include_prerelease=False, commitish=None, force_base=True
|
||||
user,
|
||||
repo,
|
||||
compare_type,
|
||||
include_prerelease=False,
|
||||
commitish=None,
|
||||
force_base=True,
|
||||
apikey=None,
|
||||
):
|
||||
from ..exceptions import NetworkError
|
||||
|
||||
nothing = None, None, None
|
||||
|
||||
headers = {}
|
||||
if apikey:
|
||||
auth = "token " + apikey
|
||||
headers = {"Authorization": auth}
|
||||
|
||||
try:
|
||||
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30))
|
||||
r = requests.get(
|
||||
RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30), headers=headers
|
||||
)
|
||||
except requests.ConnectionError as exc:
|
||||
raise NetworkError(cause=exc)
|
||||
|
||||
@@ -278,7 +291,9 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
|
||||
return True
|
||||
|
||||
|
||||
def get_latest(target, check, custom_compare=None, online=True):
|
||||
def get_latest(
|
||||
target, check, custom_compare=None, online=True, credentials=None, *args, **kwargs
|
||||
):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
user = check.get("user", None)
|
||||
@@ -319,6 +334,10 @@ def get_latest(target, check, custom_compare=None, online=True):
|
||||
check.get("release_compare", "python"), custom=custom_compare
|
||||
)
|
||||
|
||||
apikey = None
|
||||
if credentials:
|
||||
apikey = credentials.get("github")
|
||||
|
||||
remote_name, remote_tag, release_notes = _get_latest_release(
|
||||
check["user"],
|
||||
check["repo"],
|
||||
@@ -326,6 +345,7 @@ def get_latest(target, check, custom_compare=None, online=True):
|
||||
include_prerelease=include_prerelease,
|
||||
commitish=commitish,
|
||||
force_base=force_base,
|
||||
apikey=apikey,
|
||||
)
|
||||
|
||||
if not remote_name:
|
||||
|
||||
@@ -13,7 +13,7 @@ from ..exceptions import CannotCheckOffline, ConfigurationInvalid, NetworkError
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.etag")
|
||||
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
def get_latest(target, check, online=True, *args, **kwargs):
|
||||
if not online:
|
||||
raise CannotCheckOffline()
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ from ..exceptions import CannotCheckOffline, ConfigurationInvalid, NetworkError
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.jsondata")
|
||||
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
def get_latest(target, check, online=True, *args, **kwargs):
|
||||
if not online:
|
||||
raise CannotCheckOffline()
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
def get_latest(target, check, online=True, *args, **kwargs):
|
||||
local_version = check.get("local_version", "1.0.0")
|
||||
remote_version = check.get("remote_version", "1.0.1")
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
@@ -99,7 +99,7 @@ def _is_current(release_information):
|
||||
return remote_version <= local_version
|
||||
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
def get_latest(target, check, online=True, *args, **kwargs):
|
||||
from ..exceptions import CannotUpdateOffline
|
||||
|
||||
if not online and not check.get("offline", False):
|
||||
|
||||
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from ..exceptions import CannotCheckOffline, ConfigurationInvalid
|
||||
|
||||
|
||||
def get_latest(target, check, full_data=False, online=True):
|
||||
def get_latest(target, check, full_data=False, online=True, *args, **kwargs):
|
||||
python_checker = check.get("python_checker")
|
||||
if python_checker is None or not hasattr(python_checker, "get_latest"):
|
||||
raise ConfigurationInvalid(
|
||||
|
||||
@@ -175,7 +175,7 @@ def on_user_logged_out(sender, user=None):
|
||||
|
||||
|
||||
def load_user(id):
|
||||
if id is None or not userManager.enabled:
|
||||
if id is None:
|
||||
return None
|
||||
|
||||
if id == "_api":
|
||||
@@ -553,10 +553,6 @@ class Server(object):
|
||||
"falling back to FilebasedUserManager!".format(user_manager_name)
|
||||
)
|
||||
userManager = octoprint.access.users.FilebasedUserManager(groupManager)
|
||||
finally:
|
||||
userManager.enabled = self._settings.getBoolean(
|
||||
["accessControl", "enabled"]
|
||||
)
|
||||
components.update({"user_manager": userManager})
|
||||
|
||||
# create printer instance
|
||||
@@ -599,7 +595,7 @@ class Server(object):
|
||||
kwargs["tags"] = tags
|
||||
return f(*args, **kwargs)
|
||||
|
||||
setattr(wrapper, "__tagwrapped__", True)
|
||||
wrapper.__tagwrapped__ = True
|
||||
return wrapper
|
||||
|
||||
class TaggedFuncsPrinter(wrapt.ObjectProxy):
|
||||
@@ -1349,7 +1345,7 @@ class Server(object):
|
||||
if "X-Locale" in request.headers:
|
||||
return Locale.negotiate([request.headers["X-Locale"]], LANGUAGES)
|
||||
|
||||
if hasattr(g, "identity") and g.identity and userManager.enabled:
|
||||
if hasattr(g, "identity") and g.identity:
|
||||
userid = g.identity.id
|
||||
try:
|
||||
user_language = userManager.get_user_setting(
|
||||
|
||||
@@ -162,7 +162,11 @@ def pluginCommand(name):
|
||||
|
||||
@api.route("/setup/wizard", methods=["GET"])
|
||||
def wizardState():
|
||||
if not s().getBoolean(["server", "firstRun"]) and not Permissions.ADMIN.can():
|
||||
if (
|
||||
not s().getBoolean(["server", "firstRun"])
|
||||
and octoprint.server.userManager.has_been_customized()
|
||||
and not Permissions.ADMIN.can()
|
||||
):
|
||||
abort(403)
|
||||
|
||||
seen_wizards = s().get(["server", "seenWizards"])
|
||||
@@ -199,7 +203,11 @@ def wizardState():
|
||||
|
||||
@api.route("/setup/wizard", methods=["POST"])
|
||||
def wizardFinish():
|
||||
if not s().getBoolean(["server", "firstRun"]) and not Permissions.ADMIN.can():
|
||||
if (
|
||||
not s().getBoolean(["server", "firstRun"])
|
||||
and octoprint.server.userManager.has_been_customized()
|
||||
and not Permissions.ADMIN.can()
|
||||
):
|
||||
abort(403)
|
||||
|
||||
data = {}
|
||||
@@ -278,7 +286,7 @@ def login():
|
||||
if not data:
|
||||
data = request.values
|
||||
|
||||
if octoprint.server.userManager.enabled and "user" in data and "pass" in data:
|
||||
if "user" in data and "pass" in data:
|
||||
username = data["user"]
|
||||
password = data["pass"]
|
||||
|
||||
@@ -296,10 +304,10 @@ def login():
|
||||
if not user.is_active:
|
||||
return make_response(("Your account is deactivated", 403, []))
|
||||
|
||||
if octoprint.server.userManager.enabled:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.session
|
||||
g.user = user
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.session
|
||||
g.user = user
|
||||
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(
|
||||
current_app._get_current_object(), identity=Identity(user.get_id())
|
||||
|
||||
@@ -141,9 +141,6 @@ def remove_group(key):
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def get_users():
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users())))
|
||||
|
||||
|
||||
@@ -151,9 +148,6 @@ def get_users():
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def add_user():
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
@@ -189,9 +183,6 @@ def add_user():
|
||||
@api.route("/access/users/<username>", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def get_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if (
|
||||
current_user is not None
|
||||
and not current_user.is_anonymous
|
||||
@@ -213,9 +204,6 @@ def get_user(username):
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def update_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
user = userManager.find_user(username)
|
||||
if user is not None:
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
@@ -254,9 +242,6 @@ def update_user(username):
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def remove_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
try:
|
||||
userManager.remove_user(username)
|
||||
return get_users()
|
||||
@@ -302,9 +287,6 @@ def change_password_for_user(username):
|
||||
@api.route("/access/users/<username>/settings", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def get_settings_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if (
|
||||
current_user is None
|
||||
or current_user.is_anonymous
|
||||
@@ -324,9 +306,6 @@ def get_settings_for_user(username):
|
||||
@api.route("/access/users/<username>/settings", methods=["PATCH"])
|
||||
@no_firstrun_access
|
||||
def change_settings_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if (
|
||||
current_user is None
|
||||
or current_user.is_anonymous
|
||||
@@ -355,9 +334,6 @@ def change_settings_for_user(username):
|
||||
@api.route("/access/users/<username>/apikey", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
def delete_apikey_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if (
|
||||
current_user is not None
|
||||
and not current_user.is_anonymous
|
||||
|
||||
@@ -14,13 +14,16 @@ from werkzeug.exceptions import BadRequest
|
||||
import octoprint.plugin
|
||||
import octoprint.util
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server import pluginManager, printer
|
||||
from octoprint.server import pluginManager, printer, userManager
|
||||
from octoprint.server.api import NO_CONTENT, api
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
# ~~ settings
|
||||
|
||||
FOLDER_TYPES = ("uploads", "timelapse", "timelapse_tmp", "logs", "watched")
|
||||
FOLDER_MAPPING = {"timelapseTmp": "timelapse_tmp"}
|
||||
|
||||
|
||||
def _lastmodified():
|
||||
return settings().last_modified
|
||||
@@ -80,11 +83,13 @@ def _etag(lm=None):
|
||||
etag_factory=_etag,
|
||||
lastmodified_factory=_lastmodified,
|
||||
unless=lambda: request.values.get("force", "false") in valid_boolean_trues
|
||||
or settings().getBoolean(["server", "firstRun"]),
|
||||
or settings().getBoolean(["server", "firstRun"])
|
||||
or not userManager.has_been_customized(),
|
||||
)
|
||||
def getSettings():
|
||||
if not Permissions.SETTINGS_READ.can() and not settings().getBoolean(
|
||||
["server", "firstRun"]
|
||||
if not Permissions.SETTINGS_READ.can() and not (
|
||||
settings().getBoolean(["server", "firstRun"])
|
||||
or not userManager.has_been_customized()
|
||||
):
|
||||
abort(403)
|
||||
|
||||
@@ -215,6 +220,7 @@ def getSettings():
|
||||
"blockWhileDwelling": s.getBoolean(["serial", "blockWhileDwelling"]),
|
||||
"useParityWorkaround": s.get(["serial", "useParityWorkaround"]),
|
||||
"sanityCheckTools": s.getBoolean(["serial", "sanityCheckTools"]),
|
||||
"notifySuppressedCommands": s.get(["serial", "notifySuppressedCommands"]),
|
||||
"sendM112OnError": s.getBoolean(["serial", "sendM112OnError"]),
|
||||
"disableSdPrintingDetection": s.getBoolean(
|
||||
["serial", "disableSdPrintingDetection"]
|
||||
@@ -444,18 +450,33 @@ def _saveSettings(data):
|
||||
|
||||
if "folder" in data:
|
||||
try:
|
||||
if "uploads" in data["folder"]:
|
||||
s.setBaseFolder("uploads", data["folder"]["uploads"])
|
||||
if "timelapse" in data["folder"]:
|
||||
s.setBaseFolder("timelapse", data["folder"]["timelapse"])
|
||||
if "timelapseTmp" in data["folder"]:
|
||||
s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
|
||||
if "logs" in data["folder"]:
|
||||
s.setBaseFolder("logs", data["folder"]["logs"])
|
||||
if "watched" in data["folder"]:
|
||||
s.setBaseFolder("watched", data["folder"]["watched"])
|
||||
except IOError:
|
||||
return make_response("One of the configured folders is invalid", 400)
|
||||
folders = dict(
|
||||
(FOLDER_MAPPING.get(folder, folder), path)
|
||||
for folder, path in data["folder"].items()
|
||||
)
|
||||
future = {}
|
||||
for folder in FOLDER_TYPES:
|
||||
future[folder] = s.getBaseFolder(folder)
|
||||
if folder in folders:
|
||||
future[folder] = data["folder"][folder]
|
||||
|
||||
for folder in data["folder"]:
|
||||
if folder not in FOLDER_TYPES:
|
||||
continue
|
||||
for other_folder in FOLDER_TYPES:
|
||||
if folder == other_folder:
|
||||
continue
|
||||
if future[folder] == future[other_folder]:
|
||||
# duplicate detected, raise
|
||||
raise ValueError(
|
||||
"Duplicate folder path for {} and {}".format(
|
||||
folder, other_folder
|
||||
)
|
||||
)
|
||||
|
||||
s.setBaseFolder(folder, future[folder])
|
||||
except Exception:
|
||||
return make_response("At least one of the configured folders is invalid", 400)
|
||||
|
||||
if "api" in data:
|
||||
if "allowCrossOrigin" in data["api"]:
|
||||
@@ -779,6 +800,10 @@ def _saveSettings(data):
|
||||
s.setBoolean(
|
||||
["serial", "sanityCheckTools"], data["serial"]["sanityCheckTools"]
|
||||
)
|
||||
if "notifySuppressedCommands" in data["serial"]:
|
||||
value = data["serial"]["notifySuppressedCommands"]
|
||||
if value in ("info", "warn", "never"):
|
||||
s.set(["serial", "notifySuppressedCommands"], value)
|
||||
if "sendM112OnError" in data["serial"]:
|
||||
s.setBoolean(["serial", "sendM112OnError"], data["serial"]["sendM112OnError"])
|
||||
if "disableSdPrintingDetection" in data["serial"]:
|
||||
|
||||
@@ -113,10 +113,7 @@ def requireLoginRequestHandler():
|
||||
if _flask.request.endpoint.endswith(".static"):
|
||||
return
|
||||
|
||||
if not (
|
||||
octoprint.server.userManager.enabled
|
||||
and octoprint.server.userManager.has_been_customized()
|
||||
):
|
||||
if not octoprint.server.userManager.has_been_customized():
|
||||
return
|
||||
|
||||
user = flask_login.current_user
|
||||
@@ -211,11 +208,10 @@ def get_user_for_apikey(apikey):
|
||||
# master key was used
|
||||
return octoprint.server.userManager.api_user_factory()
|
||||
|
||||
if octoprint.server.userManager.enabled:
|
||||
user = octoprint.server.userManager.find_user(apikey=apikey)
|
||||
if user is not None:
|
||||
# user key was used
|
||||
return user
|
||||
user = octoprint.server.userManager.find_user(apikey=apikey)
|
||||
if user is not None:
|
||||
# user key was used
|
||||
return user
|
||||
|
||||
apikey_hooks = plugin_manager().get_hooks("octoprint.accesscontrol.keyvalidator")
|
||||
for name, hook in apikey_hooks.items():
|
||||
@@ -233,9 +229,6 @@ def get_user_for_apikey(apikey):
|
||||
|
||||
|
||||
def get_user_for_remote_user_header(request):
|
||||
if not octoprint.server.userManager.enabled:
|
||||
return None
|
||||
|
||||
if not settings().getBoolean(["accessControl", "trustRemoteUser"]):
|
||||
return None
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
from flask import make_response
|
||||
@@ -80,7 +80,7 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
||||
|
||||
# translations from plugins
|
||||
plugins = octoprint.plugin.plugin_manager().enabled_plugins
|
||||
for name, plugin in plugins.items():
|
||||
for plugin in plugins.values():
|
||||
plugin_translation_dir = os.path.join(plugin.location, "translations")
|
||||
if not os.path.isdir(plugin_translation_dir):
|
||||
continue
|
||||
@@ -1127,7 +1127,7 @@ class PreemptiveCache(object):
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
|
||||
for root, entries in data.items():
|
||||
for entries in data.values():
|
||||
if not isinstance(entries, list):
|
||||
return False
|
||||
|
||||
@@ -1523,22 +1523,17 @@ def no_firstrun_access(func):
|
||||
If you decorate a view with this, it will ensure that first setup has been
|
||||
done for OctoPrint's Access Control.
|
||||
|
||||
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
|
||||
flag from the settings being set to True and the userManager not indicating
|
||||
that it's user database has been customized from default), the decorator
|
||||
If OctoPrint's Access Control has not been setup yet (indicated by the userManager
|
||||
not reporting that its user database has been customized from default), the decorator
|
||||
will cause a HTTP 403 status code to be returned by the decorated resource.
|
||||
"""
|
||||
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
# if OctoPrint hasn't been set up yet, abort
|
||||
if (
|
||||
settings().getBoolean(["server", "firstRun"])
|
||||
and settings().getBoolean(["accessControl", "enabled"])
|
||||
and (
|
||||
octoprint.server.userManager is None
|
||||
or not octoprint.server.userManager.has_been_customized()
|
||||
)
|
||||
if settings().getBoolean(["server", "firstRun"]) and (
|
||||
octoprint.server.userManager is None
|
||||
or not octoprint.server.userManager.has_been_customized()
|
||||
):
|
||||
return flask.make_response("OctoPrint isn't setup yet", 403)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
@@ -46,7 +46,7 @@ class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session):
|
||||
return orig_send_pack(*args, **kwargs)
|
||||
|
||||
handler.send_pack = send_pack
|
||||
setattr(handler, "__orig_send_pack", orig_send_pack)
|
||||
handler.__orig_send_pack = orig_send_pack
|
||||
|
||||
return octoprint.vendor.sockjs.tornado.session.Session.set_handler(
|
||||
self, handler, start_heartbeat=start_heartbeat
|
||||
@@ -58,7 +58,7 @@ class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session):
|
||||
)
|
||||
|
||||
if getattr(handler, "__orig_send_pack", None) is not None:
|
||||
handler.send_pack = getattr(handler, "__orig_send_pack")
|
||||
handler.send_pack = handler.__orig_send_pack
|
||||
delattr(handler, "__orig_send_pack")
|
||||
|
||||
return result
|
||||
|
||||
@@ -332,7 +332,6 @@ def index():
|
||||
|
||||
if (
|
||||
request.headers.get("X-Preemptive-Recording", "no") == "no"
|
||||
and userManager.enabled
|
||||
and userManager.has_been_customized()
|
||||
):
|
||||
if not _has_permissions(Permissions.STATUS, Permissions.SETTINGS_READ):
|
||||
@@ -376,7 +375,6 @@ def index():
|
||||
|
||||
now = datetime.datetime.utcnow()
|
||||
|
||||
enable_accesscontrol = userManager.enabled
|
||||
enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"])
|
||||
enable_loading_animation = settings().getBoolean(["devel", "showLoadingAnimation"])
|
||||
enable_sd_support = settings().get(["feature", "sdSupport"])
|
||||
@@ -387,19 +385,12 @@ def index():
|
||||
sockjs_connect_timeout = settings().getInt(["devel", "sockJsConnectTimeout"])
|
||||
|
||||
def default_template_filter(template_type, template_key):
|
||||
if template_type == "navbar":
|
||||
return template_key != "login" or enable_accesscontrol
|
||||
elif template_type == "tab":
|
||||
if template_type == "tab":
|
||||
return template_key != "timelapse" or enable_timelapse
|
||||
elif template_type == "settings":
|
||||
return template_key != "accesscontrol" or enable_accesscontrol
|
||||
elif template_type == "usersettings":
|
||||
return enable_accesscontrol
|
||||
else:
|
||||
return True
|
||||
|
||||
default_additional_etag = [
|
||||
enable_accesscontrol,
|
||||
enable_timelapse,
|
||||
enable_loading_animation,
|
||||
enable_sd_support,
|
||||
@@ -613,7 +604,7 @@ def index():
|
||||
)
|
||||
|
||||
wizard = wizard_active(filtered_templates)
|
||||
accesscontrol_active = enable_accesscontrol and userManager.has_been_customized()
|
||||
accesscontrol_active = userManager.has_been_customized()
|
||||
|
||||
render_kwargs = _get_render_kwargs(
|
||||
filtered_templates, _plugin_names, _plugin_vars, now
|
||||
@@ -622,7 +613,7 @@ def index():
|
||||
{
|
||||
"enableWebcam": enable_webcam,
|
||||
"enableTemperatureGraph": enable_temperature_graph,
|
||||
"enableAccessControl": enable_accesscontrol,
|
||||
"enableAccessControl": True,
|
||||
"accessControlActive": accesscontrol_active,
|
||||
"enableLoadingAnimation": enable_loading_animation,
|
||||
"enableSdSupport": enable_sd_support,
|
||||
|
||||
@@ -161,6 +161,7 @@ default_settings = {
|
||||
"disableSdPrintingDetection": False,
|
||||
"ackMax": 1,
|
||||
"sanityCheckTools": True,
|
||||
"notifySuppressedCommands": "warn",
|
||||
"capabilities": {
|
||||
"autoreport_temp": True,
|
||||
"autoreport_sdstatus": True,
|
||||
@@ -376,7 +377,6 @@ default_settings = {
|
||||
"controls": [],
|
||||
"system": {"actions": []},
|
||||
"accessControl": {
|
||||
"enabled": True,
|
||||
"salt": None,
|
||||
"userManager": "octoprint.access.users.FilebasedUserManager",
|
||||
"groupManager": "octoprint.access.groups.FilebasedGroupManager",
|
||||
@@ -455,12 +455,52 @@ class NoSuchSettingsPath(Exception):
|
||||
|
||||
|
||||
class InvalidSettings(Exception):
|
||||
def __init__(self, message, line=None, column=None, details=None):
|
||||
self.message = message
|
||||
pass
|
||||
|
||||
|
||||
class InvalidYaml(InvalidSettings):
|
||||
def __init__(self, file, line=None, column=None, details=None):
|
||||
self.file = file
|
||||
self.line = line
|
||||
self.column = column
|
||||
self.details = details
|
||||
|
||||
def __str__(self):
|
||||
message = (
|
||||
"Error parsing the configuration file {}, "
|
||||
"it is invalid YAML.".format(self.file)
|
||||
)
|
||||
if self.line and self.column:
|
||||
message += " The parser reported an error on line {}, column {}.".format(
|
||||
self.line, self.column
|
||||
)
|
||||
return message
|
||||
|
||||
|
||||
class DuplicateFolderPaths(InvalidSettings):
|
||||
def __init__(self, folders):
|
||||
self.folders = folders
|
||||
|
||||
self.duplicates = {}
|
||||
for folder, path in folders.items():
|
||||
duplicates = []
|
||||
for other_folder, other_path in folders.items():
|
||||
if other_folder == folder:
|
||||
continue
|
||||
if other_path == path:
|
||||
duplicates.append(other_folder)
|
||||
if len(duplicates):
|
||||
self.duplicates[folder] = duplicates
|
||||
|
||||
def __str__(self):
|
||||
duplicates = [
|
||||
"{} (duplicates: {})".format(folder, ", ".join(dupes))
|
||||
for folder, dupes in self.duplicates.items()
|
||||
]
|
||||
return "There are duplicate folder paths configured: {}".format(
|
||||
", ".join(duplicates)
|
||||
)
|
||||
|
||||
|
||||
class HierarchicalChainMap(ChainMap):
|
||||
def deep_dict(self, root=None):
|
||||
@@ -942,7 +982,7 @@ class Settings(object):
|
||||
self._mtime = self.last_modified
|
||||
|
||||
except yaml.YAMLError as e:
|
||||
details = e.message
|
||||
details = str(e)
|
||||
|
||||
if hasattr(e, "problem_mark"):
|
||||
line = e.problem_mark.line
|
||||
@@ -951,8 +991,8 @@ class Settings(object):
|
||||
line = None
|
||||
column = None
|
||||
|
||||
raise InvalidSettings(
|
||||
"Invalid YAML file: {}".format(self._configfile),
|
||||
raise InvalidYaml(
|
||||
self._configfile,
|
||||
details=details,
|
||||
line=line,
|
||||
column=column,
|
||||
@@ -964,6 +1004,7 @@ class Settings(object):
|
||||
|
||||
if migrate:
|
||||
self._migrate_config()
|
||||
self._validate_config()
|
||||
|
||||
self._forget_hashes()
|
||||
|
||||
@@ -1533,6 +1574,15 @@ class Settings(object):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _validate_config(self):
|
||||
# validate uniqueness of folder paths
|
||||
folder_keys = self.get(["folder"], merged=True).keys()
|
||||
folders = dict(
|
||||
(folder_key, self.getBaseFolder(folder_key)) for folder_key in folder_keys
|
||||
)
|
||||
if len(folders.values()) != len(set(folders.values())):
|
||||
raise DuplicateFolderPaths(folders)
|
||||
|
||||
def backup(self, suffix=None, path=None, ext=None, hidden=False):
|
||||
import shutil
|
||||
|
||||
|
||||
@@ -301,6 +301,8 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
var type = event.data["type"];
|
||||
var payload = event.data["payload"];
|
||||
|
||||
var title, text, severity;
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
if (type === "PrintCancelling" && payload.firmwareError) {
|
||||
@@ -319,9 +321,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
hide: false
|
||||
});
|
||||
} else if (type === "Error" && payload.error) {
|
||||
var title = undefined,
|
||||
text = undefined;
|
||||
|
||||
switch (payload.reason) {
|
||||
case "firmware": {
|
||||
title = gettext("Error reported by printer");
|
||||
@@ -393,8 +392,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
});
|
||||
}
|
||||
} else if (type === "PrinterReset") {
|
||||
var severity = undefined,
|
||||
text = undefined;
|
||||
if (payload.idle) {
|
||||
text = gettext(
|
||||
"It looks like your printer reset while a connection was active. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD."
|
||||
|
||||
@@ -1563,3 +1563,25 @@ var determineWebcamStreamType = function (streamUrl) {
|
||||
throw "Empty streamUrl. Cannot determine stream type.";
|
||||
}
|
||||
};
|
||||
|
||||
var saveToLocalStorage = function (key, data) {
|
||||
if (!Modernizr.localstorage) return;
|
||||
localStorage[key] = JSON.stringify(data);
|
||||
};
|
||||
|
||||
var loadFromLocalStorage = function (key) {
|
||||
if (!Modernizr.localstorage) return {};
|
||||
|
||||
var currentString = localStorage[key];
|
||||
var current;
|
||||
if (currentString === undefined) {
|
||||
current = {};
|
||||
} else {
|
||||
try {
|
||||
current = JSON.parse(currentString);
|
||||
} catch (ex) {
|
||||
current = {};
|
||||
}
|
||||
}
|
||||
return current;
|
||||
};
|
||||
@@ -18,10 +18,7 @@ $(function () {
|
||||
self.access.permissions.STATUS,
|
||||
self.access.permissions.SETTINGS_READ
|
||||
) &&
|
||||
(!CONFIG_FIRST_RUN ||
|
||||
(self.coreWizardAcl &&
|
||||
self.coreWizardAcl.setup() &&
|
||||
self.coreWizardAcl.decision()))
|
||||
CONFIG_ACCESS_CONTROL_ACTIVE
|
||||
) {
|
||||
location.reload();
|
||||
}
|
||||
|
||||
@@ -312,13 +312,45 @@ $(function () {
|
||||
};
|
||||
|
||||
var folderTypes = ["uploads", "timelapse", "timelapseTmp", "logs", "watched"];
|
||||
|
||||
var checkForDuplicateFolders = function () {
|
||||
_.each(folderTypes, function (folderType) {
|
||||
var path = self["folder_" + folderType]();
|
||||
var duplicate = false;
|
||||
_.each(folderTypes, function (otherFolderType) {
|
||||
if (folderType !== otherFolderType) {
|
||||
duplicate =
|
||||
duplicate || path === self["folder_" + otherFolderType]();
|
||||
}
|
||||
});
|
||||
self.testFolderConfigDuplicate[folderType](duplicate);
|
||||
});
|
||||
};
|
||||
|
||||
self.testFolderConfigText = {};
|
||||
self.testFolderConfigOk = {};
|
||||
self.testFolderConfigBroken = {};
|
||||
self.testFolderConfigDuplicate = {};
|
||||
self.testFolderConfigError = {};
|
||||
self.testFolderConfigSuccess = {};
|
||||
_.each(folderTypes, function (folderType) {
|
||||
self.testFolderConfigText[folderType] = ko.observable("");
|
||||
self.testFolderConfigOk[folderType] = ko.observable(false);
|
||||
self.testFolderConfigBroken[folderType] = ko.observable(false);
|
||||
self.testFolderConfigDuplicate[folderType] = ko.observable(false);
|
||||
self.testFolderConfigError[folderType] = ko.pureComputed(function () {
|
||||
return (
|
||||
self.testFolderConfigBroken[folderType]() ||
|
||||
self.testFolderConfigDuplicate[folderType]()
|
||||
);
|
||||
});
|
||||
self.testFolderConfigSuccess[folderType] = ko.pureComputed(function () {
|
||||
return (
|
||||
self.testFolderConfigOk[folderType]() &&
|
||||
!self.testFolderConfigDuplicate[folderType]()
|
||||
);
|
||||
});
|
||||
self["folder_" + folderType].subscribe(checkForDuplicateFolders);
|
||||
});
|
||||
self.testFolderConfigReset = function () {
|
||||
_.each(folderTypes, function (folderType) {
|
||||
@@ -327,6 +359,13 @@ $(function () {
|
||||
self.testFolderConfigBroken[folderType](false);
|
||||
});
|
||||
};
|
||||
self.testFoldersDuplicate = ko.pureComputed(function () {
|
||||
var foundDupe = false;
|
||||
_.each(folderTypes, function (folderType) {
|
||||
foundDupe = foundDupe || self.testFolderConfigDuplicate[folderType]();
|
||||
});
|
||||
return foundDupe;
|
||||
});
|
||||
|
||||
self.observableCopies = {
|
||||
feature_waitForStart: "serial_waitForStart",
|
||||
@@ -1137,7 +1176,7 @@ $(function () {
|
||||
// map local observables based on our existing data
|
||||
var dataFromObservables = mapFromObservables(data, specialMappings);
|
||||
|
||||
data = _.extend(data, dataFromObservables);
|
||||
data = _.merge(data, dataFromObservables);
|
||||
return data;
|
||||
};
|
||||
|
||||
@@ -1311,18 +1350,26 @@ $(function () {
|
||||
} else {
|
||||
options = {
|
||||
success: successCallback,
|
||||
sending: setAsSending == true
|
||||
sending: setAsSending === true
|
||||
};
|
||||
}
|
||||
|
||||
self.settingsDialog.trigger("beforeSave");
|
||||
|
||||
self.sawUpdateEventWhileSending = false;
|
||||
self.sending(data == undefined || options.sending || false);
|
||||
self.sending(data === undefined || options.sending || false);
|
||||
|
||||
if (data == undefined) {
|
||||
if (data === undefined) {
|
||||
// we also only send data that actually changed when no data is specified
|
||||
data = getOnlyChangedData(self.getLocalData(), self.lastReceivedSettings);
|
||||
var localData = self.getLocalData();
|
||||
data = getOnlyChangedData(localData, self.lastReceivedSettings);
|
||||
}
|
||||
|
||||
// final validation
|
||||
if (self.testFoldersDuplicate()) {
|
||||
// duplicate folders configured, we refuse to send any folder config
|
||||
// to the server
|
||||
delete data.folder;
|
||||
}
|
||||
|
||||
self.active = true;
|
||||
|
||||
@@ -62,7 +62,7 @@ $(function () {
|
||||
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function (entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
return regex === undefined || !entry.line.match(regex);
|
||||
};
|
||||
|
||||
var filtered = false;
|
||||
@@ -95,7 +95,7 @@ $(function () {
|
||||
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function (entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
return regex === undefined || !entry.line.match(regex);
|
||||
};
|
||||
|
||||
var lines = self.log();
|
||||
@@ -237,7 +237,7 @@ $(function () {
|
||||
var last = self.plainLogLines()[self.plainLogLines().length - 1];
|
||||
var disabled =
|
||||
"--- client too slow, log output disabled while printing ---";
|
||||
if (last != disabled) {
|
||||
if (last !== disabled) {
|
||||
self.plainLogLines.push(disabled);
|
||||
}
|
||||
return;
|
||||
@@ -265,7 +265,7 @@ $(function () {
|
||||
return self._toInternalFormat(line);
|
||||
})
|
||||
);
|
||||
if (newData.length != data.length) {
|
||||
if (newData.length !== data.length) {
|
||||
var cutoff = "--- too many lines to buffer, cut off ---";
|
||||
newLog.push(self._toInternalFormat(cutoff, "cut"));
|
||||
}
|
||||
@@ -280,19 +280,30 @@ $(function () {
|
||||
|
||||
self._processHistoryLogData = function (data) {
|
||||
self.plainLogLines(data);
|
||||
self.log(
|
||||
_.map(data, function (line) {
|
||||
return self._toInternalFormat(line);
|
||||
})
|
||||
);
|
||||
self.log(_.map(data, self._toInternalFormat));
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self._toInternalFormat = function (line, type) {
|
||||
if (type == undefined) {
|
||||
type = "line";
|
||||
self._toInternalFormat = function (line, display, type) {
|
||||
if (display === undefined) {
|
||||
display = "line";
|
||||
}
|
||||
return {line: escapeUnprintableCharacters(line), type: type};
|
||||
|
||||
if (type === undefined) {
|
||||
if (line.startsWith("Recv:")) {
|
||||
type = "recv";
|
||||
} else if (line.startsWith("Send:")) {
|
||||
type = "send";
|
||||
} else if (line.startsWith("Warn:")) {
|
||||
type = "warn";
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
line: escapeUnprintableCharacters(line),
|
||||
display: display,
|
||||
type: type
|
||||
};
|
||||
};
|
||||
|
||||
self._processStateData = function (data) {
|
||||
@@ -307,7 +318,7 @@ $(function () {
|
||||
|
||||
self.updateFilterRegex = function () {
|
||||
var filterRegexStr = self.activeFilters().join("|").trim();
|
||||
if (filterRegexStr == "") {
|
||||
if (filterRegexStr === "") {
|
||||
self.filterRegex(undefined);
|
||||
} else {
|
||||
self.filterRegex(new RegExp(filterRegexStr));
|
||||
@@ -446,15 +457,15 @@ $(function () {
|
||||
self.handleKeyDown = function (event) {
|
||||
var keyCode = event.keyCode;
|
||||
|
||||
if (keyCode == 38 || keyCode == 40) {
|
||||
if (keyCode === 38 || keyCode === 40) {
|
||||
if (
|
||||
keyCode == 38 &&
|
||||
keyCode === 38 &&
|
||||
self.cmdHistory.length > 0 &&
|
||||
self.cmdHistoryIdx > 0
|
||||
) {
|
||||
self.cmdHistoryIdx--;
|
||||
} else if (
|
||||
keyCode == 40 &&
|
||||
keyCode === 40 &&
|
||||
self.cmdHistoryIdx < self.cmdHistory.length - 1
|
||||
) {
|
||||
self.cmdHistoryIdx++;
|
||||
@@ -478,7 +489,7 @@ $(function () {
|
||||
};
|
||||
|
||||
self.handleKeyUp = function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
if (event.keyCode === 13) {
|
||||
self.sendCommand();
|
||||
}
|
||||
|
||||
@@ -487,13 +498,61 @@ $(function () {
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function (current, previous) {
|
||||
self.tabActive = current == "#term";
|
||||
self.tabActive = current === "#term";
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self.onBrowserTabVisibilityChange = function (status) {
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self.onEventCommandSuppressed = function (payload) {
|
||||
var setting = self.settings.settings.serial.notifySuppressedCommands();
|
||||
|
||||
if (
|
||||
setting === "never" ||
|
||||
(setting === "warn" && payload.severity === "info")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
var severity = payload.severity;
|
||||
if (severity === "warn") {
|
||||
severity = "error";
|
||||
} else if (severity === "info") {
|
||||
severity = "warn";
|
||||
}
|
||||
|
||||
var text =
|
||||
"<p>" +
|
||||
gettext(
|
||||
"The command <code>%(command)s</code> was not sent " +
|
||||
"to the printer:"
|
||||
) +
|
||||
"</p><p><pre>%(message)s</pre></p>";
|
||||
|
||||
new PNotify({
|
||||
title: gettext("Suppressed command"),
|
||||
text: _.sprintf(text, payload),
|
||||
type: severity,
|
||||
hide: false
|
||||
});
|
||||
};
|
||||
|
||||
self.onEventInvalidToolReported = function (payload) {
|
||||
new PNotify({
|
||||
title: gettext("Invalid tool reported"),
|
||||
text: _.sprintf(
|
||||
gettext(
|
||||
"Your printer reported tool T%(tool)d as invalid, " +
|
||||
"reverting back to T%(fallback)d"
|
||||
),
|
||||
payload
|
||||
),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -20,10 +20,7 @@ $(function () {
|
||||
self.showDialog = function () {
|
||||
if (
|
||||
!CONFIG_WIZARD ||
|
||||
!(
|
||||
(CONFIG_FIRST_RUN && !CONFIG_ACCESS_CONTROL_ACTIVE) ||
|
||||
self.loginState.isAdmin()
|
||||
)
|
||||
!(!CONFIG_ACCESS_CONTROL_ACTIVE || self.loginState.isAdmin())
|
||||
)
|
||||
return;
|
||||
|
||||
|
||||
@@ -1,51 +1,50 @@
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
<h3>{{ _('Folders') }}</h3>
|
||||
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.uploads, success: testFolderConfigOk.uploads}">
|
||||
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigError.uploads, success: testFolderConfigSuccess.uploads}"> <label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append input-block-level">
|
||||
<input type="text" data-bind="value: folder_uploads" id="settings-folderUploads">
|
||||
<input type="text" data-bind="value: folder_uploads, valueUpdate: 'input'" id="settings-folderUploads">
|
||||
<a class="btn add-on" data-bind="click: function() { testFolderConfig('uploads'); }, enable: folder_uploads() && !testFolderConfigBusy(), css: {disabled: !folder_uploads() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: testFolderConfigBroken.uploads() || testFolderConfigOk.uploads(), text: testFolderConfigText.uploads"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.timelapse, success: testFolderConfigOk.timelapse}">
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigError.timelapse, success: testFolderConfigSuccess.timelapse}">
|
||||
<label class="control-label" for="settings-folderTimelapse">{{ _('Timelapse Folder') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append input-block-level">
|
||||
<input type="text" class="input-block-level" data-bind="value: folder_timelapse" id="settings-folderTimelapse">
|
||||
<input type="text" class="input-block-level" data-bind="value: folder_timelapse, valueUpdate: 'input'" id="settings-folderTimelapse">
|
||||
<a class="btn add-on" data-bind="click: function() { testFolderConfig('timelapse'); }, enable: folder_timelapse() && !testFolderConfigBusy(), css: {disabled: !folder_timelapse() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapse() || testFolderConfigOk.timelapse(), text: testFolderConfigText.timelapse"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.timelapseTmp, success: testFolderConfigOk.timelapseTmp}">
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigError.timelapseTmp, success: testFolderConfigSuccess.timelapseTmp}">
|
||||
<label class="control-label" for="settings-folderTimelapseTemp">{{ _('Timelapse Temp Folder') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append input-block-level">
|
||||
<input type="text" data-bind="value: folder_timelapseTmp" id="settings-folderTimelapseTemp">
|
||||
<input type="text" data-bind="value: folder_timelapseTmp, valueUpdate: 'input'" id="settings-folderTimelapseTemp">
|
||||
<a class="btn add-on" data-bind="click: function() { testFolderConfig('timelapseTmp'); }, enable: folder_timelapseTmp() && !testFolderConfigBusy(), css: {disabled: !folder_timelapseTmp() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapseTmp() || testFolderConfigOk.timelapseTmp(), text: testFolderConfigText.timelapseTmp"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.logs, success: testFolderConfigOk.logs}">
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigError.logs, success: testFolderConfigSuccess.logs}">
|
||||
<label class="control-label" for="settings-folderLogs">{{ _('Logs Folder') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append input-block-level">
|
||||
<input type="text" data-bind="value: folder_logs" id="settings-folderLogs">
|
||||
<input type="text" data-bind="value: folder_logs, valueUpdate: 'input'" id="settings-folderLogs">
|
||||
<a class="btn add-on" data-bind="click: function() { testFolderConfig('logs'); }, enable: folder_logs() && !testFolderConfigBusy(), css: {disabled: !folder_logs() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: testFolderConfigBroken.logs() || testFolderConfigOk.logs(), text: testFolderConfigText.logs"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.watched, success: testFolderConfigOk.watched}">
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigError.watched, success: testFolderConfigSuccess.watched}">
|
||||
<label class="control-label" for="settings-folderWatched">{{ _('Watched Folder') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append input-block-level">
|
||||
<input type="text" data-bind="value: folder_watched" id="settings-folderWatched">
|
||||
<input type="text" data-bind="value: folder_watched, valueUpdate: 'input'" id="settings-folderWatched">
|
||||
<a class="btn add-on" data-bind="click: function() { testFolderConfig('watched'); }, enable: folder_watched() && !testFolderConfigBusy(), css: {disabled: !folder_watched() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: testFolderConfigBroken.watched() || testFolderConfigOk.watched(), text: testFolderConfigText.watched"></span>
|
||||
@@ -58,6 +57,13 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="alert alert-error" data-bind="visible: testFoldersDuplicate">
|
||||
{% trans %}
|
||||
Two or more of the folders configured share a location. This is not
|
||||
supported. You need to fix this, until then no changes to your folder
|
||||
configuration will be persisted when saving the settings.
|
||||
{% endtrans %}
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Disk space thresholds') }}</h3>
|
||||
|
||||
|
||||
@@ -500,6 +500,20 @@
|
||||
<span class="help-block">{{ _('If enabled, OctoPrint will not send tool commands to your printer that exceed the number of extruders configured in the active printer profile, or for which the firmware has reported an "invalid extruder" error. Only uncheck this if OctoPrint or your firmware mistakingly mark valid tools as invalid and be sure to investigate the reason for that, it might be a misconfiguration you need to correct for proper operation.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Display notifications for suppressed commands')}}</label>
|
||||
<div class="controls">
|
||||
<label class="radio">
|
||||
<input type="radio" name="notifySuppressedCommandsGroup" value="info" data-bind="checked: settings.serial.notifySuppressedCommands" id="settings-serialNotifySuppressedCommands"> {{ _('Show notifications of severity "info" and "warning"') }}
|
||||
</label>
|
||||
<label class="radio">
|
||||
<input type="radio" name="notifySuppressedCommandsGroup" value="warn" data-bind="checked: settings.serial.notifySuppressedCommands" id="settings-serialNotifySuppressedCommands"> {{ _('Show notifications of severity "warning"') }}
|
||||
</label>
|
||||
<label class="radio">
|
||||
<input type="radio" name="notifySuppressedCommandsGroup" value="never" data-bind="checked: settings.serial.notifySuppressedCommands" id="settings-serialNotifySuppressedCommands"> {{ _('Never show notifications') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
var CONFIG_USERSPERPAGE = 10;
|
||||
var CONFIG_GROUPSPERPAGE = 10;
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}"; // deprecated, only left for compatibility reasons
|
||||
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_ACCESS_CONTROL = true; // deprecated, only left for compatibility reasons
|
||||
var CONFIG_ACCESS_CONTROL_ACTIVE = {% if accessControlActive -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_FIRST_RUN = {% if firstRun -%} true; {% else %} false; {%- endif %}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<div class="terminal">
|
||||
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality(), click: function(){ gotoTerminalCommand(); }, event: { scroll: terminalScrollEvent }"><span data-bind="text: line + '\n', css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
|
||||
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality(), click: function(){ gotoTerminalCommand(); }, event: { scroll: terminalScrollEvent }"><span data-bind="text: line + '\n', css: {muted: display == 'filtered' || display == 'cut', 'text-error': type == 'warn'}"></span></pre>
|
||||
<pre id="terminal-output-lowfi" style="display: none" class="pre-scrollable" data-bind="text: plainLogOutput, visible: !fancyFunctionality()"></pre>
|
||||
<div id="terminal-sendpanel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)">
|
||||
<div class="input-block-level input-append">
|
||||
|
||||
@@ -730,7 +730,7 @@ class Timelapse(object):
|
||||
|
||||
def _perform_capture(self, filename, onerror=None):
|
||||
# pre-capture hook
|
||||
for name, hook in self._pre_capture_hooks.items():
|
||||
for hook in self._pre_capture_hooks.values():
|
||||
try:
|
||||
hook(filename)
|
||||
except Exception:
|
||||
@@ -771,7 +771,7 @@ class Timelapse(object):
|
||||
err = None
|
||||
|
||||
# post-capture hook
|
||||
for name, hook in self._post_capture_hooks.items():
|
||||
for hook in self._post_capture_hooks.values():
|
||||
try:
|
||||
hook(filename, err is None)
|
||||
except Exception:
|
||||
|
||||
@@ -990,7 +990,7 @@ class fallback_dict(dict):
|
||||
def values(self):
|
||||
result = set()
|
||||
for dictionary in self._all():
|
||||
for k, v in dictionary.items():
|
||||
for k in dictionary:
|
||||
if k in result:
|
||||
continue
|
||||
result.add(k)
|
||||
@@ -1553,10 +1553,18 @@ class ResettableTimer(threading.Thread):
|
||||
kwargs (dict): The keyword arguments for the ``function`` call. Defaults to an empty dict.
|
||||
on_cancelled (callable): Callback to call when the timer finishes due to being cancelled.
|
||||
on_reset (callable): Callback to call when the timer is reset.
|
||||
daemon (bool): daemon flag to set on underlying thread.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, interval, function, args=None, kwargs=None, on_reset=None, on_cancelled=None
|
||||
self,
|
||||
interval,
|
||||
function,
|
||||
args=None,
|
||||
kwargs=None,
|
||||
on_reset=None,
|
||||
on_cancelled=None,
|
||||
daemon=True,
|
||||
):
|
||||
threading.Thread.__init__(self)
|
||||
self._event = threading.Event()
|
||||
@@ -1574,6 +1582,7 @@ class ResettableTimer(threading.Thread):
|
||||
self.kwargs = kwargs
|
||||
self.on_cancelled = on_cancelled
|
||||
self.on_reset = on_reset
|
||||
self.daemon = daemon
|
||||
|
||||
def run(self):
|
||||
while self.is_reset:
|
||||
|
||||
+98
-22
@@ -1368,6 +1368,15 @@ class MachineCom(object):
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
if "source:plugin" in tags:
|
||||
for tag in tags:
|
||||
if tag.startswith("plugin:"):
|
||||
self._logger.info(
|
||||
"Starting job on behalf of plugin {}".format(tag[7:])
|
||||
)
|
||||
elif "source:api" in tags:
|
||||
self._logger.info("Starting job on behalf of user {}".format(user))
|
||||
|
||||
try:
|
||||
with self._jobLock:
|
||||
self._consecutive_not_sd_printing = 0
|
||||
@@ -1598,6 +1607,9 @@ class MachineCom(object):
|
||||
tags=None,
|
||||
external_sd=False,
|
||||
):
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
if not self.isOperational():
|
||||
return
|
||||
|
||||
@@ -1605,14 +1617,20 @@ class MachineCom(object):
|
||||
# we aren't even printing, nothing to cancel...
|
||||
return
|
||||
|
||||
if "source:plugin" in tags:
|
||||
for tag in tags:
|
||||
if tag.startswith("plugin:"):
|
||||
self._logger.info(
|
||||
"Cancelling job on behalf of plugin {}".format(tag[7:])
|
||||
)
|
||||
elif "source:api" in tags:
|
||||
self._logger.info("Cancelling job on behalf of user {}".format(user))
|
||||
|
||||
if self.isStreaming():
|
||||
# we are streaming, we handle cancelling that differently...
|
||||
self.cancelFileTransfer()
|
||||
return
|
||||
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
def _on_M400_sent():
|
||||
# we don't call on_print_job_cancelled on our callback here
|
||||
# because we do this only after our M114 has been answered
|
||||
@@ -1736,6 +1754,15 @@ class MachineCom(object):
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
if "source:plugin" in tags:
|
||||
for tag in tags:
|
||||
if tag.startswith("plugin:"):
|
||||
self._logger.info(
|
||||
"Pausing/resuming job on behalf of plugin {}".format(tag[7:])
|
||||
)
|
||||
elif user:
|
||||
self._logger.info("Pausing/resuming job on behalf of user {}".format(user))
|
||||
|
||||
valid_paused_states = (self.STATE_PAUSED, self.STATE_PAUSING)
|
||||
valid_running_states = (
|
||||
self.STATE_PRINTING,
|
||||
@@ -2683,11 +2710,16 @@ class MachineCom(object):
|
||||
|
||||
if self._sanity_check_tools:
|
||||
# log to terminal and remember as invalid
|
||||
self._log(
|
||||
"T{} reported as invalid, reverting to T{}".format(
|
||||
invalid_tool, fallback_tool
|
||||
)
|
||||
message = "T{} reported as invalid, reverting to T{}".format(
|
||||
invalid_tool, fallback_tool
|
||||
)
|
||||
self._log("Warn: " + message)
|
||||
self._logger.warning(message)
|
||||
eventManager().fire(
|
||||
Events.INVALID_TOOL_REPORTED,
|
||||
{"tool": invalid_tool, "fallback": fallback_tool},
|
||||
)
|
||||
|
||||
self._knownInvalidTools.add(invalid_tool)
|
||||
|
||||
# we actually do send a T command here instead of just settings self._currentTool just in case
|
||||
@@ -4684,9 +4716,19 @@ class MachineCom(object):
|
||||
new_tool = int(toolMatch.group("value"))
|
||||
|
||||
if not self._validate_tool(new_tool):
|
||||
self._log(
|
||||
message = (
|
||||
"Not queuing T{}, that tool doesn't exist according to the printer profile or "
|
||||
"was reported as invalid by the firmware".format(new_tool)
|
||||
"was reported as invalid by the firmware. Make sure your "
|
||||
"printer profile is set up correctly.".format(new_tool)
|
||||
)
|
||||
self._log("Warn: " + message)
|
||||
eventManager().fire(
|
||||
Events.COMMAND_SUPPRESSED,
|
||||
{
|
||||
"command": cmd,
|
||||
"message": message,
|
||||
"severity": "warn",
|
||||
},
|
||||
)
|
||||
return (None,)
|
||||
|
||||
@@ -4718,9 +4760,21 @@ class MachineCom(object):
|
||||
if toolMatch:
|
||||
new_tool = int(toolMatch.group("value"))
|
||||
if not self._validate_tool(new_tool):
|
||||
self._log(
|
||||
"Not sending T{}, that tool doesn't exist according to the printer profile or "
|
||||
"was reported as invalid by the firmware".format(new_tool)
|
||||
message = (
|
||||
"Not sending T{}, that tool doesn't exist according to "
|
||||
"the printer profile or was reported as invalid by the "
|
||||
"firmware. Make sure your printer profile is set up "
|
||||
"correctly.".format(new_tool)
|
||||
)
|
||||
self._log("Warn: " + message)
|
||||
self._logger.warning(message)
|
||||
eventManager().fire(
|
||||
Events.COMMAND_SUPPRESSED,
|
||||
{
|
||||
"command": cmd,
|
||||
"message": message,
|
||||
"severity": "warn",
|
||||
},
|
||||
)
|
||||
return (None,)
|
||||
|
||||
@@ -4798,8 +4852,16 @@ class MachineCom(object):
|
||||
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
|
||||
):
|
||||
if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
self._log(
|
||||
'Warn: Not sending "{}", printer profile has no heated bed'.format(cmd)
|
||||
message = (
|
||||
'Not sending "{}", printer profile has no heated bed. Either '
|
||||
"configure a heated bed or remove bed commands from your "
|
||||
"GCODE.".format(cmd)
|
||||
)
|
||||
self._log("Warn: " + message)
|
||||
self._logger.warning(message)
|
||||
eventManager().fire(
|
||||
Events.COMMAND_SUPPRESSED,
|
||||
{"command": cmd, "message": message, "severity": "warn"},
|
||||
)
|
||||
return (None,) # Don't send bed commands if we don't have a heated bed
|
||||
|
||||
@@ -4809,10 +4871,16 @@ class MachineCom(object):
|
||||
self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs
|
||||
):
|
||||
if not self._printerProfileManager.get_current_or_default()["heatedChamber"]:
|
||||
self._log(
|
||||
'Warn: Not sending "{}", printer profile has no heated chamber'.format(
|
||||
cmd
|
||||
)
|
||||
message = (
|
||||
'Not sending "{}", printer profile has no heated chamber. Either '
|
||||
"configure a heated chamber or remove chamber commands from your "
|
||||
"GCODE.".format(cmd)
|
||||
)
|
||||
self._log("Warn: " + message)
|
||||
self._logger.warning(message)
|
||||
eventManager().fire(
|
||||
Events.COMMAND_SUPPRESSED,
|
||||
{"command": cmd, "message": message, "severity": "warn"},
|
||||
)
|
||||
return (
|
||||
None,
|
||||
@@ -5136,10 +5204,18 @@ class MachineCom(object):
|
||||
self.setPause(True)
|
||||
|
||||
if gcode in self._blocked_commands:
|
||||
self._logger.info(
|
||||
"Not sending {} to printer, it's configured as a blocked command".format(
|
||||
gcode
|
||||
)
|
||||
message = "Not sending {} to printer, it's configured as a blocked command".format(
|
||||
gcode
|
||||
)
|
||||
self._log("Info: " + message)
|
||||
self._logger.info(message)
|
||||
eventManager().fire(
|
||||
Events.COMMAND_SUPPRESSED,
|
||||
{
|
||||
"command": cmd,
|
||||
"message": message,
|
||||
"severity": "warn",
|
||||
},
|
||||
)
|
||||
return (None,)
|
||||
|
||||
|
||||
@@ -534,13 +534,13 @@ class gcode(object):
|
||||
)
|
||||
|
||||
if len(currentE) <= currentExtruder:
|
||||
for i in range(len(currentE), currentExtruder + 1):
|
||||
for _ in range(len(currentE), currentExtruder + 1):
|
||||
currentE.append(0.0)
|
||||
if len(maxExtrusion) <= currentExtruder:
|
||||
for i in range(len(maxExtrusion), currentExtruder + 1):
|
||||
for _ in range(len(maxExtrusion), currentExtruder + 1):
|
||||
maxExtrusion.append(0.0)
|
||||
if len(totalExtrusion) <= currentExtruder:
|
||||
for i in range(len(totalExtrusion), currentExtruder + 1):
|
||||
for _ in range(len(totalExtrusion), currentExtruder + 1):
|
||||
totalExtrusion.append(0.0)
|
||||
|
||||
if throttle is not None:
|
||||
|
||||
@@ -121,7 +121,7 @@ def get_all_template_paths(loader):
|
||||
def walk_folder(folder):
|
||||
files = []
|
||||
walk_dir = walk(folder, followlinks=True)
|
||||
for dirpath, dirnames, filenames in walk_dir:
|
||||
for dirpath, _, filenames in walk_dir:
|
||||
for filename in filenames:
|
||||
path = os.path.join(dirpath, filename)
|
||||
files.append(path)
|
||||
|
||||
@@ -544,7 +544,9 @@ class LocalPipCaller(PipCaller):
|
||||
import sys
|
||||
from distutils.sysconfig import get_python_lib
|
||||
|
||||
virtual_env = hasattr(sys, "real_prefix")
|
||||
virtual_env = hasattr(sys, "real_prefix") or (
|
||||
hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
|
||||
)
|
||||
install_dir = get_python_lib()
|
||||
writable = os.access(install_dir, os.W_OK)
|
||||
|
||||
|
||||
@@ -29,7 +29,9 @@ def produce_output(stream):
|
||||
cmd.finalize_options()
|
||||
|
||||
install_dir = cmd.install_lib
|
||||
virtual_env = hasattr(sys, "real_prefix")
|
||||
virtual_env = hasattr(sys, "real_prefix") or (
|
||||
hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
|
||||
)
|
||||
writable = os.access(install_dir, os.W_OK)
|
||||
|
||||
lines = [
|
||||
|
||||
Vendored
-3
@@ -10,9 +10,6 @@ completely removed.
|
||||
Licensed under the PSF LICENSE AGREEMENT <https://docs.python.org/3/license.html>
|
||||
"""
|
||||
|
||||
import sys
|
||||
assert sys.version_info[0] == 3 and sys.version_info[1] >= 5 # this only works on Python 3.5+
|
||||
|
||||
# (Probably) need to stay in _imp
|
||||
# noinspection PyCompatibility
|
||||
from _imp import (lock_held, acquire_lock, release_lock,
|
||||
|
||||
@@ -1 +1 @@
|
||||
Raspberry Pi Model F Rev 1.1
|
||||
Raspberry Pi Zero W Rev 1.1
|
||||
@@ -1,4 +1,4 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Unit tests for ``octoprint.server.api``.
|
||||
"""
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# coding=utf-8
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Unit tests for ``octoprint.server.api`` system.
|
||||
"""
|
||||
|
||||
Reference in new issue
Block a user