Merge branch 'devel' of github.com:OctoPrint/OctoPrint into devel

This commit is contained in:
Gina Häußge committed 2023-02-16 10:28:40 +01:00
commit bba932242f
160 files changed
+4580 -6645

No files matched your search

-11
View File
@@ -9,14 +9,3 @@ overrides:
browser: true
jquery: true
es6: true
- files:
- "tests/cypress/**"
env:
node: true
es6: true
cypress/globals: true
extends:
- "plugin:cypress/recommended"
plugins:
- cypress
+2 -2
View File
@@ -76,10 +76,10 @@ body:
Issues caused by a third party plugin are a major cause of bugs reported here, so we really need to
rule out that a plugin is at fault here. [Safe mode](https://docs.octoprint.org/en/master/features/safemode.html) is an easy way to do that. Only skip safe mode
if your particular problem *absolutely requires* third party plugins to be enabled. "It would take
too long" is **not** a reason to skip testing in safe mode, neither is "I do not know how to
too long" or "I have a long print running right now" are **not** a reason to skip testing in safe mode, neither is "I do not know how to
enable it" as you can find info on that [here](https://docs.octoprint.org/en/master/features/safemode.html).
If you really *cannot* test in safe mode, leave a short explanation as to why.
If you really *cannot* test in safe mode at all, leave a short explanation as to why. If you,can but just not right now, then wait with reporting until you can.
- type: markdown
attributes:
value: |
+7
View File
@@ -0,0 +1,7 @@
version: 2
updates:
# Check for updates to GitHub Actions every week
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
+6 -2
View File
@@ -4,10 +4,14 @@ devel:
enableRateLimiter: false
enableCsrfProtection: false
plugins:
virtual_printer:
enabled: true
softwareupdate:
checks:
octoprint:
disabled: true
tracking:
enabled: false
virtual_printer:
enabled: true
server:
firstRun: false
onlineCheck:
+3
View File
@@ -15,7 +15,10 @@ meta:
ci/cd:
- ".github/fixtures/**/*"
- ".github/workflows/*"
- ".github/dependabot.yml"
- ".github/issue-validation.yml"
- ".github/labeler.yml"
- ".github/pr-validation.yml"
docker:
- ".github/workflows/trigger_docker.yml"
+57 -23
View File
@@ -110,7 +110,6 @@ jobs:
name: 🧪 E2E tests
needs: build
runs-on: ubuntu-latest
continue-on-error: true
steps:
- name: ⬇ Checkout code
uses: actions/checkout@v3
@@ -120,11 +119,13 @@ jobs:
with:
name: dist
path: dist
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v4
with:
python-version: 3.7
- name: 🚀 Install wheel
- name: 🏗 Install OctoPrint build
run: |
pip install dist/OctoPrint-*-py2.py3-none-any.whl
@@ -133,30 +134,63 @@ jobs:
mkdir e2econfig
cp -r .github/fixtures/with_acl/* e2econfig
- name: 🚀 Run Cypress
uses: cypress-io/github-action@v4.2.0
with:
working-directory: tests/cypress
browser: chrome
start: "octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000"
wait-on: "http://127.0.0.1:5000/online.txt"
env:
CYPRESS_DEPLOYSENTINEL_ENABLED: "true"
CYPRESS_DEPLOYSENTINEL_UPLOAD_ON_PASSES: "true"
CYPRESS_DEPLOYSENTINEL_KEY: ${{ secrets.DEPLOYSENTINEL_APIKEY }}
- name: 🏗 Prepare Playwright env
working-directory: ./tests/playwright
run: |
npm ci
PLAYWRIGHT_VERSION=$(npm ls --json @playwright/test | jq --raw-output '.dependencies["@playwright/test"].version')
echo "PLAYWRIGHT_VERSION=$PLAYWRIGHT_VERSION" >> $GITHUB_ENV
- name: ⬆ Upload screenshots
- name: 🧰 Cache Playwright browser binaries
uses: actions/cache@v3
id: playwright-cache
with:
path: "~/.cache/ms-playwright"
key: "${{ runner.os }}-playwright-${{ env.PLAYWRIGHT_VERSION }}"
restore-keys: |
${{ runner.os }}-playwright-
- name: 🏗 Install Playwright browser binaries & OS dependencies
if: steps.playwright-cache.outputs.cache-hit != 'true'
working-directory: ./tests/playwright
run: |
npx playwright install --with-deps
- name: 🏗 Install Playwright OS dependencies
if: steps.playwright-cache.outputs.cache-hit == 'true'
working-directory: ./tests/playwright
run: |
npx playwright install-deps
- name: 🎭 Run Playwright
working-directory: ./tests/playwright
run: |
npx playwright test
env:
OCTOPRINT_SERVER_BASE: ${{ github.workspace }}/e2econfig
- name: 🔎 Check octoprint.log for errors
run: |
log=${{ github.workspace }}/e2econfig/logs/octoprint.log
if grep "\- ERROR \-" $log; then
echo "::error::Errors were logged to octoprint.log"
grep -Pazo '(?m)^\N+\- ERROR \-\N*\n(^\N*?\n)*?(?=\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3} \- )' $log
exit 1
fi
- name: ⬆ Upload Playwright report
uses: actions/upload-artifact@v3
if: always()
with:
name: playwright-report
path: tests/playwright/playwright-report
- name: ⬆ Upload OctoPrint logs
uses: actions/upload-artifact@v3
if: failure()
with:
name: cypress-screenshots
path: tests/cypress/screenshots
- name: ⬆ Upload videos
uses: actions/upload-artifact@v1
if: always()
with:
name: cypress-videos
path: tests/cypress/videos
name: octoprint-logs
path: ${{ github.workspace }}/e2econfig/logs
publish-on-testpypi:
name: 📦 Publish on TestPyPI
@@ -208,7 +242,7 @@ jobs:
OCTOPRINT_VERSION=$(echo $GITHUB_REF | cut -d/ -f3)
echo "OCTOPRINT_VERSION=$OCTOPRINT_VERSION" >> $GITHUB_ENV
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
uses: peter-evans/repository-dispatch@v2
with:
token: ${{ secrets.REPODISPATCH_TOKEN }}
repository: OctoPrint/OctoPi-UpToDate
+4 -4
View File
@@ -10,11 +10,11 @@ jobs:
name: 🔒 Lock issues & PRs closed over a year
runs-on: ubuntu-latest
steps:
- uses: dessant/lock-threads@v2
- uses: dessant/lock-threads@v4
with:
github-token: ${{ github.token }}
issue-lock-comment: ""
pr-lock-comment: ""
issue-comment: ""
pr-comment: ""
cleanup:
name: 🧹 Close issues marked as incomplete & older than 14 days
@@ -22,7 +22,7 @@ jobs:
steps:
- id: date
run: |
echo "::set-output name=CUTOFF::`date --date='14 days ago' +'%Y-%m-%d'`"
echo "CUTOFF=`date --date='14 days ago' +'%Y-%m-%d'`" >> $GITHUB_OUTPUT
- uses: OctoPrint/actions/close-by-query@main
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
+4 -4
View File
@@ -15,7 +15,7 @@ jobs:
fetch-depth: 0
- name: 🔀 Merge master into maintenance
uses: robotology/gh-action-nightly-merge@v1.3.3
uses: robotology/gh-action-nightly-merge@v1.4.0
with:
stable_branch: "master"
development_branch: "maintenance"
@@ -24,7 +24,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: 🔀 Merge staging/bugfix into maintenance
uses: robotology/gh-action-nightly-merge@v1.3.3
uses: robotology/gh-action-nightly-merge@v1.4.0
with:
stable_branch: "staging/bugfix"
development_branch: "maintenance"
@@ -33,7 +33,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: 🔀 Merge staging/maintenance into maintenance
uses: robotology/gh-action-nightly-merge@v1.3.3
uses: robotology/gh-action-nightly-merge@v1.4.0
with:
stable_branch: "staging/bugfix"
development_branch: "maintenance"
@@ -42,7 +42,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: 🔀 Merge maintenance into devel
uses: robotology/gh-action-nightly-merge@v1.3.3
uses: robotology/gh-action-nightly-merge@v1.4.0
with:
stable_branch: "maintenance"
development_branch: "devel"
+1 -1
View File
@@ -8,7 +8,7 @@ jobs:
pr-automation:
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@v3
- uses: actions/labeler@v4
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
+6 -7
View File
@@ -55,24 +55,23 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- name: 👀 Determine latest release
id: latest
uses: foosel/github-action-get-latest-release@master
with:
repository: "OctoPrint/OctoPrint"
run: |
OCTOPRINT_VERSION=$(curl -i https://github.com/OctoPrint/OctoPrint/releases/latest | grep -i location: | head -n1 | awk -F/ '{print $NF}' | tr -d '\r')
echo "OCTOPRINT_VERSION=$OCTOPRINT_VERSION" >> $GITHUB_ENV
- name: 🐍 Set up Python ${{ matrix.python }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python }}
- name: 👷 Build and install latest release
run: |
pip install https://github.com/OctoPrint/OctoPrint/archive/${{ steps.latest.outputs.release }}.zip
pip install https://github.com/OctoPrint/OctoPrint/archive/${{ env.OCTOPRINT_VERSION }}.zip
- name: 📧 Discord success notification
continue-on-error: true
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful"
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ env.OCTOPRINT_VERSION }}` was successful"
- name: 📧 Discord failure notification
continue-on-error: true
if: failure()
@@ -80,4 +79,4 @@ jobs:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed"
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ env.OCTOPRINT_VERSION }}` failed"
+3 -3
View File
@@ -15,7 +15,7 @@ jobs:
if: github.repository == 'OctoPrint/OctoPrint' && github.event_name != 'push'
steps:
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
uses: peter-evans/repository-dispatch@v2
with:
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
repository: ${{ github.repository_owner }}/octoprint-docker
@@ -27,7 +27,7 @@ jobs:
if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/maintenance'
steps:
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
uses: peter-evans/repository-dispatch@v2
with:
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
repository: ${{ github.repository_owner }}/octoprint-docker
@@ -39,7 +39,7 @@ jobs:
if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/devel'
steps:
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
uses: peter-evans/repository-dispatch@v2
with:
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
repository: ${{ github.repository_owner }}/octoprint-docker
+5 -1
View File
@@ -1,6 +1,10 @@
name: Trigger doc build
on:
push:
branches:
- master
- maintenance
- devel
release:
types:
- released
@@ -12,7 +16,7 @@ jobs:
if: github.repository == 'OctoPrint/OctoPrint'
steps:
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
uses: peter-evans/repository-dispatch@v2
with:
token: ${{ secrets.REPODISPATCH_TOKEN }}
repository: OctoPrint/docs.octoprint.org
-4
View File
@@ -40,7 +40,3 @@ pypy
venv*
testconf*
node_modules
tests/cypress/screenshots
tests/cypress/videos
+2 -2
View File
@@ -48,7 +48,7 @@ repos:
- id: black
additional_dependencies:
- click==8.0.4
- repo: https://gitlab.com/pycqa/flake8
- repo: https://github.com/pycqa/flake8
rev: 3.9.2
hooks:
- id: flake8
@@ -67,10 +67,10 @@ repos:
- id: eslint
additional_dependencies:
- eslint@7.19.0
- eslint-plugin-cypress@2.11.2
files: \.js$
exclude: ^(src/octoprint/vendor/|tests/static/js/lib|tests/util/_files|docs/|scripts/|translations/)
- repo: https://github.com/codespell-project/codespell
rev: v2.1.0
hooks:
- id: codespell
exclude: ^(src/octoprint/vendor/|tests/static/js/lib|tests/util/_files|tests/playwright|scripts/)
+3
View File
@@ -174,6 +174,9 @@ date of first contribution):
* [Arkadiusz Miśkiewicz](https://github.com/arekm)
* ["tempodat"](https://github.com/tempodat)
* [Frederik Kemner](https://github.com/040medien)
* [Moiz Rasheed](https://github.com/msrasheed)
* [Scott Martin](https://github.com/smartin015)
* [Shyam Sunder](https://github.com/sgsunder)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+2 -3
View File
@@ -5,10 +5,9 @@
<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>
<img src="https://img.shields.io/github/actions/workflow/status/OctoPrint/OctoPrint/build.yml?branch=master" alt="Build status"/>
<a href="https://community.octoprint.org"><img src="https://img.shields.io/discourse/users?label=forum&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>
+1 -1
View File
@@ -44,7 +44,7 @@
* [emoji](https://github.com/carpedm20/emoji/): BSD
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
* [filetype](https://h2non.github.io/filetype.py/): MIT
* [Flask](http://flask.pocoo.org/): BSD
* [Flask](https://flask.palletsprojects.com/): BSD
* [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD
* [Flask-Babel](http://github.com/mitsuhiko/flask-babel): BSD
* [Flask-Login](https://github.com/maxcountryman/flask-login): MIT
+52 -2
View File
@@ -172,11 +172,61 @@ octoprint.plugin.backup.additional_excludes
:return: A list of paths to exclude, relative to your plugin's data folder
:rtype: list
Helpers
-------
.. _sec-bundledplugins-backup-hooks-before-backup:
octoprint.plugin.backup.before_backup
+++++++++++++++++++++++++++++++++++++
.. py:function:: before_backup_hook(*args, **kwargs)
.. versionadded:: 1.9.0
Use this to perform actions right before a backup is created.
.. _sec-bundledplugins-backup-hooks-after-backup:
octoprint.plugin.backup.after_backup
++++++++++++++++++++++++++++++++++++
.. py:function:: after_backup_hook(error=False, *args, **kwargs)
.. versionadded:: 1.9.0
Use this to perform actions right after a backup was created or backup creation failed. The ``error`` parameter will be set to ``True`` if
the backup creation failed.
:param error bool: Whether the backup creation failed or not
.. _sec-bundledplugins-backup-hooks-before-restore:
octoprint.plugin.backup.before_restore
++++++++++++++++++++++++++++++++++++++
.. py:function:: before_restore_hook(*args, **kwargs)
.. versionadded:: 1.9.0
Use this to perform actions right before a backup is restored.
.. _sec-bundledplugins-backup-hooks-after-restore:
octoprint.plugin.backup.after_restore
+++++++++++++++++++++++++++++++++++++
.. py:function:: after_restore_hook(error=False, *args, **kwargs)
.. versionadded:: 1.9.0
Use this to perform actions right after a backup was restored or backup restoration failed. The ``error`` parameter will be set to ``True`` if
the backup restoration failed.
:param error bool: Whether the backup restoration failed or not
.. _sec-bundledplugins-backup-helpers:
Helpers
-------
The Backup plugin exports two helpers that can be used by other plugins or internal methods
from within OctoPrint, without going via the API.
+17
View File
@@ -60,6 +60,23 @@
:param string message: The type of message for which to register
:param function handler: The handler function
.. js:function:: OctoPrintClient.socker.removeMessage(message, handler)
Removes the ``handler`` for messages of type ``message``.
.. code-block:: javascript
const handler = (message) => {
// do something with the message object
};
OctoPrint.socket.onMessage("*", handler);
// Use the same reference to the handler function to remove it again
OctoPrint.socket.removeMessage("*", handler);
:param string message: The type of message for which to remove the handler
:param function handler: The handler function
.. js:function:: OctoPrintClient.socket.sendMessage(type, payload)
Sends a message of type ``type`` with the provided ``payload`` to the server.
+3 -8
View File
@@ -473,7 +473,7 @@ Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
OctoPrint injects the template variables that your plugin defines prefixed with ``plugin_<plugin identifier>_`` into
the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple
`Jinja2 Variable <http://jinja.octoprint.org/templates.html#variables>`_ in your plugin's template.
`Jinja2 Variable <https://jinja.palletsprojects.com/templates.html#variables>`_ in your plugin's template.
Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should
still work and point to the URL we defined as default.
@@ -1041,10 +1041,9 @@ might show what's possible with a few lines of code already. Finally, just take
.. seealso::
`Jinja Template Designer Documentation <http://jinja.octoprint.org/templates.html>`_
`Jinja Template Designer Documentation <https://jinja.palletsprojects.com/templates.html>`_
Jinja's Template Designer Documentation describes the syntax and semantics of the template language used
by OctoPrint's frontend. Linked here are the docs for Jinja 2.8.1, which OctoPrint still
relies on for backwards compatibility reasons [#f3]_.
by OctoPrint's frontend.
.. rubric:: Footnotes
@@ -1057,7 +1056,3 @@ might show what's possible with a few lines of code already. Finally, just take
.. [#f2] Refer to the `LESS documentation <http://lesscss.org/#using-less>`_ on how to do that. If you are developing
your plugin under Windows you might also want to give `WinLESS <http://winless.org/>`_ a look which will run
in the background and keep your CSS files up to date with your various project's LESS files automatically.
.. [#f3] Please always consult the Jinja documentation at `jinja.octoprint.org <http://jinja.octoprint.org>`_ instead of
the current stable documentation available at Jinja's project page. The reason for that is that for backwards
compatibility reasons OctoPrint currently sadly has to rely on an older version of Jinja. The documentation
available at `jinja.octoprint.org <http://jinja.octoprint.org>`_ matches that older version.
+4
View File
@@ -1,3 +1,7 @@
[build-system]
requires = ["setuptools>=40.8.0", "wheel"]
build-backend = "setuptools.build_meta"
[tool.black]
line-length = 90
include = '''
+55 -27
View File
@@ -10,14 +10,19 @@
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from distutils.command.build_py import build_py as _build_py
import versioneer # noqa: F401
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
import setuptools # noqa: F401,E402
import octoprint_setuptools # noqa: F401,E402
try:
import octoprint_setuptools # noqa: F401,E402
except ImportError:
octoprint_setuptools = None
import versioneer # noqa: F401
# ----------------------------------------------------------------------------------------
@@ -77,8 +82,12 @@ vendored_deps = [
"regex", # dependency of awesome-slugify
"unidecode", # dependency of awesome-slugify
]
plugin_deps = [
"OctoPrint-Setuptools>=1.0.1", # makes sure plugins can import this on setup.py based install
"wheel", # makes sure plugins can be built as wheels in OctoPrint's venv, see #4682
]
INSTALL_REQUIRES = bundled_plugins + core_deps + vendored_deps
INSTALL_REQUIRES = bundled_plugins + core_deps + vendored_deps + plugin_deps
# Additional requirements for optional install options and/or OS-specific dependencies
EXTRA_REQUIRES = {
@@ -161,28 +170,29 @@ def get_cmdclass():
cmdclass = versioneer.get_cmdclass()
# add clean command
cmdclass.update(
{
"clean": octoprint_setuptools.CleanCommand.for_options(
source_folder="src", eggs=["OctoPrint*.egg-info"]
)
}
)
# add translation commands
translation_dir = "translations"
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(
octoprint_setuptools.get_babel_commandclasses(
pot_file=pot_file,
output_dir=translation_dir,
pack_name_prefix="OctoPrint-i18n-",
pack_path_prefix="",
bundled_dir=bundled_dir,
if octoprint_setuptools:
# add clean command
cmdclass.update(
{
"clean": octoprint_setuptools.CleanCommand.for_options(
source_folder="src", eggs=["OctoPrint*.egg-info"]
)
}
)
# add translation commands
translation_dir = "translations"
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(
octoprint_setuptools.get_babel_commandclasses(
pot_file=pot_file,
output_dir=translation_dir,
pack_name_prefix="OctoPrint-i18n-",
pack_path_prefix="",
bundled_dir=bundled_dir,
)
)
)
cmdclass["build_py"] = copy_files_build_py_factory(
{
@@ -198,6 +208,22 @@ def get_cmdclass():
return cmdclass
def package_data_dirs(source, sub_folders):
dirs = []
for d in sub_folders:
folder = os.path.join(source, d)
if not os.path.exists(folder):
continue
for dirname, _, files in os.walk(folder):
dirname = os.path.relpath(dirname, source)
for f in files:
dirs.append(os.path.join(dirname, f))
return dirs
def params():
# make sure these are always available, even when run by dependabot
global versioneer, get_cmdclass, read_file_contents, here, PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES
@@ -235,6 +261,8 @@ def params():
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
@@ -258,7 +286,7 @@ def params():
"": "src",
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs(
"octoprint": package_data_dirs(
"src/octoprint", ["static", "templates", "plugins", "translations"]
)
+ ["util/piptestballoon/setup.py"]
+73 -1
View File
@@ -264,6 +264,7 @@ def init_logging(
# default logging configuration
if default_config is None:
simple_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"
default_config = {
"version": 1,
"formatters": {
@@ -280,6 +281,13 @@ def init_logging(
},
},
"serial": {"format": "%(asctime)s - %(message)s"},
"tornado": {
"()": "tornado.log.LogFormatter",
"color": False,
"format": simple_format,
"datefmt": date_format,
},
"auth": {"format": "%(asctime)s - %(message)s"},
"timings": {"format": "%(asctime)s - %(message)s"},
"timingscsv": {"format": "%(asctime)s;%(func)s;%(timing)f"},
},
@@ -310,6 +318,24 @@ def init_logging(
),
"delay": True,
},
"tornadoFile": {
"class": "octoprint.logging.handlers.TornadoLogHandler",
"level": "DEBUG",
"formatter": "tornado",
"when": "D",
"backupCount": 1,
"filename": os.path.join(
settings.getBaseFolder("logs"), "tornado.log"
),
},
"authFile": {
"class": "octoprint.logging.handlers.AuthLogHandler",
"level": "DEBUG",
"formatter": "auth",
"when": "D",
"backupCount": 1,
"filename": os.path.join(settings.getBaseFolder("logs"), "auth.log"),
},
"pluginTimingsFile": {
"class": "octoprint.logging.handlers.PluginTimingsLogHandler",
"level": "DEBUG",
@@ -337,12 +363,22 @@ def init_logging(
"handlers": ["serialFile"],
"propagate": False,
},
"AUTH": {
"level": "INFO",
"handlers": ["authFile"],
"propagate": False,
},
"PLUGIN_TIMINGS": {
"level": "INFO",
"handlers": ["pluginTimingsFile", "pluginTimingsCsvFile"],
"propagate": False,
},
"PLUGIN_TIMINGS.octoprint.plugin": {"level": "INFO"},
"tornado.access": {
"level": "INFO",
"handlers": ["tornadoFile"],
"propagate": False,
},
"octoprint": {"level": "INFO"},
"octoprint.util": {"level": "INFO"},
"octoprint.plugins": {"level": "INFO"},
@@ -506,6 +542,42 @@ def init_settings_plugin_config_migration_and_cleanup(plugin_manager):
]
def init_webcam_compat_overlay(settings, plugin_manager):
import logging
import octoprint.webcams
def set_overlay():
default_webcam = octoprint.webcams.get_default_webcam(
settings=settings, plugin_manager=plugin_manager
)
if default_webcam is None:
settings.remove_overlay("webcam_compat")
return
if not default_webcam.config or not default_webcam.config.compat:
settings.remove_overlay("webcam_compat")
return
logging.getLogger(__name__).info(
f"Installing webcam compat overlay for configured default webcam {default_webcam}"
)
overlay = {"webcam": default_webcam.config.compat.dict(by_alias=True)}
settings.add_overlay(
overlay,
key="webcam_compat",
at_end=True,
deprecated="Please use the webcam system introduced with 1.9.0, this compatibility layer will be removed in a future release.",
replace=True,
)
def callback(path, current_value, new_value):
set_overlay()
set_overlay()
settings.add_path_update_callback(["webcam", "defaultWebcam"], callback)
def init_custom_events(plugin_manager):
import logging
@@ -790,7 +862,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
if isinstance(result, list):
return result
def fetch_blacklist_from_url(url, timeout=3, cache=None):
def fetch_blacklist_from_url(url, timeout=3.05, cache=None):
result = []
try:
r = requests.get(url, timeout=timeout)
+15
View File
@@ -1,4 +1,19 @@
import logging
ADMIN_GROUP = "admins"
USER_GROUP = "users"
GUEST_GROUP = "guests"
READONLY_GROUP = "readonly"
def auth_log(message):
logging.getLogger("AUTH").info(message)
login_mechanisms = login_mechanism_lut = {
"http": "credentials",
"autologin": "autologin",
"remember_me": "Remember Me cookie",
"basic_auth": "Basic Authorization header",
"remote_user": "Remote User header",
}
+7 -7
View File
@@ -419,16 +419,16 @@ class Permissions(metaclass=PermissionsMetaClass):
RoleNeed("timelapse_delete"),
default_groups=[USER_GROUP],
)
TIMELAPSE_MANAGE_UNRENDERED = OctoPrintPermission(
"Timelapse Manage Unrendered",
gettext("Allows to list, delete and render unrendered timelapses"),
RoleNeed("timelapse_manage_unrendered"),
default_groups=[USER_GROUP],
)
TIMELAPSE_ADMIN = OctoPrintPermission(
"Timelapse Admin",
gettext(
"Allows to change the timelapse settings and delete or "
'render unrendered timelapses. Includes the "Timelapse List",'
'"Timelapse Delete" and "Timelapse Download" permissions'
),
gettext("Allows to change the timelapse settings."),
RoleNeed("timelapse_admin"),
TIMELAPSE_LIST,
TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP],
)
+2
View File
@@ -53,6 +53,7 @@ def init_platform_for_cli(ctx):
init_custom_events,
init_platform,
init_settings_plugin_config_migration_and_cleanup,
init_webcam_compat_overlay,
)
from octoprint import octoprint_plugin_inject_factory as opif
from octoprint import settings_plugin_inject_factory as spif
@@ -94,6 +95,7 @@ def init_platform_for_cli(ctx):
plugin_manager.initialize_implementations()
init_settings_plugin_config_migration_and_cleanup(plugin_manager)
init_webcam_compat_overlay(settings, plugin_manager)
return components
+20 -6
View File
@@ -259,7 +259,10 @@ class OctoPrintDevelCommands(click.MultiCommand):
)
@click.option("--all", "all_files", is_flag=True, help="Build all less files")
@click.option(
"--list", "list_files", is_flag=True, help="List all available files and exit"
"--list",
"list_files",
is_flag=True,
help="List all available files and exit",
)
def command(files, all_files, list_files):
import shutil
@@ -312,12 +315,24 @@ class OctoPrintDevelCommands(click.MultiCommand):
# Check that lessc is installed
less = shutil.which("lessc")
if not less:
# Check that less-plugin-clean-css is installed
if less:
_, _, stderr = self.command_caller.call(
[less, "--clean-css"], logged=False
)
clean_css = not any(
map(lambda x: "Unable to load plugin clean-css" in x, stderr)
)
else:
clean_css = False
if not less or not clean_css:
click.echo(
"lessc is not installed/not available, please install it first"
"lessc or less-plugin-clean-css is not installed/not available, please install it first"
)
click.echo(
"Try `npm i -g less` to install it (NOT lessc in this command!)"
"Try `npm i -g less less-plugin-clean-css` to install both (note that it does NOT say 'lessc' in this command!)"
)
sys.exit(1)
@@ -327,10 +342,9 @@ class OctoPrintDevelCommands(click.MultiCommand):
sys.exit(1)
# Build command line, with necessary options
# TODO -x is deprecated, find replacement?
less_command = [
less,
"-x",
"--clean-css=--s1 --advanced --compatibility=ie8",
available_files[less_file]["source"],
available_files[less_file]["output"],
]
+1
View File
@@ -92,6 +92,7 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None
for log in (
"octoprint.log",
"serial.log",
"tornado.log",
):
logpath = os.path.join(logbase, log)
if os.path.exists(logpath):
+1
View File
@@ -36,6 +36,7 @@ class Events:
CONNECTED = "Connected"
DISCONNECTING = "Disconnecting"
DISCONNECTED = "Disconnected"
CONNECTIONS_AUTOREFRESHED = "ConnectionsAutorefreshed"
# State changes
PRINTER_STATE_CHANGED = "PrinterStateChanged"
+8 -5
View File
@@ -181,19 +181,19 @@ def get_content_type_mapping_for_extension(extension, subtree=None):
return None
def valid_extension(extension, type=None):
def valid_extension(extension, type=None, tree=None):
if not type:
return extension in get_all_extensions()
return extension in get_all_extensions(subtree=tree)
else:
extensions = get_extensions(type)
extensions = get_extensions(type, subtree=tree)
if extensions:
return extension in extensions
def valid_file_type(filename, type=None):
def valid_file_type(filename, type=None, tree=None):
_, extension = os.path.splitext(filename)
extension = extension[1:].lower()
return valid_extension(extension, type=type)
return valid_extension(extension, type=type, tree=tree)
def get_file_type(filename):
@@ -749,6 +749,7 @@ class FileManager:
"path": path_in_storage,
"name": name,
"type": get_file_type(name),
"operation": "add",
},
)
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
@@ -786,6 +787,7 @@ class FileManager:
"path": path_in_storage,
"name": name,
"type": get_file_type(name),
"operation": "copy",
},
)
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
@@ -820,6 +822,7 @@ class FileManager:
"path": dst_path_in_storage,
"name": dst_name,
"type": get_file_type(dst_name),
"operation": "move",
},
)
eventManager().fire(
+8
View File
@@ -137,6 +137,14 @@ class PluginTimingsLogHandler(TriggeredRolloverLogHandler):
pass
class TornadoLogHandler(CleaningTimedRotatingFileHandler):
pass
class AuthLogHandler(CleaningTimedRotatingFileHandler):
pass
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, *args, **kwargs):
super().__init__(*args, **kwargs)
+5 -3
View File
@@ -212,6 +212,7 @@ def call_plugin(
error_callback=None,
sorting_context=None,
initialized=True,
manager=None,
):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
@@ -249,6 +250,7 @@ def call_plugin(
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
initialized (boolean): Ignored.
manager (PluginManager or None): The plugin manager to use. If not provided, the global plugin manager
"""
if not isinstance(types, (list, tuple)):
@@ -257,12 +259,12 @@ def call_plugin(
args = []
if kwargs is None:
kwargs = {}
if manager is None:
manager = plugin_manager()
logger = logging.getLogger(__name__)
plugins = plugin_manager().get_implementations(
*types, sorting_context=sorting_context
)
plugins = manager.get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
if not hasattr(plugin, "_identifier"):
continue
+38 -11
View File
@@ -600,7 +600,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
OctoPrint will query whether your mixin implementation will handle a
provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask
`Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object as
`Request <https://flask.palletsprojects.com/api/#flask.Request>`_ object as
parameter. If you plugin returns `True` here, OctoPrint will next call
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like
- again - the Flask Request object and the render keyword arguments as
@@ -676,7 +676,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
``UiPlugin.will_handle_ui``.
Arguments:
request (flask.Request): A Flask `Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_
request (flask.Request): A Flask `Request <https://flask.palletsprojects.com/api/#flask.Request>`_
object.
Returns:
@@ -761,12 +761,12 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
now (datetime.datetime): The datetime instance representing "now"
for this request, in case your plugin implementation needs this
information.
request (flask.Request): A Flask `Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object.
request (flask.Request): A Flask `Request <https://flask.palletsprojects.com/api/#flask.Request>`_ object.
render_kwargs (dict): The (cached) render keyword arguments that
would usually be provided to the core UI render function.
Returns:
flask.Response: Should return a Flask `Response <http://flask.pocoo.org/docs/0.10/api/#flask.Response>`_
flask.Response: Should return a Flask `Response <https://flask.palletsprojects.com/api/#flask.Response>`_
object that can be served to the requesting client directly. May be
created with ``flask.make_response`` combined with something like
``flask.render_template``.
@@ -1173,7 +1173,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
"""
Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one
resource accepting JSON commands POSTed to it. This is the easy alternative for plugin's which don't need the
full power of a `Flask Blueprint <http://flask.pocoo.org/docs/0.10/blueprints/>`_ that the :class:`BlueprintPlugin`
full power of a `Flask Blueprint <https://flask.palletsprojects.com/blueprints/>`_ that the :class:`BlueprintPlugin`
mixin offers.
Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend
@@ -1298,7 +1298,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
def on_api_get(self, request):
"""
Called by OctoPrint upon a GET request to ``/api/plugin/<plugin identifier>``. ``request`` will contain the
received `Flask request object <http://flask.pocoo.org/docs/0.9/api/#flask.Request>`_ which you may evaluate
received `Flask request object <https://flask.palletsprojects.com/api/#flask.Request>`_ which you may evaluate
for additional arguments supplied with the request.
If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content``
@@ -1317,7 +1317,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose,
be it a more sophisticated API than what is possible via the :class:`SimpleApiPlugin` or a custom web frontend.
The mechanism at work here is `Flask's <http://flask.pocoo.org/>`_ own `Blueprint mechanism <http://flask.pocoo.org/docs/0.10/blueprints/>`_.
The mechanism at work here is `Flask's <https://flask.palletsprojects.com/>`_ own `Blueprint mechanism <https://flask.palletsprojects.com/blueprints/>`_.
The mixin automatically creates a blueprint for you that will be registered under ``/plugin/<plugin identifier>/``.
All you need to do is decorate all of your view functions with the :func:`route` decorator,
@@ -1389,8 +1389,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
A decorator to mark view methods in your BlueprintPlugin subclass. Works just the same as Flask's
own ``route`` decorator available on blueprints.
See `the documentation for flask.Blueprint.route <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.route>`_
and `the documentation for flask.Flask.route <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.route>`_ for more
See `the documentation for flask.Blueprint.route <https://flask.palletsprojects.com/api/#flask.Blueprint.route>`_
and `the documentation for flask.Flask.route <https://flask.palletsprojects.com/api/#flask.Flask.route>`_ for more
information.
"""
@@ -1413,8 +1413,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's
own ``errorhandler`` decorator available on blueprints.
See `the documentation for flask.Blueprint.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.errorhandler>`_
and `the documentation for flask.Flask.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.errorhandler>`_ for more
See `the documentation for flask.Blueprint.errorhandler <https://flask.palletsprojects.com/api/#flask.Blueprint.errorhandler>`_
and `the documentation for flask.Flask.errorhandler <https://flask.palletsprojects.com/api/#flask.Flask.errorhandler>`_ for more
information.
.. versionadded:: 1.3.0
@@ -2319,3 +2319,30 @@ class ProgressPlugin(OctoPrintPlugin):
:param int progress: Current progress as a value between 0 and 100
"""
pass
class WebcamProviderPlugin(OctoPrintPlugin):
"""
The ``WebcamProviderPlugin`` can be used to provide one or more webcams visible on the frontend and used for snapshots/timelapses.
"""
def get_webcam_configurations(self):
"""
Used to retrieve a list of available webcams
Returns:
A list of :class:`~octoprint.schema.webcam.Webcam`: The available webcams, can be empty if none available.
"""
return []
def take_webcam_snapshot(self, webcamName):
"""
Used to take a JPEG snapshot of the webcam. This method may raise an exception, you can expect failures to be handled.
:param string webcamName: The name of the webcam to take a snapshot of as given by the configurations
Returns:
An iterator over bytes of the JPEG image
"""
raise NotImplementedError()
@@ -29,7 +29,7 @@ $(function () {
};
self.fromResponse = function (data) {
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
if (data && data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
self.text(data.text);
self.buttons(data.choices);
self.showPrompt();
@@ -437,7 +437,7 @@ class AnnouncementPlugin(
if data is None:
# cache not allowed or empty, fetch from network
if self._connectivity_checker.online:
if self._connectivity_checker.check_immediately():
data = self._get_channel_data_from_network(key, config)
else:
self._logger.info(
@@ -488,7 +488,7 @@ class AnnouncementPlugin(
url = config["url"]
try:
start = time.monotonic()
r = requests.get(url, timeout=30)
r = requests.get(url, timeout=3.05)
r.raise_for_status()
self._logger.info(
"Loaded channel {} from {} in {:.2}s".format(
@@ -1 +1 @@
table th.settings_plugin_announcements_channels_name,table td.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_announcements_channels_actions,table td.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table th.settings_plugin_announcements_channels_actions a,table td.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table th.settings_plugin_announcements_channels_actions a.disabled,table td.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:bold}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:black}#plugin_announcements_dialog .modal-footer .configurelink{float:left}
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}#plugin_announcements_dialog .modal-footer .configurelink{float:left}
@@ -1 +1 @@
#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a{color:black}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type="checkbox"],#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type="checkbox"]{margin-top:0}#plugin_appkeys_keygenerated .control-text{display:inline-block}
#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}#plugin_appkeys_keygenerated .control-text{display:inline-block}
@@ -1 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}#auth-choice,#auth-done,#auth-error,#auth-offline{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05);text-align:center}.form-auth-heading{margin-bottom:10px}
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}#auth-choice,#auth-done,#auth-error,#auth-offline{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05);text-align:center}.form-auth-heading{margin-bottom:10px}
+440 -356
View File
@@ -63,10 +63,8 @@ class BackupPlugin(
_pip_caller = None
# noinspection PyMissingConstructor
def __init__(self):
self._in_progress = []
self._in_progress_lock = threading.RLock()
_backup_in_progress = threading.Lock()
_restore_in_progress = threading.Lock()
# Additional permissions hook
@@ -134,7 +132,7 @@ class BackupPlugin(
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(
backups=backups,
backup_in_progress=len(self._in_progress) > 0,
backup_in_progress=self._backup_in_progress.locked(),
unknown_plugins=unknown_plugins,
restore_supported=self._restore_supported(self._settings),
max_upload_size=MAX_UPLOAD_SIZE,
@@ -509,22 +507,25 @@ class BackupPlugin(
if path is not None:
datafolder, filename = os.path.split(os.path.abspath(path))
else:
filename = self._build_backup_filename(settings=settings)
filename = None
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
click.echo(f"Creating backup at {filename}, please wait...")
self._create_backup(
filename,
def on_backup_start(name, temporary_path, exclude):
click.echo(f"Creating backup at {name}, please wait...")
path = self._create_backup(
name=filename,
exclude=exclude,
settings=settings,
plugin_manager=cli_group.plugin_manager,
datafolder=datafolder,
on_backup_start=on_backup_start,
)
click.echo("Done.")
click.echo(f"Backup located at {os.path.join(datafolder, filename)}")
click.echo(f"Backup located at {path}")
@click.command("restore")
@click.argument("path")
@@ -662,25 +663,16 @@ class BackupPlugin(
##~~ helpers
def _start_backup(self, exclude, filename=None):
if filename is None:
filename = self._build_backup_filename(settings=self._settings)
def on_backup_start(name, temporary_path, exclude):
self._logger.info(
"Creating backup zip at {} (excluded: {})...".format(
temporary_path, ",".join(exclude) if len(exclude) else "-"
)
)
with self._in_progress_lock:
self._in_progress.append(name)
self._send_client_message("backup_started", payload={"name": name})
self._send_client_message("backup_started", payload={"name": name})
def on_backup_done(name, final_path, exclude):
with self._in_progress_lock:
self._in_progress.remove(name)
self._send_client_message("backup_done", payload={"name": name})
self._send_client_message("backup_done", payload={"name": name})
self._logger.info("... done creating backup zip.")
self._event_bus.fire(
@@ -689,13 +681,6 @@ class BackupPlugin(
)
def on_backup_error(name, exc_info):
with self._in_progress_lock:
try:
self._in_progress.remove(name)
except ValueError:
# we'll ignore that
pass
self._send_client_message(
"backup_error", payload={"name": name, "error": f"{exc_info[1]}"}
)
@@ -703,8 +688,8 @@ class BackupPlugin(
thread = threading.Thread(
target=self._create_backup,
args=(filename,),
kwargs={
"name": filename,
"exclude": exclude,
"settings": self._settings,
"plugin_manager": self._plugin_manager,
@@ -855,7 +840,7 @@ class BackupPlugin(
logger = logging.getLogger(__name__)
try:
r = requests.get(url, timeout=30)
r = requests.get(url, timeout=3.05)
r.raise_for_status()
except Exception:
logger.exception(
@@ -917,7 +902,7 @@ class BackupPlugin(
@classmethod
def _create_backup(
cls,
name,
name=None,
exclude=None,
settings=None,
plugin_manager=None,
@@ -936,169 +921,207 @@ class BackupPlugin(
"watched",
)
try:
if exclude is None:
exclude = []
if not isinstance(exclude, list):
exclude = list(exclude)
with cls._backup_in_progress:
if "timelapse" in exclude:
exclude.append("timelapse_tmp")
if name is None:
name = cls._build_backup_filename(settings)
current_excludes = list(exclude)
additional_excludes = list()
plugin_data = settings.global_get_basefolder("data")
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.additional_excludes"
).items():
try:
additional = hook(current_excludes)
if isinstance(additional, list):
if "." in additional:
current_excludes.append(os.path.join("data", plugin))
additional_excludes.append(os.path.join(plugin_data, plugin))
else:
current_excludes += map(
lambda x: os.path.join("data", plugin, x), additional
)
additional_excludes += map(
lambda x: os.path.join(plugin_data, plugin, x), additional
)
except Exception:
logger.exception(
f"Error while retrieving additional excludes "
f"from plugin {name}",
extra={"plugin": plugin},
)
try:
if exclude is None:
exclude = []
if not isinstance(exclude, list):
exclude = list(exclude)
configfile = settings._configfile
basedir = settings._basedir
if "timelapse" in exclude:
exclude.append("timelapse_tmp")
temporary_path = os.path.join(datafolder, f".{name}")
final_path = os.path.join(datafolder, name)
current_excludes = list(exclude)
additional_excludes = list()
plugin_data = settings.global_get_basefolder("data")
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.additional_excludes"
).items():
try:
additional = hook(current_excludes)
if isinstance(additional, list):
if "." in additional:
current_excludes.append(os.path.join("data", plugin))
additional_excludes.append(
os.path.join(plugin_data, plugin)
)
else:
current_excludes += map(
lambda x: os.path.join("data", plugin, x), additional
)
additional_excludes += map(
lambda x: os.path.join(plugin_data, plugin, x),
additional,
)
except Exception:
logger.exception(
f"Error while retrieving additional excludes "
f"from plugin {plugin}",
extra={"plugin": plugin},
)
own_folder = datafolder
defaults = [os.path.join(basedir, "config.yaml"),] + [
os.path.join(basedir, folder)
for folder in default_settings["folder"].keys()
]
configfile = settings._configfile
basedir = settings._basedir
# check how many bytes we are about to backup
size = os.stat(configfile).st_size
for folder in default_settings["folder"].keys():
if folder in exclude or folder in exclude_by_default:
continue
size += cls._get_disk_size(
settings.global_get_basefolder(folder),
ignored=[
own_folder,
],
)
size += cls._get_disk_size(
basedir,
ignored=defaults
+ [
own_folder,
],
)
temporary_path = os.path.join(datafolder, f".{name}")
final_path = os.path.join(datafolder, name)
# since we can't know the compression ratio beforehand, we assume we need the same amount of space
if not cls._free_space(os.path.dirname(temporary_path), size):
raise InsufficientSpace()
own_folder = datafolder
defaults = [os.path.join(basedir, "config.yaml"),] + [
os.path.join(basedir, folder)
for folder in default_settings["folder"].keys()
]
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
if callable(on_backup_start):
on_backup_start(name, temporary_path, exclude)
with zipfile.ZipFile(
temporary_path, mode="w", compression=compression, allowZip64=True
) as zip:
def add_to_zip(source, target, ignored=None):
if ignored is None:
ignored = []
if source in ignored:
return
if os.path.isdir(source):
for entry in os.scandir(source):
add_to_zip(
entry.path,
os.path.join(target, entry.name),
ignored=ignored,
)
elif os.path.isfile(source):
zip.write(source, arcname=target)
# add metadata
metadata = {
"version": get_octoprint_version_string(),
"excludes": exclude,
}
zip.writestr("metadata.json", json.dumps(metadata))
# backup current config file
add_to_zip(
configfile,
"basedir/config.yaml",
ignored=[
own_folder,
],
)
# backup configured folder paths
# check how many bytes we are about to backup
size = os.stat(configfile).st_size
for folder in default_settings["folder"].keys():
if folder in exclude or folder in exclude_by_default:
continue
add_to_zip(
size += cls._get_disk_size(
settings.global_get_basefolder(folder),
"basedir/" + folder.replace("_", "/"),
ignored=[
own_folder,
]
+ additional_excludes,
],
)
# backup anything else that might be lying around in our basedir
add_to_zip(
size += cls._get_disk_size(
basedir,
"basedir",
ignored=defaults
+ [
own_folder,
]
+ additional_excludes,
],
)
# add list of installed plugins
helpers = plugin_manager.get_helpers(
"pluginmanager", "generate_plugins_json"
)
if helpers and "generate_plugins_json" in helpers:
plugins = helpers["generate_plugins_json"](
settings=settings, plugin_manager=plugin_manager
)
# since we can't know the compression ratio beforehand, we assume we need the same amount of space
if not cls._free_space(os.path.dirname(temporary_path), size):
raise InsufficientSpace()
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
shutil.move(temporary_path, final_path)
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
except Exception as exc: # noqa: F841
# TODO py3: use the exception, not sys.exc_info()
if callable(on_backup_error):
exc_info = sys.exc_info()
backup_error = False
try:
on_backup_error(name, exc_info)
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.before_backup"
).items():
try:
hook()
except Exception:
logger.exception(
f"Error while running before_backup hook from plugin {plugin}",
extra={"plugin": plugin},
)
if callable(on_backup_start):
on_backup_start(name, temporary_path, exclude)
with zipfile.ZipFile(
temporary_path, mode="w", compression=compression, allowZip64=True
) as zip:
def add_to_zip(source, target, ignored=None):
if ignored is None:
ignored = []
if source in ignored:
return
if os.path.isdir(source):
for entry in os.scandir(source):
add_to_zip(
entry.path,
os.path.join(target, entry.name),
ignored=ignored,
)
elif os.path.isfile(source):
zip.write(source, arcname=target)
# add metadata
metadata = {
"version": get_octoprint_version_string(),
"excludes": exclude,
}
zip.writestr("metadata.json", json.dumps(metadata))
# backup current config file
add_to_zip(
configfile,
"basedir/config.yaml",
ignored=[
own_folder,
],
)
# backup configured folder paths
for folder in default_settings["folder"].keys():
if folder in exclude or folder in exclude_by_default:
continue
add_to_zip(
settings.global_get_basefolder(folder),
"basedir/" + folder.replace("_", "/"),
ignored=[
own_folder,
]
+ additional_excludes,
)
# backup anything else that might be lying around in our basedir
add_to_zip(
basedir,
"basedir",
ignored=defaults
+ [
own_folder,
]
+ additional_excludes,
)
# add list of installed plugins
helpers = plugin_manager.get_helpers(
"pluginmanager", "generate_plugins_json"
)
if helpers and "generate_plugins_json" in helpers:
plugins = helpers["generate_plugins_json"](
settings=settings, plugin_manager=plugin_manager
)
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
shutil.move(temporary_path, final_path)
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
return final_path
except Exception:
backup_error = True
raise
finally:
del exc_info
raise
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.after_backup"
).items():
try:
hook(error=backup_error)
except Exception:
logger.exception(
f"Error while running after_backup hook from plugin {plugin}",
extra={"plugin": plugin},
)
except Exception as exc: # noqa: F841
# TODO py3: use the exception, not sys.exc_info()
if callable(on_backup_error):
exc_info = sys.exc_info()
try:
on_backup_error(name, exc_info)
finally:
del exc_info
raise
@classmethod
def _restore_backup(
@@ -1123,6 +1146,8 @@ class BackupPlugin(
on_restore_failed(path)
return False
logger = logging.getLogger(__name__)
restart_command = settings.global_get(
["server", "commands", "serverRestartCommand"]
)
@@ -1136,234 +1161,293 @@ class BackupPlugin(
plugin_repo = cls._get_plugin_repository_data(repo_url)
if callable(on_restore_start):
on_restore_start(path)
try:
with zipfile.ZipFile(path, "r") as zip:
# read metadata
try:
metadata_zipinfo = zip.getinfo("metadata.json")
except KeyError:
if callable(on_invalid_backup):
on_invalid_backup("Not an OctoPrint backup, lacks metadata.json")
if callable(on_restore_failed):
on_restore_failed(path)
return False
metadata_bytes = zip.read(metadata_zipinfo)
metadata = json.loads(metadata_bytes)
backup_version = get_comparable_version(metadata["version"], cut=1)
if backup_version > get_octoprint_version(cut=1):
if callable(on_invalid_backup):
on_invalid_backup(
"Backup is from a newer version of OctoPrint and cannot be applied"
with cls._restore_in_progress:
restore_error = False
try:
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.before_restore"
).items():
try:
hook()
except Exception:
logger.exception(
f"Error while running before_restore hook from plugin {plugin}",
extra={"plugin": plugin},
)
if callable(on_restore_failed):
on_restore_failed(path)
return False
# unzip to temporary folder
temp = tempfile.mkdtemp()
if callable(on_restore_start):
on_restore_start(path)
try:
if callable(on_log_progress):
on_log_progress(f"Unpacking backup to {temp}...")
abstemp = os.path.abspath(temp)
dirs = {}
for member in zip.infolist():
abspath = os.path.abspath(os.path.join(temp, member.filename))
if abspath.startswith(abstemp):
date_time = time.mktime(member.date_time + (0, 0, -1))
with zipfile.ZipFile(path, "r") as zip:
# read metadata
try:
metadata_zipinfo = zip.getinfo("metadata.json")
except KeyError:
if callable(on_invalid_backup):
on_invalid_backup(
"Not an OctoPrint backup, lacks metadata.json"
)
if callable(on_restore_failed):
on_restore_failed(path)
return False
zip.extract(member, temp)
metadata_bytes = zip.read(metadata_zipinfo)
metadata = json.loads(metadata_bytes)
if os.path.isdir(abspath):
dirs[abspath] = date_time
else:
backup_version = get_comparable_version(
metadata["version"], cut=1
)
if backup_version > get_octoprint_version(cut=1):
if callable(on_invalid_backup):
on_invalid_backup(
"Backup is from a newer version of OctoPrint and cannot be applied"
)
if callable(on_restore_failed):
on_restore_failed(path)
return False
# unzip to temporary folder
temp = tempfile.mkdtemp()
try:
if callable(on_log_progress):
on_log_progress(f"Unpacking backup to {temp}...")
abstemp = os.path.abspath(temp)
dirs = {}
for member in zip.infolist():
abspath = os.path.abspath(
os.path.join(temp, member.filename)
)
if abspath.startswith(abstemp):
date_time = time.mktime(member.date_time + (0, 0, -1))
zip.extract(member, temp)
if os.path.isdir(abspath):
dirs[abspath] = date_time
else:
os.utime(abspath, (date_time, date_time))
# set time on folders
for abspath, date_time in dirs.items():
os.utime(abspath, (date_time, date_time))
# set time on folders
for abspath, date_time in dirs.items():
os.utime(abspath, (date_time, date_time))
# sanity check
configfile = os.path.join(temp, "basedir", "config.yaml")
if not os.path.exists(configfile):
if callable(on_invalid_backup):
on_invalid_backup("Backup lacks config.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
# sanity check
configfile = os.path.join(temp, "basedir", "config.yaml")
if not os.path.exists(configfile):
if callable(on_invalid_backup):
on_invalid_backup("Backup lacks config.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
configdata = yaml.load_from_file(path=configfile)
configdata = yaml.load_from_file(path=configfile)
userfile = os.path.join(temp, "basedir", "users.yaml")
if not os.path.exists(userfile):
if callable(on_invalid_backup):
on_invalid_backup("Backup lacks users.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
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")
if callable(on_log_progress):
on_log_progress("Unpacked")
# install available plugins
plugins = []
plugin_list_file = os.path.join(temp, "plugin_list.json")
if os.path.exists(plugin_list_file):
with open(
os.path.join(temp, "plugin_list.json"), "rb"
) as f:
plugins = json.load(f)
# install available plugins
plugins = []
plugin_list_file = os.path.join(temp, "plugin_list.json")
if os.path.exists(plugin_list_file):
with open(os.path.join(temp, "plugin_list.json"), "rb") as f:
plugins = json.load(f)
known_plugins = []
unknown_plugins = []
if plugins:
if plugin_repo:
for plugin in plugins:
if plugin["key"] in plugin_manager.plugins:
# already installed
continue
known_plugins = []
unknown_plugins = []
if plugins:
if plugin_repo:
for plugin in plugins:
if plugin["key"] in plugin_manager.plugins:
# already installed
continue
if plugin["key"] in plugin_repo:
# not installed, can be installed from repository url
known_plugins.append(
plugin_repo[plugin["key"]]
)
else:
# not installed, not installable
unknown_plugins.append(plugin)
if plugin["key"] in plugin_repo:
# not installed, can be installed from repository url
known_plugins.append(plugin_repo[plugin["key"]])
else:
# not installed, not installable
unknown_plugins.append(plugin)
# no repo, all plugins are not installable
unknown_plugins = plugins
else:
# no repo, all plugins are not installable
unknown_plugins = plugins
if callable(on_log_progress):
if known_plugins:
on_log_progress(
"Known and installable plugins: {}".format(
", ".join(map(lambda x: x["id"], known_plugins))
)
)
if unknown_plugins:
on_log_progress(
"Unknown plugins: {}".format(
", ".join(
map(lambda x: x["key"], unknown_plugins)
if callable(on_log_progress):
if known_plugins:
on_log_progress(
"Known and installable plugins: {}".format(
", ".join(
map(lambda x: x["id"], known_plugins)
)
)
)
)
if unknown_plugins:
on_log_progress(
"Unknown plugins: {}".format(
", ".join(
map(
lambda x: x["key"],
unknown_plugins,
)
)
)
)
if callable(on_install_plugins):
on_install_plugins(known_plugins)
if callable(on_report_unknown_plugins):
on_report_unknown_plugins(unknown_plugins)
# move config data
basedir_backup = basedir + ".bck"
basedir_extracted = os.path.join(temp, "basedir")
if callable(on_log_progress):
on_log_progress(
f"Renaming {basedir} to {basedir_backup}..."
)
shutil.move(basedir, basedir_backup)
if callable(on_install_plugins):
on_install_plugins(known_plugins)
try:
if callable(on_log_progress):
on_log_progress(
f"Moving {basedir_extracted} to {basedir}..."
)
shutil.move(basedir_extracted, basedir)
except Exception:
if callable(on_log_error):
on_log_error(
"Error while restoring config data",
exc_info=sys.exc_info(),
)
on_log_error("Rolling back old config data")
if callable(on_report_unknown_plugins):
on_report_unknown_plugins(unknown_plugins)
shutil.move(basedir_backup, basedir)
# move config data
basedir_backup = basedir + ".bck"
basedir_extracted = os.path.join(temp, "basedir")
if callable(on_restore_failed):
on_restore_failed(path)
return False
if callable(on_log_progress):
on_log_progress(f"Renaming {basedir} to {basedir_backup}...")
shutil.move(basedir, basedir_backup)
if unknown_plugins:
if callable(on_log_progress):
on_log_progress(
"Writing info file about unknown plugins"
)
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
unknown_plugins_path = os.path.join(
datafolder, UNKNOWN_PLUGINS_FILE
)
try:
with open(unknown_plugins_path, mode="wb") as f:
f.write(to_bytes(json.dumps(unknown_plugins)))
except Exception:
if callable(on_log_error):
on_log_error(
"Could not persist list of unknown plugins to {}".format(
unknown_plugins_path
),
exc_info=sys.exc_info(),
)
finally:
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.before_restore"
).items():
try:
hook(error=restore_error)
except Exception:
logger.exception(
f"Error while running after_restore hook from plugin {plugin}",
extra={"plugin": plugin},
)
if callable(on_log_progress):
on_log_progress("Removing temporary unpacked folder")
shutil.rmtree(temp)
except Exception:
restore_error = True
exc_info = sys.exc_info()
try:
if callable(on_log_progress):
on_log_progress(f"Moving {basedir_extracted} to {basedir}...")
shutil.move(basedir_extracted, basedir)
except Exception:
if callable(on_log_error):
on_log_error(
"Error while restoring config data",
exc_info=sys.exc_info(),
)
on_log_error("Rolling back old config data")
shutil.move(basedir_backup, basedir)
on_log_error("Error while running restore", exc_info=exc_info)
if callable(on_restore_failed):
on_restore_failed(path)
return False
if unknown_plugins:
if callable(on_log_progress):
on_log_progress("Writing info file about unknown plugins")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
unknown_plugins_path = os.path.join(
datafolder, UNKNOWN_PLUGINS_FILE
)
try:
with open(unknown_plugins_path, mode="wb") as f:
f.write(to_bytes(json.dumps(unknown_plugins)))
except Exception:
if callable(on_log_error):
on_log_error(
"Could not persist list of unknown plugins to {}".format(
unknown_plugins_path
),
exc_info=sys.exc_info(),
)
finally:
del exc_info
return False
finally:
# remove zip
if callable(on_log_progress):
on_log_progress("Removing temporary unpacked folder")
shutil.rmtree(temp)
on_log_progress("Removing temporary zip")
os.remove(path)
except Exception:
exc_info = sys.exc_info()
try:
if callable(on_log_error):
on_log_error("Error while running restore", exc_info=exc_info)
if callable(on_restore_failed):
on_restore_failed(path)
finally:
del exc_info
return False
for plugin, hook in plugin_manager.get_hooks(
"octoprint.plugin.backup.after_restore"
).items():
try:
hook(error=restore_error)
except Exception:
logger.exception(
f"Error while running after_restore hook from plugin {plugin}",
extra={"plugin": plugin},
)
finally:
# remove zip
if callable(on_log_progress):
on_log_progress("Removing temporary zip")
os.remove(path)
# restart server
if not restart_command:
restart_command = (
configdata.get("server", {})
.get("commands", {})
.get("serverRestartCommand")
)
# restart server
if not restart_command:
restart_command = (
configdata.get("server", {})
.get("commands", {})
.get("serverRestartCommand")
)
if restart_command:
import sarge
if restart_command:
import sarge
if callable(on_log_progress):
on_log_progress("Restarting...")
if callable(on_restore_done):
on_restore_done(path)
if callable(on_log_progress):
on_log_progress("Restarting...")
if callable(on_restore_done):
on_restore_done(path)
try:
sarge.run(restart_command, close_fds=True, async_=True)
except Exception:
if callable(on_log_error):
on_log_error(
f"Error while restarting via command {restart_command}",
exc_info=sys.exc_info(),
)
on_log_error("Please restart OctoPrint manually")
return False
try:
sarge.run(restart_command, close_fds=True, async_=True)
except Exception:
else:
if callable(on_restore_done):
on_restore_done(path)
if callable(on_log_error):
on_log_error(
f"Error while restarting via command {restart_command}",
exc_info=sys.exc_info(),
"No restart command configured. Please restart OctoPrint manually."
)
on_log_error("Please restart OctoPrint manually")
return False
else:
if callable(on_restore_done):
on_restore_done(path)
if callable(on_log_error):
on_log_error(
"No restart command configured. Please restart OctoPrint manually."
)
return True
@@ -1 +1 @@
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:black}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type="checkbox"]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:bold}#settings_plugin_backup_restoredialog_output .error{font-weight:bold;color:#990000}#settings_plugin_backup_restoredialog_output .stdout{color:#333333}#settings_plugin_backup_restoredialog_output .stderr{color:#990000}#settings_plugin_backup_restoredialog_output .call{color:#000099}
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009}
@@ -0,0 +1,248 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
import threading
import requests
from flask_babel import gettext
import octoprint.plugin
from octoprint.schema.webcam import RatioEnum, Webcam, WebcamCompatibility
from octoprint.webcams import WebcamNotAbleToTakeSnapshotException
class ClassicWebcamPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.WebcamProviderPlugin,
octoprint.plugin.WizardPlugin,
):
def __init__(self):
self._capture_mutex = threading.Lock()
self._webcam_name = "classic"
# ~~ TemplatePlugin API
def get_assets(self):
return {
"js": [
"js/classicwebcam.js",
"js/classicwebcam_settings.js",
"js/classicwebcam_wizard.js",
],
"less": ["less/classicwebcam.less"],
"css": ["css/classicwebcam.css"],
}
def get_template_configs(self):
return [
{
"type": "settings",
"template": "classicwebcam_settings.jinja2",
"custom_bindings": True,
},
{
"type": "webcam",
"name": "Classic Webcam",
"template": "classicwebcam_webcam.jinja2",
"custom_bindings": True,
"suffix": "_real",
},
{
"type": "wizard",
"name": "Classic Webcam Wizard",
"template": "classicwebcam_wizard.jinja2",
"suffix": "_wizard",
},
]
# ~~ WebcamProviderPlugin API
def get_webcam_configurations(self):
streamRatio = self._settings.get(["streamRatio"])
if streamRatio == "4:3":
streamRatio = RatioEnum.four_three
else:
streamRatio = RatioEnum.sixteen_nine
webRtcServers = self._settings.get(["streamWebrtcIceServers"])
cacheBuster = self._settings.get_boolean(["cacheBuster"])
stream = self._get_stream_url()
snapshot = self._get_snapshot_url()
flipH = self._settings.get_boolean(["flipH"])
flipV = self._settings.get_boolean(["flipV"])
rotate90 = self._settings.get_boolean(["rotate90"])
snapshotSslValidation = self._settings.get_boolean(["snapshotSslValidation"])
try:
streamTimeout = int(self._settings.get(["streamTimeout"]))
except Exception:
streamTimeout = 5
try:
snapshotTimeout = int(self._settings.get(["snapshotTimeout"]))
except Exception:
snapshotTimeout = 5
return [
Webcam(
name=self._webcam_name,
displayName="Classic Webcam",
flipH=flipH,
flipV=flipV,
rotate90=rotate90,
snapshotDisplay=snapshot,
canSnapshot=self._can_snapshot(),
compat=WebcamCompatibility(
stream=stream,
streamTimeout=streamTimeout,
streamRatio=streamRatio,
cacheBuster=cacheBuster,
streamWebrtcIceServers=webRtcServers,
snapshot=snapshot,
snapshotTimeout=snapshotTimeout,
snapshotSslValidation=snapshotSslValidation,
),
extras=dict(
stream=stream,
streamTimeout=streamTimeout,
streamRatio=streamRatio,
streamWebrtcIceServers=webRtcServers,
cacheBuster=cacheBuster,
),
),
]
def _get_snapshot_url(self):
return self._settings.get(["snapshot"])
def _get_stream_url(self):
return self._settings.get(["stream"])
def _can_snapshot(self):
snapshot = self._get_snapshot_url()
return snapshot is not None and snapshot.strip() != ""
def take_webcam_snapshot(self, _):
snapshot_url = self._get_snapshot_url()
if not self._can_snapshot():
raise WebcamNotAbleToTakeSnapshotException(self._webcam_name)
with self._capture_mutex:
self._logger.debug(f"Capturing image from {snapshot_url}")
r = requests.get(
snapshot_url,
stream=True,
timeout=self._settings.get_int(["snapshotTimeout"]),
verify=self._settings.get_boolean(["rosnapshotSslValidationtate90"]),
)
r.raise_for_status()
return r.iter_content(chunk_size=1024)
# ~~ SettingsPlugin API
def get_settings_defaults(self):
return dict(
flipH=False,
flipV=False,
rotate90=False,
stream="",
streamTimeout=5,
streamRatio="16:9",
streamWebrtcIceServers=["stun:stun.l.google.com:19302"],
snapshot="",
cacheBuster=False,
snapshotSslValidation=True,
snapshotTimeout=5,
)
def get_settings_version(self):
return 1
def on_settings_migrate(self, target, current):
if current is None:
config = self._settings.global_get(["webcam"])
if config:
self._logger.info(
"Migrating settings from webcam to plugins.classicwebcam..."
)
# flipH
self._settings.set_boolean(["flipH"], config.get("flipH", False))
self._settings.global_remove(["webcam", "flipH"])
# flipV
self._settings.set_boolean(["flipV"], config.get("flipV", False))
self._settings.global_remove(["webcam", "flipV"])
# rotate90
self._settings.set_boolean(["rotate90"], config.get("rotate90", False))
self._settings.global_remove(["webcam", "rotate90"])
# stream
self._settings.set(["stream"], config.get("stream", ""))
self._settings.global_remove(["webcam", "stream"])
# streamTimeout
self._settings.set_int(["streamTimeout"], config.get("streamTimeout", 5))
self._settings.global_remove(["webcam", "streamTimeout"])
# streamRatio
self._settings.set(["streamRatio"], config.get("streamRatio", "16:9"))
self._settings.global_remove(["webcam", "streamRatio"])
# streamWebrtcIceServers
self._settings.set(
["streamWebrtcIceServers"],
config.get(
"streamWebrtcIceServers", ["stun:stun.l.google.com:19302"]
),
)
self._settings.global_remove(["webcam", "streamWebrtcIceServers"])
# snapshot
self._settings.set(["snapshot"], config.get("snapshot", ""))
self._settings.global_remove(["webcam", "snapshot"])
# cacheBuster
self._settings.set_boolean(
["cacheBuster"], config.get("cacheBuster", False)
)
self._settings.global_remove(["webcam", "cacheBuster"])
# snapshotTimeout
self._settings.set_int(
["snapshotTimeout"], config.get("snapshotTimeout", 5)
)
self._settings.global_remove(["webcam", "snapshotTimeout"])
# snapshotSslValidation
self._settings.set_boolean(
["snapshotSslValidation"], config.get("snapshotSslValidation", True)
)
self._settings.global_remove(["webcam", "snapshotSslValidation"])
# ~~ WizardPlugin API
def is_wizard_required(self):
required = (
not self._get_stream_url()
or not self._get_snapshot_url()
or not self._settings.global_get(["webcam", "ffmpegPath"])
)
firstrun = self._settings.global_get(["server", "firstRun"])
return required and firstrun
def get_wizard_version(self):
return 1
__plugin_name__ = gettext("Classic Webcam")
__plugin_author__ = "Christian Würthner"
__plugin_description__ = "Provides a simple webcam viewer in OctoPrint's UI, images provided by an MJPEG webcam."
__plugin_disabling_discouraged__ = gettext(
"This plugin provides the standard webcam in OctoPrint. If you do not have any other plugin providing a webcam set up, the webcam section in the control tab will no longer be visible."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=3.7,<4"
__plugin_implementation__ = ClassicWebcamPlugin()
@@ -0,0 +1 @@
#webcam_video_container{width:100%;position:relative;outline:0}#webcam_video_container .video-controls{position:absolute;bottom:0;right:8px;z-index:10;opacity:.4}#webcam_video_container:hover .video-controls{opacity:1}#webcam_video_container #webcam_hls,#webcam_video_container #webcam_rtsp{width:100%;height:100%}#webcam_video_container .webcam_rotated{position:relative;width:100%;padding-bottom:56.25%;display:flex;justify-content:center;align-items:center;margin:auto}#webcam_video_container .webcam_rotated .rotation_target{position:absolute;transform:rotate(-90deg);width:100%}#webcam_img_container,#webcam_video_container .webcam_unrotated{width:100%;position:relative}#webcam_video_container .webcam_rotated .rotation_target div{width:100%;height:100%}#webcam_img_container{outline:0;background-color:#000}#webcam_img_container .keycontrol_overlay{position:absolute;left:10px;right:10px;bottom:10px;background:rgba(0,0,0,.5);font-size:85%;color:#fff;padding:0}#webcam_img_container .keycontrol_overlay kbd{border:1px solid #eee;border-radius:3px;margin-left:2px;margin-right:2px;font-size:90%;padding:2px;min-width:1em}#webcam_img_container .keycontrol_overlay .keycontrol_overlay_heading{position:relative;padding:10px;font-weight:700}#webcam_img_container .keycontrol_overlay .keycontrol_overlay_column{position:relative;width:45%;padding:10px;float:left}#webcam_img_container .nowebcam{position:absolute;top:0;left:0;right:0;bottom:0}#webcam_img_container .nowebcam .text{color:#fff;text-align:center;position:relative;margin:auto;width:80%;top:50%;transform:translateY(-50%);display:block}#webcam_img_container .nowebcam .text.webcam_loading{animation:pulsate 3s ease-out;animation-iteration-count:infinite}#webcam_img_container .webcam_rotated{position:relative;width:100%;padding-bottom:100%;pointer-events:none}#webcam_img_container .webcam_rotated .webcam_fixed_ratio{position:absolute;transform:rotate(-90deg);top:0;bottom:0;pointer-events:none}#webcam_img_container .webcam_rotated .webcam_fixed_ratio .webcam_fixed_ratio_inner{width:100%;height:100%;pointer-events:none}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio{width:100%;pointer-events:none;padding-bottom:100%;position:relative}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio43{padding-bottom:75%}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio169{padding-bottom:56.25%}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio1610{padding-bottom:62.5%}#webcam_img_container .webcam_unrotated .webcam_fixed_ratio .webcam_fixed_ratio_inner{position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none}#webcam_img_container img{width:100%;height:100%;object-fit:contain}#webcamTestContainer{min-height:384px}
@@ -0,0 +1,359 @@
$(function () {
function ClassicWebcamViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.settings = parameters[1];
self.webcamStreamVisible = false;
self.webcamDisableTimeout = undefined;
self.webcamLoaded = ko.observable(false);
self.webcamMjpgEnabled = ko.observable(false);
self.webcamHlsEnabled = ko.observable(false);
self.webcamWebRTCEnabled = ko.observable(false);
self.webcamError = ko.observable(false);
self.webcamMuted = ko.observable(true);
self.webRTCPeerConnection = null;
self.webcamElementHls = null;
self.webcamElementWebrtc = null;
self.webcamRatioClass = ko.pureComputed(function () {
if (self.settings.streamRatio() == "4:3") {
return "ratio43";
} else {
return "ratio169";
}
});
self.onBeforeBinding = function () {
// Subscribe to rotation event to ensure we update calculations.
// We need to wait for the CSS to be updated by KO, thus we use a timeout to
// ensure our calculations run after the CSS was updated
self.settings.rotate90.subscribe(function () {
window.setTimeout(function () {
self._updateVideoTagWebcamLayout();
}, 1);
});
self.streamUrlEscaped = ko.pureComputed(function () {
return encodeURI(self.settings.streamUrl());
});
self.webcamStreamType = ko.pureComputed(function () {
try {
return self.determineWebcamStreamType(self.streamUrlEscaped());
} catch (e) {
console.error(e);
return "test";
}
});
self.webcamStreamValid = ko.pureComputed(function () {
var url = self.streamUrlEscaped();
return !url || validateWebcamUrl(url);
});
};
self.onWebcamVisbilityChange = function (visible) {
self.webcamStreamVisible = visible;
if (self.webcamStreamVisible) {
self._enableWebcam();
} else {
self._disableWebcam();
}
};
self.onEventSettingsUpdated = function (payload) {
// the webcam url might have changed, make sure we replace it now if the
// view is visible
self._enableWebcamIfVisible();
};
self._getActiveWebcamVideoElement = function () {
if (self.webcamWebRTCEnabled()) {
return self.webcamElementWebrtc;
} else {
return self.webcamElementHls;
}
};
self.launchWebcamPictureInPicture = function () {
self._getActiveWebcamVideoElement().requestPictureInPicture();
};
self.launchWebcamFullscreen = function () {
self._getActiveWebcamVideoElement().requestFullscreen();
};
self.toggleWebcamMute = function () {
self.webcamMuted(!self.webcamMuted());
self.webcamElementWebrtc.muted = self.webcamMuted();
self.webcamElementHls.muted = self.webcamMuted();
};
self._disableWebcam = function () {
// only disable webcam stream if element is out of view for more than 5s,
// otherwise we might cause more load by the constant connection creation
// than by the actual webcam stream
// safari bug doesn't release the mjpeg stream, so we just disable this for
// safari.
if (OctoPrint.coreui.browser.safari) {
return;
}
var timeout = self.settings.streamTimeout() || 5;
self.webcamDisableTimeout = setTimeout(function () {
log.debug("Unloading webcam stream after", timeout, "seconds");
$("#webcam_image").attr("src", "");
self.webcamLoaded(false);
}, timeout * 1000);
};
self._enableWebcamIfVisible = function () {
if (self.webcamStreamVisible) {
self._enableWebcam();
}
};
self._enableWebcam = function () {
if (
OctoPrint.coreui.selectedTab != "#control" ||
!OctoPrint.coreui.browserTabVisible
) {
return;
}
if (self.webcamDisableTimeout != undefined) {
clearTimeout(self.webcamDisableTimeout);
}
// IF disabled then we dont need to do anything
if (self.settings.webcamEnabled() == false) {
console.log("Webcam not enabled");
return;
}
// Determine stream type and switch to corresponding webcam.
var streamType = self.webcamStreamType();
if (streamType == "mjpg") {
self._switchToMjpgWebcam();
} else if (streamType == "hls") {
self._switchToHlsWebcam();
} else if (isWebRTCAvailable() && streamType == "webrtc") {
self._switchToWebRTCWebcam();
} else {
throw "Unknown stream type " + streamType;
}
};
self.onWebcamLoaded = function () {
if (self.webcamLoaded()) return;
log.debug("Webcam stream loaded");
self.webcamLoaded(true);
self.webcamError(false);
};
self.onWebcamErrored = function () {
log.debug("Webcam stream failed to load/disabled");
self.webcamLoaded(false);
self.webcamError(true);
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.syncWebcamElements();
};
self.syncWebcamElements = function () {
self.webcamElementHls = document.getElementById("webcam_hls");
self.webcamElementWebrtc = document.getElementById("webcam_webrtc");
};
self.onStartup = function () {
self.syncWebcamElements();
};
self._switchToMjpgWebcam = function () {
var webcamImage = $("#webcam_image");
var currentSrc = webcamImage.attr("src");
// safari bug doesn't release the mjpeg stream, so we just set it up the once
if (OctoPrint.coreui.browser.safari && currentSrc != undefined) {
return;
}
var newSrc = self.streamUrlEscaped();
if (currentSrc != newSrc) {
if (self.settings.cacheBuster()) {
if (newSrc.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
newSrc += "?";
}
newSrc += new Date().getTime();
}
self.webcamLoaded(false);
self.webcamError(false);
webcamImage.attr("src", newSrc);
self.webcamHlsEnabled(false);
self.webcamMjpgEnabled(true);
self.webcamWebRTCEnabled(false);
}
};
self._switchToHlsWebcam = function () {
var video = self.webcamElementHls;
video.onresize = self._updateVideoTagWebcamLayout;
// Ensure WebRTC is unloaded
if (self.webRTCPeerConnection != null) {
self.webRTCPeerConnection.close();
self.webRTCPeerConnection = null;
}
// Check for native playback options: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType
if (
video != null &&
typeof video.canPlayType != undefined &&
video.canPlayType("application/vnd.apple.mpegurl") == "probably"
) {
video.src = self.streamUrlEscaped();
} else if (Hls.isSupported()) {
self.hls = new Hls();
self.hls.loadSource(self.streamUrlEscaped());
self.hls.attachMedia(video);
}
self.webcamMjpgEnabled(false);
self.webcamHlsEnabled(true);
self.webcamWebRTCEnabled(false);
};
self._switchToWebRTCWebcam = function () {
if (!isWebRTCAvailable()) {
return;
}
var video = self.webcamElementWebrtc;
video.onresize = self._updateVideoTagWebcamLayout;
// Ensure HLS is unloaded
if (self.hls != null) {
self.webcamElementHls.src = null;
self.hls.destroy();
self.hls = null;
}
// Close any existing, disconnected connection
if (
self.webRTCPeerConnection != null &&
self.webRTCPeerConnection.connectionState != "connected"
) {
self.webRTCPeerConnection.close();
self.webRTCPeerConnection = null;
}
// Open a new connection if necessary
if (self.webRTCPeerConnection == null) {
self.webRTCPeerConnection = startWebRTC(
video,
self.streamUrlEscaped(),
self.settings.streamWebrtcIceServers()
);
}
self.webcamMjpgEnabled(false);
self.webcamHlsEnabled(false);
self.webcamWebRTCEnabled(true);
};
self._updateVideoTagWebcamLayout = function () {
// Get all elements we need
var player = self._getActiveWebcamVideoElement();
var rotationContainer = document.querySelector(
"#webcam_video_container .webcam_rotated"
);
var rotationTarget = document.querySelector(
"#webcam_video_container .webcam_rotated .rotation_target"
);
var unrotationContainer = document.querySelector(
"#webcam_video_container .webcam_unrotated"
);
var unrotationTarget = document.querySelector(
"#webcam_video_container .webcam_unrotated .rotation_target"
);
// If we found the rotation container, the view is rotated 90 degrees. This
// means we need to manually calculate the player dimensions and apply them
// to the rotation target where height = width and width = height (to
// accommodate the rotation). The target is centered in the container and
// rotated around its center, so after we manually resized the container
// everything will layout nicely.
if (rotationContainer && player.videoWidth && player.videoHeight) {
// Calculate the height the video will have in the UI, based on the
// video width and the aspect ratio.
var aspectRatio = player.videoWidth / player.videoHeight;
var height = aspectRatio * rotationContainer.offsetWidth;
// Enforce the height on the rotation container and the rotation target.
// Width of the container will be 100%, height will be calculated
//
// The size of the rotation target (the element that has the 90 deg
// transform) is the inverse size of the container (so height -> width
// and width -> height)
rotationContainer.style.height = height + "px";
rotationTarget.style.height = rotationContainer.offsetWidth + "px";
rotationTarget.style.width = rotationContainer.offsetHeight + "px";
// Remove the padding we used to give the element an initial height.
rotationContainer.style.paddingBottom = 0;
}
// We are not rotated, clean up all changes we might have done before
if (unrotationContainer) {
unrotationContainer.style.height = null;
unrotationContainer.style.paddingBottom = 0;
unrotationTarget.style.height = null;
unrotationTarget.style.width = null;
}
};
self.determineWebcamStreamType = function (streamUrl) {
if (!streamUrl) {
throw "Empty streamUrl. Cannot determine stream type.";
}
var parsed = validateWebcamUrl(streamUrl);
if (!parsed) {
throw "Invalid streamUrl. Cannot determine stream type.";
}
if (parsed.protocol === "webrtc:" || parsed.protocol === "webrtcs:") {
return "webrtc";
}
var lastDotPosition = parsed.pathname.lastIndexOf(".");
if (lastDotPosition !== -1) {
var extension = parsed.pathname.substring(lastDotPosition + 1);
if (extension.toLowerCase() === "m3u8") {
return "hls";
}
}
// By default, 'mjpg' is the stream type.
return "mjpg";
};
}
OCTOPRINT_VIEWMODELS.push({
construct: ClassicWebcamViewModel,
dependencies: ["loginStateViewModel", "classicWebcamSettingsViewModel"],
elements: ["#classicwebcam_container"]
});
});
@@ -0,0 +1,236 @@
$(function () {
function ClassicWebcamSettingsViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.settings = parameters[1];
self._subscriptions = [];
self.webRtcServersToText = function (list) {
self.streamWebrtcIceServersText(self.streamWebrtcIceServers().join(", "));
};
self.textToWebRtcServers = function (list) {
self.streamWebrtcIceServers(
splitTextToArray(self.streamWebrtcIceServersText(), ",", true)
);
};
self.onBeforeBinding = function () {
self.snapshotUrl = self.settings.settings.plugins.classicwebcam.snapshot;
self.flipH = self.settings.settings.plugins.classicwebcam.flipH;
self.flipV = self.settings.settings.plugins.classicwebcam.flipV;
self.rotate90 = self.settings.settings.plugins.classicwebcam.rotate90;
self.streamUrl = self.settings.settings.plugins.classicwebcam.stream;
self.webcamEnabled = self.settings.settings.webcam.webcamEnabled;
self.streamRatio = self.settings.settings.plugins.classicwebcam.streamRatio;
self.streamTimeout =
self.settings.settings.plugins.classicwebcam.streamTimeout;
self.streamWebrtcIceServers =
self.settings.settings.plugins.classicwebcam.streamWebrtcIceServers;
self.streamWebrtcIceServersText = ko.observable("");
self.cacheBuster = self.settings.settings.plugins.classicwebcam.cacheBuster;
self.available_ratios = ["16:9", "4:3"];
self.webRtcServersToText();
self.streamWebrtcIceServers.subscribe(function (value) {
self.webRtcServersToText();
});
};
self.onSettingsBeforeSave = function () {
self.textToWebRtcServers();
};
self.onUserSettingsHidden = function () {
self.webRtcServersToText();
};
self.streamUrlEscaped = ko.pureComputed(function () {
return encodeURI(self.streamUrl());
});
self.streamType = ko.pureComputed(function () {
try {
return determineWebcamStreamType(self.streamUrlEscaped());
} catch (e) {
return "";
}
});
self.streamValid = ko.pureComputed(function () {
var url = self.streamUrlEscaped();
return !url || validateWebcamUrl(url);
});
self.testWebcamStreamUrlBusy = ko.observable(false);
self.testWebcamStreamUrl = function () {
var url = self.streamUrlEscaped();
if (!url) {
return;
}
if (self.testWebcamStreamUrlBusy()) {
return;
}
var text = gettext(
"If you see your webcam stream below, the entered stream URL is ok."
);
var streamType;
try {
streamType = self.streamType();
} catch (e) {
streamType = "";
}
var webcam_element;
var webrtc_peer_connection;
if (streamType === "mjpg") {
webcam_element = $('<img src="' + url + '">');
} else if (streamType === "hls") {
webcam_element = $(
'<video id="webcam_hls" muted autoplay style="width: 100%"/>'
);
video_element = webcam_element[0];
if (video_element.canPlayType("application/vnd.apple.mpegurl")) {
video_element.src = url;
} else if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(url);
hls.attachMedia(video_element);
}
} else if (isWebRTCAvailable() && streamType === "webrtc") {
webcam_element = $(
'<video id="webcam_webrtc" muted autoplay playsinline controls style="width: 100%"/>'
);
video_element = webcam_element[0];
webrtc_peer_connection = startWebRTC(
video_element,
url,
self.streamWebrtcIceServers()
);
} else {
throw "Unknown stream type " + streamType;
}
var message = $("<div id='webcamTestContainer'></div>")
.append($("<p></p>"))
.append(text)
.append(webcam_element);
self.testWebcamStreamUrlBusy(true);
showMessageDialog({
title: gettext("Stream test"),
message: message,
onclose: function () {
self.testWebcamStreamUrlBusy(false);
if (webrtc_peer_connection != null) {
webrtc_peer_connection.close();
webrtc_peer_connection = null;
}
}
});
};
self.testWebcamSnapshotUrlBusy = ko.observable(false);
self.testWebcamSnapshotUrl = function (viewModel, event) {
if (!self.snapshotUrl()) {
return;
}
if (self.testWebcamSnapshotUrlBusy()) {
return;
}
var errorText = gettext(
"Could not retrieve snapshot URL, please double check the URL"
);
var errorTitle = gettext("Snapshot test failed");
self.testWebcamSnapshotUrlBusy(true);
OctoPrint.util
.testUrl(self.snapshotUrl(), {
method: "GET",
response: "bytes",
timeout: self.settings.settings.webcam.snapshotTimeout(),
validSsl: self.settings.settings.webcam.snapshotSslValidation(),
content_type_whitelist: ["image/*"],
content_type_guess: true
})
.done(function (response) {
if (!response.result) {
if (
response.status &&
response.response &&
response.response.content_type
) {
// we could contact the server, but something else was wrong, probably the mime type
errorText = gettext(
"Could retrieve the snapshot URL, but it didn't look like an " +
"image. Got this as a content type header: <code>%(content_type)s</code>. Please " +
"double check that the URL is returning static images, not multipart data " +
"or videos."
);
errorText = _.sprintf(errorText, {
content_type: _.escape(response.response.content_type)
});
}
showMessageDialog({
title: errorTitle,
message: errorText,
onclose: function () {
self.testWebcamSnapshotUrlBusy(false);
}
});
return;
}
var content = response.response.content;
var contentType = response.response.assumed_content_type;
var mimeType = "image/jpeg";
if (contentType) {
mimeType = contentType.split(";")[0];
}
var text = gettext(
"If you see your webcam snapshot picture below, the entered snapshot URL is ok."
);
showMessageDialog({
title: gettext("Snapshot test"),
message: $(
"<p>" +
text +
'</p><p><img src="data:' +
mimeType +
";base64," +
content +
'" style="border: 1px solid black" /></p>'
),
onclose: function () {
self.testWebcamSnapshotUrlBusy(false);
}
});
})
.fail(function () {
showMessageDialog({
title: errorTitle,
message: errorText,
onclose: function () {
self.testWebcamSnapshotUrlBusy(false);
}
});
});
};
}
OCTOPRINT_VIEWMODELS.push({
construct: ClassicWebcamSettingsViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel"],
elements: ["#classicwebcam_settings"]
});
});
@@ -0,0 +1,19 @@
$(function () {
function ClassicWebcamWizardViewModel(parameters) {
var self = this;
self.settingsViewModel = parameters[0];
self.onWizardFinish = function () {
if (self.settingsViewModel.streamUrl()) {
return "reload";
}
};
}
OCTOPRINT_VIEWMODELS.push({
construct: ClassicWebcamWizardViewModel,
dependencies: ["classicWebcamSettingsViewModel"],
elements: ["#wizard_classicwebcam"]
});
});
@@ -0,0 +1,183 @@
#webcam_video_container {
width: 100%;
position: relative;
outline: none;
.video-controls {
position: absolute;
bottom: 0px;
right: 8px;
z-index: 10;
opacity: 0.4;
}
&:hover {
.video-controls {
opacity: 1;
}
}
#webcam_hls,
#webcam_rtsp {
width: 100%;
height: 100%;
}
.webcam_rotated {
position: relative;
width: 100%;
padding-bottom: 56.25%;
display: flex;
justify-content: center;
align-items: center;
margin: auto;
.rotation_target {
position: absolute;
transform: rotate(-90deg);
width: 100%;
div {
width: 100%;
height: 100%;
}
}
}
.webcam_unrotated {
position: relative;
width: 100%;
}
}
#webcam_img_container {
width: 100%;
position: relative;
outline: none;
background-color: black;
.keycontrol_overlay {
position: absolute;
left: 10px;
right: 10px;
bottom: 10px;
background: rgba(0, 0, 0, 0.5);
font-size: 85%;
color: white;
padding: 0;
kbd {
border: 1px solid #eeeeee;
border-radius: 3px;
margin-left: 2px;
margin-right: 2px;
font-size: 90%;
padding: 2px;
min-width: 1em;
}
.keycontrol_overlay_heading {
position: relative;
padding: 10px;
font-weight: bold;
}
.keycontrol_overlay_column {
position: relative;
width: 45%;
padding: 10px;
float: left;
}
}
.nowebcam {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
.text {
color: white;
text-align: center;
position: relative;
margin: auto;
width: 80%;
top: 50%;
transform: translateY(-50%);
display: block;
&.webcam_loading {
animation: pulsate 3s ease-out;
animation-iteration-count: infinite;
}
}
}
.webcam_rotated {
position: relative;
width: 100%;
padding-bottom: 100%;
pointer-events: none;
.webcam_fixed_ratio {
position: absolute;
transform: rotate(-90deg);
top: 0;
bottom: 0;
pointer-events: none;
.webcam_fixed_ratio_inner {
width: 100%;
height: 100%;
pointer-events: none;
}
}
}
.webcam_unrotated {
.webcam_fixed_ratio {
width: 100%;
pointer-events: none;
padding-bottom: 100%;
&.ratio43 {
padding-bottom: 75%;
}
&.ratio169 {
padding-bottom: 56.25%;
}
&.ratio1610 {
padding-bottom: 62.5%;
}
position: relative;
.webcam_fixed_ratio_inner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
pointer-events: none;
}
}
}
img {
width: 100%;
height: 100%;
object-fit: contain;
}
}
// Predict height of webcam test container for modal positioning
// height is 3/4 the fixed modal width, for 4:3 webcam stream.
// Yes it's hardcoded, but so is the modal width.
#webcamTestContainer {
min-height: 384px;
}
@@ -0,0 +1,23 @@
<div id="classicwebcam_settings">
<h3>{{ _('Stream') }}</h3>
<form class="form-horizontal" onsubmit="return false;">
{% include "snippets/classicwebcamStreamUrl.jinja2" %}
{% include "snippets/classicwebcamStreamRatio.jinja2" %}
{% include "snippets/classicwebcamOrientation.jinja2" %}
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.form-horizontal', container: '.hide' }"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
{% include "snippets/classicwebcamStreamTimeout.jinja2" %}
{% include "snippets/classicwebcamCacheBuster.jinja2" %}
{% include "snippets/classicwebcamStreamWebrtcIceServers.jinja2" %}
</div>
</div>
</form>
<h3>{{ _('Snapshots & Timelapse') }}</h3>
<form class="form-horizontal" onsubmit="return false;">
{% include "snippets/classicwebcamSnapshotUrl.jinja2" %}
</form>
</div>
@@ -0,0 +1,47 @@
<div id="classicwebcam_container">
<!-- Init style with display none to hide the content while we are binding -->
<div id="webcam_video_container" tabindex="0" data-bind="visible: webcamWebRTCEnabled() || webcamHlsEnabled(), css: { webcam_rotated: settings.rotate90(), webcam_unrotated: !settings.rotate90() }" style="display: none;">
<div class="video-controls btn-group action-buttons">
<div class="btn btn-mini" data-bind="click: function(data, event) { $root.launchWebcamFullscreen() }"><i class="fas fa-expand"></i></div>
<div class="btn btn-mini" data-bind="visible: document.pictureInPictureEnabled, click: function(data, event) { $root.launchWebcamPictureInPicture() }"><i class="fas fa-images"></i></div>
<div class="btn btn-mini" data-bind="click: function(data, event) { $root.toggleWebcamMute() }">
<!-- ko if: webcamMuted() -->
<i class="fas fa-volume-mute"></i>
<!-- /ko -->
<!-- ko ifnot: webcamMuted() -->
<i class="fas fa-volume-up"></i>
<!-- /ko -->
</div>
</div>
<div data-bind="css: { webcam_rotated: settings.rotate90(), webcam_unrotated: !settings.rotate90() }">
<div class="rotation_target">
<div data-bind="css: { flipH: settings.flipH(), flipV: settings.flipV() }">
<video id="webcam_webrtc" muted autoplay playsinline style="width: 100%" data-bind="visible: webcamWebRTCEnabled()"></video>
<video id="webcam_hls" muted autoplay playsinline style="width: 100%" data-bind="visible: webcamHlsEnabled()"></video>
</div>
</div>
</div>
</div>
<!-- Init style with display none to hide the content while we are binding -->
<div id="webcam_img_container" tabindex="0" data-bind="visible: webcamMjpgEnabled()" style="display: none;">
<div class="nowebcam" data-bind="visible: !webcamLoaded()">
<div class="text webcam_loading" data-bind="visible: !webcamLoaded() && !webcamError()">
<p><strong>{{ _('Webcam stream loading...') }}</strong></p>
</div>
<div class="text webcam_error" data-bind="visible: !webcamLoaded() && webcamError()">
<p><strong>{{ _('Webcam stream not loaded') }}</strong></p>
<p data-bind="visible: !loginState.isAdmin()"><small>{{ _('It might not be configured correctly or require authentication. To have this fixed, get in touch with an administrator of this OctoPrint instance.') }}</small></p>
<p data-bind="visible: loginState.isAdmin"><small>{{ _('It might not be configured correctly or require authentication. You can change the URL of the stream under "Settings" > "Classic Webcam" > "Stream URL". If you don\'t have a webcam you can also just disable webcam support there.') }}</small></p>
<p data-bind="visible: loginState.isUser"><small>{{ _('Currently configured stream URL') }}: <a target="_blank" rel="noreferrer" data-bind="attr: {href: settings.streamUrl}, text: settings.streamUrl"></a></small></p>
</div>
</div>
<div id="webcam_rotator" data-bind="css: { webcam_rotated: settings.rotate90(), webcam_unrotated: !settings.rotate90() }">
<div class="webcam_fixed_ratio" data-bind="css: webcamRatioClass">
<div class="webcam_fixed_ratio_inner">
<img id="webcam_image" data-bind="css: { flipH: settings.flipH(), flipV: settings.flipV() }, event: { load: onWebcamLoaded, error: onWebcamErrored }, visible: !webcamError()">
</div>
</div>
</div>
</div>
</div>
@@ -25,18 +25,7 @@
a fully qualified URL reachable <strong>from the OctoPrint server</strong>.
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel" onsubmit="return false;">
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
</form>
<h4>{{ _('Timelapse Recordings') }}</h4>
{% trans %}<p>
To render the snapshots into timelapse recordings, OctoPrint also needs to
know the correct <strong>path to FFMPEG</strong>.
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel" onsubmit="return false;">
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
<form id="wizard_classicwebcam" class="form-horizontal" data-bind="with: settingsViewModel" onsubmit="return false;">
{% include "snippets/classicwebcamStreamUrl.jinja2" %}
{% include "snippets/classicwebcamSnapshotUrl.jinja2" %}
</form>
@@ -1,7 +1,7 @@
<div class="control-group" title="{{ _('Enable the cache buster on the webcam URl')|edq }}">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_cacheBuster" id="settings-webcamCacheBuster">
<input type="checkbox" data-bind="checked: cacheBuster" id="settings-webcamCacheBuster">
{{ _('Enable Cache buster') }}
<span class="help-block">
<span class="label label-warning">{{ _("Warning") }}</span>
@@ -0,0 +1,17 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: flipH" id="settings-webcamFlipH"> {{ _('Flip webcam horizontally') }}
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: flipV" id="settings-webcamFlipV"> {{ _('Flip webcam vertically') }}
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: rotate90" id="settings-webcamRotate90"> {{ _('Rotate webcam 90 degrees counter clockwise') }}
</label>
</div>
</div>
@@ -0,0 +1,10 @@
<div class="control-group" title="{{ _('URL to use for retrieving webcam snapshot images for timelapse creation')|edq }}">
<label class="control-label" for="settings-webcamSnapshotUrl">{{ _('Snapshot URL') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: snapshotUrl, valueUpdate: 'afterkeydown'" id="settings-webcamSnapshotUrl">
<button class="btn" type="button" data-bind="click: testWebcamSnapshotUrl, enable: snapshotUrl() && !testWebcamSnapshotUrlBusy(), css: {disabled: !snapshotUrl() || testWebcamSnapshotUrlBusy()}"><i class="fas fa-spinner fa-spin" data-bind="visible: testWebcamSnapshotUrlBusy"></i> {{ _('Test') }}</button>
</div>
<span class="help-inline">{% trans %}Fully qualified URL, needs to be reachable by OctoPrint's server{% endtrans %}</span>
</div>
</div>
@@ -1,7 +1,7 @@
<div class="control-group" title="{{ _('Aspect ratio of the webcam stream, either 16:9 or 4:3')|edq }}">
<label class="control-label" for="settings-webcamStreamRatio">{{ _('Stream aspect ratio') }}</label>
<div class="controls">
<select data-bind="options: webcam_available_ratios, value: webcam_streamRatio" id="settings-webcamStreamRatio"></select>
<select data-bind="options: available_ratios, value: streamRatio" id="settings-webcamStreamRatio"></select>
<span class="help-inline">{% trans %}If the stream has a different aspect ratio than configured here it will be letterboxed.{% endtrans %}</span>
</div>
</div>
@@ -2,7 +2,7 @@
<label class="control-label" for="settings-webcamStreamTimeout">{{ _('Stream timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini text-right" data-bind="value: webcam_streamTimeout" id="settings-webcamStreamTimeout">
<input type="number" min="1" class="input-mini text-right" data-bind="value: streamTimeout" id="settings-webcamStreamTimeout">
<span class="add-on">sec</span>
</div>
</div>
@@ -0,0 +1,13 @@
<div class="control-group" title="{{ _('URL to embed into the UI for live viewing of the webcam stream')|edq }}" data-bind="css: { error: !streamValid() }">
<label class="control-label" for="settings-webcamStreamUrl">{{ _('Stream URL') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: streamUrl, valueUpdate: 'afterkeydown'" id="settings-webcamStreamUrl">
<button class="btn" type="button" data-bind="click: testWebcamStreamUrl, enable: !testWebcamStreamUrlBusy() && streamValid(), css: {disabled: testWebcamStreamUrlBusy() || !streamValid()}"><i class="fas fa-spinner fa-spin" data-bind="visible: testWebcamStreamUrlBusy"></i> {{ _('Test') }}</button>
</div>
<span class="help-block">
<p>{% trans %}Needs to be reachable from the browser displaying the OctoPrint UI, used to embed the webcam stream into the page.{% endtrans %}</p>
<p data-bind="visible: streamType() === 'webrtc'">{% trans %}<strong>Heads-up!</strong> WebRTC support is still in beta and subject to change, monitor the changelog of future versions closely for heads-ups regarding the WebRTC support in OctoPrint.{% endtrans %}</p>
</span>
</div>
</div>
@@ -1,7 +1,7 @@
<div class="control-group" title="{{ _('ICE server (STUN and/or TURN) to use for WebRTC')|edq }}">
<label class="control-label" for="settings-webcamStreamWebrtcIceServers">{{ _('WebRTC ICE endpoint') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: webcam_streamWebrtcIceServers, valueUpdate: 'afterkeydown'" id="settings-webcamStreamWebrtcIceServers">
<input type="text" class="input-block-level" data-bind="value: streamWebrtcIceServersText, valueUpdate: 'afterkeydown'" id="settings-webcamStreamWebrtcIceServers">
<span class="help-block"><span class="label">{{ _('WebRTC') }}</span> {% trans %}Only used for WebRTC streams. Optionally specify the ICE server(s) (STUN and/or TURN) to use for WebRTC. Multiple servers should be separated by a comma. If unsure, leave at the default of <code>stun:stun.l.google.com:19302</code>.{% endtrans %}</span>
</div>
</div>
@@ -106,34 +106,6 @@ $(function () {
};
}
function CoreWizardWebcamViewModel(parameters) {
var self = this;
self.settingsViewModel = parameters[0];
self.required = false;
self.onWizardDetails = function (response) {
self.required =
response &&
response.corewizard &&
response.corewizard.details &&
response.corewizard.details.webcam &&
response.corewizard.details.webcam.required;
};
self.onWizardFinish = function () {
if (!self.required) return;
if (
self.settingsViewModel.webcam_streamUrl() ||
(self.settingsViewModel.webcam_snapshotUrl() &&
self.settingsViewModel.webcam_ffmpegPath())
) {
return "reload";
}
};
}
function CoreWizardServerCommandsViewModel(parameters) {
var self = this;
@@ -359,11 +331,6 @@ $(function () {
dependencies: ["loginStateViewModel"],
elements: ["#wizard_plugin_corewizard_acl"]
},
{
construct: CoreWizardWebcamViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_webcam"]
},
{
construct: CoreWizardServerCommandsViewModel,
dependencies: ["settingsViewModel"],
@@ -37,25 +37,6 @@ class ServerCommandsSubwizard:
return gettext("Server Commands")
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class WebcamSubwizard:
def _is_webcam_wizard_firstrunonly(self):
return True
def _is_webcam_wizard_required(self):
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
def _get_webcam_wizard_details(self):
return {"required": self._is_webcam_wizard_required()}
def _get_webcam_wizard_name(self):
return gettext("Webcam & Timelapse")
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class AclSubwizard:
def _is_acl_wizard_firstrunonly(self):
@@ -1 +1 @@
#gcode .progress{width:588px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode .canvas_container{position:relative}#gcode .canvas_container:hover,#gcode .canvas_container:active{outline:0}#gcode .layer-buttons{padding-top:5px;padding-bottom:7px}#gcode #gcode_layer_slider{position:absolute;right:0;top:0;height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}
#gcode .progress{width:588px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode .canvas_container{position:relative}#gcode .canvas_container:active,#gcode .canvas_container:hover{outline:0}#gcode .layer-buttons{padding-top:5px;padding-bottom:7px}#gcode #gcode_layer_slider{position:absolute;right:0;top:0;height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}
@@ -1 +1 @@
table th.settings_logs_checkbox,table td.settings_logs_checkbox{text-align:center;width:10px}table th.settings_logs_checkbox input[type="checkbox"],table td.settings_logs_checkbox input[type="checkbox"]{margin-top:0}table th.settings_logs_name,table td.settings_logs_name{text-overflow:ellipsis;text-align:left}table th.settings_logs_size,table td.settings_logs_size{text-align:right;width:70px}table th.settings_logs_date,table td.settings_logs_date{text-align:left;width:130px}table th.settings_logs_action,table td.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table th.settings_logs_action a,table td.settings_logs_action a{text-decoration:none;color:#000}table th.settings_logs_action a.disabled,table td.settings_logs_action a.disabled{color:#ccc;cursor:default}
table td.settings_logs_checkbox,table th.settings_logs_checkbox{text-align:center;width:10px}table td.settings_logs_checkbox input[type=checkbox],table th.settings_logs_checkbox input[type=checkbox]{margin-top:0}table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
+170 -36
View File
@@ -105,12 +105,6 @@ def map_repository_entry(entry):
return result
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
success_string = "Successfully installed"
failure_string = "Could not install"
python_mismatch_string = "requires a different Python:"
class PluginManagerPlugin(
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
@@ -123,6 +117,7 @@ class PluginManagerPlugin(
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar", ".gz", ".whl")
PYTHON_EXTENSIONS = (".py",)
JSON_EXTENSIONS = (".json",)
# valid pip install URL schemes according to https://pip.pypa.io/en/stable/reference/pip_install/
URL_SCHEMES = (
@@ -174,6 +169,7 @@ class PluginManagerPlugin(
self._repository_available = False
self._repository_plugins = []
self._repository_plugins_by_id = {}
self._repository_cache_path = None
self._repository_cache_ttl = 0
self._repository_mtime = None
@@ -192,6 +188,7 @@ class PluginManagerPlugin(
self._install_task = None
self._install_lock = threading.RLock()
self._jsoninstall_lock = threading.Lock()
self._queued_installs = []
self._queued_installs_abort_timer = None
@@ -348,7 +345,9 @@ class PluginManagerPlugin(
return {
"all": plugins,
"thirdparty": list(filter(lambda p: not p["bundled"], plugins)),
"file_extensions": self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS,
"file_extensions": self.ARCHIVE_EXTENSIONS
+ self.PYTHON_EXTENSIONS
+ self.JSON_EXTENSIONS,
}
def get_template_types(self, template_sorting, template_rules, *args, **kwargs):
@@ -391,7 +390,7 @@ class PluginManagerPlugin(
exts = list(
filter(
lambda x: upload_name.lower().endswith(x),
self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS,
self.ARCHIVE_EXTENSIONS + self.PYTHON_EXTENSIONS + self.JSON_EXTENSIONS,
)
)
if not len(exts):
@@ -445,11 +444,15 @@ class PluginManagerPlugin(
def export_plugin_list(self):
import json
plugins = self.generate_plugins_json(self._settings, self._plugin_manager)
plugins = self.generate_plugins_json(
self._settings,
self._plugin_manager,
repo_plugins=self._repository_plugins_by_id,
)
return Response(
json.dumps(plugins),
mimetype="text/plain",
mimetype="application/json",
headers={"Content-Disposition": 'attachment; filename="plugin_list.json"'},
)
@@ -472,6 +475,7 @@ class PluginManagerPlugin(
"supported_extensions": {
"archive": self.ARCHIVE_EXTENSIONS,
"python": self.PYTHON_EXTENSIONS,
"json": self.JSON_EXTENSIONS,
},
}
@@ -877,6 +881,18 @@ class PluginManagerPlugin(
return False
def _is_jsonfile(self, path):
_, ext = os.path.splitext(path)
if ext in PluginManagerPlugin.JSON_EXTENSIONS:
import json
try:
with open(path) as f:
json.load(f)
return True
except Exception as exc:
self._logger.exception(f"Could not parse {path} as json file: {exc}")
def command_install(
self,
url=None,
@@ -885,6 +901,7 @@ class PluginManagerPlugin(
force=False,
reinstall=None,
dependency_links=False,
partial=False,
):
folder = None
@@ -909,11 +926,25 @@ class PluginManagerPlugin(
force=force,
reinstall=reinstall,
dependency_links=dependency_links,
partial=partial,
)
elif self._is_pythonfile(path):
result = self._command_install_pythonfile(
path, source=source, source_type=source_type, name=name
path,
source=source,
source_type=source_type,
name=name,
partial=partial,
)
elif self._is_jsonfile(path):
result = self._command_install_jsonfile(
path,
source=source,
source_type=source_type,
name=name,
partial=partial,
)
else:
@@ -927,7 +958,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": f"Could not fetch plugin from server, got {e}",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
except exceptions.InvalidPackageFormat:
self._logger.error(
@@ -942,7 +973,7 @@ class PluginManagerPlugin(
"reason": "Could not install plugin from {}, was neither "
"a plugin archive nor a single file plugin".format(source),
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
except Exception:
error_msg = (
@@ -957,7 +988,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": error_msg,
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
finally:
if folder is not None:
@@ -975,6 +1006,7 @@ class PluginManagerPlugin(
force=False,
reinstall=None,
dependency_links=False,
partial=False,
):
throttled = self._get_throttled()
if (
@@ -995,7 +1027,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": error_msg,
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
from urllib.parse import quote as url_quote
@@ -1049,11 +1081,11 @@ class PluginManagerPlugin(
source
),
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
if is_python_mismatch(stderr):
return self.handle_python_mismatch(source, source_type)
return self.handle_python_mismatch(source, source_type, partial=partial)
if force:
# We don't use --upgrade here because that will also happily update all our dependencies - we'd rather
@@ -1072,7 +1104,7 @@ class PluginManagerPlugin(
source
),
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
if is_python_mismatch(stderr):
@@ -1091,7 +1123,7 @@ class PluginManagerPlugin(
"reason": "Could not parse output from pip, see plugin_pluginmanager_console.log "
"for generated output",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
# We'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split
@@ -1118,7 +1150,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": "Pip did not report successful installation",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
installed = list(
@@ -1145,7 +1177,7 @@ class PluginManagerPlugin(
"was_reinstalled": False,
"plugin": "unknown",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
self._plugin_manager.reload_plugins()
@@ -1201,10 +1233,10 @@ class PluginManagerPlugin(
or reinstall is not None,
"plugin": self._to_external_plugin(new_plugin),
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
def _handle_python_mismatch(self, source, source_type):
def _handle_python_mismatch(self, source, source_type, partial=False):
self._logger.error(
"Installing the plugin from {} failed, pip reported a Python version mismatch".format(
source
@@ -1217,11 +1249,13 @@ class PluginManagerPlugin(
"reason": "Pip reported a Python version mismatch",
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
# noinspection DuplicatedCode
def _command_install_pythonfile(self, path, source=None, source_type=None, name=None):
def _command_install_pythonfile(
self, path, source=None, source_type=None, name=None, partial=False
):
if name is None:
name = os.path.basename(path)
@@ -1250,7 +1284,7 @@ class PluginManagerPlugin(
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
pythoncompat = metadata.get(
@@ -1264,7 +1298,7 @@ class PluginManagerPlugin(
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
# copy plugin
@@ -1279,7 +1313,7 @@ class PluginManagerPlugin(
"source_type": source_type,
"reason": "Plugin could not be copied",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
plugins = self._plugin_manager.find_plugins(existing={}, ignore_uninstalled=False)
@@ -1299,7 +1333,7 @@ class PluginManagerPlugin(
"was_reinstalled": False,
"plugin": "unknown",
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
self._plugin_manager.reload_plugins()
@@ -1343,7 +1377,96 @@ class PluginManagerPlugin(
"was_reinstalled": new_plugin.key in all_plugins_before,
"plugin": self._to_external_plugin(new_plugin),
}
self._send_result_notification("install", result)
self._send_result_notification("install", result, partial=partial)
return result
def _command_install_jsonfile(
self, path, source=None, source_type=None, name=None, partial=False
):
import json
sub_results = []
try:
if not self._jsoninstall_lock.acquire(blocking=False):
self._logger.error(
"Attempting to install from json file from within an install running from a json install - this is not supported"
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Recursive json install",
}
self._send_result_notification("install", result, partial=partial)
return result
if name is None:
name = os.path.basename(path)
self._logger.info(f"Installing plugins from export {name} from {source}")
with open(path) as f:
export = json.load(f)
if not isinstance(export, list):
self._logger.error(
f"Installing plugins from export {name} from {source} failed, export is not a list"
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Invalid export",
}
self._send_result_notification("install", result, partial=partial)
return result
for entry in export:
if isinstance(entry, dict):
archive = entry.get("archive")
name = None
if archive is None:
if not self._repository_available:
continue
key = entry.get("key")
if not key:
continue
repo_entry = self._repository_plugins_by_id.get(key)
if not repo_entry:
continue
archive = repo_entry.get("archive")
if not archive:
continue
elif isinstance(entry, str):
# just a URL?
archive = entry
try:
message = f"Installing plugin from {archive}"
self._logger.info(message)
self._log_message(message)
sub_result = self.command_install(
url=archive, name=name, partial=True
)
sub_results.append(sub_result)
except Exception:
self._logger.exception(
f"Installing plugin from {archive} failed, continuing with next entry"
)
finally:
self._jsoninstall_lock.release()
result = {
"result": True,
"source": source,
"source_type": source_type,
"sub_results": sub_results,
}
self._send_result_notification("install", result, partial=partial)
return result
def command_uninstall(self, plugin, cleanup=False):
@@ -1680,8 +1803,11 @@ class PluginManagerPlugin(
return None
def _send_result_notification(self, action, result):
notification = {"type": "result", "action": action}
def _send_result_notification(self, action, result, partial=False):
notification = {
"type": "partial_result" if partial else "result",
"action": action,
}
notification.update(result)
self._plugin_manager.send_plugin_message(self._identifier, notification)
@@ -1864,7 +1990,7 @@ class PluginManagerPlugin(
repository_url = self._settings.get(["repository"])
try:
r = requests.get(repository_url, timeout=30)
r = requests.get(repository_url, timeout=3.05)
r.raise_for_status()
self._logger.info(f"Loaded plugin repository data from {repository_url}")
except Exception as e:
@@ -1912,6 +2038,7 @@ class PluginManagerPlugin(
self._repository_plugins = list(
filter(lambda x: x is not None, map(map_repository_entry, repo_data))
)
self._repository_plugins_by_id = {x["id"]: x for x in self._repository_plugins}
return True
def _is_notices_cache_valid(self, mtime=None):
@@ -1953,7 +2080,7 @@ class PluginManagerPlugin(
notices_url = self._settings.get(["notices"])
try:
r = requests.get(notices_url, timeout=30)
r = requests.get(notices_url, timeout=3.05)
r.raise_for_status()
self._logger.info(f"Loaded plugin notices data from {notices_url}")
except Exception as e:
@@ -2089,7 +2216,11 @@ class PluginManagerPlugin(
@staticmethod
def generate_plugins_json(
settings, plugin_manager, ignore_bundled=True, ignore_plugins_folder=True
settings,
plugin_manager,
ignore_bundled=True,
ignore_plugins_folder=True,
repo_plugins=None,
):
plugins = []
plugin_folder = settings.getBaseFolder("plugins")
@@ -2102,7 +2233,10 @@ class PluginManagerPlugin(
# ignore bundled or from the plugins folder already included in the backup
continue
plugins.append({"key": plugin.key, "name": plugin.name, "url": plugin.url})
data = {"key": plugin.key, "name": plugin.name, "url": plugin.url}
if repo_plugins and plugin.key in repo_plugins:
data["archive"] = repo_plugins[plugin.key]["archive"]
plugins.append(data)
return plugins
def _to_external_plugin(self, plugin):
@@ -1 +1 @@
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox{text-align:center;width:10px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox input[type="checkbox"],#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox input[type="checkbox"]{margin-top:0}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px !important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px;padding-right:10px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty{overflow:hidden;width:100%;height:400px;background-image:url("../img/repo_unavailable.png");text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:bold}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:bold;color:#990000}#settings_plugin_pluLine truncated
#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox],#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox],#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{color:#000;text-decoration:none}#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox{text-align:center;width:10px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output{font-size:.8em}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugLine truncated
@@ -212,6 +212,7 @@ $(function () {
self.online = ko.observable();
self.supportedArchiveExtensions = ko.observableArray([]);
self.supportedPythonExtensions = ko.observableArray([]);
self.supportedJsonExtensions = ko.observableArray([]);
var createExtensionsHelp = function (extensions) {
return _.reduce(
@@ -235,15 +236,21 @@ $(function () {
self.supportedExtensionsHelp = ko.pureComputed(function () {
var archiveExts = createExtensionsHelp(self.supportedArchiveExtensions());
var pythonExts = createExtensionsHelp(self.supportedPythonExtensions());
var jsonExts = createExtensionsHelp(self.supportedJsonExtensions());
return _.sprintf(
gettext(
"This does not look like a valid plugin. Valid plugins should be " +
"either archives installable via <code>pip</code> that " +
"have the extension %(archiveExtensions)s, or single file python " +
"plugins with the extension %(pythonExtensions)s."
"plugins with the extension %(pythonExtensions)s, or a plugin list " +
"export with the extension %(jsonExtensions)s."
),
{archiveExtensions: archiveExts, pythonExtensions: pythonExts}
{
archiveExtensions: archiveExts,
pythonExtensions: pythonExts,
jsonExtensions: jsonExts
}
);
});
@@ -429,21 +436,19 @@ $(function () {
);
});
self.hasExtension = function (name, extensions) {
const lowerName = name.toLocaleLowerCase();
return extensions.some((ext) => lowerName.endsWith(ext));
};
self.invalidFile = ko.pureComputed(function () {
var allowedFileExtensions = self
.supportedArchiveExtensions()
.concat(self.supportedPythonExtensions());
.concat(self.supportedPythonExtensions())
.concat(self.supportedJsonExtensions());
var name = self.uploadFilename();
var lowerName = name !== undefined ? name.toLocaleLowerCase() : undefined;
var lowerNameHasExtension = function (extension) {
return _.endsWith(lowerName, extension);
};
return (
name !== undefined && !_.any(allowedFileExtensions, lowerNameHasExtension)
);
return name !== undefined && !self.hasExtension(name, allowedFileExtensions);
});
self.enableFileInstall = ko.pureComputed(function () {
@@ -468,18 +473,44 @@ $(function () {
return false;
}
self.uploadFilename(data.files[0].name);
var name = data.files[0].name;
self.uploadFilename(name);
var isJsonFile =
name !== undefined &&
self.hasExtension(name, self.supportedJsonExtensions());
self.uploadButton.unbind("click");
self.uploadButton.bind("click", function () {
self._markWorking(
gettext("Installing plugin..."),
gettext("Installing plugin from uploaded file...")
);
data.formData = {
dependency_links: self.followDependencyLinks()
const proceed = () => {
self._markWorking(
isJsonFile
? gettext("Installing plugins...")
: gettext("Installing plugin..."),
isJsonFile
? gettext("Installing plugins from uploaded file...")
: gettext("Installing plugin from uploaded file...")
);
data.formData = {
dependency_links: self.followDependencyLinks()
};
data.submit();
};
data.submit();
if (isJsonFile) {
showConfirmationDialog({
title: gettext("Confirm installation of multiple plugins"),
message: gettext(
"Please confirm you want to perform all plugins specified in the json file."
),
cancel: gettext("Cancel"),
proceed: gettext("Install"),
proceedClass: "primary",
onproceed: proceed
});
} else {
proceed();
}
return false;
});
},
@@ -736,6 +767,7 @@ $(function () {
if (!data) return;
self.supportedArchiveExtensions(data.archive || []);
self.supportedPythonExtensions(data.python || []);
self.supportedJsonExtensions(data.json || []);
};
self.dataPluginsDeferred = undefined;
@@ -1617,35 +1649,77 @@ $(function () {
};
self._processPluginManagementResult = function (response, action, plugin) {
if (response.result) {
if (self.queuedInstalls().length > 0 && action === "install") {
var plugin_dequeue = ko.utils.arrayFirst(
self.queuedInstalls(),
function (item) {
return item.url === response.source;
}
);
if (plugin_dequeue) {
self.queuedInstalls.remove(plugin_dequeue);
if (response.type == "partial_result") {
if (!response.result) {
self.loglines.push({line: gettext("Error!"), stream: "error"});
self.loglines.push({line: response.reason, stream: "error"});
if (response.faq) {
self.loglines.push({
line: _.sprintf(
gettext(
"You can find more info on this issue in the FAQ at %(url)s"
),
{url: faq}
),
stream: "error"
});
}
if (self.queuedInstalls().length === 0) {
self.multiInstallRunning(false);
}
self.loglines.push({line: "", stream: "separator"});
self.loglines.push({
line: _.repeat("+", 50),
stream: "separator"
});
self.loglines.push({line: "", stream: "separator"});
} else {
if (response.result) {
if (self.queuedInstalls().length > 0 && action === "install") {
var plugin_dequeue = ko.utils.arrayFirst(
self.queuedInstalls(),
function (item) {
return item.url === response.source;
}
);
if (plugin_dequeue) {
self.queuedInstalls.remove(plugin_dequeue);
}
if (self.queuedInstalls().length === 0) {
self.multiInstallRunning(false);
self._markDone();
}
} else if (self.multiInstallRunning() && action === "install") {
// A MultiInstall job has finished
self.alertMultiInstallJobDone(response);
} else {
self._markDone();
}
} else if (self.multiInstallRunning() && action === "install") {
// A MultiInstall job has finished
self.alertMultiInstallJobDone(response);
} else {
self._markDone();
self._markDone(response.reason, response.faq);
}
} else {
self._markDone(response.reason, response.faq);
}
self._displayPluginManagementNotification(response, action, plugin);
self._addPluginManagementLog(response, action, plugin);
self._displayPluginManagementNotification();
};
self._displayPluginManagementNotification = function (response, action, plugin) {
self._extractActionAndNameFromResult = function (result) {
var action = result.action;
var name = "Unknown";
if (result.hasOwnProperty("plugin")) {
if (result.plugin !== "unknown") {
if (_.isPlainObject(result.plugin)) {
name = result.plugin.name;
} else {
name = result.plugin;
}
}
}
return {action: action, name: name};
};
self._addPluginManagementLog = function (response, action, plugin) {
self.logContents.action.restart =
self.logContents.action.restart || response.needs_restart;
self.logContents.action.refresh =
@@ -1658,7 +1732,9 @@ $(function () {
result: response.result,
faq: response.faq
});
};
self._displayPluginManagementNotification = function () {
var title = gettext("Plugin management log");
var text = "<p><ul>";
@@ -1737,7 +1813,11 @@ $(function () {
"</p>";
type = "warning";
if (self.restartCommandSpec && !self.multiInstallRunning()) {
if (
self.restartCommandSpec &&
!self.multiInstallRunning() &&
!self.working()
) {
var restartClicked = false;
confirm = {
confirm: true,
@@ -1792,7 +1872,7 @@ $(function () {
"</p>";
type = "warning";
if (!self.multiInstallRunning()) {
if (!self.multiInstallRunning() && !self.working()) {
var refreshClicked = false;
confirm = {
confirm: true,
@@ -2240,21 +2320,13 @@ $(function () {
self.loglines.push(self._preprocessLine(line));
});
self._scrollWorkingOutputToEnd();
} else if (messageType === "result") {
var action = data.action;
var name = "Unknown";
if (data.hasOwnProperty("plugin")) {
if (data.plugin !== "unknown") {
if (_.isPlainObject(data.plugin)) {
name = data.plugin.name;
} else {
name = data.plugin;
}
}
}
} else if (messageType === "result" || messageType === "partial_result") {
var {action, name} = self._extractActionAndNameFromResult(data);
self._processPluginManagementResult(data, action, name);
self.requestPluginData();
if (messageType === "result") {
self._displayPluginManagementNotification();
self.requestPluginData();
}
} else if (messageType === "queued_installs") {
if (data.hasOwnProperty("queued")) {
self.queuedInstalls(data.queued);
@@ -161,10 +161,17 @@
}
#settings_plugin_pluginmanager_workingdialog_output {
font-size: 0.8em;
.message {
font-weight: bold;
}
.separator {
font-weight: bold;
color: #666666;
}
.error {
font-weight: bold;
color: #990000;
@@ -211,7 +211,7 @@
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line + '\n', css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
@@ -423,7 +423,7 @@ class SoftwareUpdatePlugin(
def _get_check_overlay(self, url):
self._logger.info(f"Fetching check overlays from {url}")
try:
r = requests.get(url, timeout=3.1)
r = requests.get(url, timeout=3.05)
r.raise_for_status()
data = r.json()
except Exception as exc:
@@ -1147,7 +1147,7 @@ class SoftwareUpdatePlugin(
)
def view():
self._environment_ready.wait(timeout=30.0)
self._environment_ready.wait(timeout=10.0)
try:
(
@@ -1765,9 +1765,9 @@ class SoftwareUpdatePlugin(
self._save_version_cache()
self._get_versions_data = information, update_available, update_possible
self._get_versions_data_ready.set()
finally:
self._get_versions_mutex.release()
self._get_versions_data_ready.set()
else: # something's already in progress, let's wait for it to complete and use its result
self._get_versions_data_ready.wait()
@@ -2118,7 +2118,7 @@ class SoftwareUpdatePlugin(
self._send_client_message("success", {"results": target_results})
def _perform_update(self, target, check, force, credentials=None):
online = self._connectivity_checker.online
online = self._connectivity_checker.check_immediately()
information, update_available, update_possible, _, _ = self._get_current_version(
target, check, online=online, credentials=credentials
@@ -1 +1 @@
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#990000}#settings_plugin_softwareupdate_workingdialog_output .call{color:#000099}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#990000}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}.progress-softwareupdate.progress{position:relative;display:flex;overflow:hidden;height:25px;font-size:12px}.progress-softwareupdate.progress .bar{display:flex;justify-content:center;align-items:center;width:100%;color:white;height:25px;font-size:12px}.progress-softwareupdate.progress .progress-text{position:absolute;display:flex;justify-content:center;align-items:center;left:0;right:0;top:0;bottom:0;background:white;transition:clip-path 1s linear;height:25px;font-size:12px}
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}.progress-softwareupdate.progress{position:relative;display:flex;overflow:hidden;height:25px;font-size:12px}.progress-softwareupdate.progress .bar{display:flex;justify-content:center;align-items:center;width:100%;color:#fff;height:25px;font-size:12px}.progress-softwareupdate.progress .progress-text{position:absolute;display:flex;justify-content:center;align-items:center;left:0;right:0;top:0;bottom:0;background:#fff;transition:clip-path 1s linear;height:25px;font-size:12px}
@@ -212,7 +212,7 @@
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px; display: none" data-bind="visible: $root.updateAccess(), foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px; display: none" data-bind="visible: $root.updateAccess(), foreach: loglines"><span data-bind="text: line + '\n', css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
<p style="display: none" data-bind="visible: !$root.updateAccess() && $root.working()"><i class="fas fa-spinner fa-spin"></i> {{ _('Update in progress, please wait.') }}</p>
<p style="display: none" data-bind="visible: !$root.updateAccess() && !$root.working()">{{ _('Update done, please close this window.') }}</p>
</div>
@@ -49,7 +49,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
headers["authorization"] = f"Basic {auth_value}"
try:
r = requests.get(url, headers=headers, timeout=(3.05, 30))
r = requests.get(url, headers=headers, timeout=(3.05, 7))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
@@ -21,7 +21,7 @@ def get_latest(target, check, online=True, *args, **kwargs):
raise ConfigurationInvalid("jsondata version check needs jsondata set")
try:
with requests.get(url) as r:
with requests.get(url, timeout=(3.05, 7)) as r:
data = r.json()
except Exception as exc:
raise NetworkError(cause=exc)
@@ -67,7 +67,7 @@ def _get_latest_release(package, include_prerelease):
from ..exceptions import NetworkError
try:
r = requests.get(INFO_URL.format(package=package), timeout=(3.05, 30))
r = requests.get(INFO_URL.format(package=package), timeout=(3.05, 7))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
+2 -2
View File
@@ -518,9 +518,9 @@ class TrackingPlugin(
params = urlencode(kwargs, doseq=True).replace("+", "%20")
if body:
requests.post(url, data=params, timeout=3.1, headers=headers)
requests.post(url, data=params, timeout=3.05, headers=headers)
else:
requests.get(url, params=params, timeout=3.1, headers=headers)
requests.get(url, params=params, timeout=3.05, headers=headers)
self._logger.info(f"Sent tracking event {event}, payload: {kwargs!r}")
except Exception:
@@ -54,6 +54,7 @@ class VirtualPrinterPlugin(
"AUTOREPORT_POS": False,
"EMERGENCY_PARSER": True,
"EXTENDED_M20": False,
"LFN_WRITE": False,
},
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}",
@@ -10,6 +10,7 @@ import queue
import re
import threading
import time
from typing import Any, Dict, List, Optional
from serial import SerialTimeoutException
@@ -665,8 +666,7 @@ class VirtualPrinter:
filename = data.split(None, 1)[1].strip()
if filename.startswith("/"):
filename = filename[1:]
files = self._mappedSdList()
file = files.get(filename.lower())
file = self._getSdFileData(filename)
if file is not None:
self._send(file["name"])
@@ -1411,16 +1411,13 @@ class VirtualPrinter:
else:
line += " {name}"
files = self._mappedSdList()
items = map(lambda x: line.format(**x), files.values())
self._send("Begin file list")
for item in items:
for item in map(lambda x: line.format(**x), self._getSdFiles()):
self._send(item)
self._send("End file list")
def _mappedSdList(self) -> collections.OrderedDict:
result = collections.OrderedDict()
def _mappedSdList(self) -> Dict[str, Dict[str, Any]]:
result = {}
for entry in os.scandir(self._virtualSd):
if not entry.is_file():
continue
@@ -1429,27 +1426,41 @@ class VirtualPrinter:
).lower()
if entry.name.startswith("."):
dosname = "." + dosname
result[dosname] = {
data = {
"name": entry.name,
"path": entry.path,
"dosname": dosname,
"size": entry.stat().st_size,
"timestamp": unix_timestamp_to_m20_timestamp(entry.stat().st_mtime),
}
# index by lower case, we simulate a case insensitive filesystem like FAT,
# which should be closest to what we encounter in reality
result[entry.name.lower()] = data
result[dosname.lower()] = entry.name.lower()
return result
def _getSdFileData(self, filename: str) -> Optional[Dict[str, Any]]:
files = self._mappedSdList()
data = files.get(filename.lower())
if isinstance(data, str):
data = files.get(data.lower())
return data
def _getSdFiles(self) -> List[Dict[str, Any]]:
files = self._mappedSdList()
return [x for x in files.values() if isinstance(x, dict)]
def _selectSdFile(self, filename: str, check_already_open: bool = False) -> None:
if filename.startswith("/"):
filename = filename[1:]
files = self._mappedSdList()
file = files.get(filename)
file = self._getSdFileData(filename)
if (
file is None
or not os.path.exists(file["path"])
or not os.path.isfile(file["path"])
):
self._send("open failed, File: %s." % filename)
self._send(f"open failed, File: {file['name']}.")
return
if self._selectedSdFile == file["path"] and check_already_open:
@@ -1458,7 +1469,7 @@ class VirtualPrinter:
self._selectedSdFile = file["path"]
self._selectedSdFileSize = file["size"]
if self._settings.get_boolean(["includeFilenameInOpened"]):
self._send("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
self._send(f"File opened: {file['name']} Size: {self._selectedSdFileSize}")
else:
self._send("File opened")
self._send("File selected")
@@ -1480,8 +1491,7 @@ class VirtualPrinter:
def _reportSdStatus(self):
if self._sdPrinter is not None and self._sdPrintingSemaphore.is_set:
self._send(
"SD printing byte %d/%d"
% (self._selectedSdFilePos, self._selectedSdFileSize)
f"SD printing byte {self._selectedSdFilePos}/{self._selectedSdFileSize}"
)
else:
self._send("Not SD printing")
@@ -1796,10 +1806,9 @@ class VirtualPrinter:
self._lastE = 0
def _writeSdFile(self, filename: str) -> None:
filename = filename
if filename.startswith("/"):
filename = filename[1:]
file = os.path.join(self._virtualSd, filename.lower())
file = os.path.join(self._virtualSd, filename)
if os.path.exists(file):
if os.path.isfile(file):
os.remove(file)
@@ -1815,7 +1824,7 @@ class VirtualPrinter:
self._writingToSdFile = file
self._writingToSd = True
self._selectedSdFile = file
self._send("Writing to file: %s" % filename)
self._send(f"Writing to file: {filename}")
def _finishSdFile(self):
try:
@@ -1927,8 +1936,7 @@ class VirtualPrinter:
def _deleteSdFile(self, filename: str) -> None:
if filename.startswith("/"):
filename = filename[1:]
files = self._mappedSdList()
file = files.get(filename)
file = self._getSdFileData(filename)
if (
file is not None
and os.path.exists(file["path"])
+15 -12
View File
@@ -257,11 +257,13 @@ class PrinterProfileManager:
def __init__(self):
self._current = None
self._folder = settings().getBaseFolder("printerProfiles")
self._logger = logging.getLogger(__name__)
fresh = settings().checkBaseFolder("printerProfiles")
self._folder = settings().getBaseFolder("printerProfiles")
self._migrate_old_default_profile()
self._verify_default_available()
self._verify_default_available(fresh=fresh)
def _migrate_old_default_profile(self):
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
@@ -291,23 +293,24 @@ class PrinterProfileManager:
)
)
def _verify_default_available(self):
def _verify_default_available(self, fresh=False):
default_id = settings().get(["printerProfiles", "default"])
if default_id is None:
default_id = "_default"
if not self.exists(default_id):
if not self.exists("_default"):
if default_id == "_default":
self._logger.error(
"Profile _default does not exist, creating _default again and setting it as default"
)
else:
self._logger.error(
"Selected default profile {} and _default do not exist, creating _default again and setting it as default".format(
default_id
if not fresh:
if default_id == "_default":
self._logger.error(
"Profile _default does not exist, creating _default again and setting it as default"
)
else:
self._logger.error(
"Selected default profile {} and _default do not exist, creating _default again and setting it as default".format(
default_id
)
)
)
self.save(self.__class__.default, allow_overwrite=True, make_default=True)
else:
self._logger.error(
+20 -16
View File
@@ -78,7 +78,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# sd handling
self._sdPrinting = False
self._sdStreaming = False
self._sdFilelistAvailable = threading.Event()
self._streamingFinishedCallback = None
self._streamingFailedCallback = None
@@ -1007,12 +1006,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if tags is None:
tags = set()
remote_name = self._get_free_remote_name(filename)
self._create_estimator("stream")
self._comm.startFileTransfer(
remote_name = self._comm.startFileTransfer(
path,
filename,
"/" + remote_name,
special=not valid_file_type(filename, "gcode"),
tags=tags | {"trigger:printer.add_sd_file"},
)
@@ -1049,12 +1046,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
if not self._comm or not self._comm.isSdReady():
return
self._sdFilelistAvailable.clear()
self._comm.refreshSdFiles(
tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"}
tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"},
blocking=blocking,
timeout=kwargs.get("timeout", 10),
)
if blocking and not self.is_printing():
self._sdFilelistAvailable.wait(kwargs.get("timeout", 10))
# ~~ state monitoring
@@ -1225,7 +1221,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
)
)
def _setJobData(self, filename, filesize, sd, user=None):
def _setJobData(self, filename, filesize, sd, user=None, data=None):
with self._selectedFileMutex:
if filename is not None:
if sd:
@@ -1278,11 +1274,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
date = None
filament = None
display_name = name_in_storage
if path_on_disk:
# Use a string for mtime because it could be float and the
# Use an int for mtime because it could be float and the
# javascript needs to exact match
if not sd:
date = int(os.stat(path_on_disk).st_mtime)
date = int(os.stat(path_on_disk).st_mtime)
try:
fileData = self._fileManager.get_metadata(
@@ -1329,6 +1325,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
self._selectedFile["estimatedPrintTimeType"] = "analysis"
elif data:
display_name = data.longname
date = data.timestamp
self._stateMonitor.set_job_data(
self._dict(
file=self._dict(
@@ -1491,12 +1491,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm is not None:
self._comm = None
with self._selectedFileMutex:
if self._selectedFile is not None:
eventManager().fire(Events.FILE_DESELECTED)
self._setJobData(None, None, None)
self._updateProgressData()
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setOffsets(None)
self._addTemperatureData()
self._printerProfileManager.deselect()
eventManager().fire(Events.DISCONNECTED)
self._setState(state, state_string=state_string, error_string=error_string)
@@ -1539,9 +1544,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
def on_comm_sd_files(self, files):
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
self._sdFilelistAvailable.set()
def on_comm_file_selected(self, full_path, size, sd, user=None):
def on_comm_file_selected(self, full_path, size, sd, user=None, data=None):
if full_path is not None:
payload = self._payload_for_print_job_event(
location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
@@ -1564,7 +1568,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"Print job deselected - user: {}".format(user if user else "n/a")
)
self._setJobData(full_path, size, sd, user=user)
self._setJobData(full_path, size, sd, user=user, data=data)
self._stateMonitor.set_state(
self._dict(
text=self.get_state_string(),
+15
View File
@@ -70,13 +70,22 @@ class SerialCapabilities(BaseModel):
"""Whether to enable temperature autoreport in the firmware if its support is detected"""
autoreport_sdstatus: bool = True
"""Whether to enable SD printing autoreport in the firmware if its support is detected"""
autoreport_pos: bool = True
"""Whether to enable position autoreport in the firmware if its support is detected"""
busy_protocol: bool = True
"""Whether to shorten the communication timeout if the firmware seems to support the busy protocol"""
emergency_parser: bool = True
"""Whether to send emergency commands out of band if the firmware seems to support the emergency parser"""
extended_m20: bool = True
"""Whether to request extended M20 (file list) output from the firmware if its support is detected"""
lfn_write: bool = True
"""Whether to enable long filename support for SD card writes if the firmware reports support for it"""
@with_attrs_docs
@@ -96,6 +105,12 @@ class SerialConfig(BaseModel):
autoconnect: bool = False
"""Whether to try to automatically connect to the printer on startup or not"""
autorefresh: bool = True
"""Whether to automatically refresh the port list while no connection is established"""
autorefreshInterval: int = 1
"""Interval in seconds at which to refresh the port list while no connection is established"""
log: bool = False
"""Whether to log whole communication to serial.log (warning: might decrease performance)"""
+6
View File
@@ -102,6 +102,9 @@ class PluginBlacklistConfig(BaseModel):
ttl: int = CONST_15MIN
"""Time to live of the cached blacklist, in seconds (default: 15 minutes)."""
timeout: float = 3.05
"""Timeout for fetching the blacklist, in seconds (default: 3.05 seconds)."""
@with_attrs_docs
class DiskspaceConfig(BaseModel):
@@ -204,3 +207,6 @@ class ServerConfig(BaseModel):
cookies: CookiesConfig = CookiesConfig()
"""Settings for further configuration of the cookies that OctoPrint sets (login, remember me, ...)."""
allowedLoginRedirectPaths: List[str] = []
"""List of paths that are allowed to be used as redirect targets for the login page, in addition to the default ones (`/`, `/recovery/` and `/plugin/appkeys/auth/`)"""
+3 -30
View File
@@ -2,17 +2,12 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
from enum import Enum
from typing import List, Optional
from typing import Optional
from octoprint.schema import BaseModel
from octoprint.vendor.with_attrs_docs import with_attrs_docs
class RatioEnum(str, Enum):
sixteen_nine = "16:9"
four_three = "4:3"
class TimelapseTypeEnum(str, Enum):
off = "off"
zchange = "zchange"
@@ -54,20 +49,6 @@ class WebcamConfig(BaseModel):
timelapseEnabled: bool = True
"""Use this option to enable timelapse support via snapshot, e.g. via MJPG-Streamer. Timelapse support will be disabled if not set."""
stream: Optional[str] = None
streamRatio: RatioEnum = RatioEnum.sixteen_nine
streamTimeout: int = 5
streamWebrtcIceServers: List[str] = ["stun:stun.l.google.com:19302"]
snapshot: Optional[str] = None
snapshotTimeout: int = 5
snapshotSslValidation: bool = True
ffmpeg: Optional[str] = None
"""Path to ffmpeg binary to use for creating timelapse recordings. Timelapse support will be disabled if not set."""
@@ -83,15 +64,6 @@ class WebcamConfig(BaseModel):
watermark: bool = True
"""Whether to include a "created with OctoPrint" watermark in the generated timelapse recordings."""
flipH: bool = False
"""Whether to flip the webcam horizontally."""
flipV: bool = False
"""Whether to flip the webcam vertically."""
rotate90: bool = False
"""Whether to rotate the webcam 90° counter clockwise."""
ffmpegCommandline: str = '{ffmpeg} -framerate {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"'
ffmpegThumbnailCommandline: str = (
@@ -104,4 +76,5 @@ class WebcamConfig(BaseModel):
cleanTmpAfterDays: int = 7
"""After how many days unrendered timelapses will be deleted."""
cacheBuster: bool = False
defaultWebcam: str = "classic"
"""The name of the default webcam"""
+72
View File
@@ -0,0 +1,72 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
from enum import Enum
from typing import List, Optional
from octoprint.schema import BaseModel
from octoprint.vendor.with_attrs_docs import with_attrs_docs
class RatioEnum(str, Enum):
sixteen_nine = "16:9"
four_three = "4:3"
@with_attrs_docs
class WebcamCompatibility(BaseModel):
streamTimeout: int = 5
"""The timeout of the stream in seconds"""
streamRatio: RatioEnum = RatioEnum.sixteen_nine
"""The stream's native aspect ratio"""
streamWebrtcIceServers: List[str] = ["stun:stun.l.google.com:19302"]
"""The WebRTC STUN and TURN servers"""
cacheBuster: bool = False
"""Whether the the URL should be randomized to bust caches"""
stream: str
"""The URL to get an MJPEG stream from"""
snapshot: str = None
"""The URL to get the snapshot from"""
snapshotTimeout: int = 5
"""The timeout when retrieving snapshots"""
snapshotSslValidation: bool = True
"""Whether to validate SSL certificates when retrieving a snapshot"""
@with_attrs_docs
class Webcam(BaseModel):
name: str
"""Identifier of this webcam"""
displayName: str
"""Displayable name for this webcam"""
canSnapshot: bool = False
"""Whether this webcam can take a snapshot."""
snapshotDisplay: str = None
"""Human readable information about how a snapshot is captured or a HTTP URL from which the snapshot is loaded (optional, only for user reference)"""
flipH: bool = False
"""Whether to flip the webcam horizontally."""
flipV: bool = False
"""Whether to flip the webcam vertically."""
rotate90: bool = False
"""Whether to rotate the webcam 90° counter clockwise."""
extras: dict = {}
"""Unstructured data describing this webcam"""
compat: Optional[WebcamCompatibility] = None
"""A compatibility configuration to allow older clients to make use of this webcam"""
+94 -13
View File
@@ -34,12 +34,14 @@ from flask_login import ( # noqa: F401
LoginManager,
current_user,
session_protected,
user_loaded_from_cookie,
user_logged_out,
)
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
from werkzeug.exceptions import HTTPException
import octoprint.events
import octoprint.filemanager
import octoprint.util
import octoprint.util.net
@@ -190,6 +192,12 @@ def on_user_logged_out(sender, user=None):
_clear_identity(sender)
@user_loaded_from_cookie.connect_via(app)
def on_user_loaded_from_cookie(sender, user=None):
if user:
session["login_mechanism"] = "remember_me"
def load_user(id):
if id is None:
return None
@@ -612,6 +620,7 @@ class Server:
from octoprint import (
init_custom_events,
init_settings_plugin_config_migration_and_cleanup,
init_webcam_compat_overlay,
)
from octoprint import octoprint_plugin_inject_factory as opif
from octoprint import settings_plugin_inject_factory as spif
@@ -628,6 +637,7 @@ class Server:
pluginManager.initialize_implementations()
init_settings_plugin_config_migration_and_cleanup(pluginManager)
init_webcam_compat_overlay(self._settings, pluginManager)
pluginManager.log_all_plugins()
@@ -669,7 +679,9 @@ class Server:
## Tornado initialization starts here
ioloop = IOLoop()
ioloop = (
IOLoop()
) # TODO: This way to create the ioloop is deprecated and logs a warning
ioloop.install()
enable_cors = settings().getBoolean(["api", "allowCrossOrigin"])
@@ -1150,6 +1162,60 @@ class Server:
"Something went wrong while attempting to automatically connect to the printer"
)
# auto refresh serial ports while not connected
if self._settings.getBoolean(["serial", "autorefresh"]):
from octoprint.util.comm import serialList
last_ports = None
autorefresh = None
def refresh_serial_list():
nonlocal last_ports
new_ports = sorted(serialList())
if new_ports != last_ports:
self._logger.info(
"Serial port list was updated, refreshing the port list in the frontend"
)
eventManager.fire(
events.Events.CONNECTIONS_AUTOREFRESHED,
payload={"ports": new_ports},
)
last_ports = new_ports
def autorefresh_active():
return printer.is_closed_or_error()
def autorefresh_stopped():
nonlocal autorefresh
self._logger.info("Autorefresh of serial port list stopped")
autorefresh = None
def run_autorefresh():
nonlocal autorefresh
if autorefresh is not None:
autorefresh.cancel()
autorefresh = None
autorefresh = octoprint.util.RepeatedTimer(
self._settings.getInt(["serial", "autorefreshInterval"]),
refresh_serial_list,
run_first=True,
condition=autorefresh_active,
on_finish=autorefresh_stopped,
)
autorefresh.name = "Serial autorefresh worker"
self._logger.info("Starting autorefresh of serial port list")
autorefresh.start()
run_autorefresh()
eventManager.subscribe(
octoprint.events.Events.DISCONNECTED, lambda e, p: run_autorefresh()
)
# start up watchdogs
try:
watched = self._settings.getBaseFolder("watched")
@@ -1339,31 +1405,49 @@ class Server:
def _get_locale(self):
global LANGUAGES
l10n = None
default_language = self._settings.get(["appearance", "defaultLanguage"])
if "l10n" in request.values:
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
# request: query param
l10n = request.values["l10n"].split(",")
if "X-Locale" in request.headers:
return Locale.negotiate([request.headers["X-Locale"]], LANGUAGES)
elif "X-Locale" in request.headers:
# request: header
l10n = request.headers["X-Locale"].split(",")
if hasattr(g, "identity") and g.identity:
elif hasattr(g, "identity") and g.identity:
# user setting
userid = g.identity.id
try:
user_language = userManager.get_user_setting(
userid, ("interface", "language")
)
if user_language is not None and not user_language == "_default":
return Locale.negotiate([user_language], LANGUAGES)
l10n = [user_language]
except octoprint.access.users.UnknownUser:
pass
default_language = self._settings.get(["appearance", "defaultLanguage"])
if (
elif (
default_language is not None
and not default_language == "_default"
and default_language in LANGUAGES
):
return Locale.negotiate([default_language], LANGUAGES)
# instance setting
l10n = [default_language]
if l10n:
# canonicalize and get rid of invalid language codes
l10n_canoicalized = []
for x in l10n:
try:
l10n_canoicalized.append(str(Locale.parse(x)))
except Exception:
# invalid language code, ignore
continue
return Locale.negotiate(l10n_canoicalized, LANGUAGES)
# request: preference
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
def _setup_heartbeat_logging(self):
@@ -1502,10 +1586,7 @@ class Server:
# add available translations
for locale in locales:
result.add(locale.language)
if locale.territory:
# if a territory is specified, add that too
result.add(f"{locale.language}_{locale.territory}")
result.add(str(locale))
return result
+16 -1
View File
@@ -22,6 +22,7 @@ import octoprint.access.users
import octoprint.plugin
import octoprint.server
import octoprint.util.net as util_net
from octoprint.access import auth_log
from octoprint.access.permissions import Permissions
from octoprint.events import Events, eventManager
from octoprint.server import NO_CONTENT
@@ -298,6 +299,7 @@ def login():
if "user" in data and "pass" in data:
username = data["user"]
password = data["pass"]
remote_addr = get_remote_address(request)
if "remember" in data and data["remember"] in valid_boolean_trues:
remember = True
@@ -311,6 +313,9 @@ def login():
if user is not None:
if octoprint.server.userManager.check_password(username, password):
if not user.is_active:
auth_log(
f"Failed login attempt for user {username} from {remote_addr}, user is deactivated"
)
abort(403)
user = octoprint.server.userManager.login_user(user)
@@ -326,7 +331,6 @@ def login():
)
session["login_mechanism"] = "http"
remote_addr = get_remote_address(request)
logging.getLogger(__name__).info(
"Actively logging in user {} from {}".format(
user.get_id(), remote_addr
@@ -348,9 +352,19 @@ def login():
eventManager().fire(
Events.USER_LOGGED_IN, payload={"username": user.get_id()}
)
auth_log(f"Logging in user {username} from {remote_addr} via credentials")
return r
else:
auth_log(
f"Failed login attempt for user {username} from {remote_addr}, wrong password"
)
else:
auth_log(
f"Failed login attempt for user {username} from {remote_addr}, user is unknown"
)
abort(403)
elif "passive" in data:
@@ -377,6 +391,7 @@ def logout():
if username:
eventManager().fire(Events.USER_LOGGED_OUT, payload={"username": username})
auth_log(f"Logging out user {username} from {get_remote_address(request)}")
return r
+6 -3
View File
@@ -335,10 +335,13 @@ def _getFileList(
file.update({"date": f["date"]})
files.append(file)
else:
# PERF: Only retrieve the extension tree once
extension_tree = octoprint.filemanager.full_extension_tree()
filter_func = None
if filter:
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(
entry, type=filter
entry, type=filter, tree=extension_tree
)
with _file_cache_mutex:
@@ -396,7 +399,7 @@ def _getFileList(
if (
"analysis" in file_or_folder
and octoprint.filemanager.valid_file_type(
file_or_folder["name"], type="gcode"
file_or_folder["name"], type="gcode", tree=extension_tree
)
):
file_or_folder["gcodeAnalysis"] = file_or_folder["analysis"]
@@ -405,7 +408,7 @@ def _getFileList(
if (
"history" in file_or_folder
and octoprint.filemanager.valid_file_type(
file_or_folder["name"], type="gcode"
file_or_folder["name"], type="gcode", tree=extension_tree
)
):
# convert print log
+84 -16
View File
@@ -55,7 +55,7 @@ def getInstalledLanguagePacks():
).total_seconds()
loc = Locale.parse(locale)
meta["locale"] = locale
meta["locale"] = str(loc)
meta["locale_display"] = loc.display_name
meta["locale_english"] = loc.english_name
return meta
@@ -140,11 +140,12 @@ def uploadLanguagePack():
target_path = settings().getBaseFolder("translations")
if zipfile.is_zipfile(upload_path):
_unpack_uploaded_zipfile(upload_path, target_path)
else:
if not zipfile.is_zipfile(upload_path):
abort(400, description="No zip file included")
if not _validate_and_install_language_pack(upload_path, target_path):
abort(400, description="Invalid language pack archive")
return getInstalledLanguagePacks()
@@ -168,23 +169,90 @@ def deleteInstalledLanguagePack(locale, pack):
return getInstalledLanguagePacks()
def _unpack_uploaded_zipfile(path, target):
with zipfile.ZipFile(path, "r") as zip:
# sanity check
for info in zip.infolist():
_validate_zip_info(info, target)
def _validate_and_install_language_pack(path, target):
import tempfile
# unpack everything
zip.extractall(target)
if not zipfile.is_zipfile(path):
return False
something_installed = False
with tempfile.TemporaryDirectory() as temp_dir:
with zipfile.ZipFile(path, mode="r") as zip:
# protect against path traversal
if any(
map(
lambda x: not os.path.abspath(os.path.join(temp_dir, x)).startswith(
temp_dir + os.path.sep
),
zip.namelist(),
)
):
return False
zip.extractall(temp_dir)
something_installed = (
_validate_and_install_translations(temp_dir, target) or something_installed
)
if os.path.exists(os.path.join(temp_dir, "_plugins")):
something_installed = (
_validate_and_install_plugin_language_pack(
os.path.join(temp_dir, "_plugins"), os.path.join(target, "_plugins")
)
or something_installed
)
return something_installed
def _validate_archive_name(name, target):
if not os.path.abspath(os.path.join(target, name)).startswith(target + os.path.sep):
raise InvalidLanguagePack(f"Provided language pack contains invalid name {name}")
def _validate_and_install_plugin_language_pack(path, target):
something_installed = False
for entry in os.scandir(path):
if not entry.is_dir():
continue
something_installed = (
_validate_and_install_translations(
entry.path, os.path.join(target, entry.name)
)
or something_installed
)
return something_installed
def _validate_zip_info(info, target):
_validate_archive_name(info.filename, target)
def _validate_and_install_translations(path, target):
import shutil
from babel.core import Locale
something_installed = False
for entry in os.scandir(path):
if not entry.is_dir():
continue
try:
loc = Locale.parse(entry.name)
except Exception:
continue
if not os.path.isfile(os.path.join(entry.path, "meta.yaml")):
continue
if not os.path.isdir(os.path.join(entry.path, "LC_MESSAGES")):
continue
if not os.path.isfile(os.path.join(entry.path, "LC_MESSAGES", "messages.mo")):
continue
# looks like a valid translation folder incl. metadata, let's move it
if not os.path.exists(target):
os.makedirs(target)
shutil.move(entry.path, os.path.join(target, str(loc)))
something_installed = True
return something_installed
class InvalidLanguagePack(Exception):
+88 -47
View File
@@ -15,11 +15,29 @@ from octoprint.server import pluginManager, printer, userManager
from octoprint.server.api import api
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking
from octoprint.settings import settings, valid_boolean_trues
from octoprint.webcams import (
get_default_webcam,
get_snapshot_webcam,
get_webcams_as_dicts,
)
# ~~ settings
FOLDER_TYPES = ("uploads", "timelapse", "watched")
TIMELAPSE_BITRATE_PATTERN = re.compile(r"\d+[KMGTPEZY]?i?B?", flags=re.IGNORECASE)
DEPRECATED_WEBCAM_KEYS = (
"streamUrl",
"streamRatio",
"streamTimeout",
"streamWebrtcIceServers",
"snapshotUrl",
"snapshotTimeout",
"snapshotSslValidation",
"cacheBuster",
"flipH",
"flipV",
"rotate90",
)
def _lastmodified():
@@ -112,27 +130,6 @@ def getSettings():
"closeModalsWithClick": s.getBoolean(["appearance", "closeModalsWithClick"]),
"showInternalFilename": s.getBoolean(["appearance", "showInternalFilename"]),
},
"webcam": {
"webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]),
"timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]),
"streamUrl": s.get(["webcam", "stream"]),
"streamRatio": s.get(["webcam", "streamRatio"]),
"streamTimeout": s.getInt(["webcam", "streamTimeout"]),
"streamWebrtcIceServers": s.get(["webcam", "streamWebrtcIceServers"]),
"snapshotUrl": s.get(["webcam", "snapshot"]),
"snapshotTimeout": s.getInt(["webcam", "snapshotTimeout"]),
"snapshotSslValidation": s.getBoolean(["webcam", "snapshotSslValidation"]),
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
"ffmpegCommandline": s.get(["webcam", "ffmpegCommandline"]),
"bitrate": s.get(["webcam", "bitrate"]),
"ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
"ffmpegVideoCodec": s.get(["webcam", "ffmpegVideoCodec"]),
"watermark": s.getBoolean(["webcam", "watermark"]),
"flipH": s.getBoolean(["webcam", "flipH"]),
"flipV": s.getBoolean(["webcam", "flipV"]),
"rotate90": s.getBoolean(["webcam", "rotate90"]),
"cacheBuster": s.getBoolean(["webcam", "cacheBuster"]),
},
"feature": {
"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
@@ -257,6 +254,7 @@ def getSettings():
["serial", "capabilities", "emergency_parser"]
),
"capExtendedM20": s.getBoolean(["serial", "capabilities", "extended_m20"]),
"capLfnWrite": s.getBoolean(["serial", "capabilities", "lfn_write"]),
"resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]),
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
@@ -341,6 +339,60 @@ def getSettings():
if len(plugin_settings):
data["plugins"] = plugin_settings
if Permissions.WEBCAM.can() is True:
webcamsDict = get_webcams_as_dicts()
data["webcam"] = {
"webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]),
"timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]),
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
"ffmpegCommandline": s.get(["webcam", "ffmpegCommandline"]),
"bitrate": s.get(["webcam", "bitrate"]),
"ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
"ffmpegVideoCodec": s.get(["webcam", "ffmpegVideoCodec"]),
"watermark": s.getBoolean(["webcam", "watermark"]),
# webcams & defaults
"webcams": webcamsDict,
"defaultWebcam": None,
"snapshotWebcam": None,
}
for key in DEPRECATED_WEBCAM_KEYS:
data["webcam"][key] = None
defaultWebcam = get_default_webcam()
if defaultWebcam:
data["webcam"].update(
{
"flipH": defaultWebcam.config.flipH,
"flipV": defaultWebcam.config.flipV,
"rotate90": defaultWebcam.config.rotate90,
"defaultWebcam": defaultWebcam.config.name,
}
)
compatWebcam = defaultWebcam.config.compat if defaultWebcam is not None else None
if compatWebcam:
data["webcam"].update(
{
"streamUrl": compatWebcam.stream,
"streamRatio": compatWebcam.streamRatio,
"streamTimeout": compatWebcam.streamTimeout,
"streamWebrtcIceServers": compatWebcam.streamWebrtcIceServers,
"snapshotUrl": compatWebcam.snapshot,
"snapshotTimeout": compatWebcam.snapshotTimeout,
"snapshotSslValidation": compatWebcam.snapshotSslValidation,
"cacheBuster": compatWebcam.cacheBuster,
}
)
snapshotWebcam = get_snapshot_webcam()
if snapshotWebcam:
data["webcam"].update(
{
"snapshotWebcam": snapshotWebcam.config.name,
}
)
return jsonify(data)
@@ -513,30 +565,18 @@ def _saveSettings(data):
)
if "webcam" in data:
for key in DEPRECATED_WEBCAM_KEYS:
if key in data["webcam"]:
logger.warning(
f"Setting webcam.{key} via the API is no longer supported, please use the individual settings of the default webcam instead."
)
if "webcamEnabled" in data["webcam"]:
s.setBoolean(["webcam", "webcamEnabled"], data["webcam"]["webcamEnabled"])
if "timelapseEnabled" in data["webcam"]:
s.setBoolean(
["webcam", "timelapseEnabled"], data["webcam"]["timelapseEnabled"]
)
if "streamUrl" in data["webcam"]:
s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
if "streamRatio" in data["webcam"] and data["webcam"]["streamRatio"] in (
"16:9",
"4:3",
):
s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"])
if "streamTimeout" in data["webcam"]:
s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"])
if "streamWebrtcIceServers" in data["webcam"] and isinstance(
data["webcam"]["streamWebrtcIceServers"], (list, tuple)
):
s.set(
["webcam", "streamWebrtcIceServers"],
data["webcam"]["streamWebrtcIceServers"],
)
if "snapshotUrl" in data["webcam"]:
s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
if "snapshotTimeout" in data["webcam"]:
s.setInt(["webcam", "snapshotTimeout"], data["webcam"]["snapshotTimeout"])
if "snapshotSslValidation" in data["webcam"]:
@@ -589,14 +629,10 @@ def _saveSettings(data):
s.set(["webcam", "ffmpegVideoCodec"], data["webcam"]["ffmpegVideoCodec"])
if "watermark" in data["webcam"]:
s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
if "flipH" in data["webcam"]:
s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
if "flipV" in data["webcam"]:
s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "rotate90" in data["webcam"]:
s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
if "cacheBuster" in data["webcam"]:
s.setBoolean(["webcam", "cacheBuster"], data["webcam"]["cacheBuster"])
if "defaultWebcam" in data["webcam"]:
s.set(["webcam", "defaultWebcam"], data["webcam"]["defaultWebcam"])
if "snapshotWebcam" in data["webcam"]:
s.set(["webcam", "snapshotWebcam"], data["webcam"]["snapshotWebcam"])
if "feature" in data:
if "temperatureGraph" in data["feature"]:
@@ -940,6 +976,11 @@ def _saveSettings(data):
["serial", "capabilities", "extended_m20"],
data["serial"]["capExtendedM20"],
),
if "capLfnWrite" in data["serial"]:
s.setBoolean(
["serial", "capabilities", "lfn_write"],
data["serial"]["capLfnWrite"],
)
if "resendRatioThreshold" in data["serial"]:
s.setInt(
["serial", "resendRatioThreshold"], data["serial"]["resendRatioThreshold"]
+2 -2
View File
@@ -209,7 +209,7 @@ def deleteTimelapse(filename):
@api.route("/timelapse/unrendered/<name>", methods=["DELETE"])
@no_firstrun_access
@Permissions.TIMELAPSE_DELETE.require(403)
@Permissions.TIMELAPSE_MANAGE_UNRENDERED.require(403)
def deleteUnrenderedTimelapse(name):
octoprint.timelapse.delete_unrendered_timelapse(name)
return NO_CONTENT
@@ -217,7 +217,7 @@ def deleteUnrenderedTimelapse(name):
@api.route("/timelapse/unrendered/<name>", methods=["POST"])
@no_firstrun_access
@Permissions.TIMELAPSE_ADMIN.require(403)
@Permissions.TIMELAPSE_MANAGE_UNRENDERED.require(403)
def processUnrenderedTimelapseCommand(name):
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {"render": []}
+17 -2
View File
@@ -268,6 +268,8 @@ def get_user_for_remote_user_header(request):
)
user = octoprint.server.userManager.findUser(userid=header)
if user:
_flask.session["login_mechanism"] = "remote_user"
return user
@@ -299,6 +301,8 @@ def get_user_for_authorization_header(header):
# password check enabled and password don't match
return None
if user:
_flask.session["login_mechanism"] = "basic_auth"
return user
@@ -459,7 +463,7 @@ def validate_local_redirect(url, allowed_paths):
Args:
url (str): URL to validate
allowed_paths (List[str]): List of allowed paths, only paths contained
will be considered valid.
or prefixed (if allowed path ends with "*") will be considered valid.
Returns:
bool: Whether the `url` passed validation or not.
@@ -467,4 +471,15 @@ def validate_local_redirect(url, allowed_paths):
from urllib.parse import urlparse
parsed = urlparse(url)
return parsed.scheme == "" and parsed.netloc == "" and parsed.path in allowed_paths
return (
parsed.scheme == ""
and parsed.netloc == ""
and any(
map(
lambda x: parsed.path.startswith(x[:-1])
if x.endswith("*")
else parsed.path == x,
allowed_paths,
)
)
)
+15 -6
View File
@@ -36,6 +36,7 @@ import octoprint.access.users
import octoprint.plugin
import octoprint.server
import octoprint.vendor.flask_principal as flask_principal
from octoprint.access import auth_log, login_mechanisms
from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import DefaultOrderedDict, deprecated, yaml
@@ -85,11 +86,11 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
continue
dirs.append(plugin_translation_dir)
result = [Locale.parse(default_locale)]
result = {Locale.parse(default_locale)}
for dir in dirs:
result += list_translations(dir)
return result
result.update(list_translations(dir))
return list(result)
def fixed_get_translations():
"""Returns the correct gettext translations that should be used for
@@ -677,7 +678,16 @@ def passive_login():
def login(u):
# login known user
if not u.is_anonymous:
if not flask.g.identity or not flask.g.identity.id:
# the user was just now found
login_mechanism = login_mechanisms.get(
flask.session.get("login_mechanism", "unknown"), "unknown mechanism"
)
auth_log(
f"Logging in user {u.get_id()} from {remote_address} via {login_mechanism}"
)
u = octoprint.server.userManager.login_user(u)
flask_login.login_user(u)
flask_principal.identity_changed.send(
flask.current_app._get_current_object(),
@@ -720,9 +730,7 @@ def passive_login():
autologin_user = octoprint.server.userManager.find_user(autologin_as)
if autologin_user is not None and autologin_user.is_active:
logger.info(
"Passively logging in user {} from {} via autologin".format(
autologin_as, remote_address
)
f"Logging in user {autologin_as} from {remote_address} via autologin"
)
flask.session["login_mechanism"] = "autologin"
return autologin_user
@@ -1754,6 +1762,7 @@ def collect_core_assets(preferred_stylesheet="css"):
assets["js"] = [
"js/app/bindings/allowbindings.js",
"js/app/bindings/contextmenu.js",
"js/app/bindings/gettext.js",
"js/app/bindings/invisible.js",
"js/app/bindings/popover.js",
"js/app/bindings/qrcode.js",
+8
View File
@@ -795,6 +795,14 @@ class WsgiInputContainer:
environ["CONTENT_TYPE"] = request.headers.pop("Content-Type")
if "Content-Length" in request.headers:
environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length")
# remove transfer encoding header if chunked, otherwise flask wsgi entrypoint makes input empty
if (
"Transfer-Encoding" in request.headers
and request.headers.get("Transfer-Encoding") == "chunked"
):
request.headers.pop("Transfer-Encoding")
for key, value in request.headers.items():
environ["HTTP_" + key.replace("-", "_").upper()] = value
return environ
+37 -15
View File
@@ -89,7 +89,7 @@ def _preemptive_data(
d = {
"path": path,
"base_url": base_url,
"query_string": "l10n={}".format(g.locale.language if g.locale else "en"),
"query_string": f"l10n={_locale_str(g.locale)}",
}
if key != "_default":
@@ -103,7 +103,7 @@ def _preemptive_data(
if data:
if "query_string" in data:
data["query_string"] = "l10n={}&{}".format(
g.locale.language, data["query_string"]
_locale_str(g.locale), data["query_string"]
)
d.update(data)
except Exception:
@@ -131,7 +131,7 @@ def _cache_key(ui, url=None, locale=None, additional_key_data=None):
if url is None:
url = request.base_url
if locale is None:
locale = g.locale.language if g.locale else "en"
locale = _locale_str(g.locale)
k = f"ui:{ui}:{url}:{locale}"
if callable(additional_key_data):
@@ -170,14 +170,33 @@ def _add_additional_assets(hook_name):
return result
def _locale_str(locale):
return str(locale) if locale else "en"
@app.route("/login")
@app.route("/login/")
def login():
from flask_login import current_user
default_redirect_url = request.script_root + url_for("index")
default_redirect_url = url_for("index")
redirect_url = request.args.get("redirect", default_redirect_url)
allowed_paths = [url_for("index"), url_for("recovery")]
configured_allowed_paths = settings().get(["server", "allowedLoginRedirectPaths"])
if configured_allowed_paths is None or not isinstance(configured_allowed_paths, list):
configured_allowed_paths = []
configured_allowed_paths = list(
filter(
lambda x: isinstance(x, str),
configured_allowed_paths,
)
)
allowed_paths = [
url_for("index"),
url_for("recovery"),
url_for("plugin.appkeys.handle_auth_dialog", app_token="*"),
] + configured_allowed_paths
if not validate_local_redirect(redirect_url, allowed_paths):
_logger.warning(
@@ -359,7 +378,7 @@ def index():
preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"])
locale = g.locale.language if g.locale else "en"
locale = _locale_str(g.locale)
# helper to check if wizards are active
def wizard_active(templates):
@@ -388,9 +407,7 @@ def index():
enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"])
enable_loading_animation = settings().getBoolean(["devel", "showLoadingAnimation"])
enable_sd_support = settings().get(["feature", "sdSupport"])
enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"]) and bool(
settings().get(["webcam", "stream"])
)
enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"])
enable_temperature_graph = settings().get(["feature", "temperatureGraph"])
sockjs_connect_timeout = settings().getInt(["devel", "sockJsConnectTimeout"])
@@ -465,9 +482,7 @@ def index():
files = _get_all_templates()
files += _get_all_assets()
files += _get_all_translationfiles(
g.locale.language if g.locale else "en", "messages"
)
files += _get_all_translationfiles(_locale_str(g.locale), "messages")
if callable(additional_files):
try:
@@ -731,8 +746,9 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
locales = {}
for loc in LOCALES:
try:
locales[loc.language] = {
"language": loc.language,
key = _locale_str(loc)
locales[key] = {
"language": key,
"display": loc.display_name,
"english": loc.english_name,
}
@@ -765,7 +781,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
def fetch_template_data(refresh=False):
global _templates, _plugin_names, _plugin_vars
locale = g.locale.language if g.locale else "en"
locale = _locale_str(g.locale)
if (
not refresh
@@ -813,6 +829,11 @@ def fetch_template_data(refresh=False):
"template": lambda x: x + "_wizard.jinja2",
"to_entry": lambda data: (data["name"], data),
},
"webcam": {
"div": lambda x: "webcam_plugin_" + x,
"template": lambda x: x + "_webcam.jinja2",
"to_entry": lambda data: (data["name"], data),
},
"about": {
"div": lambda x: "about_plugin_" + x,
"template": lambda x: x + "_about.jinja2",
@@ -849,6 +870,7 @@ def fetch_template_data(refresh=False):
},
"usersettings": {"add": "append", "key": "name"},
"wizard": {"add": "append", "key": "name", "key_extractor": wizard_key_extractor},
"webcam": {"add": "append", "key": "name"},
"about": {"add": "append", "key": "name"},
"generic": {"add": "append", "key": None},
}
+109 -2
View File
@@ -27,7 +27,7 @@ import re
import sys
import threading
import time
from collections import ChainMap
from collections import ChainMap, defaultdict
from collections.abc import KeysView
from yaml import YAMLError
@@ -490,6 +490,8 @@ class Settings:
self._get_preprocessors = {"controls": self._process_custom_controls}
self._set_preprocessors = {}
self._path_update_callbacks = defaultdict(list)
self._deprecated_paths = defaultdict(dict)
self._init_basedir(basedir)
@@ -549,6 +551,36 @@ class Settings:
"CSRF Protection is disabled, this is a security risk. Do not run this in production."
)
def _is_deprecated_path(self, path):
if path and isinstance(path[-1], (list, tuple)):
prefix = path[:-1]
return any(
map(lambda x: bool(self._deprecated_paths[tuple(prefix + [x])]), path[-1])
)
if (
tuple(path) not in self._deprecated_paths
or not self._deprecated_paths[tuple(path)]
):
return False
try:
return list(self._deprecated_paths[tuple(path)].values())[-1]
except StopIteration:
return False
def _path_modified(self, path, current_value, new_value):
callbacks = self._path_update_callbacks.get(tuple(path))
if callbacks:
for callback in callbacks:
try:
if callable(callback):
callback(path, current_value, new_value)
except Exception:
self._logger.exception(
f"Error while executing callback {callback} for path {path}"
)
def _get_default_folder(self, type):
folder = default_settings["folder"][type]
if folder is None:
@@ -912,7 +944,9 @@ class Settings:
self._migrate_config(config)
return config
def add_overlay(self, overlay, at_end=False, key=None):
def add_overlay(
self, overlay, at_end=False, key=None, deprecated=None, replace=False
):
assert isinstance(overlay, dict)
if key is None:
@@ -923,6 +957,17 @@ class Settings:
hash.update(overlay_yaml.encode("utf-8"))
key = hash.hexdigest()
if replace:
self.remove_overlay(key)
if deprecated is not None:
self._logger.debug(
f"Marking all (recursive) paths in this overlay as deprecated: {overlay}"
)
for path in _paths([], overlay):
self._deprecated_paths[tuple(path)][key] = deprecated
overlay[self.OVERLAY_KEY] = key
if at_end:
self._map.insert_map(-1, overlay)
@@ -936,12 +981,37 @@ class Settings:
for i, overlay in enumerate(self._overlay_layers):
if key == overlay.get(self.OVERLAY_KEY):
index = i
overlay = self._map._unflatten(overlay)
break
if index > -1:
self._map.delete_map(index + 1)
self._logger.debug(
f"Removing all deprecation marks for (recursive) paths in this overlay: {overlay}"
)
for path in _paths([], overlay):
try:
del self._deprecated_paths[tuple(path)][key]
except KeyError:
# key not in dict
pass
return True
return False
def add_path_update_callback(self, path, callback):
callbacks = self._path_update_callbacks[tuple(path)]
if callback not in callbacks:
callbacks.append(callback)
def remove_path_update_callback(self, path, callback):
try:
self._path_update_callbacks[tuple(path)].remove(callback)
except ValueError:
# callback not in list
pass
def _migrate_config(self, config=None, persist=False):
if config is None:
config = self._map.top_map
@@ -1531,6 +1601,13 @@ class Settings:
if not path:
raise NoSuchSettingsPath()
is_deprecated = self._is_deprecated_path(path)
if is_deprecated:
self._logger.warning(
f"DeprecationWarning: Detected access to deprecated settings path {path}, returned value is derived from compatibility overlay. {is_deprecated if isinstance(is_deprecated, str) else ''}"
)
config = {}
chain = self._map.with_config_defaults(config=config, defaults=defaults)
if preprocessors is None:
@@ -1684,6 +1761,19 @@ class Settings:
return value.lower() in valid_boolean_trues
return value is not None
def checkBaseFolder(self, type):
if type != "base" and type not in default_settings["folder"]:
return False
if type == "base":
return os.path.exists(self._basedir)
folder = self.get(["folder", type])
default_folder = self._get_default_folder(type)
if folder is None:
folder = default_folder
return os.path.exists(folder)
def getBaseFolder(
self,
type,
@@ -1807,6 +1897,13 @@ class Settings:
raise NoSuchSettingsPath()
return
is_deprecated = self._is_deprecated_path(path)
if is_deprecated:
self._logger.warning(
f"[Deprecation] Prevented write of `{value}` to deprecated settings path {path}. {is_deprecated if isinstance(is_deprecated, str) else ''}"
)
return
if self._mtime is not None and self.last_modified != self._mtime:
self.load()
@@ -1844,6 +1941,7 @@ class Settings:
try:
chain.del_by_path(path)
self._mark_dirty()
self._path_modified(path, current, value)
except KeyError:
if error_on_path:
raise NoSuchSettingsPath()
@@ -1855,6 +1953,7 @@ class Settings:
):
chain.set_by_path(path, value)
self._mark_dirty()
self._path_modified(path, current, value)
# we've changed the interface to no longer mutate the passed in config, so we
# must manually do that here
@@ -2006,3 +2105,11 @@ def _validate_folder(folder, create=True, check_writable=True, deep_check_writab
except Exception:
logger.exception(f"Could not write test file to {testfile}")
raise OSError(error)
def _paths(prefix, data):
if isinstance(data, dict):
for k, v in data.items():
yield from _paths(prefix + [k], v)
else:
yield prefix
+1 -1
View File
@@ -1 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type="text"],.form-signin input[type="password"]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error-credentials,#login-error-rate,#login-offline{display:none}#login-error-credentials.in,#login-error-rate.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:white}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#ffffff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center}
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .checkbox,.form-signin .form-signin-heading{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error-credentials,#login-error-rate,#login-offline{display:none}#login-error-credentials.in,#login-error-rate.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#fff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center}
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #fff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #fff, #e6e6e6);background-image:-o-linear-gradient(top, #fff, #e6e6e6);background-image:linear-gradient(to bottom, #fff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #08c, #04c);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#04c));background-image:-webkit-linear-gradient(top, #08c, #04c);background-image:-o-linear-gradient(top, #08c, #04c);background-image:linear-gradient(to bottom, #08c, #04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btnLine truncated
.btn,.octoprint-container .nav{margin-bottom:0}.actioncol,.btn{text-align:center}.btn,.btn-link,ul.dropdown-menu li a{cursor:pointer}.btn,.slider .slider-handle{background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6))}.btn,.btn-danger,.btn-info,.btn-inverse,.btn-primary,.btn-success,.btn-warning{filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x}.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;font-size:14px;line-height:20px;vertical-align:middle;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);*background-color:#e6e6e6;border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-color:#ccc\9;background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-primary,.slider .slider-selection{text-shadow:0 -1px 0 rgba(0,0,0,.25);background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c)}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small [class*=" icon-"],.btn-small [class^=icon-],table td.timelapse_files_checkbox input[type=checkbox],table td.timelapse_unrendered_checkbox input[type=checkbox],table th.timelapse_files_checkbox input[type=checkbox],table th.timelapse_unrendered_checkbox input[type=checkbox]{margin-top:0}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-danger.active,.btn-info.active,.btn-inverse.active,.btn-primary.active,.btn-success.active,.btn-warning.active{color:rgba(255,255,255,.75)}.btn-primary{color:#fff;background-color:#006dcc;background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039\9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605\9}.btn-danger{color:#fff;teLine truncated
+1 -1
View File
@@ -1 +1 @@
#workdialog .pre-output span{display:block}#workdialog .pre-output .message{font-weight:bold}#workdialog .pre-output .error{font-weight:bold;color:#990000}#workdialog .pre-output .stdout{color:#333333}#workdialog .pre-output .stderr{color:#990000}#workdialog .pre-output .call{color:#000099}
#workdialog .pre-output span{display:block}#workdialog .pre-output .message{font-weight:700}#workdialog .pre-output .error{font-weight:700;color:#900}#workdialog .pre-output .stdout{color:#333}#workdialog .pre-output .stderr{color:#900}#workdialog .pre-output .call{color:#009}
@@ -0,0 +1,16 @@
ko.bindingHandlers.gettext = {
init: function () {
// Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
// It should also make things faster, as we no longer have to consider whether the text node might be bindable.
return {controlsDescendantBindings: true};
},
update: function (element, valueAccessor) {
var gt =
gettext ||
function (text) {
return text;
};
ko.utils.setTextContent(element, gt(valueAccessor()));
}
};
ko.virtualElements.allowedBindings["gettext"] = true;
@@ -220,6 +220,18 @@
return this;
};
OctoPrintSocketClient.prototype.removeMessage = function (message, handler) {
if (!this.registeredHandlers.hasOwnProperty(message)) {
// No handlers registered, do nothing
return;
}
const index = OctoPrint.socket.registeredHandlers[message].indexOf(handler);
if (index > -1) {
OctoPrint.socket.registeredHandlers[message].splice(index, 1);
}
};
OctoPrintSocketClient.prototype.onReconnectAttempt = function (trial) {};
OctoPrintSocketClient.prototype.onReconnectFailed = function () {};
OctoPrintSocketClient.prototype.onConnected = function () {};
+5 -3
View File
@@ -619,7 +619,8 @@ function formatDate(unixTimestamp, options) {
options = {seconds: false};
}
if (!unixTimestamp) return "-";
var placeholder = options.placeholder || "-";
if (!unixTimestamp) return placeholder;
var format = gettext(/* L10N: Date format */ "YYYY-MM-DD HH:mm");
if (options.seconds) {
@@ -629,8 +630,9 @@ function formatDate(unixTimestamp, options) {
return moment.unix(unixTimestamp).format(format);
}
function formatTimeAgo(unixTimestamp) {
if (!unixTimestamp) return "-";
function formatTimeAgo(unixTimestamp, placeholder) {
placeholder = placeholder || "-";
if (!unixTimestamp) return placeholder;
return moment.unix(unixTimestamp).fromNow();
}
@@ -11,6 +11,8 @@ $(function () {
self.systeminfo = ko.observableArray();
self.devmode = getQueryParameterByName("devmode") !== null;
self.getSystemInfo = function () {
if (!self.loginState.hasPermission(self.access.permissions.SYSTEM)) return;
return OctoPrint.system.getInfo().done(self.fromSystemInfo);
@@ -220,6 +220,10 @@ $(function () {
self.requestData();
};
self.onEventConnectionsAutorefreshed = function () {
self.requestData();
};
self.onStartup = function () {
var connectionTab = $("#connection");
connectionTab.on("show", function () {
+62 -290
View File
@@ -38,17 +38,6 @@ $(function () {
self.controlsFromServer = [];
self.additionalControls = [];
self.webcamDisableTimeout = undefined;
self.webcamLoaded = ko.observable(false);
self.webcamMjpgEnabled = ko.observable(false);
self.webcamHlsEnabled = ko.observable(false);
self.webcamWebRTCEnabled = ko.observable(false);
self.webcamError = ko.observable(false);
self.webcamMuted = ko.observable(true);
self.webRTCPeerConnection = null;
self.webcamElementHls = null;
self.webcamElementWebrtc = null;
self.keycontrolActive = ko.observable(false);
self.keycontrolHelpActive = ko.observable(false);
self.keycontrolPossible = ko.pureComputed(function () {
@@ -64,22 +53,66 @@ $(function () {
return self.keycontrolActive() && self.keycontrolPossible();
});
self.webcamRatioClass = ko.pureComputed(function () {
if (self.settings.webcam_streamRatio() == "4:3") {
return "ratio43";
} else {
return "ratio169";
}
});
self._visibleWebcam = undefined;
// Subscribe to rotation event to ensure we update calculations.
// We need to wait for the CSS to be updated by KO, thus we use a timeout to
// ensure our calculations run after the CSS was updated
self.settings.webcam_rotate90.subscribe(function () {
window.setTimeout(function () {
self._updateVideoTagWebcamLayout();
}, 1);
});
self._dispatchWebcamVisibilityChange = function (target, visible) {
var vm = ko.dataFor(target.children[0]);
if (vm === self) {
console.debug(
`VM for webcam #${target.id} is not bound, skipping visibility update`
);
} else if (vm === undefined) {
console.debug(
`VM for webcam #${target.id} not found, skipping visibility update`
);
} else if (typeof vm.onWebcamVisbilityChange === "function") {
vm.onWebcamVisbilityChange(visible);
} else {
console.debug(
`VM for webcam #${target.id} does not declare 'onWebcamVisbilityChange(visible)', skipping visibility update (vm=${vm.constructor.name})`
);
}
};
self.onAfterBinding = function () {
// We are using the IntersectionObserver API to determine whether a webcam is visible or not.
// A webcam will not intersect with the control tab if the control tab is invisible because another tab
// is selected or if the webcam isn't shown because another webcam is active.
//
// Whenever the webacam changes visibility we will call onWebcamVisbilityChange() which the webcam's
// VM can use to start or stop the stream.
document
.querySelectorAll("#webcam-group .tab-pane")
.forEach(function (target) {
var options = {
root: document.querySelector("#control"),
rootMargin: "0px",
threshold: 1.0
};
var callback = function (entries) {
var visible = entries[0].isIntersecting;
self._dispatchWebcamVisibilityChange(target, visible);
// Keep track which webcam is currently visible (if any)
if (visible) {
self._visibleWebcam = target;
} else if (self._visibleWebcam === target && !visible) {
self._visibleWebcam = undefined;
}
};
var observer = new IntersectionObserver(callback, options);
observer.observe(target);
});
};
self.onBrowserTabVisibilityChange = function (tabVisible) {
// We also observe the the browser tab. If any webcam is currently visible, we will update
// it with the tab status as well.
if (self._visibleWebcam !== undefined) {
self._dispatchWebcamVisibilityChange(self._visibleWebcam, tabVisible);
}
};
self.settings.printerProfiles.currentProfileData.subscribe(function () {
self._updateExtruderCount();
@@ -136,10 +169,7 @@ $(function () {
self.isLoading(data.flags.loading);
};
self.onEventSettingsUpdated = function (payload) {
// the webcam url might have changed, make sure we replace it now if the
// tab is focused
self._enableWebcam();
self.onEventSettingsUpdated = function () {
self.requestData();
};
@@ -342,28 +372,6 @@ $(function () {
}
};
self._getActiveWebcamVideoElement = function () {
if (self.webcamWebRTCEnabled()) {
return self.webcamElementWebrtc;
} else {
return self.webcamElementHls;
}
};
self.launchWebcamPictureInPicture = function () {
self._getActiveWebcamVideoElement().requestPictureInPicture();
};
self.launchWebcamFullscreen = function () {
self._getActiveWebcamVideoElement().requestFullscreen();
};
self.toggleWebcamMute = function () {
self.webcamMuted(!self.webcamMuted());
self.webcamElementWebrtc.muted = self.webcamMuted();
self.webcamElementHls.muted = self.webcamMuted();
};
self.sendJogCommand = function (axis, multiplier, distance) {
if (typeof distance === "undefined") distance = self.distance();
if (
@@ -532,89 +540,9 @@ $(function () {
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.syncWebcamElements();
self.requestData();
};
self._disableWebcam = function () {
// only disable webcam stream if tab is out of focus for more than 5s,
// otherwise we might cause more load by the constant connection creation
// than by the actual webcam stream
// safari bug doesn't release the mjpeg stream, so we just disable this for
// safari.
if (OctoPrint.coreui.browser.safari) {
return;
}
var timeout = self.settings.webcam_streamTimeout() || 5;
self.webcamDisableTimeout = setTimeout(function () {
log.debug("Unloading webcam stream");
$("#webcam_image").attr("src", "");
self.webcamLoaded(false);
}, timeout * 1000);
};
self._enableWebcam = function () {
if (
OctoPrint.coreui.selectedTab != "#control" ||
!OctoPrint.coreui.browserTabVisible
) {
return;
}
if (self.webcamDisableTimeout != undefined) {
clearTimeout(self.webcamDisableTimeout);
}
// IF disabled then we dont need to do anything
if (self.settings.webcam_webcamEnabled() == false) {
return;
}
// Determine stream type and switch to corresponding webcam.
var streamType = self.settings.webcam_streamType();
if (streamType == "mjpg") {
self._switchToMjpgWebcam();
} else if (streamType == "hls") {
self._switchToHlsWebcam();
} else if (isWebRTCAvailable() && streamType == "webrtc") {
self._switchToWebRTCWebcam();
} else {
throw "Unknown stream type " + streamType;
}
};
self.onWebcamLoaded = function () {
if (self.webcamLoaded()) return;
log.debug("Webcam stream loaded");
self.webcamLoaded(true);
self.webcamError(false);
};
self.onWebcamErrored = function () {
log.debug("Webcam stream failed to load/disabled");
self.webcamLoaded(false);
self.webcamError(true);
};
self.onTabChange = function (current, previous) {
if (current == "#control") {
self._enableWebcam();
} else if (previous == "#control") {
self._disableWebcam();
}
};
self.onBrowserTabVisibilityChange = function (status) {
if (status) {
self._enableWebcam();
} else {
self._disableWebcam();
}
};
self.onAllBound = function (allViewModels) {
var additionalControls = [];
callViewModels(allViewModels, "getAdditionalControls", function (method) {
@@ -624,7 +552,6 @@ $(function () {
self.additionalControls = additionalControls;
self.rerenderControls();
}
self._enableWebcam();
self.extrusionAmount(
self.settings.printerProfiles
@@ -633,15 +560,6 @@ $(function () {
);
};
self.syncWebcamElements = function () {
self.webcamElementHls = document.getElementById("webcam_hls");
self.webcamElementWebrtc = document.getElementById("webcam_webrtc");
};
self.onStartup = function () {
self.syncWebcamElements();
};
self.onFocus = function (data, event) {
if (!self.settings.feature_keyboardControl()) return;
self.keycontrolActive(true);
@@ -649,13 +567,13 @@ $(function () {
self.onMouseOver = function (data, event) {
if (!self.settings.feature_keyboardControl()) return;
$("#webcam_container").focus();
$("#webcam_plugins_container").focus();
self.keycontrolActive(true);
};
self.onMouseOut = function (data, event) {
if (!self.settings.feature_keyboardControl()) return;
$("#webcam_container").blur();
$("#webcam_plugins_container").blur();
self.keycontrolActive(false);
};
@@ -753,152 +671,6 @@ $(function () {
self.stripDistanceDecimal = function (distance) {
return distance.toString().replace(".", "");
};
self._switchToMjpgWebcam = function () {
var webcamImage = $("#webcam_image");
var currentSrc = webcamImage.attr("src");
// safari bug doesn't release the mjpeg stream, so we just set it up the once
if (OctoPrint.coreui.browser.safari && currentSrc != undefined) {
return;
}
var newSrc = self.settings.webcam_streamUrlEscaped();
if (currentSrc != newSrc) {
if (self.settings.webcam_cacheBuster()) {
if (newSrc.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
newSrc += "?";
}
newSrc += new Date().getTime();
}
self.webcamLoaded(false);
self.webcamError(false);
webcamImage.attr("src", newSrc);
self.webcamHlsEnabled(false);
self.webcamMjpgEnabled(true);
self.webcamWebRTCEnabled(false);
}
};
self._switchToHlsWebcam = function () {
var video = self.webcamElementHls;
video.onresize = self._updateVideoTagWebcamLayout;
// Ensure WebRTC is unloaded
if (self.webRTCPeerConnection != null) {
self.webRTCPeerConnection.close();
self.webRTCPeerConnection = null;
}
// Check for native playback options: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType
if (
video != null &&
typeof video.canPlayType != undefined &&
video.canPlayType("application/vnd.apple.mpegurl") == "probably"
) {
video.src = self.settings.webcam_streamUrlEscaped();
} else if (Hls.isSupported()) {
self.hls = new Hls();
self.hls.loadSource(self.settings.webcam_streamUrlEscaped());
self.hls.attachMedia(video);
}
self.webcamMjpgEnabled(false);
self.webcamHlsEnabled(true);
self.webcamWebRTCEnabled(false);
};
self._switchToWebRTCWebcam = function () {
if (!isWebRTCAvailable()) {
return;
}
var video = self.webcamElementWebrtc;
video.onresize = self._updateVideoTagWebcamLayout;
// Ensure HLS is unloaded
if (self.hls != null) {
self.webcamElementHls.src = null;
self.hls.destroy();
self.hls = null;
}
// Close any existing, disconnected connection
if (
self.webRTCPeerConnection != null &&
self.webRTCPeerConnection.connectionState != "connected"
) {
self.webRTCPeerConnection.close();
self.webRTCPeerConnection = null;
}
// Open a new connection if necessary
if (self.webRTCPeerConnection == null) {
self.webRTCPeerConnection = startWebRTC(
video,
self.settings.webcam_streamUrlEscaped(),
self.settings.webcam_streamWebrtcIceServers()
);
}
self.webcamMjpgEnabled(false);
self.webcamHlsEnabled(false);
self.webcamWebRTCEnabled(true);
};
self._updateVideoTagWebcamLayout = function () {
// Get all elements we need
var player = self._getActiveWebcamVideoElement();
var rotationContainer = document.querySelector(
"#webcam_video_container .webcam_rotated"
);
var rotationTarget = document.querySelector(
"#webcam_video_container .webcam_rotated .rotation_target"
);
var unrotationContainer = document.querySelector(
"#webcam_video_container .webcam_unrotated"
);
var unrotationTarget = document.querySelector(
"#webcam_video_container .webcam_unrotated .rotation_target"
);
// If we found the rotation container, the view is rotated 90 degrees. This
// means we need to manually calculate the player dimensions and apply them
// to the rotation target where height = width and width = height (to
// accommodate the rotation). The target is centered in the container and
// rotated around its center, so after we manually resized the container
// everything will layout nicely.
if (rotationContainer && player.videoWidth && player.videoHeight) {
// Calculate the height the video will have in the UI, based on the
// video width and the aspect ratio.
var aspectRatio = player.videoWidth / player.videoHeight;
var height = aspectRatio * rotationContainer.offsetWidth;
// Enforce the height on the rotation container and the rotation target.
// Width of the container will be 100%, height will be calculated
//
// The size of the rotation target (the element that has the 90 deg
// transform) is the inverse size of the container (so height -> width
// and width -> height)
rotationContainer.style.height = height + "px";
rotationTarget.style.height = rotationContainer.offsetWidth + "px";
rotationTarget.style.width = rotationContainer.offsetHeight + "px";
// Remove the padding we used to give the element an initial height.
rotationContainer.style.paddingBottom = 0;
}
// We are not rotated, clean up all changes we might have done before
if (unrotationContainer) {
unrotationContainer.style.height = null;
unrotationContainer.style.paddingBottom = 0;
unrotationTarget.style.height = null;
unrotationTarget.style.width = null;
}
};
}
OCTOPRINT_VIEWMODELS.push({
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more