Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e4c1f5246 | ||
|
|
d813a0cc86 | ||
|
|
7489b3c398 | ||
|
|
6e009d2544 | ||
|
|
59054cc1e5 | ||
|
|
fcb9eaebda | ||
|
|
b151152c00 | ||
|
|
a1d95dd44b | ||
|
|
c01216cfab | ||
|
|
a47b5187bb | ||
|
|
40d71f1242 | ||
|
|
3088c3be0b | ||
|
|
135249c554 | ||
|
|
814c3a1519 | ||
|
|
68191cfbf4 | ||
|
|
c5b56ae11b | ||
|
|
cc47b41bae | ||
|
|
397de4e3a7 | ||
|
|
9179545c33 | ||
|
|
7659c811f5 | ||
|
|
7d336bd098 | ||
|
|
a68916f05a | ||
|
|
dfced1118a | ||
|
|
588a1c4cc8 | ||
|
|
ab3ebf101f | ||
|
|
1875623f05 | ||
|
|
ac6240a3a3 | ||
|
|
ae407492bc | ||
|
|
de3a12999e | ||
|
|
395354212c | ||
|
|
b38785a25a | ||
|
|
f28a53f3e6 | ||
|
|
d94e13e9dc | ||
|
|
eb9e144746 | ||
|
|
b4d0ed30ab | ||
|
|
8e9c09a818 | ||
|
|
5091487719 | ||
|
|
2f62feaaec | ||
|
|
27a576e352 | ||
|
|
2703d528a3 | ||
|
|
be0d452ab9 | ||
|
|
0093d96da4 | ||
|
|
73c199c98c | ||
|
|
f334decb33 | ||
|
|
daa5dbc4d6 | ||
|
|
147d982c87 | ||
|
|
b87b965fc5 | ||
|
|
9bc2d54196 | ||
|
|
d0d226f3e0 | ||
|
|
59a0c8e8d7 | ||
|
|
0db80dc0c9 | ||
|
|
3c8f8c84f4 | ||
|
|
b447779e33 | ||
|
|
14aec95898 | ||
|
|
dc201416b6 | ||
|
|
e550c94068 | ||
|
|
0d89198464 | ||
|
|
3092734c62 | ||
|
|
452dcdfbcc | ||
|
|
92e8a2a138 | ||
|
|
40e6217ac1 | ||
|
|
b83b57406e | ||
|
|
3cca3a43f3 | ||
|
|
ef95ef1c10 | ||
|
|
2cbeb27140 | ||
|
|
c87a7b6851 | ||
|
|
6af0ce48dc | ||
|
|
3e3c11811e | ||
|
|
a33622e0b7 | ||
|
|
ae1cba8d91 | ||
|
|
9f1ffde4c0 | ||
|
|
fd2db95508 | ||
|
|
87f4a4e8c9 | ||
|
|
91ef0c0d99 | ||
|
|
dabdd40806 | ||
|
|
4a9b18582d | ||
|
|
5753ee3cfa | ||
|
|
c18a5046d5 | ||
|
|
422e3d2b66 |
No files matched your search
@@ -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: |
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<!--
|
||||
Thank you for your interest into contributing to OctoPrint, it's
|
||||
Thank you for your interest in contributing to OctoPrint, it's
|
||||
highly appreciated!
|
||||
|
||||
Please make sure you have read the "guidelines for contributing" as
|
||||
linked just above this form, there's a section on Pull Requests in there
|
||||
as well that contains important information.
|
||||
as well which contains important information.
|
||||
|
||||
As a summary, please make sure you have ticked all points on this
|
||||
checklist:
|
||||
@@ -16,25 +16,25 @@ checklist:
|
||||
made sure your changes don't interfere with current development by
|
||||
talking it through with the maintainers, e.g. through a
|
||||
Brainstorming ticket
|
||||
* [ ] Your PR targets OctoPrint's devel branch if it's a completely
|
||||
new feature, or maintenance if it's a bug fix or improvement of
|
||||
* [ ] Your PR targets OctoPrint's `devel` branch if it's a completely
|
||||
new feature, or `maintenance` if it's a bug fix or improvement of
|
||||
existing functionality for the current stable version (no PRs
|
||||
against master or anything else please)
|
||||
against `master` or anything else please)
|
||||
* [ ] Your PR was opened from a custom branch on your repository
|
||||
(no PRs from your version of master, maintenance or devel please),
|
||||
e.g. dev/my_new_feature or fix/my_bugfix
|
||||
(no PRs from your version of `master`, `maintenance`, or `devel`
|
||||
please), e.g. `dev/my_new_feature` or `fix/my_bugfix`
|
||||
* [ ] Your PR only contains relevant changes: no unrelated files,
|
||||
no dead code, ideally only one commit - rebase and squash your PR
|
||||
if necessary!
|
||||
* [ ] Your changes follow the existing coding style
|
||||
* [ ] If your changes include style sheets: You have modified the
|
||||
.less source files, not the .css files (those are generated with
|
||||
lessc)
|
||||
`.less` source files, not the `.css` files (those are generated
|
||||
with `lessc`)
|
||||
* [ ] You have tested your changes (please state how!) - ideally you
|
||||
have added unit tests
|
||||
* [ ] You have run the existing unit tests against your changes and
|
||||
nothing broke
|
||||
* [ ] You have added yourself to the AUTHORS.md file :)
|
||||
* [ ] You have added yourself to the `AUTHORS.md` file :)
|
||||
|
||||
<!--
|
||||
Describe your PR further using the template provided below. The more
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Check for updates to GitHub Actions every week
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
@@ -1,5 +1,8 @@
|
||||
accessControl:
|
||||
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
|
||||
devel:
|
||||
enableRateLimiter: false
|
||||
enableCsrfProtection: false
|
||||
plugins:
|
||||
virtual_printer:
|
||||
enabled: true
|
||||
|
||||
@@ -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"
|
||||
|
||||
+19
-22
@@ -11,11 +11,11 @@ jobs:
|
||||
name: 🔨 Build distribution
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: 🏗 Set up Python 3.7
|
||||
uses: actions/setup-python@v1
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: 3.7
|
||||
- name: 🏗 Install build dependencies
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
run: |
|
||||
python setup.py sdist bdist_wheel
|
||||
- name: ⬆ Upload build result
|
||||
uses: actions/upload-artifact@v1
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
@@ -34,9 +34,9 @@ jobs:
|
||||
name: 🧹 Pre-commit
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
- name: 🏗 Set up Python 3.7
|
||||
uses: actions/setup-python@v1
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: 3.7
|
||||
- name: 🏗 Set up dev dependencies
|
||||
@@ -53,9 +53,9 @@ jobs:
|
||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
- name: 🏗 Set up Python ${{ matrix.python }}
|
||||
uses: actions/setup-python@v1
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python }}
|
||||
- name: 🏗 Set up test dependencies
|
||||
@@ -70,13 +70,14 @@ jobs:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
- name: 🏗 Set up test dependencies
|
||||
run: |
|
||||
npm -g install node-qunit-puppeteer@2.1.0
|
||||
- name: 🚀 Run helpers.js test suite
|
||||
run: |
|
||||
node-qunit-puppeteer tests/static/js/test-helpers.html
|
||||
node-qunit-puppeteer tests/static/js/test-client-base.html
|
||||
|
||||
test-install:
|
||||
name: 🧪 Installation tests
|
||||
@@ -88,12 +89,12 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: ⬇ Download build result
|
||||
uses: actions/download-artifact@v1
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
- name: 🏗 Set up Python ${{ matrix.python }}
|
||||
uses: actions/setup-python@v1
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python }}
|
||||
- name: 🚀 Install wheel
|
||||
@@ -112,15 +113,15 @@ jobs:
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- name: ⬇ Checkout code
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: ⬇ Download build result
|
||||
uses: actions/download-artifact@v1
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
- name: 🏗 Set up Python 3.7
|
||||
uses: actions/setup-python@v1
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: 3.7
|
||||
- name: 🚀 Install wheel
|
||||
@@ -133,19 +134,15 @@ jobs:
|
||||
cp -r .github/fixtures/with_acl/* e2econfig
|
||||
|
||||
- name: 🚀 Run Cypress
|
||||
uses: cypress-io/github-action@v2
|
||||
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: ⬆ Upload screenshots
|
||||
uses: actions/upload-artifact@v1
|
||||
uses: actions/upload-artifact@v3
|
||||
if: failure()
|
||||
with:
|
||||
name: cypress-screenshots
|
||||
@@ -169,7 +166,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: ⬇ Download build result
|
||||
uses: actions/download-artifact@v1
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
@@ -187,7 +184,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: ⬇ Download build result
|
||||
uses: actions/download-artifact@v1
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
@@ -207,7 +204,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
|
||||
|
||||
@@ -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 }}"
|
||||
|
||||
@@ -7,7 +7,7 @@ jobs:
|
||||
issue-automation:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v5
|
||||
- uses: actions/github-script@v6
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
@@ -72,7 +72,7 @@ jobs:
|
||||
# with:
|
||||
# repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- uses: actions/github-script@v5
|
||||
- uses: actions/github-script@v6
|
||||
env:
|
||||
REMINDER: >
|
||||
Hi @${{ github.event.issue.user.login }}!
|
||||
|
||||
@@ -7,7 +7,7 @@ jobs:
|
||||
linkifyBundles:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v2
|
||||
- uses: actions/github-script@v6
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
@@ -38,14 +38,14 @@ jobs:
|
||||
});
|
||||
text += "\n*edited by @github-actions to add bundle viewer links*\n";
|
||||
|
||||
github.issues.updateComment({
|
||||
github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: context.payload.comment.id,
|
||||
body: text
|
||||
});
|
||||
} else if (botWasHere !== -1) {
|
||||
github.issues.updateComment({
|
||||
github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: context.payload.comment.id,
|
||||
|
||||
@@ -10,12 +10,12 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: ⬇ Checkout
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
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"
|
||||
@@ -23,8 +23,26 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: 🔀 Merge staging/bugfix into maintenance
|
||||
uses: robotology/gh-action-nightly-merge@v1.4.0
|
||||
with:
|
||||
stable_branch: "staging/bugfix"
|
||||
development_branch: "maintenance"
|
||||
allow_ff: false
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: 🔀 Merge staging/maintenance into maintenance
|
||||
uses: robotology/gh-action-nightly-merge@v1.4.0
|
||||
with:
|
||||
stable_branch: "staging/bugfix"
|
||||
development_branch: "maintenance"
|
||||
allow_ff: false
|
||||
env:
|
||||
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"
|
||||
|
||||
@@ -8,11 +8,11 @@ jobs:
|
||||
pr-automation:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/labeler@v3
|
||||
- uses: actions/labeler@v4
|
||||
with:
|
||||
repo-token: "${{ secrets.GITHUB_TOKEN }}"
|
||||
|
||||
- uses: actions/github-script@v5
|
||||
- uses: actions/github-script@v6
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
|
||||
@@ -19,11 +19,11 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: 🐍 Set up Python ${{ matrix.python }}
|
||||
uses: actions/setup-python@v2
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python }}
|
||||
- name: ⬇ Checkout code
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
ref: ${{ matrix.branch }}
|
||||
fetch-depth: 0
|
||||
@@ -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@v2
|
||||
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"
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -43,17 +43,19 @@ repos:
|
||||
hooks:
|
||||
- id: isort
|
||||
- repo: https://github.com/psf/black
|
||||
rev: 22.3.0
|
||||
rev: 22.1.0
|
||||
hooks:
|
||||
- id: black
|
||||
args: ["--config", "black.toml"]
|
||||
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
|
||||
additional_dependencies:
|
||||
- flake8-bugbear==22.3.20
|
||||
- flake8-bugbear==22.1.11
|
||||
- importlib-metadata<5.0
|
||||
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||
rev: v2.5.1
|
||||
hooks:
|
||||
|
||||
+7
-7
@@ -18,16 +18,16 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.9.0
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.8.0
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.9.0 fa2c4680cca0d1d6b46e6c1ed68ceea4d9b79afb pep440-dev
|
||||
fix/.* 1.9.0 fa2c4680cca0d1d6b46e6c1ed68ceea4d9b79afb pep440-dev
|
||||
improve/.* 1.9.0 fa2c4680cca0d1d6b46e6c1ed68ceea4d9b79afb pep440-dev
|
||||
maintenance 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||
fix/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||
improve/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||
|
||||
# staging/bugfix is the branch for preparation of the 1.8.1 bugfix release
|
||||
# staging/bugfix is the branch for preparation of the 1.8.7 bugfix release
|
||||
# so are any bug/... branches
|
||||
staging/bugfix 1.8.1 d2a9aacedacf2b582faca462d6e915f88676a3d5 pep440-dev
|
||||
bug/.* 1.8.1 d2a9aacedacf2b582faca462d6e915f88676a3d5 pep440-dev
|
||||
staging/bugfix 1.8.7 1875623f05e14c3a197c6ff324f02dce55cec7d2 pep440-dev
|
||||
bug/.* 1.8.7 1875623f05e14c3a197c6ff324f02dce55cec7d2 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.8.0rc6
|
||||
# so is regressionfix/...
|
||||
|
||||
@@ -165,8 +165,6 @@ date of first contribution):
|
||||
* [Johan Verrept](https://github.com/JoveToo)
|
||||
* [Nicu Surdu](https://github.com/surdu)
|
||||
* [Zack Lewis](https://github.com/lima3w)
|
||||
* [Billy Richardson](https://github.com/richardsondev)
|
||||
* [Christian Bianchini](https://github.com/max246)
|
||||
|
||||
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
|
||||
|
||||
@@ -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>
|
||||
@@ -21,7 +20,7 @@ and released under the [GNU Affero General Public License V3](https://www.gnu.or
|
||||
|
||||
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme). It also serves as central knowledge base.
|
||||
The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme). It also serves as a central knowledge base.
|
||||
|
||||
An invite to the Discord server can be found at [discord.octoprint.org](https://discord.octoprint.org).
|
||||
|
||||
|
||||
+1
-9
@@ -1,11 +1,3 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Always update to the latest version of OctoPrint to keep up with security patches.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Email to security@octoprint.org.
|
||||
|
||||
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
|
||||
OctoPrint's security policy can be found [here](https://octoprint.org/security/).
|
||||
+10
-21
@@ -10,55 +10,49 @@ thanks to everyone who contributed!
|
||||
* 3DPrinterOS
|
||||
* Al Mucci
|
||||
* Arnljot Arntsen
|
||||
* Artillery 3D
|
||||
* Ash King
|
||||
* Ben Fritsch
|
||||
* BigTreeTech
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* BuildBee
|
||||
* Calvin Vette
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* Christian Würthner
|
||||
* Christoph Sigrist
|
||||
* Craig Parker
|
||||
* CooperSpartan
|
||||
* Creality3D
|
||||
* David Bounds
|
||||
* DeltaMaker 3D Printers
|
||||
* Dennis Breining
|
||||
* Douglas Floyd
|
||||
* Dr. Frank Wester
|
||||
* Eric Betts
|
||||
* Ed Crump
|
||||
* Ernesto Martinez
|
||||
* Franziska Kunsmann
|
||||
* George Robles
|
||||
* Greg Holloway
|
||||
* Hog Duske
|
||||
* Itay Shem-tov
|
||||
* Jacob Renstrom
|
||||
* James Mackay
|
||||
* Jeff Green
|
||||
* Jeff Moe
|
||||
* jeffiel
|
||||
* Jeremy Cole
|
||||
* Joshua Wills
|
||||
* John Cassel
|
||||
* Julian Melo
|
||||
* Justin Kaufman
|
||||
* Kaile Riser
|
||||
* Kazuhiro Ogura
|
||||
* Kenneth Jiang
|
||||
* Kurt Wubbels
|
||||
* Kyle Menigoz
|
||||
* Lachlan Bell
|
||||
* Lefteris Lertas
|
||||
* LulzBot
|
||||
* Makespace Madrid
|
||||
* Mark Greenwald
|
||||
* Mark Walker
|
||||
* Matt Van Itallie
|
||||
* Michael Aumock
|
||||
* Mike Kershaw
|
||||
* Miles Flavel
|
||||
* Mosaic Manufacturing
|
||||
* Norman Jaffe
|
||||
* Obico
|
||||
* Ory Weaver
|
||||
* Peopoly
|
||||
* Pete Barnwell
|
||||
* Raise3D
|
||||
@@ -68,17 +62,12 @@ thanks to everyone who contributed!
|
||||
* Richard Michaud
|
||||
* Richard Stocks
|
||||
* Robert Gusek
|
||||
* Ronald Griehsler
|
||||
* Sean Jensen-Grey
|
||||
* Sebastien Andrivet
|
||||
* SimplyPrint
|
||||
* Stefan Krister
|
||||
* Steve Dougherty
|
||||
* Steve Thompson
|
||||
* TH3D
|
||||
* The Spaghetti Detective
|
||||
* TJ Horner
|
||||
* Trent Shumay
|
||||
* Ulrich Kempken
|
||||
* Yehuda Katz
|
||||
|
||||
and 2279 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
and 2036 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
@@ -28,7 +28,6 @@
|
||||
* [md5.js](https://blueimp.github.io/JavaScript-MD5/): MIT
|
||||
* [Modernizr](http://modernizr.com): MIT
|
||||
* [Moment.js](http://momentjs.com/): MIT
|
||||
* [Pako](https://github.com/nodeca/pako): MIT
|
||||
* [PNotify](http://sciactive.com/pnotify/): GPL, LGPL, MPL (triple licensed)
|
||||
* [pusher.color.js](http://cache.preserve.io/5g18q0pw/index.html) (original link dead): MIT
|
||||
* [SockJS](https://github.com/sockjs/sockjs-client): MIT
|
||||
|
||||
File renamed without changes.
Vendored
+27
@@ -1,3 +1,14 @@
|
||||
/* override table width restrictions */
|
||||
.wy-table-responsive table td, .wy-table-responsive table th {
|
||||
/* !important prevents the common CSS stylesheets from
|
||||
overriding this as on RTD they are loaded after this stylesheet */
|
||||
white-space: normal !important;
|
||||
}
|
||||
|
||||
.wy-table-responsive {
|
||||
overflow: visible !important;
|
||||
}
|
||||
|
||||
/* style headlink for code block captions like other headlinks */
|
||||
.code-block-caption .headerlink {
|
||||
display: none;
|
||||
@@ -31,3 +42,19 @@
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* make code tags non-red again */
|
||||
code,
|
||||
.rst-content tt {
|
||||
color: #000 !important;
|
||||
}
|
||||
|
||||
a code,
|
||||
.rst-content a tt {
|
||||
color: #2980B9 !important;
|
||||
}
|
||||
|
||||
a:visited code,
|
||||
.rst-content a:visited tt {
|
||||
color: #9B59B6 !important;
|
||||
}
|
||||
|
||||
+10
-4
@@ -238,16 +238,22 @@ Change a user's password
|
||||
|
||||
Changes the password of a user.
|
||||
|
||||
Expects a JSON object with a single property ``password`` as request body.
|
||||
Expects a JSON object with a property ``password`` containing the new password as
|
||||
request body. Without the ``SETTINGS`` permission, an additional property ``current``
|
||||
is also required to be set on the request body, containing the user's current password.
|
||||
|
||||
Requires the ``SETTINGS`` permission or to be logged in as the user.
|
||||
Requires the ``SETTINGS`` permission or to be logged in as the user. Note that ``current``
|
||||
will be evaluated even in presence of the ``SETTINGS`` permission, if set.
|
||||
|
||||
:param username: Name of the user to change the password for
|
||||
:json password: The new password to set
|
||||
:json current: The current password
|
||||
:status 200: No error
|
||||
:status 400: If the request doesn't contain a ``password`` property or the request
|
||||
:status 400: If the request doesn't contain a ``password`` property, doesn't
|
||||
contain a ``current`` property even though required, or the request
|
||||
is otherwise invalid
|
||||
:status 403: No admin rights and not logged in as the user
|
||||
:status 403: No admin rights, not logged in as the user or a current password
|
||||
mismatch
|
||||
:status 404: The user is unknown
|
||||
|
||||
.. _sec-api-access-users-settings-get:
|
||||
|
||||
+24
-1
@@ -135,7 +135,7 @@ check the corresponding checkbox in the API settings dialog.
|
||||
|
||||
.. warning::
|
||||
|
||||
This means any browser page can send requests to the OctoPrint API. Authorization is still required however.
|
||||
This means any browser page can send requests to the OctoPrint API. Authorization via an API-Key is still required however.
|
||||
|
||||
If CORS is not enabled you will get errors like the following::
|
||||
|
||||
@@ -151,6 +151,29 @@ If CORS is not enabled you will get errors like the following::
|
||||
the login mechanism (or reusing an existing login session). When accessing OctoPrint
|
||||
via CORS, you'll therefore always need to use an API key.
|
||||
|
||||
.. _sec-api-general-csrf:
|
||||
|
||||
CSRF Protection
|
||||
===============
|
||||
|
||||
.. versionadded:: 1.8.3
|
||||
|
||||
To protect OctoPrint against `CSRF attacks <https://owasp.org/www-community/attacks/csrf>`_ against the non CORS affected upload endpoints, in case of browser session based authorization the API
|
||||
is protected using the `Double Submit Cookie mitigation strategy <https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie>`_.
|
||||
On first page load of the UI, the login page or the recovery page, a ``csrf_token_P<port>`` or ``csrf_token_P<port>_R<root>`` cookie is set
|
||||
that can be read via client-side JavaScript. All requests towards the API that are not ``GET``, ``HEAD`` or ``OPTIONS``
|
||||
and rely on cookie based authorization (so not on an API key but rather an active login session) are required
|
||||
to send both the ``csrf_token`` cookie as well as an ``X-CSRF-Token`` header containing its value.
|
||||
|
||||
.. note::
|
||||
|
||||
If you use the :ref:`JS Client library <sec-jsclientlib>`, this will take care of doing the needful for you. Any code in the *Core UI* calling
|
||||
API functions through ``$.ajax`` or ``$.get`` or ``$.post`` will also take care of this for you. If you use another library for
|
||||
accessing OctoPrint's API in a browser context, you'll need to make sure to send the ``X-CSRF-Token`` header yourself. Examples for
|
||||
several JS frameworks can be found in the `OWASP cheatsheet on CSRF attacks <https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#javascript-guidance-for-auto-inclusion-of-csrf-tokens-as-an-ajax-request-header>`_.
|
||||
Take a look at the implementations of ``OctoPrintClient.getCookie`` and ``OctoPrintClient.getHeaders`` in ``src/octoprint/static/js/client/base.js``
|
||||
for details on how to retrieve the cookie value and how to construct the header.
|
||||
|
||||
.. _sec-api-general-login:
|
||||
|
||||
Login
|
||||
|
||||
@@ -627,11 +627,9 @@ Profile
|
||||
- ``float``
|
||||
- The diameter of the printer's nozzle(s) in mm.
|
||||
* - ``extruder.sharedNozzle``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether there's only one nozzle shared among all extruders (true) or one nozzle per extruder (false).
|
||||
* - ``extruder.defaultExtrusionLength``
|
||||
- 0..1
|
||||
- ``int``
|
||||
- Default extrusion length used in Control tab on initial page load in mm.
|
||||
* - ``extruder.count``
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ following message types are currently available for usage by 3rd party clients:
|
||||
* ``connected``: Initial connection information, sent only right after establishing the socket connection. See
|
||||
:ref:`the payload data model <sec-api-push-datamodel-connected>`.
|
||||
* ``reauthRequired``: A reauthentication of the current login session is required. The ``reason`` parameter in the
|
||||
payload defines whether a full active login is necessary (values ``logout`` and ``removed``) or a simple passive
|
||||
payload defines whether a full active login is necessary (values ``logout``, ``stale``, ``removed``) or a simple passive
|
||||
login will suffice (all other values).
|
||||
* ``current``: Rate limited general state update, payload contains information about the printer's state, job progress,
|
||||
accumulated temperature points and log lines since last update. OctoPrint will send these updates when new information
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
.. _sec-api-user:
|
||||
|
||||
****
|
||||
User
|
||||
****
|
||||
|
||||
.. note::
|
||||
|
||||
This API endpoint has been moved and is now part of :ref:`Access Control <sec-api-access-users>`.
|
||||
+1
-1
@@ -76,7 +76,7 @@ Various tests
|
||||
* ``content_type_whitelist``: Optional array of supported content types. If set and the URL returns a content
|
||||
type not included in this list, the test will fail. E.g. ``["image/*", "text/plain"]``.
|
||||
* ``content_type_blacklist``: Optional array of unsupported content types. If set and the URL returns a content
|
||||
type included in this list, the test will fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist``
|
||||
type included in this list, the test wil fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist``
|
||||
to further limit broader content type definition, e.g. by putting ``image/*`` into the whitelist, but disallowing
|
||||
PNG by including ``image/png`` on the blacklist.
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
.. _sec-bundledplugins-loginui:
|
||||
|
||||
Login UI
|
||||
========
|
||||
|
||||
The Login UI plugin's functionality has been merged into OctoPrint's core as of OctoPrint 1.4.2.
|
||||
+8
-4
@@ -43,7 +43,6 @@ extensions = [
|
||||
"sphinx.ext.napoleon",
|
||||
"sphinxcontrib.mermaid",
|
||||
"sphinx.ext.intersphinx",
|
||||
"sphinx_rtd_theme"
|
||||
]
|
||||
todo_include_todos = True
|
||||
intersphinx_mapping = {
|
||||
@@ -109,7 +108,7 @@ exclude_patterns = ["_build"]
|
||||
# show_authors = False
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = "stata-dark"
|
||||
pygments_style = "sphinx"
|
||||
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
# modindex_common_prefix = []
|
||||
@@ -123,14 +122,19 @@ mermaid_version = ""
|
||||
|
||||
# -- Options for HTML output ---------------------------------------------------
|
||||
|
||||
import sphinx_rtd_theme
|
||||
|
||||
html_theme = "sphinx_rtd_theme"
|
||||
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of built-in themes.
|
||||
html_theme = "sphinx_rtd_theme"
|
||||
# html_theme = "sphinx_rtd_theme"
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
# documentation.
|
||||
html_theme_options = {}
|
||||
# html_theme_options = {}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
||||
|
||||
@@ -72,10 +72,6 @@ Use the following settings to enable access control:
|
||||
# If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.
|
||||
addRemoteUsers: false
|
||||
|
||||
# Secret salt used for password hashing, DO NOT TOUCH. If changed you will no longer be able to log in with your
|
||||
# existing accounts.
|
||||
salt: someSecretSalt
|
||||
|
||||
.. _sec-configuration-config_yaml-api:
|
||||
|
||||
API
|
||||
@@ -451,7 +447,7 @@ Use the following settings to enable or disable OctoPrint features:
|
||||
|
||||
# whether G90/G91 also influence absolute/relative mode of extruders
|
||||
g90InfluencesExtruder: false
|
||||
|
||||
|
||||
# Replace all special characters and spaces with text equivalent to make them universally compatible.
|
||||
# Most OS filesystems work fine with unicode characters, but just in case you can revert to the
|
||||
# older behaviour by setting this to true.
|
||||
|
||||
@@ -329,6 +329,10 @@ Visual Studio Code (vscode)
|
||||
{
|
||||
"python.defaultInterpreterPath": "venv/bin/python",
|
||||
"python.formatting.provider": "black",
|
||||
"python.formatting.blackArgs": [
|
||||
"--config",
|
||||
"black.toml"
|
||||
],
|
||||
"editor.formatOnSave": true,
|
||||
"python.sortImports.args": [
|
||||
"--profile=black",
|
||||
|
||||
@@ -110,7 +110,7 @@ The subnet to use is usually the IP address range of your LAN, which sounds scar
|
||||
actually isn't. Just `figure out your PC's IP address and subnet mask <https://lifehacker.com/how-to-find-your-local-and-external-ip-address-5833108>`_
|
||||
and then combine both with a / in between.
|
||||
|
||||
On OctoPi (or another Linux distribution) you can use the following command:
|
||||
On OctoPi (or another Linux distribution) you can use the follwing command:
|
||||
|
||||
.. code-block::
|
||||
|
||||
@@ -165,7 +165,7 @@ further down there's also a dedicated list of steps for OctoPi specifically.
|
||||
|
||||
1. Shutdown OctoPrint
|
||||
2. Make a backup of your config.yaml
|
||||
3. Open it in a text editor (e.g. nano). Right at the very top it'll say something like
|
||||
3. Open it in a text editor (e.g. nano). Look if right at the very top it says something like
|
||||
this:
|
||||
|
||||
.. code-block:: yaml
|
||||
@@ -173,7 +173,7 @@ further down there's also a dedicated list of steps for OctoPi specifically.
|
||||
accessControl:
|
||||
salt: aabbccddee1234523452345
|
||||
|
||||
Edit this, adding lines so it looks like this (making absolutely sure not to touch the
|
||||
If so, edit this, adding lines so it looks like this (making absolutely sure not to touch the
|
||||
salt line):
|
||||
|
||||
.. code-block:: yaml
|
||||
@@ -187,9 +187,22 @@ further down there's also a dedicated list of steps for OctoPi specifically.
|
||||
- "::1/128"
|
||||
- "<yourAddressRange>"
|
||||
|
||||
Otherwise, add the following lines to the very top of the file, making sure to keep the
|
||||
indentation:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
accessControl:
|
||||
autologinLocal: true
|
||||
autologinAs: "<yourUsername>"
|
||||
localNetworks:
|
||||
- "127.0.0.0/8"
|
||||
- "::1/128"
|
||||
- "<yourAddressRange>"
|
||||
|
||||
4. Restart OctoPrint, check that everything works.
|
||||
|
||||
This will automatically log you in as the user you specified whenever you connect to
|
||||
This will automatically log you in as the user you specified whenver you connect to
|
||||
OctoPrint from an address in the address range (e.g. a device on your local network).
|
||||
|
||||
OctoPi specific steps
|
||||
@@ -200,7 +213,7 @@ the following commands:
|
||||
|
||||
1. ``sudo service octoprint stop``
|
||||
2. ``cp ~/.octoprint/config.yaml ~/.octoprint/config.yaml.back``
|
||||
3. ``nano ~/.octoprint/config.yaml, make the edits as described above``
|
||||
3. ``nano ~/.octoprint/config.yaml``, make the edits as described above
|
||||
4. ``sudo service octoprint start``
|
||||
|
||||
If something went wrong, you can restore the config backup with
|
||||
|
||||
@@ -44,7 +44,7 @@ a GCODE script including user input.
|
||||
- name: Example for multiple commands
|
||||
children:
|
||||
- name: Move X (static)
|
||||
confirm: You are about to move the X axis right by 10mm with 3000mm/min.
|
||||
confirm: You are about to move the X axis right by 10mm with 3000mm/s.
|
||||
commands:
|
||||
- G91
|
||||
- G1 X10 F3000
|
||||
|
||||
@@ -84,8 +84,6 @@ All GCODE scripts have access to the following template variables through the te
|
||||
to the corresponding temperature in degrees Celsius. Note that not all tools your printer has must necessarily be
|
||||
present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also
|
||||
note that ``actual`` and ``target`` might be ``None``.
|
||||
* ``last_fanspeed``: Last fan speed set. It contains the value taken from command (M106 and M107) sent through OctoPrint.
|
||||
The value might be ``None`` if no fan speed has been set.
|
||||
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
|
||||
and ``script.name`` respectively.
|
||||
* ``plugins``: An object containing variables provided by plugins (e.g ``plugins.myplugin.myvariable``)
|
||||
@@ -101,7 +99,6 @@ There are a few additional template variables available for the following specif
|
||||
"Log position on pause" under Settings > Serial > Advanced options!
|
||||
* ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
* ``pause_fanspeed``: Last known fan speed value when the print was paused. See ``last_fanspeed`` above for the structure to expect here.
|
||||
|
||||
* ``afterPrintCancelled``
|
||||
|
||||
@@ -112,7 +109,6 @@ There are a few additional template variables available for the following specif
|
||||
"Log position on cancel" under Settings > Serial > Advanced options!
|
||||
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
* ``cancel_fanspeed``: Last known fan speed value when the print was cancelled. See ``last_fanspeed`` above for the structure to expect here.
|
||||
|
||||
* ``beforeToolChange`` and ``afterToolChange``
|
||||
|
||||
|
||||
@@ -74,15 +74,39 @@
|
||||
|
||||
:returns string: The base url to use to access OctoPrint's API.
|
||||
|
||||
.. js:function:: OctoPrintClient.getRequestHeaders(additional)
|
||||
.. js:function:: OctoPrintClient.getCookie(name)
|
||||
|
||||
.. versionadded:: 1.8.3
|
||||
|
||||
Returns the value of the cookie with name ``name``. The port based cookie suffix and if
|
||||
necessary also the script root based suffix will be automatically applied to the ``name``
|
||||
prior to looking up the value.
|
||||
|
||||
:return string: The value of the cookie, if set & accessible, else an empty string.
|
||||
|
||||
.. js:function:: OctoPrintClient.getRequestHeaders(method, additional, opts)
|
||||
|
||||
.. versionchanged:: 1.8.3
|
||||
|
||||
Generates a dictionary of HTTP headers to use for API requests against OctoPrint with all
|
||||
necessary headers and any additionally provided ones.
|
||||
|
||||
At the moment this entails setting the ``X-Api-Key`` header based on the current value of
|
||||
``OctoPrint.options.apikey`` at a minimum.
|
||||
``OctoPrint.options.apikey``, if set. Otherwise, for non-cross-domain requests targeting
|
||||
methods other than ``GET``, ``HEAD`` or ``OPTIONS``, the current CSRF token is read from the
|
||||
associated cookie and set as ``X-CSRF-Token``.
|
||||
|
||||
:param object additional: Additional headers to add to the request.
|
||||
.. note::
|
||||
|
||||
Up until OctoPrint 1.8.3, this method's signature consisted only of the ``additional``
|
||||
parameter. It has been changed in a backward compatible way so that calling it with the
|
||||
first parameter being the set of additional headers will still work. This mode of operation
|
||||
is deprecated however and will be removed in a future version.
|
||||
A warning will be logged to the debug console accordingly.
|
||||
|
||||
:param str method: Method of the request for which to set headers
|
||||
:param object additional: Additional headers to add to the request, optional.
|
||||
:param object opts: Additional opts passed to the request, used to read cross domain setting, optional.
|
||||
:returns object: HTTP headers to use for requests.
|
||||
|
||||
.. js:function:: OctoPrintClient.ajax(method, url, opts)
|
||||
|
||||
@@ -20,7 +20,7 @@ development environment::
|
||||
$ virtualenv venv
|
||||
[...]
|
||||
$ source venv/bin/activate
|
||||
(venv) $ pip install -e .[develop,plugins]
|
||||
(venv) $ pip install -e '.[develop,plugins]'
|
||||
[...]
|
||||
(venv) $ octoprint --help
|
||||
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
|
||||
@@ -55,6 +55,7 @@ development environment::
|
||||
We'll start at the most basic form a plugin can take - just a few simple lines of Python code:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0.0"
|
||||
@@ -90,7 +91,8 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
|
||||
"Hello World!" to the log upon server startup. Modify our ``helloworld.py`` like this:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 1-5,11
|
||||
:emphasize-lines: 4-8,14
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -118,7 +120,7 @@ up and ready to serve requests.
|
||||
|
||||
You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system
|
||||
injects :ref:`a some useful objects <sec-plugins-mixins-injectedproperties>` into our plugin implementation classes,
|
||||
one of those being a fully instantiated :py:mod:`python logger <logging>` ready to be
|
||||
one of those being a fully instantiated :ref:`python logger <logging>` ready to be
|
||||
used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld``
|
||||
for our little plugin here, or more generally ``octoprint.plugins.<plugin identifier>``.
|
||||
|
||||
@@ -161,7 +163,7 @@ Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a ne
|
||||
email [you@example.com]: you@somewhere.net
|
||||
github_username [you]: yourGithubName
|
||||
plugin_version [0.1.0]: 1.0.0
|
||||
plugin_description [TODO]: A quick "Hello World" example plugin for OCtoPrint
|
||||
plugin_description [TODO]: A quick "Hello World" example plugin for OctoPrint
|
||||
plugin_license [AGPLv3]:
|
||||
plugin_homepage [https://github.com/yourGithubName/OctoPrint-Helloworld]:
|
||||
plugin_source [https://github.com/yourGithubName/OctoPrint-Helloworld]:
|
||||
@@ -176,6 +178,9 @@ Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a ne
|
||||
This will create a project structure in the ``OctoPrint-HelloWorld`` folder we just changed to that looks like this::
|
||||
|
||||
extras/
|
||||
github/
|
||||
bug_report.yml
|
||||
feature_request.yml
|
||||
README.txt
|
||||
helloworld.md
|
||||
octoprint_helloworld/
|
||||
@@ -198,6 +203,7 @@ This will create a project structure in the ``OctoPrint-HelloWorld`` folder we j
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
setup.cfg
|
||||
|
||||
While we'll need some of those folders later on, we'll now delete everything that we don't need right now first, that
|
||||
will make it easier to understand what folder does what later on. Delete the following folders and anything in them:
|
||||
@@ -217,6 +223,7 @@ The final project structure should look like this for now::
|
||||
MANIFEST.in
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.cfg
|
||||
setup.py
|
||||
|
||||
Out of curiosity, take a look into the ``setup.py`` file. The cookiecutter template should have prefilled all the
|
||||
@@ -268,6 +275,7 @@ Something is still a bit ugly though. Take a look into ``__init__.py`` and ``set
|
||||
of information now defined twice:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: __init__.py
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
@@ -275,6 +283,7 @@ of information now defined twice:
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: setup.py
|
||||
|
||||
plugin_name = "OctoPrint-HelloWorld"
|
||||
@@ -286,6 +295,7 @@ within ``setup.py``! So, we don't really need to define all this data twice. Rem
|
||||
and ``__plugin_description__`` from ``__init__.py``, but leave ``__plugin_implementation__`` and ``__plugin_pythoncompat__``:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -308,6 +318,7 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 7
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -353,6 +364,7 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 4
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -369,6 +381,7 @@ Next, we'll create a sub folder ``templates`` underneath our ``octoprint_hellowo
|
||||
``helloworld_navbar.jinja2`` like so:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<a href="https://en.wikipedia.org/wiki/Hello_world">Hello World!</a>
|
||||
|
||||
@@ -385,6 +398,7 @@ Our plugin's directory structure should now look like this::
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
setup.cfg
|
||||
|
||||
Restart OctoPrint and open the web interface in your browser (make sure to clear your browser's cache!).
|
||||
|
||||
@@ -415,6 +429,7 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 5, 7, 9-10
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -446,6 +461,7 @@ Adjust your plugin's ``__init__.py`` like this:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 12-13
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -468,6 +484,7 @@ Adjust your plugin's ``__init__.py`` like this:
|
||||
Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<a href="{{ plugin_helloworld_url|escape }}">Hello World!</a>
|
||||
|
||||
@@ -504,6 +521,7 @@ So in your plugin's ``templates`` folder create a new file ``helloworld_settings
|
||||
into it:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
@@ -525,6 +543,7 @@ Now adjust your ``templates/helloworld_navbar.jinja2`` file to use a ``data-bind
|
||||
settings view model into the ``href`` attribute of the link tag:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<a href="#" data-bind="attr: {href: settings.settings.plugins.helloworld.url}">Hello World!</a>
|
||||
|
||||
@@ -547,6 +566,7 @@ again since we don't use that anymore:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 12-16
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -604,6 +624,7 @@ First let us create the Jinja2 template for our tab. In your plugin's ``template
|
||||
``helloworld_tab.jinja2`` like so:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
|
||||
@@ -633,6 +654,7 @@ look like this::
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
setup.cfg
|
||||
|
||||
We need to tell OctoPrint about this new static asset so that it will properly inject it into the page. For this we
|
||||
just need to subclass :class:`~octoprint.plugin.AssetPlugin` and override its method :func:`~octoprint.plugin.AssetPlugin.get_assets`
|
||||
@@ -640,6 +662,7 @@ like so:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 6,19-22
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -677,6 +700,7 @@ Then we'll create our custom `Knockout <http://knockoutjs.com/documentation/intr
|
||||
like so:
|
||||
|
||||
.. code-block:: javascript
|
||||
:linenos:
|
||||
|
||||
$(function() {
|
||||
function HelloWorldViewModel(parameters) {
|
||||
@@ -751,6 +775,7 @@ So it appears that this stuff is working great already. Only one thing is a bit
|
||||
our ``helloworld_tab.jinja2``:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
:emphasize-lines: 6
|
||||
|
||||
<div class="input-append">
|
||||
@@ -789,6 +814,7 @@ First we'll create a new folder within our plugin's ``static`` folder called ``c
|
||||
Put something like the following into ``helloworld.css``:
|
||||
|
||||
.. code-block:: css
|
||||
:linenos:
|
||||
|
||||
#tab_plugin_helloworld iframe {
|
||||
width: 100%;
|
||||
@@ -799,6 +825,7 @@ Put something like the following into ``helloworld.css``:
|
||||
Don't forget to remove the ``style`` attribute from the ``iframe`` tag in ``helloworld_tab.jinja2``:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
:emphasize-lines: 6
|
||||
|
||||
<div class="input-append">
|
||||
@@ -813,6 +840,7 @@ a reference to our CSS file:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 23
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -895,6 +923,7 @@ Then adjust our returned assets to include our LESS file as well:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 24
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -944,6 +973,7 @@ source code. In the ``head`` section of the page you'll see that instead of your
|
||||
embedded the ``helloworld.less`` file instead:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
:emphasize-lines: 5
|
||||
|
||||
<head>
|
||||
@@ -972,6 +1002,7 @@ setting it to ``css``, e.g.
|
||||
Restart and shift-reload and take another look at the ``head``:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
:emphasize-lines: 5
|
||||
|
||||
<head>
|
||||
@@ -1001,6 +1032,7 @@ stop it from doing that at the start of this section, we should switch this back
|
||||
Just out of curiosity, restart, shift-reload and take a final look at the ``head``:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
:emphasize-lines: 3-5
|
||||
|
||||
<head>
|
||||
|
||||
@@ -11,6 +11,7 @@ An example for providing some helper functions to the system can be found in the
|
||||
which provides its SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:emphasize-lines: 11-20
|
||||
:caption: Excerpt from the Discovery Plugin showing the declaration of its exported helpers.
|
||||
:name: sec-plugin-concepts-helpers-example-export
|
||||
@@ -41,6 +42,7 @@ Using :meth:`~octoprint.plugin.code.PluginManager.get_helpers` plugins can retri
|
||||
them as (hopefully) documented.
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:emphasize-lines: 6-8,20
|
||||
:caption: Excerpt from the Growl Plugin showing utilization of the helpers published by the Discovery Plugin.
|
||||
:name: sec-plugin-concepts-helpers-example-usage
|
||||
|
||||
+29
-2
@@ -26,6 +26,7 @@ lines to OctoPrint's :ref:`GCODE scripts <sec-features-gcode_scripts>`, either a
|
||||
or as ``postfix`` (after the existing lines).
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts")
|
||||
|
||||
@@ -74,6 +75,7 @@ property instead, manually instantiate your implementation instance and then add
|
||||
``__plugin_hooks__`` property and itself to the ``__plugin_implementation__`` property. See the following example.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_action_command.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_action_command.py>`__
|
||||
:name: sec-plugin-concepts-hooks-example
|
||||
@@ -93,6 +95,7 @@ An example should help clear this up. Let's assume we have the following plugin
|
||||
hook called ``octoprint.plugin.ordertest.callback``:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: ordertest.py
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -117,6 +120,7 @@ hook called ``octoprint.plugin.ordertest.callback``:
|
||||
And these three plugins defining handlers for that hook:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: oneorderedhook.py
|
||||
|
||||
import logging
|
||||
@@ -131,6 +135,7 @@ And these three plugins defining handlers for that hook:
|
||||
}
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: anotherorderedhook.py
|
||||
|
||||
import logging
|
||||
@@ -145,6 +150,7 @@ And these three plugins defining handlers for that hook:
|
||||
}
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: yetanotherhook.py
|
||||
|
||||
import logging
|
||||
@@ -231,7 +237,7 @@ octoprint.access.permissions
|
||||
.. code-block:: python
|
||||
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
|
||||
|
||||
def get_additional_permissions(*args, **kwargs):
|
||||
return [
|
||||
dict(key="ADMIN",
|
||||
@@ -310,6 +316,7 @@ octoprint.accesscontrol.keyvalidator
|
||||
and merely provided for educational purposes):
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_keyvalidator.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_keyvalidator.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_keyvalidator.py>`_
|
||||
|
||||
@@ -343,6 +350,7 @@ octoprint.cli.commands
|
||||
OctoPrint:
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_cli_command.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_cli_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_cli_command.py>`_
|
||||
|
||||
@@ -535,6 +543,7 @@ octoprint.comm.protocol.action
|
||||
Logs if the ``custom`` action (``// action:custom``) is received from the printer's firmware.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_action_command.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_action_command.py>`__
|
||||
|
||||
@@ -585,6 +594,7 @@ This describes actually two hooks:
|
||||
different name).
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_atcommand.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_atcommand.py>`__
|
||||
|
||||
@@ -739,6 +749,7 @@ This actually describes four hooks:
|
||||
parameter) upon queuing and logs all sent ``M106``.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/rewrite_m107.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `rewrite_m107.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/rewrite_m107.py>`_
|
||||
|
||||
@@ -781,6 +792,7 @@ octoprint.comm.protocol.gcode.received
|
||||
Looks for the response of an ``M115``, which contains information about the ``MACHINE_TYPE``, among other things.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/read_m115_response.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `read_m115_response.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/read_m115_response.py>`_
|
||||
|
||||
@@ -819,6 +831,7 @@ octoprint.comm.protocol.gcode.error
|
||||
plugin.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/comm_error_handler_test.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `comm_error_handler_test.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/comm_error_handler_test.py>`_
|
||||
|
||||
@@ -855,6 +868,7 @@ octoprint.comm.protocol.scripts
|
||||
Appends an ``M117 OctoPrint connected`` to the configured ``afterPrinterConnected`` GCODE script.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/message_on_connect.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `message_on_connect.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/message_on_connect.py>`_
|
||||
|
||||
@@ -863,6 +877,7 @@ octoprint.comm.protocol.scripts
|
||||
Provides the variable ``myvariable`` to the configured ``beforePrintStarted`` GCODE script.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/gcode_script_variables.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `gcode_script_variables.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/gcode_script_variables.py>`_
|
||||
|
||||
@@ -903,6 +918,7 @@ octoprint.comm.protocol.temperatures.received
|
||||
The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/sanitize_temperatures.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `sanitize_temperatures.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/sanitize_temperatures.py>`_
|
||||
|
||||
@@ -968,6 +984,7 @@ octoprint.comm.transport.serial.factory
|
||||
or ``AUTO``.
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
def default(comm_instance, port, baudrate, connection_timeout):
|
||||
if port is None or port == 'AUTO':
|
||||
@@ -1026,6 +1043,7 @@ octoprint.events.register_custom_events
|
||||
and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``.
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
def register_custom_events(*args, **kwargs):
|
||||
return ["my_custom_event", "my_other_custom_event"]
|
||||
@@ -1060,6 +1078,7 @@ octoprint.filemanager.analysis.factory
|
||||
The following handler would replace the existing analysis queue for ``gcode`` files with a custom implementation:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from octoprint.filemanager.analysis import AbstractAnalysisQueue
|
||||
|
||||
@@ -1092,6 +1111,7 @@ octoprint.filemanager.extension_tree
|
||||
and ``s3g``:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
def support_x3g_machinecode(*args, **kwargs):
|
||||
return dict(
|
||||
@@ -1132,6 +1152,7 @@ octoprint.filemanager.preprocessor
|
||||
The following plugin example strips all comments from uploaded/generated GCODE files ending on the name postfix ``_strip``.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/strip_all_comments.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `strip_all_comments.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/strip_all_comments.py>`_
|
||||
|
||||
@@ -1433,7 +1454,7 @@ octoprint.server.http.access_validator
|
||||
|
||||
Allows adding additional access validators to the default tornado routers.
|
||||
|
||||
Your plugin might need to this to restrict access to downloads and webcam snapshots further.
|
||||
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further.
|
||||
|
||||
.. important::
|
||||
|
||||
@@ -1475,6 +1496,7 @@ octoprint.server.http.bodysize
|
||||
size (as multipart request with the file upload residing in request parameter ``file``) and observe the behaviour.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/increase_bodysize.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `increase_bodysize.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/increase_bodysize.py>`_
|
||||
|
||||
@@ -1534,6 +1556,7 @@ octoprint.server.http.routes
|
||||
in the webserver which roughly replicate the functionality of ``/downloads/files/local`` and ``/downloads/camera/current``.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/add_tornado_route.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `add_tornado_route.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/add_tornado_route.py>`_
|
||||
|
||||
@@ -1823,20 +1846,24 @@ octoprint.ui.web.templatetypes
|
||||
First the provider:
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_template_provider/__init__.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_template_provider/__init__.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_template_provider/__init__.py>`_
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_template_provider/templates/custom_template_provider_settings.jinja2
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_template_provider/templates/custom_template_provider_settings.jinja2 <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_template_provider/templates/custom_template_provider_settings.jinja2>`_
|
||||
|
||||
Then the consumer:
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_template_consumer/__init__.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_template_consumer/__init__.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_template_consumer/__init__.py>`_
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_template_consumer/templates/custom_template_consumer_awesometemplate.jinja2
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_template_consumer/templates/custom_template_consumer_awesometemplate.jinja2 <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_template_consumer/templates/custom_template_consumer_awesometemplate.jinja2>`_
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ merged into one big asset map (differing between javascripts and stylesheets of
|
||||
rendition of the UI.
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
|
||||
for name, implementation in asset_plugins.items():
|
||||
@@ -78,6 +79,7 @@ and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get
|
||||
``plugin_b`` and ``plugin_c`` both return ``1`` for the sorting context ``StartupPlugin.on_startup``, ``None`` otherwise:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: plugin_a.py
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -93,6 +95,7 @@ and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get
|
||||
__plugin_implementation__ = PluginA()
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: plugin_b.py
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -113,6 +116,7 @@ and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get
|
||||
__plugin_implementation__ = PluginB()
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: plugin_c.py
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -134,6 +138,7 @@ and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get
|
||||
__plugin_implementation__ = PluginC()
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
:caption: plugin_d.py
|
||||
|
||||
# in this example this is bundled with OctoPrint
|
||||
|
||||
@@ -235,7 +235,7 @@ will now fail with an error. You'll need to explicitly make the import a relativ
|
||||
|
||||
from . import my_sub_package
|
||||
|
||||
To make your code behave the same in that regard in both Python 2 and Python 3, you should add the corresponding
|
||||
To make your code behave the same in that regard unter both Python 2 and Python 3, you should add the corresponding
|
||||
future import:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -31,9 +31,10 @@ SETUP_REQUIRES = []
|
||||
bundled_plugins = [
|
||||
"OctoPrint-FileCheck>=2021.2.23",
|
||||
"OctoPrint-FirmwareCheck>=2021.10.11",
|
||||
"OctoPrint-PiSupport>=2022.3.28",
|
||||
"OctoPrint-PiSupport>=2022.6.13",
|
||||
]
|
||||
core_deps = [
|
||||
"argon2_cffi>=21.3.0,<22",
|
||||
"cachelib>=0.2,<0.3",
|
||||
"Click>=8.0.3,<9",
|
||||
"colorlog>=6,<7",
|
||||
@@ -42,13 +43,15 @@ core_deps = [
|
||||
"filetype>=1.0.7,<2",
|
||||
"Flask-Assets>=2.0,<3",
|
||||
"Flask-Babel>=2.0,<3",
|
||||
"Flask-Login>=0.6,<0.7", # breaking changes can happen on minor version increases
|
||||
"flask>=2,<3",
|
||||
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
|
||||
"Flask-Limiter>=2.6,<3",
|
||||
"flask>=2.1,<2.2", # flask 2.2 requires werkzeug 2.2+
|
||||
"frozendict>=2.0,<3",
|
||||
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
|
||||
"markdown>=3.2.2,<4",
|
||||
"netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases
|
||||
"netifaces>=0.11,<1",
|
||||
"passlib>=1.7.4,<2",
|
||||
"pathvalidate>=2.4.1,<3",
|
||||
"pkginfo>=1.7.1,<2",
|
||||
"psutil>=5.8,<6",
|
||||
@@ -62,12 +65,10 @@ core_deps = [
|
||||
"tornado>=6.0.4,<7",
|
||||
"watchdog>=1,<2",
|
||||
"websocket-client>=1.2.1,<2",
|
||||
"werkzeug>=2.1,<2.2", # breaking changes can happen on minor version increases
|
||||
"werkzeug>=2.0,<2.1", # breaking changes can happen on minor version increases, flask-login 0.5 is incompatible with 2.1
|
||||
"wrapt>=1.14,<1.15",
|
||||
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
|
||||
"zipstream-ng>=1.3.4,<2.0.0",
|
||||
"pydantic>=1.9.1,<2",
|
||||
"pydantic-settings>=0.2.5,<1", # TODO: replace with vendored with_attrs_docs
|
||||
]
|
||||
vendored_deps = [
|
||||
"blinker>=1.4,<2", # dependency of flask_principal
|
||||
@@ -99,11 +100,11 @@ EXTRA_REQUIRES = {
|
||||
"plugins": ["cookiecutter>=1.7.2,<1.8"],
|
||||
# Dependencies for building the documentation
|
||||
"docs": [
|
||||
"readthedocs-sphinx-ext>=2.1.5,<3",
|
||||
"sphinx_rtd_theme>=1,<2",
|
||||
"sphinx>=4,<5",
|
||||
"sphinxcontrib-httpdomain>=1.8.0,<2",
|
||||
"sphinxcontrib-mermaid>=0.7.1,<0.8",
|
||||
"readthedocs-sphinx-ext",
|
||||
"sphinx_rtd_theme",
|
||||
"sphinx>=3,<4",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
+28
-28
@@ -497,8 +497,8 @@ def init_settings_plugin_config_migration_and_cleanup(plugin_manager):
|
||||
)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while trying to migrate settings for " "plugin %s, ignoring it",
|
||||
implementation._identifier,
|
||||
"Error while trying to migrate settings for "
|
||||
"plugin {}, ignoring it".format(implementation._identifier),
|
||||
extra={"plugin": implementation._identifier},
|
||||
)
|
||||
|
||||
@@ -526,16 +526,13 @@ def init_custom_events(plugin_manager):
|
||||
event, prefix=f"plugin_{name}_"
|
||||
)
|
||||
logger.debug(
|
||||
'Registered event %s of plugin %s as Events. %s = "%s"',
|
||||
event,
|
||||
name,
|
||||
constant,
|
||||
value,
|
||||
'Registered event {} of plugin {} as Events.{} = "{}"'.format(
|
||||
event, name, constant, value
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Error while retrieving custom event list from plugin %s",
|
||||
name,
|
||||
f"Error while retrieving custom event list from plugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
|
||||
@@ -664,7 +661,7 @@ def init_pluginsystem(
|
||||
disabled_from_overlays[name] = (disabled_plugins, order)
|
||||
|
||||
settings_overlays[name] = overlay
|
||||
logger.debug("Found settings overlay on plugin %s", name)
|
||||
logger.debug(f"Found settings overlay on plugin {name}")
|
||||
|
||||
def handle_plugins_loaded(
|
||||
startup=False, initialize_implementations=True, force_reload=None
|
||||
@@ -689,22 +686,24 @@ def init_pluginsystem(
|
||||
|
||||
if addon in already_processed:
|
||||
logger.info(
|
||||
"Plugin %s wants to disable plugin %s, but that was already processed",
|
||||
name,
|
||||
addon,
|
||||
"Plugin {} wants to disable plugin {}, but that was already processed".format(
|
||||
name, addon
|
||||
)
|
||||
)
|
||||
|
||||
if addon not in already_processed and addon not in disabled_list:
|
||||
disabled_list.append(addon)
|
||||
logger.info(
|
||||
"Disabling plugin %s as defined by plugin %s", addon, name
|
||||
"Disabling plugin {} as defined by plugin {}".format(
|
||||
addon, name
|
||||
)
|
||||
)
|
||||
already_processed.append(name)
|
||||
|
||||
def handle_plugin_enabled(name, plugin):
|
||||
if name in settings_overlays:
|
||||
settings.add_overlay(settings_overlays[name])
|
||||
logger.info("Added settings overlay from plugin %s", name)
|
||||
logger.info(f"Added settings overlay from plugin {name}")
|
||||
|
||||
pm.on_plugin_loaded = handle_plugin_loaded
|
||||
pm.on_plugins_loaded = handle_plugins_loaded
|
||||
@@ -757,22 +756,22 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
|
||||
if "pluginversions" in entry:
|
||||
logger.debug(
|
||||
"Blacklisted plugin: %s, versions: %s",
|
||||
entry["plugin"],
|
||||
", ".join(entry["pluginversions"]),
|
||||
"Blacklisted plugin: {}, versions: {}".format(
|
||||
entry["plugin"], ", ".join(entry["pluginversions"])
|
||||
)
|
||||
)
|
||||
for version in entry["pluginversions"]:
|
||||
result.append((entry["plugin"], version))
|
||||
elif "versions" in entry:
|
||||
logger.debug(
|
||||
"Blacklisted plugin: %s, versions: %s",
|
||||
entry["plugin"],
|
||||
", ".join(entry["versions"]),
|
||||
"Blacklisted plugin: {}, versions: {}".format(
|
||||
entry["plugin"], ", ".join(entry["versions"])
|
||||
)
|
||||
)
|
||||
for version in entry["versions"]:
|
||||
result.append((entry["plugin"], f"=={version}"))
|
||||
else:
|
||||
logger.debug("Blacklisted plugin: %s", entry["plugin"])
|
||||
logger.debug("Blacklisted plugin: {}".format(entry["plugin"]))
|
||||
result.append(entry["plugin"])
|
||||
|
||||
return result
|
||||
@@ -809,9 +808,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"Unable to fetch plugin blacklist from %s, proceeding without it: %s",
|
||||
url,
|
||||
e,
|
||||
"Unable to fetch plugin blacklist from {}, proceeding without it: {}".format(
|
||||
url, e
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -833,9 +832,10 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
|
||||
if blacklist:
|
||||
logger.info(
|
||||
"Blacklist processing done, adding %s blacklisted plugin versions: %s",
|
||||
len(blacklist),
|
||||
format_blacklist(blacklist),
|
||||
"Blacklist processing done, "
|
||||
"adding {} blacklisted plugin versions: {}".format(
|
||||
len(blacklist), format_blacklist(blacklist)
|
||||
)
|
||||
)
|
||||
else:
|
||||
logger.info("Blacklist processing done")
|
||||
|
||||
+124
-59
@@ -4,11 +4,13 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import wrapt
|
||||
from flask_login import AnonymousUserMixin, UserMixin
|
||||
from passlib.hash import pbkdf2_sha256
|
||||
from werkzeug.local import LocalProxy
|
||||
|
||||
from octoprint.access.groups import Group, GroupChangeListener
|
||||
@@ -18,6 +20,23 @@ from octoprint.util import atomic_write, deprecated, generate_api_key
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
from octoprint.util import to_bytes, yaml
|
||||
|
||||
password_hashers = []
|
||||
|
||||
try:
|
||||
from passlib.hash import argon2
|
||||
|
||||
# test if we can actually hash and verify, if not we won't use this backend
|
||||
hash = argon2.hash("test")
|
||||
argon2.verify("test", hash)
|
||||
|
||||
password_hashers.append(argon2)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning(
|
||||
"Argon2 passlib backend is not available, not using it for password hashing"
|
||||
)
|
||||
|
||||
password_hashers.append(pbkdf2_sha256)
|
||||
|
||||
|
||||
class UserManager(GroupChangeListener):
|
||||
def __init__(self, group_manager, settings=None):
|
||||
@@ -127,29 +146,18 @@ class UserManager(GroupChangeListener):
|
||||
for session, user in list(self._session_users_by_session.items()):
|
||||
if not isinstance(user, SessionUser):
|
||||
continue
|
||||
if user.created + (24 * 60 * 60) < time.monotonic():
|
||||
if user.touched + (15 * 60) < time.monotonic():
|
||||
self._logger.info(
|
||||
"Cleaning up user session {} for user {}".format(
|
||||
session, user.get_id()
|
||||
)
|
||||
f"Cleaning up user session {session} for user {user.get_id()}"
|
||||
)
|
||||
self.logout_user(user, stale=True)
|
||||
|
||||
@staticmethod
|
||||
def create_password_hash(password, salt=None, settings=None):
|
||||
if not salt:
|
||||
if settings is None:
|
||||
settings = s()
|
||||
salt = settings.get(["accessControl", "salt"])
|
||||
if salt is None:
|
||||
import string
|
||||
from random import choice
|
||||
|
||||
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
|
||||
salt = "".join(choice(chars) for _ in range(32))
|
||||
settings.set(["accessControl", "salt"], salt)
|
||||
settings.save()
|
||||
def create_password_hash(password, *args, **kwargs):
|
||||
return password_hashers[0].hash(password)
|
||||
|
||||
@staticmethod
|
||||
def create_legacy_password_hash(password, salt):
|
||||
return hashlib.sha512(
|
||||
to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)
|
||||
).hexdigest()
|
||||
@@ -159,23 +167,34 @@ class UserManager(GroupChangeListener):
|
||||
if not user:
|
||||
return False
|
||||
|
||||
hash = UserManager.create_password_hash(password, settings=self._settings)
|
||||
if user.check_password(hash):
|
||||
# new hash matches, correct password
|
||||
if user.check_password(password):
|
||||
# password matches, correct password
|
||||
return True
|
||||
else:
|
||||
# new hash doesn't match, but maybe the old one does, so check that!
|
||||
oldHash = UserManager.create_password_hash(
|
||||
password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW", settings=self._settings
|
||||
# new hash doesn't match, check legacy hash
|
||||
salt = self._settings.get(["accessControl"], asdict=True, merged=True).get(
|
||||
"salt", None
|
||||
)
|
||||
if user.check_password(oldHash):
|
||||
# old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
|
||||
if salt is None:
|
||||
return False
|
||||
|
||||
legacy_hash = UserManager.create_legacy_password_hash(password, salt)
|
||||
if user.check_password(legacy_hash, legacy=True):
|
||||
# legacy hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
|
||||
self.change_user_password(username, password)
|
||||
return True
|
||||
else:
|
||||
# old hash doesn't match either, wrong password
|
||||
# legacy hash doesn't match either, wrong password
|
||||
return False
|
||||
|
||||
def cleanup_legacy_hashes(self):
|
||||
pass
|
||||
|
||||
def signature_key_for_user(self, username, secret):
|
||||
return hashlib.sha512(
|
||||
to_bytes(username, encoding="utf-8", errors="replace") + to_bytes(secret)
|
||||
).hexdigest()
|
||||
|
||||
def add_user(self, username, password, active, permissions, groups, overwrite=False):
|
||||
pass
|
||||
|
||||
@@ -227,21 +246,28 @@ class UserManager(GroupChangeListener):
|
||||
del self._sessionids_by_userid[username]
|
||||
|
||||
def validate_user_session(self, userid, session):
|
||||
self._cleanup_sessions()
|
||||
|
||||
if session in self._session_users_by_session:
|
||||
user = self._session_users_by_session[session]
|
||||
return userid == user.get_id()
|
||||
|
||||
return False
|
||||
|
||||
def find_user(self, userid=None, session=None):
|
||||
def find_user(self, userid=None, session=None, fresh=False):
|
||||
self._cleanup_sessions()
|
||||
|
||||
if session is not None and session in self._session_users_by_session:
|
||||
user = self._session_users_by_session[session]
|
||||
if userid is None or userid == user.get_id():
|
||||
user.touch()
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
def find_sessions_for(self, matcher):
|
||||
self._cleanup_sessions()
|
||||
|
||||
result = []
|
||||
for user in self.get_all_users():
|
||||
if matcher(user):
|
||||
@@ -249,7 +275,9 @@ class UserManager(GroupChangeListener):
|
||||
session_ids = self._sessionids_by_userid[user.get_id()]
|
||||
for session_id in session_ids:
|
||||
try:
|
||||
result.append(self._session_users_by_session[session_id])
|
||||
session_user = self._session_users_by_session[session_id]
|
||||
session_user.touch()
|
||||
result.append(session_user)
|
||||
except KeyError:
|
||||
# unknown session after all
|
||||
continue
|
||||
@@ -339,23 +367,6 @@ class UserManager(GroupChangeListener):
|
||||
|
||||
# TODO: Remove deprecated methods in OctoPrint 1.5.0
|
||||
|
||||
@staticmethod
|
||||
def createPasswordHash(*args, **kwargs):
|
||||
"""
|
||||
.. deprecated: 1.4.0
|
||||
|
||||
Replaced by :func:`~UserManager.create_password_hash`
|
||||
"""
|
||||
# we can't use the deprecated decorator here since this method is static
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"createPasswordHash has been renamed to create_password_hash",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return UserManager.create_password_hash(*args, **kwargs)
|
||||
|
||||
@deprecated(
|
||||
"changeUserRoles has been replaced by change_user_permissions",
|
||||
includedoc="Replaced by :func:`change_user_permissions`",
|
||||
@@ -489,6 +500,8 @@ class LoginStatusListener:
|
||||
|
||||
|
||||
class FilebasedUserManager(UserManager):
|
||||
FILE_VERSION = 2
|
||||
|
||||
def __init__(self, group_manager, path=None, settings=None):
|
||||
UserManager.__init__(self, group_manager, settings=settings)
|
||||
|
||||
@@ -520,6 +533,17 @@ class FilebasedUserManager(UserManager):
|
||||
)
|
||||
raise CorruptUserStorage()
|
||||
|
||||
version = data.pop("_version", 1)
|
||||
if version != self.FILE_VERSION:
|
||||
self._logger.info(
|
||||
f"Making a backup of the users.yaml file before migrating from version {version} to {self.FILE_VERSION}"
|
||||
)
|
||||
shutil.copy(
|
||||
self._userfile,
|
||||
os.path.splitext(self._userfile)[0] + f".v{version}.yaml",
|
||||
)
|
||||
self._dirty = True
|
||||
|
||||
for name, attributes in data.items():
|
||||
if not isinstance(attributes, dict):
|
||||
continue
|
||||
@@ -567,6 +591,8 @@ class FilebasedUserManager(UserManager):
|
||||
if self._dirty:
|
||||
self._save()
|
||||
|
||||
self.cleanup_legacy_hashes()
|
||||
|
||||
self._customized = True
|
||||
else:
|
||||
self._customized = False
|
||||
@@ -575,7 +601,7 @@ class FilebasedUserManager(UserManager):
|
||||
if not self._dirty and not force:
|
||||
return
|
||||
|
||||
data = {}
|
||||
data = {"_version": self.FILE_VERSION}
|
||||
for name, user in self._users.items():
|
||||
if not user or not isinstance(user, User):
|
||||
continue
|
||||
@@ -618,11 +644,11 @@ class FilebasedUserManager(UserManager):
|
||||
apikey=None,
|
||||
overwrite=False,
|
||||
):
|
||||
if not permissions:
|
||||
if permissions is None:
|
||||
permissions = []
|
||||
permissions = self._to_permissions(*permissions)
|
||||
|
||||
if not groups:
|
||||
if groups is None:
|
||||
groups = self._group_manager.default_groups
|
||||
groups = self._to_groups(*groups)
|
||||
|
||||
@@ -773,12 +799,42 @@ class FilebasedUserManager(UserManager):
|
||||
if username not in self._users:
|
||||
raise UnknownUser(username)
|
||||
|
||||
passwordHash = UserManager.create_password_hash(password, settings=self._settings)
|
||||
user = self._users[username]
|
||||
if user._passwordHash != passwordHash:
|
||||
user._passwordHash = passwordHash
|
||||
self._dirty = True
|
||||
self._save()
|
||||
user._passwordHash = UserManager.create_password_hash(password)
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
self._trigger_on_user_modified(user)
|
||||
|
||||
def cleanup_legacy_hashes(self):
|
||||
no_legacy = all(
|
||||
map(
|
||||
lambda u: u._passwordHash.startswith("$argon2id$")
|
||||
or u._passwordHash.startswith("$pbkdf2-"),
|
||||
self._users.values(),
|
||||
)
|
||||
)
|
||||
salt = self._settings.get(["accessControl"], asdict=True, merged=True).get(
|
||||
"salt", None
|
||||
)
|
||||
|
||||
if no_legacy and salt:
|
||||
# no legacy hashs left, kill salt
|
||||
self._settings.backup("cleanup_legacy_hashes")
|
||||
self._settings.remove(["accessControl", "salt"])
|
||||
self._settings.save()
|
||||
|
||||
def signature_key_for_user(self, username, secret):
|
||||
if username == "_api":
|
||||
return super().signature_key_for_user(username, secret)
|
||||
if username not in self._users:
|
||||
raise UnknownUser(username)
|
||||
user = self._users[username]
|
||||
|
||||
return hashlib.sha512(
|
||||
to_bytes(username + user._passwordHash, encoding="utf-8", errors="replace")
|
||||
+ to_bytes(secret)
|
||||
).hexdigest()
|
||||
|
||||
def change_user_setting(self, username, key, value):
|
||||
if username not in self._users:
|
||||
@@ -845,10 +901,10 @@ class FilebasedUserManager(UserManager):
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def find_user(self, userid=None, apikey=None, session=None):
|
||||
def find_user(self, userid=None, apikey=None, session=None, fresh=False):
|
||||
user = UserManager.find_user(self, userid=userid, session=session)
|
||||
|
||||
if user is not None:
|
||||
if user is not None or (session and fresh):
|
||||
return user
|
||||
|
||||
if userid is not None:
|
||||
@@ -1126,8 +1182,18 @@ class User(UserMixin):
|
||||
"roles": self._roles,
|
||||
}
|
||||
|
||||
def check_password(self, passwordHash):
|
||||
return self._passwordHash == passwordHash
|
||||
def check_password(self, password, legacy=False):
|
||||
if legacy:
|
||||
return self._passwordHash == password
|
||||
|
||||
for password_hash in password_hashers:
|
||||
if password_hash.identify(self._passwordHash):
|
||||
try:
|
||||
return password_hash.verify(password, self._passwordHash)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return False
|
||||
|
||||
def get_id(self):
|
||||
return self.get_name()
|
||||
@@ -1383,8 +1449,7 @@ class SessionUser(wrapt.ObjectProxy):
|
||||
wrapt.ObjectProxy.__init__(self, user)
|
||||
|
||||
self._self_session = "".join("%02X" % z for z in bytes(uuid.uuid4().bytes))
|
||||
self._self_created = time.monotonic()
|
||||
self._self_touched = time.monotonic()
|
||||
self._self_created = self._self_touched = time.monotonic()
|
||||
|
||||
@property
|
||||
def session(self):
|
||||
|
||||
@@ -954,6 +954,12 @@ class LocalFileStorage(StorageInterface):
|
||||
source, destination, must_not_equal=True
|
||||
)
|
||||
|
||||
if not octoprint.filemanager.valid_file_type(destination_data["name"]):
|
||||
raise StorageError(
|
||||
f"{destination_data['name']} is an unrecognized file type",
|
||||
code=StorageError.INVALID_FILE,
|
||||
)
|
||||
|
||||
try:
|
||||
shutil.copy2(source_data["fullpath"], destination_data["fullpath"])
|
||||
except Exception as e:
|
||||
@@ -983,6 +989,12 @@ class LocalFileStorage(StorageInterface):
|
||||
source, destination
|
||||
)
|
||||
|
||||
if not octoprint.filemanager.valid_file_type(destination_data["name"]):
|
||||
raise StorageError(
|
||||
f"{destination_data['name']} is an unrecognized file type",
|
||||
code=StorageError.INVALID_FILE,
|
||||
)
|
||||
|
||||
# only a display rename? Update that and bail early
|
||||
if source_data["fullpath"] == destination_data["fullpath"]:
|
||||
self._set_display_metadata(destination_data)
|
||||
|
||||
@@ -500,7 +500,7 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
:widths: 5 95
|
||||
|
||||
* - icon
|
||||
- Icon to use for the sidebar header, should be the full name of a Font Awesome icon including the ``fas``/``far``/``fab`` prefix, eg. ``fas fa-plus``.
|
||||
- Icon to use for the sidebar header, should be the name of a Font Awesome icon without the leading ``icon-`` part.
|
||||
* - template_header
|
||||
- Additional template to include in the head section of the sidebar item. For an example of this, see the additional
|
||||
options included in the "Files" section.
|
||||
@@ -631,10 +631,12 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
at it being a mobile device:
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/__init__.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `dummy_mobile_ui/__init__.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui/__init__.py>`_
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2>`_
|
||||
|
||||
@@ -1189,6 +1191,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
|
||||
Take this example of a plugin registered under plugin identifier ``mysimpleapiplugin``:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -1324,6 +1327,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
which behaves exactly the same like Flask's regular ``route`` decorators. Example:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
import octoprint.plugin
|
||||
import flask
|
||||
@@ -1348,8 +1352,39 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo"
|
||||
|
||||
.. warning::
|
||||
|
||||
As of OctoPrint 1.8.3, endpoints provided through a ``BlueprintPlugin`` do **not** automatically fall under
|
||||
OctoPrint's :ref:`CSRF protection <sec-api-general-csrf>`, for reasons of backwards compatibility. There will be a short grace period before this changes. You
|
||||
can and should however already opt into CSRF protection for your endpoints by implementing ``is_blueprint_csrf_protected``
|
||||
and returning ``True`` from it. You can exempt certain endpoints from CSRF protection by decorating them with
|
||||
``@octoprint.plugin.BlueprintPlugin.csrf_exempt``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class MyPlugin(octoprint.plugin.BlueprintPlugin):
|
||||
@octoprint.plugin.BlueprintPlugin.route("/hello_world", methods=["GET"])
|
||||
def hello_world(self):
|
||||
# This is a GET request and thus not subject to CSRF protection
|
||||
return "Hello world!"
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/hello_you", methods=["POST"])
|
||||
def hello_you(self):
|
||||
# This is a POST request and thus subject to CSRF protection. It is not exempt.
|
||||
return "Hello you!"
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/hello_me", methods=["POST"])
|
||||
@octoprint.plugin.BlueprintPlugin.csrf_exempt()
|
||||
def hello_me(self):
|
||||
# This is a POST request and thus subject to CSRF protection, but this one is exempt.
|
||||
return "Hello me!"
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
|
||||
|
||||
.. versionchanged:: 1.8.3
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@@ -1368,7 +1403,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
def decorator(f):
|
||||
# We attach the decorator parameters directly to the function object, because that's the only place
|
||||
# we can access right now.
|
||||
# This neat little trick was adapter from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/
|
||||
# This neat little trick was adapted from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/
|
||||
if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None:
|
||||
f._blueprint_rules = defaultdict(list)
|
||||
f._blueprint_rules[f.__name__].append((rule, options))
|
||||
@@ -1401,6 +1436,27 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
return decorator
|
||||
|
||||
@staticmethod
|
||||
def csrf_exempt():
|
||||
"""
|
||||
A decorator to mark a view method in your BlueprintPlugin as exempt from :ref:`CSRF protection <sec-api-general-csrf>`. This makes sense
|
||||
if you offer an authenticated API for a certain workflow (see e.g. the bundled appkeys plugin) but in most
|
||||
cases should not be needed.
|
||||
|
||||
.. versionadded:: 1.8.3
|
||||
"""
|
||||
|
||||
def decorator(f):
|
||||
if (
|
||||
not hasattr(f, "_blueprint_csrf_exempt")
|
||||
or f._blueprint_csrf_exempt is None
|
||||
):
|
||||
f._blueprint_csrf_exempt = set()
|
||||
f._blueprint_csrf_exempt.add(f.__name__)
|
||||
return f
|
||||
|
||||
return decorator
|
||||
|
||||
# noinspection PyProtectedMember
|
||||
def get_blueprint(self):
|
||||
"""
|
||||
@@ -1418,22 +1474,29 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
import flask
|
||||
|
||||
from octoprint.server.util.csrf import add_exempt_view
|
||||
|
||||
kwargs = self.get_blueprint_kwargs()
|
||||
blueprint = flask.Blueprint(self._identifier, self._identifier, **kwargs)
|
||||
|
||||
# we now iterate over all members of ourselves and look if we find an attribute
|
||||
# that has data originating from one of our decorators - we ignore anything
|
||||
# starting with a _ to only handle public stuff
|
||||
for member in [x for x in dir(self) if not x.startswith("_")]:
|
||||
for member in [member for member in dir(self) if not member.startswith("_")]:
|
||||
f = getattr(self, member)
|
||||
|
||||
if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules:
|
||||
# this attribute was annotated with our @route decorator
|
||||
for blueprint_rule in f._blueprint_rules[member]:
|
||||
rule, options = blueprint_rule
|
||||
blueprint.add_url_rule(
|
||||
rule, options.pop("endpoint", f.__name__), view_func=f, **options
|
||||
)
|
||||
endpoint = options.pop("endpoint", f.__name__)
|
||||
blueprint.add_url_rule(rule, endpoint, view_func=f, **options)
|
||||
|
||||
if (
|
||||
hasattr(f, "_blueprint_csrf_exempt")
|
||||
and member in f._blueprint_csrf_exempt
|
||||
):
|
||||
add_exempt_view(f"plugin.{self._identifier}.{endpoint}")
|
||||
|
||||
if (
|
||||
hasattr(f, "_blueprint_error_handler")
|
||||
@@ -1482,6 +1545,29 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
"""
|
||||
return True
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_blueprint_csrf_protected(self):
|
||||
"""
|
||||
Whether a blueprint's endpoints are :ref:`CSRF protected <sec-api-general-csrf>`. For now, this defaults to ``False`` to leave it up to
|
||||
plugins to decide which endpoints *should* be protected. Long term, this will default to ``True`` and hence
|
||||
enforce protection unless a plugin opts out by returning False here.
|
||||
|
||||
If you do not override this method in your mixin implementation, a warning will be logged to the console
|
||||
to alert you of the requirement to make a decision here and to not rely on the default implementation, due to the
|
||||
forthcoming change in implemented default behaviour.
|
||||
|
||||
.. versionadded:: 1.8.3
|
||||
"""
|
||||
self._logger.warning(
|
||||
"The Blueprint of this plugin is relying on the default implementation of "
|
||||
"is_blueprint_csrf_protected (newly added in OctoPrint 1.8.3), which in a future version will "
|
||||
"be switched from False to True for security reasons. Plugin authors should ensure they explicitly "
|
||||
"declare the CSRF protection status in their BlueprintPlugin mixin implementation. "
|
||||
"Recommendation is to enable CSRF protection and exempt views that must not use it with the "
|
||||
"octoprint.plugin.BlueprintPlugin.csrf_exempt decorator."
|
||||
)
|
||||
return False
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_blueprint_api_prefixes(self):
|
||||
"""
|
||||
|
||||
@@ -95,7 +95,7 @@ class ActionCommandNotificationPlugin(
|
||||
{
|
||||
"type": "sidebar",
|
||||
"name": gettext("Printer Notifications"),
|
||||
"icon": "far fa-bell",
|
||||
"icon": "bell-o",
|
||||
"styles_wrapper": ["display: none"],
|
||||
"template_header": "action_command_notification_sidebar_header.jinja2",
|
||||
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
|
||||
|
||||
@@ -291,6 +291,9 @@ class AnnouncementPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
|
||||
@@ -161,6 +161,7 @@ class AppKeysPlugin(
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
|
||||
@octoprint.plugin.BlueprintPlugin.csrf_exempt()
|
||||
@no_firstrun_access
|
||||
def handle_request(self):
|
||||
data = flask.request.json
|
||||
@@ -196,7 +197,7 @@ class AppKeysPlugin(
|
||||
)
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def handle_decision_poll(self, app_token):
|
||||
result = self._get_pending_by_app_token(app_token)
|
||||
@@ -214,7 +215,7 @@ class AppKeysPlugin(
|
||||
|
||||
return flask.abort(404)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/auth/<app_token>")
|
||||
@octoprint.plugin.BlueprintPlugin.route("/auth/<app_token>", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def handle_auth_dialog(self, app_token):
|
||||
user_id = current_user.get_name()
|
||||
@@ -284,6 +285,9 @@ class AppKeysPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False # No API key required to request API access
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True # protect anything that isn't explicitly marked as exempt
|
||||
|
||||
##~~ SimpleApiPlugin mixin
|
||||
|
||||
def get_api_commands(self):
|
||||
|
||||
@@ -356,6 +356,9 @@ class BackupPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
##~~ WizardPlugin
|
||||
|
||||
def is_wizard_required(self):
|
||||
@@ -370,7 +373,7 @@ class BackupPlugin(
|
||||
|
||||
def route_hook(self, *args, **kwargs):
|
||||
from octoprint.server import app
|
||||
from octoprint.server.util.flask import admin_validator
|
||||
from octoprint.server.util.flask import permission_validator
|
||||
from octoprint.server.util.tornado import (
|
||||
LargeResponseHandler,
|
||||
access_validation_factory,
|
||||
@@ -378,17 +381,26 @@ class BackupPlugin(
|
||||
)
|
||||
from octoprint.util import is_hidden_path
|
||||
|
||||
plugin_folder = self.get_plugin_data_folder()
|
||||
|
||||
def path_check(path):
|
||||
joined = os.path.join(plugin_folder, path)
|
||||
return not is_hidden_path(joined) and self._valid_backup(joined)
|
||||
|
||||
return [
|
||||
(
|
||||
r"/download/(.*)",
|
||||
LargeResponseHandler,
|
||||
{
|
||||
"path": self.get_plugin_data_folder(),
|
||||
"path": plugin_folder,
|
||||
"as_attachment": True,
|
||||
"path_validation": path_validation_factory(
|
||||
lambda path: not is_hidden_path(path), status_code=404
|
||||
path_check,
|
||||
status_code=404,
|
||||
),
|
||||
"access_validation": access_validation_factory(
|
||||
app, permission_validator, Permissions.PLUGIN_BACKUP_ACCESS
|
||||
),
|
||||
"access_validation": access_validation_factory(app, admin_validator),
|
||||
},
|
||||
)
|
||||
]
|
||||
@@ -730,9 +742,7 @@ class BackupPlugin(
|
||||
for entry in os.scandir(self.get_plugin_data_folder()):
|
||||
if is_hidden_path(entry.path):
|
||||
continue
|
||||
if not entry.is_file():
|
||||
continue
|
||||
if not entry.name.endswith(".zip"):
|
||||
if not self._valid_backup(entry.path):
|
||||
continue
|
||||
|
||||
backups.append(
|
||||
@@ -1359,14 +1369,18 @@ class BackupPlugin(
|
||||
|
||||
@classmethod
|
||||
def _build_backup_filename(cls, settings):
|
||||
backup_prefix = cls._get_backup_prefix(settings)
|
||||
return "{}-backup-{}.zip".format(
|
||||
backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _get_backup_prefix(cls, settings):
|
||||
if settings.global_get(["appearance", "name"]) == "":
|
||||
backup_prefix = "octoprint"
|
||||
else:
|
||||
backup_prefix = settings.global_get(["appearance", "name"])
|
||||
backup_prefix = sanitize(backup_prefix)
|
||||
return "{}-backup-{}.zip".format(
|
||||
backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT)
|
||||
)
|
||||
return sanitize(backup_prefix)
|
||||
|
||||
@classmethod
|
||||
def _restore_supported(cls, settings):
|
||||
@@ -1377,6 +1391,17 @@ class BackupPlugin(
|
||||
not in valid_boolean_trues
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _valid_backup(cls, path):
|
||||
if not path.endswith(".zip") or not zipfile.is_zipfile(path):
|
||||
return False
|
||||
|
||||
try:
|
||||
with zipfile.ZipFile(path) as z:
|
||||
return "metadata.json" in z.namelist()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _send_client_message(self, message, payload=None):
|
||||
if payload is None:
|
||||
payload = {}
|
||||
|
||||
@@ -40,7 +40,6 @@ $(function () {
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function (e, data) {
|
||||
if (data.files.length === 0) {
|
||||
// no files? ignore
|
||||
|
||||
@@ -74,6 +74,11 @@ class CoreWizardPlugin(
|
||||
else:
|
||||
return {}
|
||||
|
||||
# ~~ BlueprintPlugin API
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
# ~~ WizardPlugin API
|
||||
|
||||
def is_wizard_required(self):
|
||||
|
||||
@@ -134,6 +134,9 @@ class DiscoveryPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
|
||||
|
||||
def on_startup(self, host, port):
|
||||
|
||||
@@ -18,10 +18,10 @@ from octoprint.util.version import (
|
||||
)
|
||||
|
||||
SENTRY_URL_SERVER = (
|
||||
"https://f4265899b96044f3a31e6414c315a0d1@o118517.ingest.sentry.io/1373987"
|
||||
"https://9c242ccf183444eaacd046d86d8b0ea2@o118517.ingest.sentry.io/1373987"
|
||||
)
|
||||
SENTRY_URL_COREUI = (
|
||||
"https://2f33808cb0cb4027afd005c35eebfeb4@o118517.ingest.sentry.io/1374096"
|
||||
"https://4d9844043596415faa606ff722174b90@o118517.ingest.sentry.io/1374096"
|
||||
)
|
||||
|
||||
SETTINGS_DEFAULTS = {
|
||||
@@ -158,7 +158,9 @@ def _enable_errortracking():
|
||||
|
||||
unique_id = str(uuid.uuid4())
|
||||
s.set(
|
||||
["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults
|
||||
["plugins", "errortracking", "unique_id"],
|
||||
unique_id,
|
||||
defaults=plugin_defaults,
|
||||
)
|
||||
s.save()
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ class GcodeviewerPlugin(
|
||||
"js/viewer/ui.js",
|
||||
"js/viewer/reader.js",
|
||||
"js/viewer/renderer.js",
|
||||
"js/viewer/pako.js",
|
||||
]
|
||||
|
||||
return {
|
||||
@@ -48,8 +47,6 @@ class GcodeviewerPlugin(
|
||||
"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
|
||||
"sizeThreshold": 20 * 1024 * 1024, # 20MB
|
||||
"skipUntilThis": None,
|
||||
"alwaysCompress": False,
|
||||
"compressionSizeThreshold": 200 * 1024 * 1024,
|
||||
}
|
||||
|
||||
def get_settings_version(self):
|
||||
|
||||
@@ -8,7 +8,6 @@ $(function () {
|
||||
|
||||
self.sizeThresholdStr = undefined;
|
||||
self.mobileSizeThresholdStr = undefined;
|
||||
self.compressionSizeThresholdStr = undefined;
|
||||
|
||||
self.ui_progress_busy = ko.observable(false);
|
||||
self.ui_progress_percentage = ko.observable();
|
||||
@@ -84,7 +83,6 @@ $(function () {
|
||||
|
||||
self.reader_hideEmptyLayers = ko.observable(true);
|
||||
self.reader_ignoreOutsideBed = ko.observable(true);
|
||||
self.reader_forceCompression = ko.observable(false);
|
||||
|
||||
self.layerSelectionEnabled = ko.observable(false);
|
||||
self.layerUpEnabled = ko.observable(false);
|
||||
@@ -129,12 +127,7 @@ $(function () {
|
||||
|
||||
var reader = {
|
||||
purgeEmptyLayers: self.reader_hideEmptyLayers(),
|
||||
ignoreOutsideBed: self.reader_ignoreOutsideBed(),
|
||||
alwaysCompress:
|
||||
self.settings.settings.plugins.gcodeviewer.alwaysCompress(),
|
||||
compressionSizeThreshold:
|
||||
self.settings.settings.plugins.gcodeviewer.compressionSizeThreshold(),
|
||||
forceCompression: self.reader_forceCompression()
|
||||
ignoreOutsideBed: self.reader_ignoreOutsideBed()
|
||||
};
|
||||
if (additionalReaderOptions) {
|
||||
_.extend(reader, additionalReaderOptions);
|
||||
@@ -177,7 +170,6 @@ $(function () {
|
||||
|
||||
self.reader_hideEmptyLayers.subscribe(self.readerOptionUpdated);
|
||||
self.reader_ignoreOutsideBed.subscribe(self.readerOptionUpdated);
|
||||
self.reader_forceCompression.subscribe(self.readerOptionUpdated);
|
||||
|
||||
self._printerProfileUpdated = function () {
|
||||
if (!self.enabled) return;
|
||||
@@ -368,9 +360,6 @@ $(function () {
|
||||
self.mobileSizeThresholdStr = sizeObservable(
|
||||
self.settings.settings.plugins.gcodeviewer.mobileSizeThreshold
|
||||
);
|
||||
self.compressionSizeThresholdStr = sizeObservable(
|
||||
self.settings.settings.plugins.gcodeviewer.compressionSizeThreshold
|
||||
);
|
||||
|
||||
var layerSliderElement = $("#gcode_slider_layers");
|
||||
var commandSliderElement = $("#gcode_slider_commands");
|
||||
@@ -407,13 +396,6 @@ $(function () {
|
||||
return;
|
||||
}
|
||||
|
||||
self.settings.settings.plugins.gcodeviewer.alwaysCompress.subscribe(
|
||||
self.readerOptionUpdated
|
||||
);
|
||||
self.settings.settings.plugins.gcodeviewer.compressionSizeThreshold.subscribe(
|
||||
self.readerOptionUpdated
|
||||
);
|
||||
|
||||
self.synchronizeOptions();
|
||||
self.enabled = true;
|
||||
self._fromLocalStorage();
|
||||
@@ -453,7 +435,6 @@ $(function () {
|
||||
|
||||
self.reader_hideEmptyLayers(true);
|
||||
self.reader_ignoreOutsideBed(true);
|
||||
self.reader_forceCompression(false);
|
||||
};
|
||||
|
||||
self.clear = function () {
|
||||
@@ -541,6 +522,10 @@ $(function () {
|
||||
var findThis = self.settings.settings.plugins.gcodeviewer.skipUntilThis();
|
||||
if (findThis && findThis !== "") {
|
||||
var indexPos = response.indexOf("\n" + findThis);
|
||||
// Try windows newlines if not found
|
||||
if (indexPos === -1) {
|
||||
indexPos = response.indexOf("\r" + findThis);
|
||||
}
|
||||
if (indexPos !== -1) {
|
||||
// Slice and make sure we comment out any string left back after slicing - so if a user configures something like "G1" we dont end up with a snippet of gcode commands
|
||||
// Yes it would be prettier to parse it line by line and remove the entire line, that is very slow and uses mem - this way we find the string, and remove it
|
||||
@@ -950,7 +935,6 @@ $(function () {
|
||||
showBoundingBox: self.renderer_showBoundingBox(),
|
||||
showLayerBoundingBox: self.renderer_showLayerBoundingBox(),
|
||||
hideEmptyLayers: self.reader_hideEmptyLayers()
|
||||
// reader_forceCompression is never saved.
|
||||
});
|
||||
};
|
||||
self._fromLocalStorage = function () {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,7 @@
|
||||
GCODE.gCodeReader = (function () {
|
||||
// ***** PRIVATE ******
|
||||
var gcode, lines;
|
||||
var model = [];
|
||||
var max = {x: undefined, y: undefined, z: undefined};
|
||||
var min = {x: undefined, y: undefined, z: undefined};
|
||||
var modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
@@ -38,31 +39,11 @@ GCODE.gCodeReader = (function () {
|
||||
},
|
||||
ignoreOutsideBed: false,
|
||||
g90InfluencesExtruder: false,
|
||||
bedZ: 0,
|
||||
alwaysCompress: false,
|
||||
compressionSizeThreshold: 0,
|
||||
forceCompression: false
|
||||
bedZ: 0
|
||||
};
|
||||
|
||||
// This is the data as received from the worker.
|
||||
// This is preserved so the user can turn on or off
|
||||
// the "purgeEmptyLayers" option without forcing
|
||||
// a new download and reparsing of the gcode data
|
||||
// by the worker.
|
||||
var model = [];
|
||||
var emptyLayers = [];
|
||||
var percentageByLayer = [];
|
||||
|
||||
// This is the data after being processed here in the
|
||||
// reader. It has empty indexes removed and
|
||||
// any layers without extrusion when the "purgeEmptyLayers"
|
||||
// option is set.
|
||||
// This is the data that is passed to the renderer.
|
||||
var rendererModel = undefined;
|
||||
var rendererEmptyLayers = undefined;
|
||||
var rendererPercentageByLayer = undefined;
|
||||
var layerPercentageLookup = [];
|
||||
|
||||
var cachedLayer = undefined;
|
||||
var cachedCmd = undefined;
|
||||
|
||||
@@ -100,17 +81,17 @@ GCODE.gCodeReader = (function () {
|
||||
}
|
||||
|
||||
function searchInCmds(layer, lower, upper, key) {
|
||||
var cmds = GCODE.renderer.getLayer(layer);
|
||||
while (lower < upper) {
|
||||
var middle = Math.floor((lower + upper) / 2);
|
||||
|
||||
if (
|
||||
cmds[middle].percentage == key ||
|
||||
(cmds[middle].percentage <= key && cmds[middle + 1].percentage > key)
|
||||
rendererModel[layer][middle].percentage == key ||
|
||||
(rendererModel[layer][middle].percentage <= key &&
|
||||
rendererModel[layer][middle + 1].percentage > key)
|
||||
)
|
||||
return middle;
|
||||
|
||||
if (cmds[middle].percentage > key) {
|
||||
if (rendererModel[layer][middle].percentage > key) {
|
||||
upper = middle - 1;
|
||||
} else {
|
||||
lower = middle + 1;
|
||||
@@ -127,7 +108,7 @@ GCODE.gCodeReader = (function () {
|
||||
if (key == null) return {layer: cachedLayer, cmd: cachedCmd};
|
||||
|
||||
var layer = searchInLayers(0, rendererModel.length - 1, key);
|
||||
var cmd = searchInCmds(layer, 0, GCODE.renderer.getLayer(layer).length - 1, key);
|
||||
var cmd = searchInCmds(layer, 0, rendererModel[layer].length - 1, key);
|
||||
|
||||
// remember last position
|
||||
cachedLayer = layer;
|
||||
@@ -136,51 +117,52 @@ GCODE.gCodeReader = (function () {
|
||||
return {layer: layer, cmd: cmd};
|
||||
};
|
||||
|
||||
var cleanModel = function (m) {
|
||||
var sanitizeModel = function (m) {
|
||||
if (!m) return [];
|
||||
return _.filter(m, function (layer) {
|
||||
return !!layer;
|
||||
});
|
||||
};
|
||||
|
||||
var result = [];
|
||||
rendererEmptyLayers = [];
|
||||
rendererPercentageByLayer = [];
|
||||
for (var i = 0; i < m.length; i++) {
|
||||
// remove any empty indexes that might be in the model.
|
||||
if (!m[i]) continue;
|
||||
// if the purgeEmptyLayers option is set, remove any layer
|
||||
// with commands but without extrusion.
|
||||
if (gCodeOptions["purgeEmptyLayers"] && emptyLayers[i]) continue;
|
||||
|
||||
result.push(m[i]);
|
||||
rendererPercentageByLayer.push(percentageByLayer[i]);
|
||||
if (emptyLayers[i]) rendererEmptyLayers[result.length - 1] = true;
|
||||
}
|
||||
return result;
|
||||
var purgeEmptyLayers = function (m) {
|
||||
return _.filter(m, function (layer) {
|
||||
return (
|
||||
!!layer &&
|
||||
layer.length > 0 &&
|
||||
_.find(layer, function (cmd) {
|
||||
return cmd && cmd.extrude;
|
||||
}) !== undefined
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
var rebuildLayerPercentageLookup = function (m) {
|
||||
var result = [];
|
||||
|
||||
if (m && m.length > 0) {
|
||||
for (var i = 0; i < m.length - 1; i++) {
|
||||
// start is first command of current layer
|
||||
var start =
|
||||
rendererPercentageByLayer[i] !== undefined
|
||||
? rendererPercentageByLayer[i]
|
||||
: -1;
|
||||
var start = m[i].length ? m[i][0].percentage : -1;
|
||||
|
||||
var end = -1;
|
||||
for (var j = i + 1; j < m.length; j++) {
|
||||
// end is percentage of first command that follows our start, might
|
||||
// be later layers if the next layer is empty!
|
||||
if (!rendererEmptyLayers[j]) {
|
||||
end = rendererPercentageByLayer[j];
|
||||
if (m[j].length) {
|
||||
end = m[j][0].percentage;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
result[i] = [start, end];
|
||||
}
|
||||
|
||||
// final start-end-pair is start percentage of last layer and 100%
|
||||
result[result.length] = [rendererPercentageByLayer[m.length - 1], 100];
|
||||
result[m.length - 1] = m[m.length - 1].length
|
||||
? [m[m.length - 1][0].percentage, 100]
|
||||
: [-1, -1];
|
||||
}
|
||||
|
||||
layerPercentageLookup = result;
|
||||
};
|
||||
|
||||
@@ -200,8 +182,6 @@ GCODE.gCodeReader = (function () {
|
||||
maxZ: undefined
|
||||
};
|
||||
rendererModel = undefined;
|
||||
rendererEmptyLayers = undefined;
|
||||
rendererPercentageByLayer = undefined;
|
||||
layerPercentageLookup = undefined;
|
||||
cachedLayer = undefined;
|
||||
cachedCmd = undefined;
|
||||
@@ -229,12 +209,6 @@ GCODE.gCodeReader = (function () {
|
||||
reader.target.result = null;
|
||||
prepareGCode(totalSize);
|
||||
|
||||
var mustCompress =
|
||||
gCodeOptions["forceCompression"] ||
|
||||
gCodeOptions["alwaysCompress"] ||
|
||||
(gCodeOptions["compressionSizeThreshold"] > 0 &&
|
||||
gCodeOptions["compressionSizeThreshold"] <= totalSize);
|
||||
|
||||
GCODE.ui.worker.postMessage({
|
||||
cmd: "parseGCode",
|
||||
msg: {
|
||||
@@ -245,8 +219,7 @@ GCODE.gCodeReader = (function () {
|
||||
bed: gCodeOptions["bed"],
|
||||
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
|
||||
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"],
|
||||
bedZ: gCodeOptions["bedZ"],
|
||||
compress: mustCompress
|
||||
bedZ: gCodeOptions["bedZ"]
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -265,11 +238,14 @@ GCODE.gCodeReader = (function () {
|
||||
},
|
||||
|
||||
passDataToRenderer: function () {
|
||||
rendererModel = cleanModel(model);
|
||||
rebuildLayerPercentageLookup(rendererModel);
|
||||
var m = sanitizeModel(model);
|
||||
if (gCodeOptions["purgeEmptyLayers"]) m = purgeEmptyLayers(m);
|
||||
|
||||
GCODE.renderer.doRender(rendererModel, 0);
|
||||
return rendererModel;
|
||||
rendererModel = m;
|
||||
rebuildLayerPercentageLookup(m);
|
||||
|
||||
GCODE.renderer.doRender(m, 0);
|
||||
return m;
|
||||
},
|
||||
|
||||
processLayersFromWorker: function (msg) {
|
||||
@@ -289,8 +265,6 @@ GCODE.gCodeReader = (function () {
|
||||
speedsByLayer = msg.speedsByLayer;
|
||||
printTime = msg.printTime;
|
||||
printTimeByLayer = msg.printTimeByLayer;
|
||||
emptyLayers = msg.emptyLayers;
|
||||
percentageByLayer = msg.percentageByLayer;
|
||||
},
|
||||
|
||||
getLayerFilament: function (z) {
|
||||
@@ -317,8 +291,8 @@ GCODE.gCodeReader = (function () {
|
||||
|
||||
getGCodeLines: function (layer, fromSegments, toSegments) {
|
||||
var result = {
|
||||
first: GCODE.renderer.getLayer(layer)[fromSegments].gcodeLine,
|
||||
last: GCODE.renderer.getLayer(layer)[toSegments].gcodeLine
|
||||
first: model[layer][fromSegments].gcodeLine,
|
||||
last: model[layer][toSegments].gcodeLine
|
||||
};
|
||||
return result;
|
||||
},
|
||||
|
||||
@@ -99,32 +99,6 @@ GCODE.renderer = (function () {
|
||||
var deg270 = Math.PI * 1.5;
|
||||
var deg360 = Math.PI * 2.0;
|
||||
|
||||
var layerCache = [];
|
||||
|
||||
var decompress = function (data) {
|
||||
if (!(data instanceof Uint8Array)) return data;
|
||||
|
||||
return JSON.parse(pako.inflate(data, {to: "string"}));
|
||||
};
|
||||
|
||||
var getLayer = function (layer) {
|
||||
if (!model[layer]) return undefined;
|
||||
if (!layerCache[layer]) layerCache[layer] = decompress(model[layer]);
|
||||
|
||||
return layerCache[layer];
|
||||
};
|
||||
|
||||
var cleanCache = function (layer) {
|
||||
var newCache = [];
|
||||
for (var l in layerCache) {
|
||||
if (l == layer || l == layer + 1) newCache[l] = layerCache[l];
|
||||
if (l == layer - 1 && renderOptions["showPreviousLayer"])
|
||||
newCache[l] = layerCache[l];
|
||||
}
|
||||
|
||||
layerCache = newCache;
|
||||
};
|
||||
|
||||
function notifyIfViewportChanged() {
|
||||
if (viewportChanged) {
|
||||
if (renderOptions["onViewportChange"]) {
|
||||
@@ -188,15 +162,13 @@ GCODE.renderer = (function () {
|
||||
} else {
|
||||
console.log("Got request to render non-existent layer");
|
||||
}
|
||||
|
||||
cleanCache(layerNumStore);
|
||||
}
|
||||
};
|
||||
|
||||
function getLayerBounds(layer) {
|
||||
if (!model || !model[layer]) return;
|
||||
|
||||
var cmds = getLayer(layer);
|
||||
var cmds = model[layer];
|
||||
var firstExtrusion;
|
||||
var i;
|
||||
|
||||
@@ -886,7 +858,7 @@ GCODE.renderer = (function () {
|
||||
|
||||
if (!model || !model[layerNum]) return;
|
||||
|
||||
var cmds = getLayer(layerNum);
|
||||
var cmds = model[layerNum];
|
||||
var x, y;
|
||||
|
||||
//~~ find our initial prevX/prevY tuple
|
||||
@@ -903,7 +875,7 @@ GCODE.renderer = (function () {
|
||||
// previous layer exists, use last x/y as prevX/prevY
|
||||
prevX = undefined;
|
||||
prevY = undefined;
|
||||
var prevModelLayer = getLayer(layerNum - 1);
|
||||
var prevModelLayer = model[layerNum - 1];
|
||||
for (i = prevModelLayer.length - 1; i >= 0; i--) {
|
||||
if (prevX === undefined && prevModelLayer[i].x !== undefined) {
|
||||
prevX = prevModelLayer[i].x;
|
||||
@@ -1070,14 +1042,7 @@ GCODE.renderer = (function () {
|
||||
if (renderOptions["showMoves"] && !isNotCurrentLayer) {
|
||||
// move => draw line from (prevX, prevY) to (x, y) in move color
|
||||
ctx.lineWidth = lineWidthFactor;
|
||||
|
||||
if (cmd.direction !== undefined && cmd.direction !== 0) {
|
||||
var arc = getArcParams(cmd);
|
||||
var ccw = cmd.direction < 0; // Y-axis is inverted so direction is also inverted
|
||||
ctx.arc(arc.x, arc.y, arc.r, arc.startAngle, arc.endAngle, ccw);
|
||||
} else {
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
} else if (cmd.extrude) {
|
||||
if (cmd.retract == 0) {
|
||||
@@ -1375,14 +1340,11 @@ GCODE.renderer = (function () {
|
||||
},
|
||||
getLayerNumSegments: function (layer) {
|
||||
if (model) {
|
||||
return model[layer] ? getLayer(layer).length : 1;
|
||||
return model[layer] ? model[layer].length : 1;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
},
|
||||
getLayer: function (layer) {
|
||||
return getLayer(layer);
|
||||
},
|
||||
clear: function () {
|
||||
offsetModelX = 0;
|
||||
offsetModelY = 0;
|
||||
@@ -1393,7 +1355,6 @@ GCODE.renderer = (function () {
|
||||
speeds = [];
|
||||
speedsByLayer = {};
|
||||
modelInfo = undefined;
|
||||
layerCache = [];
|
||||
|
||||
this.doRender([], 0);
|
||||
},
|
||||
@@ -1411,7 +1372,7 @@ GCODE.renderer = (function () {
|
||||
speeds = modelInfo.speeds;
|
||||
speedsByLayer = modelInfo.speedsByLayer;
|
||||
if (model[layerNum]) {
|
||||
toProgress = getLayer(layerNum).length;
|
||||
toProgress = model[layerNum].length;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1433,7 +1394,7 @@ GCODE.renderer = (function () {
|
||||
if (!model || !model[layerNum]) {
|
||||
return "-1";
|
||||
}
|
||||
var cmds = getLayer(layerNum);
|
||||
var cmds = model[layerNum];
|
||||
for (var i = 0; i < cmds.length; i++) {
|
||||
if (cmds[i].prevZ !== undefined) return cmds[i].prevZ;
|
||||
}
|
||||
|
||||
@@ -36,22 +36,6 @@ var layerHeight = 0;
|
||||
var layerCnt = 0;
|
||||
var speeds = {extrude: [], retract: [], move: []};
|
||||
var speedsByLayer = {extrude: {}, retract: {}, move: {}};
|
||||
var emptyLayers = [];
|
||||
var percentageByLayer = [];
|
||||
|
||||
var mustCompress = false;
|
||||
|
||||
importScripts("pako.js");
|
||||
|
||||
var compress = function (data) {
|
||||
if (!mustCompress) return data;
|
||||
|
||||
return pako.deflate(JSON.stringify(data));
|
||||
};
|
||||
|
||||
var decompress = function (data) {
|
||||
return JSON.parse(pako.inflate(data, {to: "string"}));
|
||||
};
|
||||
|
||||
var sendLayersToParent = function (layers, progress) {
|
||||
var l = [];
|
||||
@@ -62,7 +46,6 @@ var sendLayersToParent = function (layers, progress) {
|
||||
var m = [];
|
||||
for (var i = 0; i < l.length; i++) {
|
||||
if (!model[l[i]]) continue;
|
||||
if (!(model[l[i]] instanceof Uint8Array)) model[l[i]] = compress(model[l[i]]);
|
||||
m[l[i]] = model[l[i]];
|
||||
}
|
||||
|
||||
@@ -102,9 +85,7 @@ var sendAnalyzeDone = function () {
|
||||
layerTotal: model.length,
|
||||
speeds: speeds,
|
||||
speedsByLayer: speedsByLayer,
|
||||
printTimeByLayer: printTimeByLayer,
|
||||
percentageByLayer: percentageByLayer,
|
||||
emptyLayers: emptyLayers
|
||||
printTimeByLayer: printTimeByLayer
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -116,10 +97,8 @@ var purgeLayers = function () {
|
||||
if (!model[i]) {
|
||||
purge = true;
|
||||
} else {
|
||||
var cmds = model[i];
|
||||
if (cmds instanceof Uint8Array) cmds = decompress(cmds);
|
||||
for (var j = 0; j < cmds.length; j++) {
|
||||
if (cmds[j].extrude) purge = false;
|
||||
for (var j = 0; j < model[i].length; j++) {
|
||||
if (model[i][j].extrude) purge = false;
|
||||
}
|
||||
}
|
||||
if (!purge) {
|
||||
@@ -176,13 +155,7 @@ var analyzeModel = function () {
|
||||
for (var i = 0; i < model.length; i++) {
|
||||
var cmds = model[i];
|
||||
if (!cmds) continue;
|
||||
if (cmds instanceof Uint8Array) cmds = decompress(cmds);
|
||||
|
||||
if (cmds.length > 0) {
|
||||
percentageByLayer[i] = cmds[0].percentage;
|
||||
}
|
||||
|
||||
var layerExtrude = false;
|
||||
for (var j = 0; j < cmds.length; j++) {
|
||||
var tool = cmds[j].tool;
|
||||
|
||||
@@ -315,16 +288,7 @@ var analyzeModel = function () {
|
||||
if (speedsByLayer[type][cmds[j].prevZ].indexOf(cmds[j].speed) === -1) {
|
||||
speedsByLayer[type][cmds[j].prevZ][speedIndex] = cmds[j].speed;
|
||||
}
|
||||
|
||||
if (extrude) {
|
||||
layerExtrude = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!layerExtrude) {
|
||||
emptyLayers[i] = true;
|
||||
}
|
||||
|
||||
sendSizeProgress((i / model.length) * 100);
|
||||
}
|
||||
purgeLayers();
|
||||
@@ -646,9 +610,6 @@ var doParse = function () {
|
||||
|
||||
if (addToModel) {
|
||||
if (!model[layer]) model[layer] = [];
|
||||
if (model[layer] instanceof Uint8Array)
|
||||
model[layer] = decompress(model[layer]);
|
||||
|
||||
var command = {
|
||||
x: x,
|
||||
y: y,
|
||||
@@ -684,17 +645,11 @@ var doParse = function () {
|
||||
// there's something to be checked in the Z-lift cache
|
||||
if (prevZ < maxLiftZ) {
|
||||
zLiftMoves.forEach(function (zLiftMove) {
|
||||
if (model[zLiftMove.layer] instanceof Uint8Array)
|
||||
model[zLiftMove.layer] = decompress(
|
||||
model[zLiftMove.layer]
|
||||
);
|
||||
// move command from move layer...
|
||||
model[zLiftMove.layer].splice(
|
||||
model[layer].indexOf(zLiftMove.command),
|
||||
1
|
||||
);
|
||||
if (model[zLiftLayer] instanceof Uint8Array)
|
||||
model[zLiftLayer] = decompress(model[zLiftLayer]);
|
||||
// ... to z-lift layer
|
||||
model[zLiftLayer].push(zLiftMove.command);
|
||||
});
|
||||
@@ -777,7 +732,6 @@ var parseGCode = function (message) {
|
||||
ignoreOutsideBed = message.options.ignoreOutsideBed;
|
||||
g90InfluencesExtruder = message.options.g90InfluencesExtruder;
|
||||
boundingBox.minZ = min.z = message.options.bedZ;
|
||||
mustCompress = message.options.compress;
|
||||
|
||||
doParse();
|
||||
gcode = [];
|
||||
|
||||
@@ -1,22 +1,17 @@
|
||||
<h3>{{ _("GCode Viewer") }}</h3>
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
<div class="control-group" title="{{ _('Skip/hide gcode until this string')}}">
|
||||
<label class="control-label" for="settings-gcodeviewer-skipUntilThis">{{ _('Skip to this') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.settings.plugins.gcodeviewer.skipUntilThis" id="settings-gcodeviewer-skipUntilThis" placeholder="; layer 1">
|
||||
<span class="help-block">
|
||||
{% trans %}If provided, the GCode Viewer will search for a line beginning with this string. If found, all GCode up to that point will be skipped. This can be used to skip "purge/nozzle wipe" GCode in the viewer. Note the search is case sensitive. Example: <code>; layer 1</code>{% endtrans %}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Maximum size for which the GCode Viewer autoloads the file for preview')|edq }}">
|
||||
<label class="control-label" for="settings-gcodeviewer-featureSizeThreshold">{{ _('File size threshold') }}</label>
|
||||
<label class="control-label" for="settings-gcodeviewer-featureSizeThreshold">{{ _('GCode Viewer file size threshold') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: sizeThresholdStr" id="settings-gcodeviewer-featureSizeThreshold">
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: sizeThresholdStr" id="settings-gcodeviewer-featureSizeThreshold">
|
||||
</div>
|
||||
<span class="help-inline">{{ _('on desktop')}}</span>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: mobileSizeThresholdStr">
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: mobileSizeThresholdStr">
|
||||
</div>
|
||||
<span class="help-inline">{{ _('on mobile')}}</span>
|
||||
</div>
|
||||
<div class="controls">
|
||||
@@ -25,29 +20,13 @@
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<fieldset>
|
||||
<legend>{{ _('In-memory model compression') }}</legend>
|
||||
<p>{% trans %}
|
||||
In-memory model compression can help in reducing the memory consumption of the GCode Viewer and thus enable processing of files that would be too large to view otherwise.
|
||||
{% endtrans %}</p>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.settings.plugins.gcodeviewer.alwaysCompress" id="settings-gcodeviewer-compressionEnabled" /> {{ _('Always enable compression') }}
|
||||
</label>
|
||||
<span class="help-block">{% trans %}If turned on, the GCode Viewer will always use in-memory compression of the layer data. {% endtrans %}</span>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Skip/hide gcode until this string')}}">
|
||||
<label class="control-label" for="settings-gcodeviewer-skipUntilThis">{{ _('Skip to this') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.settings.plugins.gcodeviewer.skipUntilThis" id="settings-gcodeviewer-skipUntilThis" placeholder="; layer 1">
|
||||
<span class="help-inline">
|
||||
{% trans %}If provided, the GCode Viewer will search for a line beginning with this string. If found, all GCode up to that point will be skipped. This can be used to skip "purge/nozzle wipe" GCode in the viewer. Note the search is case sensitive. Example: <code>; layer 1</code>{% endtrans %}
|
||||
</span>
|
||||
</div>
|
||||
<div data-bind="ifnot: (settings.settings.plugins.gcodeviewer.alwaysCompress())">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-gcodeviewer-compressionSizeThreshold">{{ _('Compression threshold') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: compressionSizeThresholdStr, disable: settings.settings.plugins.gcodeviewer.alwaysCompress" id="settings-gcodeviewer-compressionSizeThreshold">
|
||||
<span class="help-block">
|
||||
{% trans %}If this is non-zero, the GCode Viewer will always use in-memory compression for GCode files if they exceed this size. Provide values including size unit. Allowed units are: b, byte, bytes, kb, mb, gb, tb (case insensitive). Example: <code>5MB</code>, <code>500KB</code>{% endtrans %}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
</form>
|
||||
@@ -134,26 +134,7 @@
|
||||
Are you sure you want to visualize this file nevertheless?
|
||||
</p>{% endtrans %}
|
||||
|
||||
<p>
|
||||
<button class="btn btn-warning btn-block" data-bind="click: approveLargeFile">
|
||||
{{ _('Yes, please visualize %(name)s regardless of its size', name='<span data-bind="text: selectedFile.name"></span>') }}
|
||||
</button>
|
||||
<p>
|
||||
|
||||
<div data-bind="ifnot: ((settings.settings.plugins.gcodeviewer.alwaysCompress()) ||
|
||||
((settings.settings.plugins.gcodeviewer.compressionSizeThreshold() > 0) &&
|
||||
(settings.settings.plugins.gcodeviewer.compressionSizeThreshold() <= selectedFile.size())))">
|
||||
{% trans %}<p>
|
||||
You may want to turn on in-memory compression to keep the memory usage of this page to a reasonable
|
||||
level. You can change the main settings for compression in the plugin settings or you can force
|
||||
compression for just this file here. It may also help if this file would normally make your browser
|
||||
unresponsive or crash. Loading the file will become considerably slower.
|
||||
</p>{% endtrans %}
|
||||
|
||||
<p>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: reader_forceCompression">{{ _('Force compression') }}
|
||||
</label>
|
||||
<p>
|
||||
</div>
|
||||
<button class="btn btn-warning btn-block" data-bind="click: approveLargeFile">
|
||||
{{ _('Yes, please visualize %(name)s regardless of its size', name='<span data-bind="text: selectedFile.name"></span>') }}
|
||||
</button>
|
||||
</div>
|
||||
@@ -127,6 +127,9 @@ class LoggingPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
def _get_usage(self):
|
||||
import psutil
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ def map_repository_entry(entry):
|
||||
entry["compatibility"]["python"]
|
||||
)
|
||||
else:
|
||||
# we default to only assume py2 compatibility for now
|
||||
# we default to only assume py2 compatiblity for now
|
||||
result["is_compatible"]["python"] = is_python_compatible(">=2.7,<3")
|
||||
|
||||
return result
|
||||
@@ -228,7 +228,7 @@ class PluginManagerPlugin(
|
||||
"name": "List plugins",
|
||||
"description": gettext("Allows to list installed plugins."),
|
||||
"default_groups": [READONLY_GROUP, USER_GROUP, ADMIN_GROUP],
|
||||
"roles": ["manage"],
|
||||
"roles": ["list"],
|
||||
},
|
||||
{
|
||||
"key": "MANAGE",
|
||||
@@ -609,6 +609,9 @@ class PluginManagerPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
|
||||
@@ -266,7 +266,7 @@
|
||||
<div class="row-fluid">
|
||||
<div class="span12">
|
||||
<div class="span3 pull-right">
|
||||
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="fas fa-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
<div data-bind="visible: $data.disabled !== undefined" style="text-align: center"><small><a data-bind="attr: {href: page}" target="_blank">{{ _('"Why?"') }}</a></small></div>
|
||||
</div>
|
||||
<div>
|
||||
|
||||
@@ -773,9 +773,7 @@ class SoftwareUpdatePlugin(
|
||||
def on_settings_save(self, data):
|
||||
# ~~ plugin settings
|
||||
|
||||
defaults = self.get_settings_defaults()
|
||||
|
||||
for key in defaults:
|
||||
for key in self.get_settings_defaults():
|
||||
if key in (
|
||||
"checks",
|
||||
"cache_ttl",
|
||||
@@ -785,7 +783,6 @@ class SoftwareUpdatePlugin(
|
||||
"octoprint_checkout_folder",
|
||||
"octoprint_type",
|
||||
"octoprint_release_channel",
|
||||
"credentials",
|
||||
):
|
||||
continue
|
||||
if key in data:
|
||||
@@ -915,14 +912,6 @@ class SoftwareUpdatePlugin(
|
||||
if update_pip_check_config:
|
||||
self._invalidate_version_cache("pip")
|
||||
|
||||
# ~~ credentials
|
||||
|
||||
if "credentials" in data:
|
||||
credentials = data["credentials"]
|
||||
for key in defaults["credentials"]:
|
||||
if key in credentials:
|
||||
self._settings.set(["credentials", key], credentials[key])
|
||||
|
||||
def get_settings_version(self):
|
||||
return 9
|
||||
|
||||
@@ -1464,6 +1453,9 @@ class SoftwareUpdatePlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
# ~~ Asset API
|
||||
|
||||
def get_assets(self):
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
<strong>There is not enough free disk space available to run an update.</strong>
|
||||
</p>
|
||||
<p>
|
||||
To reduce the likelihood of running into update problems due to insufficient disk space, OctoPrint requires
|
||||
To reduce the likelihood of running into update problems due to insuffient disk space, OctoPrint requires
|
||||
a minimum of {{ min_free_storage }} free disk space in various locations:
|
||||
</p>
|
||||
{% endtrans %}
|
||||
|
||||
@@ -94,7 +94,7 @@ A printer profile is a ``dict`` of the following structure:
|
||||
- Information about the printer's X axis
|
||||
* - ``axes.x.speed``
|
||||
- ``float``
|
||||
- Speed of the X axis in mm/min
|
||||
- Speed of the X axis in mm/s
|
||||
* - ``axes.x.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
@@ -103,7 +103,7 @@ A printer profile is a ``dict`` of the following structure:
|
||||
- Information about the printer's Y axis
|
||||
* - ``axes.y.speed``
|
||||
- ``float``
|
||||
- Speed of the Y axis in mm/min
|
||||
- Speed of the Y axis in mm/s
|
||||
* - ``axes.y.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
@@ -112,7 +112,7 @@ A printer profile is a ``dict`` of the following structure:
|
||||
- Information about the printer's Z axis
|
||||
* - ``axes.z.speed``
|
||||
- ``float``
|
||||
- Speed of the Z axis in mm/min
|
||||
- Speed of the Z axis in mm/s
|
||||
* - ``axes.z.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True)
|
||||
@@ -121,7 +121,7 @@ A printer profile is a ``dict`` of the following structure:
|
||||
- Information about the printer's E axis
|
||||
* - ``axes.e.speed``
|
||||
- ``float``
|
||||
- Speed of the E axis in mm/min
|
||||
- Speed of the E axis in mm/s
|
||||
* - ``axes.e.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change extrudes (False, default) or retracts (True) filament
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
__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"
|
||||
@@ -1,54 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import List, Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
from .access_control import AccessControlConfig
|
||||
from .api import ApiConfig
|
||||
from .appearance import AppearanceConfig
|
||||
from .controls import ContainerConfig, ControlConfig
|
||||
from .devel import DevelConfig
|
||||
from .estimation import EstimationConfig
|
||||
from .events import EventsConfig
|
||||
from .feature import FeatureConfig
|
||||
from .folder import FolderConfig
|
||||
from .gcode_analysis import GcodeAnalysisConfig
|
||||
from .plugins import PluginsConfig
|
||||
from .printer_parameters import PrinterParametersConfig
|
||||
from .printer_profiles import PrinterProfilesConfig
|
||||
from .scripts import ScriptsConfig
|
||||
from .serial import SerialConfig
|
||||
from .server import ServerConfig
|
||||
from .slicing import SlicingConfig
|
||||
from .system import SystemConfig
|
||||
from .temperature import TemperatureConfig
|
||||
from .terminalfilters import DEFAULT_TERMINAL_FILTERS, TerminalFilterEntry
|
||||
from .webcam import WebcamConfig
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class Config(BaseModel):
|
||||
accessControl: AccessControlConfig = AccessControlConfig()
|
||||
api: ApiConfig = ApiConfig()
|
||||
appearance: AppearanceConfig = AppearanceConfig()
|
||||
controls: List[Union[ControlConfig, ContainerConfig]] = []
|
||||
devel: DevelConfig = DevelConfig()
|
||||
estimation: EstimationConfig = EstimationConfig()
|
||||
events: EventsConfig = EventsConfig()
|
||||
feature: FeatureConfig = FeatureConfig()
|
||||
folder: FolderConfig = FolderConfig()
|
||||
gcodeAnalysis: GcodeAnalysisConfig = GcodeAnalysisConfig()
|
||||
plugins: PluginsConfig = PluginsConfig()
|
||||
printerParameters: PrinterParametersConfig = PrinterParametersConfig()
|
||||
printerProfiles: PrinterProfilesConfig = PrinterProfilesConfig()
|
||||
scripts: ScriptsConfig = ScriptsConfig()
|
||||
serial: SerialConfig = SerialConfig()
|
||||
server: ServerConfig = ServerConfig()
|
||||
slicing: SlicingConfig = SlicingConfig()
|
||||
system: SystemConfig = SystemConfig()
|
||||
temperature: TemperatureConfig = TemperatureConfig()
|
||||
terminalFilters: List[TerminalFilterEntry] = DEFAULT_TERMINAL_FILTERS
|
||||
webcam: WebcamConfig = WebcamConfig()
|
||||
@@ -1,52 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class AccessControlConfig(BaseModel):
|
||||
salt: Optional[str] = None
|
||||
"""Secret salt used for password hashing. **DO NOT TOUCH!** If changed you will no longer be able to log in with your existing accounts. Default unset, generated on first run."""
|
||||
|
||||
userManager: str = "octoprint.access.users.FilebasedUserManager"
|
||||
"""The user manager implementation to use for accessing user information. Currently only a filebased user manager is implemented which stores configured accounts in a YAML file (Default: `users.yaml` in the default configuration folder)."""
|
||||
|
||||
groupManager: str = "octoprint.access.groups.FilebasedGroupManager"
|
||||
"""The group manager implementation to use for accessing group information. Currently only a filebased user manager is implemented which stores configured groups in a YAML file (Default: `groups.yaml` in the default configuration folder)."""
|
||||
|
||||
permissionManager: str = "octoprint.access.permissions.PermissionManager"
|
||||
"""The permission manager implementation to use."""
|
||||
|
||||
userfile: Optional[str] = None
|
||||
"""The YAML user file to use. If left out defaults to `users.yaml` in the default configuration folder."""
|
||||
|
||||
groupfile: Optional[str] = None
|
||||
"""The YAML group file to use. If left out defaults to `groups.yaml` in the default configuration folder."""
|
||||
|
||||
autologinLocal: bool = False
|
||||
"""If set to true, will automatically log on clients originating from any of the networks defined in `localNetworks` as the user defined in `autologinAs`."""
|
||||
|
||||
localNetworks: List[str] = ["127.0.0.0/8", "::1/128"]
|
||||
"""A list of networks or IPs for which an automatic logon as the user defined in `autologinAs` will take place. If available OctoPrint will evaluate the `X-Forwarded-For` HTTP header for determining the client's IP address. Defaults to anything originating from localhost."""
|
||||
|
||||
autologinAs: Optional[str] = None
|
||||
"""The name of the user to automatically log on clients originating from `localNetworks` as. Must be the name of one of your configured users."""
|
||||
|
||||
trustBasicAuthentication: bool = False
|
||||
"""Whether to trust Basic Authentication headers. If you have setup Basic Authentication in front of OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will be logged into OctoPrint as the user user during Basic Authentication. **ONLY ENABLE THIS** if your OctoPrint instance is only accessible through a connection locked down through Basic Authentication!"""
|
||||
|
||||
checkBasicAuthenticationPassword: bool = True
|
||||
"""Whether to also check the password provided through Basic Authentication, if the Basic Authentication header is to be trusted. Disabling this will only match the user name in the Basic Authentication header and login the user without further checks, thus disable with caution."""
|
||||
|
||||
trustRemoteUser: bool = False
|
||||
"""Whether to trust remote user headers. If you have setup authentication in front of OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will be logged into OctoPrint as the user provided in the header. **ONLY ENABLE THIS** if your OctoPrint instance is only accessible through a connection locked down through an authenticating reverse proxy!"""
|
||||
|
||||
remoteUserHeader: str = "REMOTE_USER"
|
||||
"""Header used by the reverse proxy to convey the authenticated user."""
|
||||
|
||||
addRemoteUsers: bool = False
|
||||
"""If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint."""
|
||||
@@ -1,18 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import Dict
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ApiConfig(BaseModel):
|
||||
key: str = None
|
||||
"""Global API key, deprecated, use User API keys instead. Unset by default, will be generated on first run."""
|
||||
|
||||
apps: Dict[str, str] = {}
|
||||
|
||||
allowCrossOrigin: bool = False
|
||||
"""Whether to allow cross origin access to the API or not."""
|
||||
@@ -1,164 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from enum import Enum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
class ColorEnum(str, Enum):
|
||||
red = "red"
|
||||
orange = "orange"
|
||||
yellow = "yellow"
|
||||
green = "green"
|
||||
blue = "blue"
|
||||
violet = "violet"
|
||||
default = "default"
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ComponentOrderConfig(BaseModel):
|
||||
navbar: List[str] = [
|
||||
"settings",
|
||||
"systemmenu",
|
||||
"plugin_announcements",
|
||||
"plugin_logging_seriallog",
|
||||
"plugin_logging_plugintimingslog",
|
||||
"plugin_pi_support",
|
||||
"login",
|
||||
]
|
||||
"""Order of navbar items."""
|
||||
|
||||
sidebar: List[str] = [
|
||||
"plugin_firmware_check_warning",
|
||||
"plugin_firmware_check_info",
|
||||
"connection",
|
||||
"state",
|
||||
"files",
|
||||
]
|
||||
"""Order of sidebar items."""
|
||||
|
||||
tab: List[str] = [
|
||||
"temperature",
|
||||
"control",
|
||||
"plugin_gcodeviewer",
|
||||
"terminal",
|
||||
"timelapse",
|
||||
]
|
||||
"""Order of tabs."""
|
||||
|
||||
settings: List[str] = [
|
||||
"section_printer",
|
||||
"serial",
|
||||
"printerprofiles",
|
||||
"temperatures",
|
||||
"terminalfilters",
|
||||
"gcodescripts",
|
||||
"section_features",
|
||||
"features",
|
||||
"webcam",
|
||||
"accesscontrol",
|
||||
"plugin_gcodeviewer",
|
||||
"api",
|
||||
"plugin_appkeys",
|
||||
"section_octoprint",
|
||||
"server",
|
||||
"folders",
|
||||
"appearance",
|
||||
"plugin_logging",
|
||||
"plugin_pluginmanager",
|
||||
"plugin_softwareupdate",
|
||||
"plugin_announcements",
|
||||
"plugin_eventmanager",
|
||||
"plugin_backup",
|
||||
"plugin_tracking",
|
||||
"plugin_errortracking",
|
||||
"plugin_pi_support",
|
||||
]
|
||||
"""Order of settings."""
|
||||
|
||||
usersettings: List[str] = ["access", "interface"]
|
||||
"""Order of user settings."""
|
||||
|
||||
wizard: List[str] = [
|
||||
"plugin_softwareupdate_update",
|
||||
"plugin_backup",
|
||||
"plugin_corewizard_acl",
|
||||
"plugin_corewizard_onlinecheck",
|
||||
]
|
||||
"""Order of wizards."""
|
||||
|
||||
about: List[str] = [
|
||||
"about",
|
||||
"plugin_pi_support",
|
||||
"supporters",
|
||||
"authors",
|
||||
"changelog",
|
||||
"license",
|
||||
"thirdparty",
|
||||
"plugin_pluginmanager",
|
||||
]
|
||||
"""Order of about dialog items."""
|
||||
|
||||
generic: List[str] = []
|
||||
"""Order of generic items."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ComponentDisabledConfig(BaseModel):
|
||||
navbar: List[str] = []
|
||||
"""Disabled navbar items."""
|
||||
sidebar: List[str] = []
|
||||
"""Disabled sidebar items."""
|
||||
tab: List[str] = []
|
||||
"""Disabled tabs."""
|
||||
settings: List[str] = []
|
||||
"""Disabled settings."""
|
||||
usersettings: List[str] = []
|
||||
"""Disabled user settings."""
|
||||
wizard: List[str] = []
|
||||
"""Disabled wizards."""
|
||||
about: List[str] = []
|
||||
"""Disabled about dialog items."""
|
||||
generic: List[str] = []
|
||||
"""Disabled generic items."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ComponentConfig(BaseModel):
|
||||
order: ComponentOrderConfig = ComponentOrderConfig()
|
||||
"""Defines the order of the components within their respective containers."""
|
||||
|
||||
disabled: ComponentDisabledConfig = ComponentDisabledConfig()
|
||||
"""Disabled components per container. If a component is included here it will not be included in OctoPrint's UI at all. Note that this might mean that critical functionality will not be available if no replacement is registered."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class AppearanceConfig(BaseModel):
|
||||
name: str = ""
|
||||
"""Use this to give your OctoPrint instance a name. It will be displayed in the title bar (as "<Name> [OctoPrint]") and in the navigation bar (as "OctoPrint: <>")"""
|
||||
|
||||
color: ColorEnum = "default"
|
||||
"""Use this to color the navigation bar."""
|
||||
|
||||
colorTransparent: bool = False
|
||||
"""Makes the color of the navigation bar "transparent". In case your printer uses acrylic for its frame 😉."""
|
||||
|
||||
colorIcon: bool = True
|
||||
|
||||
defaultLanguage: str = "_default"
|
||||
"""Default language of OctoPrint. If left unset OctoPrint will try to match up available languages with the user's browser settings."""
|
||||
|
||||
showFahrenheitAlso: bool = False
|
||||
|
||||
fuzzyTimes: bool = True
|
||||
|
||||
closeModalsWithClick: bool = True
|
||||
|
||||
showInternalFilename: bool = True
|
||||
"""Show the internal filename in the files sidebar, if necessary."""
|
||||
|
||||
components: ComponentConfig = ComponentConfig()
|
||||
"""Configures the order and availability of the UI components."""
|
||||
@@ -1,86 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from enum import Enum
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
class LayoutEnum(str, Enum):
|
||||
horizontal = "horizontal"
|
||||
vertical = "vertical"
|
||||
|
||||
|
||||
class ControlSliderInputConfig(BaseModel):
|
||||
min: int = 0
|
||||
"""Minimum value of the slider."""
|
||||
|
||||
max: int = 255
|
||||
"""Maximum value of the slider."""
|
||||
|
||||
step: int = 1
|
||||
"""Step size per slider tick."""
|
||||
|
||||
|
||||
class ControlInputConfig(BaseModel):
|
||||
name: str
|
||||
"""Name to display for the input field."""
|
||||
|
||||
parameter: str
|
||||
"""Internal parameter name for the input field, used as a placeholder in `command`/`commands`."""
|
||||
|
||||
default: Union[str, int, float, bool]
|
||||
"""Default value for the input field."""
|
||||
|
||||
slider: Optional[ControlSliderInputConfig] = None
|
||||
"""If this attribute is included, instead of an input field a slider control will be rendered."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ContainerConfig(BaseModel):
|
||||
children: "List[Union[ContainerConfig, ControlConfig]]" = []
|
||||
"""A list of children controls or containers contained within this container."""
|
||||
|
||||
name: Optional[str] = None
|
||||
"""A name to display above the container, basically a section header."""
|
||||
|
||||
layout: LayoutEnum = "vertical"
|
||||
"""The layout to use for laying out the contained children, either from top to bottom (`vertical`) or from left to right (`horizontal`)."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ControlConfig(BaseModel):
|
||||
name: str
|
||||
"""The name of the control, will be displayed either on the button if it's a control sending a command or as a label for controls which only display output."""
|
||||
|
||||
command: Optional[str] = None
|
||||
"""A single GCODE command to send to the printer. Will be rendered as a button which sends the command to the printer upon click. The button text will be the value of the `name` attribute. Mutually exclusive with `commands` and `script`. The rendered button be disabled if the printer is currently offline or printing or alternatively if the requirements defined via the `enabled` attribute are not met."""
|
||||
|
||||
commands: Optional[List[str]] = None
|
||||
"""A list of GCODE commands to send to the printer. Will be rendered as a button which sends the commands to the printer upon click. The button text will be the value of the `name` attribute. Mutually exclusive with `command` and `script`. The rendered button will be disabled if the printer is currently offline or printing or alternatively if the requirements defined via the `enabled` attribute are not met."""
|
||||
|
||||
script: Optional[str] = None
|
||||
"""The name of a full blown [GCODE script]() to send to the printer. Will be rendered as a button which sends the script to the printer upon click. The button text will be the value of the `name` attribute. Mutually exclusive with `command` and `commands`. The rendered button will be disabled if the printer is currently offline or printing or alternatively if the requirements defined via the `enabled` attribute are not met. Values of input parameters will be available in the template context under the `parameter` variable (e.g. an input parameter `speed` will be available in the script template as `parameter.speed`). On top of that all other variables defined in the [GCODE template context]() will be available."""
|
||||
|
||||
javascript: Optional[str] = None
|
||||
"""A JavaScript snippet to be executed when the button rendered for `command` or `commands` is clicked. This allows to override the direct sending of the command or commands to the printer with more sophisticated behaviour. The JavaScript snippet is `eval`'d and processed in a context where the control it is part of is provided as local variable `data` and the `ControlViewModel` is available as `self`."""
|
||||
|
||||
additionalClasses: Optional[str] = None
|
||||
"""Additional classes to apply to the button of a `command`, `commands`, `script` or `javascript` control, other than the default `btn`. Can be used to visually style the button, e.g. set to `btn-danger` to turn the button red."""
|
||||
|
||||
enabled: Optional[str] = None
|
||||
"""A JavaScript snippet returning either `true` or `false` determining whether the control should be enabled or not. This allows to override the default logic for the enable state of the control (disabled if printer is offline). The JavaScript snippet is `eval`'d and processed in a context where the control it is part of is provided as local variable `data` and the `ControlViewModel` is available as `self`."""
|
||||
|
||||
input: Optional[List[ControlInputConfig]] = []
|
||||
"""A list of definitions of input parameters for a `command` or `commands`, to be rendered as additional input fields. `command`/`commands` may contain placeholders to be replaced by the values obtained from the user for the defined input fields."""
|
||||
|
||||
regex: Optional[str] = None
|
||||
"""A [regular expression <re-syntax>](https://docs.python.org/3/library/re.html#regular-expression-syntax) to match against lines received from the printer to retrieve information from it (e.g. specific output). Together with `template` this allows rendition of received data from the printer within the UI."""
|
||||
|
||||
template: Optional[str] = None
|
||||
r"""A template to use for rendering the match of `regex`. May contain placeholders in [Python Format String Syntax](https://docs.python.org/3/library/string.html#formatstrings) for either named groups within the regex (e.g. `Temperature: {temperature}` for a regex `T:\s*(?P<temperature>\d+(\.\d*)`) or positional groups within the regex (e.g. `Position: X={0}, Y={1}, Z={2}, E={3}` for a regex `X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)`)."""
|
||||
|
||||
confirm: Optional[str] = None
|
||||
"""A text to display to the user to confirm his button press. Can be used with sensitive custom controls like changing EEPROM values in order to prevent accidental clicks. The text will be displayed in a confirmation dialog."""
|
||||
@@ -1,55 +0,0 @@
|
||||
__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 pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
class StylesheetEnum(str, Enum):
|
||||
css = "css"
|
||||
less = "less"
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class DevelWebassetsConfig(BaseModel):
|
||||
bundle: bool = True
|
||||
"""If set to true, OctoPrint will merge all JS, all CSS and all Less files into one file per type to reduce request count. Setting it to false will load all assets individually. Note: if this is set to false, no minification will take place regardless of the `minify` setting."""
|
||||
|
||||
clean_on_startup: bool = True
|
||||
"""Whether to delete generated web assets on server startup (forcing a regeneration)."""
|
||||
|
||||
minify: bool = True
|
||||
"""If set to true, OctoPrint will the core and library javascript assets. Note: if `bundle` is set to false, no minification will take place either."""
|
||||
|
||||
minify_plugins: bool = False
|
||||
"""If set to true, OctoPrint will also minify the third party plugin javascript assets. Note: if `bundle` or `minify` are set to false, no minification of the plugin assets will take place either."""
|
||||
|
||||
|
||||
class DevelCacheConfig(BaseModel):
|
||||
enabled: bool = True
|
||||
"""Whether to enable caching. Defaults to true. Setting it to false will cause the UI to alway be fully rerendered on request to `/` on the server."""
|
||||
|
||||
preemptive: bool = True
|
||||
"""Whether to enable the preemptive cache."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class DevelConfig(BaseModel):
|
||||
stylesheet: StylesheetEnum = "css"
|
||||
"""Settings for stylesheet preference. OctoPrint will prefer to use the stylesheet type specified here. Usually (on a production install) that will be the compiled css (default). Developers may specify less here too."""
|
||||
|
||||
cache: DevelCacheConfig = DevelCacheConfig()
|
||||
"""Settings for OctoPrint's internal caching."""
|
||||
|
||||
webassets: DevelWebassetsConfig = DevelWebassetsConfig()
|
||||
"""Settings for OctoPrint's web asset merging and minifying."""
|
||||
|
||||
useFrozenDictForPrinterState: bool = True
|
||||
|
||||
showLoadingAnimation: bool = True
|
||||
"""Enable or disable the loading animation."""
|
||||
|
||||
sockJsConnectTimeout: float = 30
|
||||
pluginTimings: bool = False
|
||||
@@ -1,29 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class PrintTimeEstimationConfig(BaseModel):
|
||||
statsWeighingUntil: float = 0.5
|
||||
"""Until which percentage to do a weighted mixture of statistical duration (analysis or past prints) with the result from the calculated estimate if that's already available. Utilized to compensate for the fact that the earlier in a print job, the least accuracy even a stable calculated estimate provides."""
|
||||
|
||||
validityRange: float = 0.15
|
||||
"""Range the assumed percentage (based on current estimated statistical, calculated or mixed total vs elapsed print time so far) needs to be around the actual percentage for the result to be used."""
|
||||
|
||||
forceDumbFromPercent: float = 0.3
|
||||
"""If no estimate could be calculated until this percentage and no statistical data is available, use dumb linear estimate. Value between 0 and 1.0."""
|
||||
|
||||
forceDumbAfterMin: float = 30.0
|
||||
"""If no estimate could be calculated until this many minutes into the print and no statistical data is available, use dumb linear estimate."""
|
||||
|
||||
stableThreshold: int = 60
|
||||
"""Average fluctuation between individual calculated estimates to consider in stable range. Seconds of difference."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class EstimationConfig(BaseModel):
|
||||
printTime: PrintTimeEstimationConfig = PrintTimeEstimationConfig()
|
||||
"""Parameters for the print time estimation during an ongoing print job."""
|
||||
@@ -1,40 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from enum import Enum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
class SubscriptionTypeEnum(str, Enum):
|
||||
system = "system"
|
||||
gcode = "gcode"
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class EventSubscription(BaseModel):
|
||||
event: str
|
||||
"""The event to subscribe to."""
|
||||
|
||||
command: str
|
||||
"""The command to execute when the event is triggered, either a GCODE or a system command."""
|
||||
|
||||
type: SubscriptionTypeEnum
|
||||
"""The type of the command."""
|
||||
|
||||
enabled: bool = True
|
||||
"""Whether the event subscription should be enabled."""
|
||||
|
||||
debug: bool = False
|
||||
"""If set to `true`, OctoPrint will log the command after performing all placeholder replacements."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class EventsConfig(BaseModel):
|
||||
enabled: bool = True
|
||||
"""Whether event subscriptions should be enabled or not."""
|
||||
|
||||
subscriptions: List[EventSubscription] = []
|
||||
"""A list of event subscriptions."""
|
||||
@@ -1,45 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class FeatureConfig(BaseModel):
|
||||
temperatureGraph: bool = True
|
||||
"""Whether to enable the temperature graph in the UI or not."""
|
||||
|
||||
sdSupport: bool = True
|
||||
"""Specifies whether support for SD printing and file management should be enabled."""
|
||||
|
||||
keyboardControl: bool = True
|
||||
"""Whether to enable the keyboard control feature in the control tab."""
|
||||
|
||||
pollWatched: bool = False
|
||||
"""Whether to actively poll the watched folder (true) or to rely on the OS's file system notifications instead (false)."""
|
||||
|
||||
modelSizeDetection: bool = True
|
||||
"""Whether to enable model size detection and warning (true) or not (false)."""
|
||||
|
||||
rememberFileFolder: bool = False
|
||||
"""Whether to remember the selected folder on the file manager."""
|
||||
|
||||
printStartConfirmation: bool = False
|
||||
"""Whether to show a confirmation on print start (true) or not (false)"""
|
||||
|
||||
printCancelConfirmation: bool = True
|
||||
"""Whether to show a confirmation on print cancelling (true) or not (false)"""
|
||||
|
||||
uploadOverwriteConfirmation: bool = True
|
||||
|
||||
autoUppercaseBlacklist: List[str] = ["M117", "M118"]
|
||||
"""Commands that should never be auto-uppercased when sent to the printer through the Terminal tab."""
|
||||
|
||||
g90InfluencesExtruder: bool = False
|
||||
"""Whether `G90`/`G91` also influence absolute/relative mode of extruders."""
|
||||
|
||||
enforceReallyUniversalFilenames: bool = False
|
||||
"""Replace all special characters and spaces with text equivalent to make them universally compatible. Most OS filesystems work fine with unicode characters, but just in case you can revert to the older behaviour by setting this to true."""
|
||||
@@ -1,49 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class FolderConfig(BaseModel):
|
||||
uploads: Optional[str] = None
|
||||
"""Absolute path where to store gcode uploads. Defaults to the `uploads` folder in OctoPrint's base folder."""
|
||||
|
||||
timelapse: Optional[str] = None
|
||||
"""Absolute path where to store finished timelase recordings. Defaults to the `timelapse` folder in OctoPrint's base folder."""
|
||||
|
||||
timelapse_tmp: Optional[str] = None
|
||||
"""Absolute path where to store temporary timelapse snapshots. Defaults to the `timelapse/tmp` folder in OctoPrint's base folder."""
|
||||
|
||||
logs: Optional[str] = None
|
||||
"""Absolute path where to store logs. Defaults to the `logs` folder in OctoPrint's base folder."""
|
||||
|
||||
virtualSd: Optional[str] = None
|
||||
"""Absolute path where to store the virtual printer's SD card files. Defaults to the `virtualSd` folder in OctoPrint's base folder."""
|
||||
|
||||
watched: Optional[str] = None
|
||||
"""Absolute path to the watched folder. Defaults to the `watched` folder in OctoPrint's base folder."""
|
||||
|
||||
plugins: Optional[str] = None
|
||||
"""Absolute path where to locate and install single file plugins. Defaults to the `plugins` folder in OctoPrint's base folder."""
|
||||
|
||||
slicingProfiles: Optional[str] = None
|
||||
"""Absolute path where to store slicing profiles. Defaults to the `slicingProfiles` folder in OctoPrint's base folder."""
|
||||
|
||||
printerProfiles: Optional[str] = None
|
||||
"""Absolute path where to store printer profiles. Defaults to the `printerProfiles` folder in OctoPrint's base folder."""
|
||||
|
||||
scripts: Optional[str] = None
|
||||
"""Absolute path where to store (GCODE) scripts. Defaults to the `scripts` folder in OctoPrint's base folder."""
|
||||
|
||||
translations: Optional[str] = None
|
||||
"""Absolute path where to store additional translations. Defaults to the `translations` folder in OctoPrint's base folder."""
|
||||
|
||||
generated: Optional[str] = None
|
||||
"""Absolute path where to store generated files. Defaults to the `generated` folder in OctoPrint's base folder."""
|
||||
|
||||
data: Optional[str] = None
|
||||
"""Absolute path where to store additional data. Defaults to the `data` folder in OctoPrint's base folder."""
|
||||
@@ -1,34 +0,0 @@
|
||||
__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 pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
class RunAtEnum(str, Enum):
|
||||
never: str = "never"
|
||||
idle: str = "idle"
|
||||
always: str = "always"
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class GcodeAnalysisConfig(BaseModel):
|
||||
maxExtruders: int = 10
|
||||
"""Maximum number of extruders to support/to sanity check for."""
|
||||
|
||||
throttle_normalprio: float = 0.01
|
||||
"""Pause between each processed GCODE line batch in normal priority mode, seconds."""
|
||||
|
||||
throttle_highprio: float = 0.0
|
||||
"""Pause between each processed GCODE line batch in high priority mode (e.g. on fresh uploads), seconds."""
|
||||
|
||||
throttle_lines: int = 100
|
||||
"""GCODE line batch size."""
|
||||
|
||||
runAt: RunAtEnum = "idle"
|
||||
"""Whether to run the analysis only when idle (not printing), regardless of printing state or never."""
|
||||
|
||||
bedZ: float = 0.0
|
||||
"""Z position considered the location of the bed."""
|
||||
@@ -1,19 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import Dict, List
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class PluginsConfig(BaseModel):
|
||||
disabled: List[str] = Field([], alias="_disabled")
|
||||
"""Identifiers of installed but disabled plugins."""
|
||||
|
||||
forced_compatible: List[str] = Field([], alias="_forcedCompatible")
|
||||
"""Identifiers of plugins for which python compatibility information will be ignored and the plugin considered compatible in any case. Only for development, do **NOT** use in production."""
|
||||
|
||||
sorting_order: Dict[str, Dict[str, int]] = Field({}, alias="_sortingOrder")
|
||||
"""Custom sorting of hooks and implementations provided by plugins. Two-tiered dictionary structure, plugin identifier mapping to a dictionary of order overrides mapped by sorting context/hook name."""
|
||||
@@ -1,12 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class PrinterParametersConfig(BaseModel):
|
||||
pauseTriggers: List[str] = []
|
||||
@@ -1,13 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class PrinterProfilesConfig(BaseModel):
|
||||
default: Optional[str] = None
|
||||
"""Name of the printer profile to default to."""
|
||||
@@ -1,31 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class GcodeScriptsConfig(BaseModel):
|
||||
afterPrinterConnected: Optional[str] = None
|
||||
beforePrinterDisconnected: Optional[str] = None
|
||||
beforePrintStarted: Optional[str] = None
|
||||
afterPrintCancelled: Optional[
|
||||
str
|
||||
] = "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0"
|
||||
afterPrintDone: Optional[str] = None
|
||||
beforePrintPaused: Optional[str] = None
|
||||
afterPrintResumed: Optional[str] = None
|
||||
beforeToolChange: Optional[str] = None
|
||||
afterToolChange: Optional[str] = None
|
||||
snippets: Dict[str, str] = {
|
||||
"disable_hotends": "{% if printer_profile.extruder.sharedNozzle %}M104 T0 S0\n{% else %}{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}{% endif %}",
|
||||
"disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}",
|
||||
}
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ScriptsConfig(BaseModel):
|
||||
gcode: GcodeScriptsConfig = GcodeScriptsConfig()
|
||||
@@ -1,238 +0,0 @@
|
||||
__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 pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
class AlwaysDetectNeverEnum(str, Enum):
|
||||
always = "always"
|
||||
detect = "detect"
|
||||
never = "never"
|
||||
|
||||
|
||||
class InfoWarnNeverEnum(str, Enum):
|
||||
info = "info"
|
||||
warn = "warn"
|
||||
never = "never"
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class SerialTimeoutConfig(BaseModel):
|
||||
detectionFirst: float = 10.0
|
||||
detectionConsecutive: float = 2.0
|
||||
|
||||
connection: float = 10.0
|
||||
"""Timeout for waiting to establish a connection with the selected port, in seconds"""
|
||||
|
||||
communication: float = 30.0
|
||||
"""Timeout during serial communication, in seconds"""
|
||||
|
||||
communicationBusy: float = 3.0
|
||||
"""Timeout during serial communication when busy protocol support is detected, in seconds"""
|
||||
|
||||
temperature: float = 5.0
|
||||
"""Timeout after which to query temperature when no target is set"""
|
||||
|
||||
temperatureTargetSet: float = 2.0
|
||||
"""Timeout after which to query temperature when a target is set"""
|
||||
|
||||
temperatureAutoreport: float = 2.0
|
||||
|
||||
sdStatus: float = 1.0
|
||||
"""Timeout after which to query the SD status while SD printing"""
|
||||
|
||||
sdStatusAutoreport: float = 1.0
|
||||
posAutoreport: float = 5.0
|
||||
resendOk: float = 0.5
|
||||
baudrateDetectionPause: float = 1.0
|
||||
positionLogWait: float = 10.0
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class SerialMaxTimeouts(BaseModel):
|
||||
idle: int = 2
|
||||
"""Max. timeouts when the printer is idle"""
|
||||
|
||||
printing: int = 5
|
||||
"""Max. timeouts when the printer is printing"""
|
||||
|
||||
long: int = 5
|
||||
"""Max. timeouts when a long running command is active"""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class SerialCapabilities(BaseModel):
|
||||
autoreport_temp: bool = True
|
||||
"""Whether to enable temperature autoreport in the firmware if its support is detected"""
|
||||
|
||||
autoreport_sdstatus: bool = True
|
||||
autoreport_pos: bool = True
|
||||
|
||||
busy_protocol: bool = True
|
||||
"""Whether to shorten the communication timeout if the firmware seems to support the busy protocol"""
|
||||
|
||||
emergency_parser: bool = True
|
||||
extended_m20: bool = True
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class SerialConfig(BaseModel):
|
||||
port: Optional[str] = None
|
||||
"""The default port to use to connect to the printer. If unset or set to `AUTO`, the port will be auto-detected."""
|
||||
|
||||
baudrate: Optional[int] = None
|
||||
"""The default baudrate to use to connect to the printer. If unset or set to 0, the baudrate will be auto-detected."""
|
||||
|
||||
exclusive: bool = True
|
||||
"""Whether to request the serial port exclusively or not"""
|
||||
|
||||
lowLatency: bool = False
|
||||
"""Whether to request low latency mode on the serial port or not"""
|
||||
|
||||
autoconnect: bool = False
|
||||
"""Whether to try to automatically connect to the printer on startup or not"""
|
||||
|
||||
log: bool = False
|
||||
"""Whether to log whole communication to serial.log (warning: might decrease performance)"""
|
||||
|
||||
timeout: SerialTimeoutConfig = SerialTimeoutConfig()
|
||||
"""Timeouts used for the serial connection to the printer, you might want to adjust these if you are experiencing connection problems"""
|
||||
|
||||
maxCommunicationTimeouts: SerialMaxTimeouts = SerialMaxTimeouts()
|
||||
|
||||
maxWritePasses: int = 5
|
||||
"""Maximum number of write attempts to serial during which nothing can be written before the communication with the printer is considered dead and OctoPrint will disconnect with an error"""
|
||||
|
||||
additionalPorts: List[str] = []
|
||||
"""Use this to define additional patterns to consider for serial port listing. Must be a valid ["glob" pattern](http://docs.python.org/3/library/glob.html)"""
|
||||
|
||||
additionalBaudrates: List[int] = []
|
||||
"""Use this to define additional baud rates to offer for connecting to serial ports. Must be a valid integer"""
|
||||
|
||||
blacklistedPorts: List[str] = []
|
||||
blacklistedBaudrates: List[int] = []
|
||||
|
||||
longRunningCommands: List[str] = [
|
||||
"G4",
|
||||
"G28",
|
||||
"G29",
|
||||
"G30",
|
||||
"G32",
|
||||
"M400",
|
||||
"M226",
|
||||
"M600",
|
||||
]
|
||||
"""Commands which are known to take a long time to be acknowledged by the firmware, e.g. homing, dwelling, auto leveling etc."""
|
||||
|
||||
blockedCommands: List[str] = ["M0", "M1"]
|
||||
"""Commands which should not be sent to the printer, e.g. because they are known to block serial communication until physical interaction with the printer as is the case on most firmwares with the default M0 and M1."""
|
||||
|
||||
ignoredCommands: List[str] = []
|
||||
"""Commands which should not be sent to the printer and just silently ignored. An example of when you may wish to use this could be useful if you wish to manually change a filament on M600, by using that as a Pausing command."""
|
||||
|
||||
pausingCommands: List[str] = ["M0", "M1", "M25"]
|
||||
"""Commands which should cause OctoPrint to pause any ongoing prints."""
|
||||
|
||||
emergencyCommands: List[str] = ["M112", "M108", "M410"]
|
||||
|
||||
checksumRequiringCommands: List[str] = ["M110"]
|
||||
"""Commands which need to always be send with a checksum."""
|
||||
|
||||
helloCommand: str = "M110 N0"
|
||||
"""Command to send in order to initiate a handshake with the printer."""
|
||||
|
||||
disconnectOnErrors: bool = True
|
||||
"""Whether to disconnect from the printer on errors or not."""
|
||||
|
||||
ignoreErrorsFromFirmware: bool = False
|
||||
"""Whether to completely ignore errors from the firmware or not."""
|
||||
|
||||
terminalLogSize: int = 20
|
||||
lastLineBufferSize: int = 50
|
||||
|
||||
logResends: bool = True
|
||||
"""Whether to log resends to octoprint.log or not. Invaluable debug tool without performance impact, leave on if possible please."""
|
||||
|
||||
supportResendsWithoutOk: AlwaysDetectNeverEnum = "detect"
|
||||
"""Whether to support resends without follow-up ok or not."""
|
||||
|
||||
logPositionOnPause: bool = True
|
||||
logPositionOnCancel: bool = False
|
||||
abortHeatupOnCancel: bool = True
|
||||
|
||||
waitForStartOnConnect: bool = False
|
||||
"""Whether OctoPrint should wait for the `start` response from the printer before trying to send commands during connect."""
|
||||
|
||||
alwaysSendChecksum: bool = False
|
||||
"""Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for successful communication with Repetier firmware."""
|
||||
|
||||
neverSendChecksum: bool = False
|
||||
|
||||
sendChecksumWithUnknownCommands: bool = False
|
||||
r"""Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not* detected as valid GCODE (as in, they do not match the regular expression `^\s*([GM]\d+|T)`)."""
|
||||
|
||||
unknownCommandsNeedAck: bool = False
|
||||
r"""Specifies whether OctoPrint should also use up acknowledgments (`ok`) for commands that are *not* detected as valid GCODE (as in, they do not match the regular expression `^\s*([GM]\d+|T)`)."""
|
||||
|
||||
sdRelativePath: bool = False
|
||||
"""Specifies whether firmware expects relative paths for selecting SD files."""
|
||||
|
||||
sdAlwaysAvailable: bool = False
|
||||
"""Whether to always assume that an SD card is present in the printer. Needed by some firmwares which don't report the SD card status properly."""
|
||||
|
||||
sdLowerCase: bool = False
|
||||
sdCancelCommand: str = "M25"
|
||||
maxNotSdPrinting: int = 2
|
||||
swallowOkAfterResend: bool = True
|
||||
|
||||
repetierTargetTemp: bool = False
|
||||
"""Whether the printer sends repetier style target temperatures in the format `TargetExtr0:<temperature>` instead of attaching that information to the regular `M105` responses."""
|
||||
|
||||
externalHeatupDetection: bool = True
|
||||
"""Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to communication, so disable for printers running Repetier firmware."""
|
||||
|
||||
supportWait: bool = True
|
||||
|
||||
ignoreIdenticalResends: bool = False
|
||||
"""Whether to ignore identical resends from the printer (true, repetier) or not (false)."""
|
||||
|
||||
identicalResendsCountdown: int = 7
|
||||
"""If `ignoreIdenticalResends` is true, how many consecutive identical resends to ignore."""
|
||||
|
||||
supportFAsCommand: bool = False
|
||||
"""Whether to support `F` on its own as a valid GCODE command (true) or not (false)."""
|
||||
|
||||
firmwareDetection: bool = True
|
||||
"""Whether to attempt to auto detect the firmware of the printer and adjust settings accordingly (true) or not and rely on manual configuration (false)."""
|
||||
|
||||
blockWhileDwelling: bool = False
|
||||
"""Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier) or not (false)."""
|
||||
|
||||
useParityWorkaround: AlwaysDetectNeverEnum = "detect"
|
||||
maxConsecutiveResends: int = 10
|
||||
sendM112OnError: bool = True
|
||||
disableSdPrintingDetection: bool = False
|
||||
ackMax: int = 1
|
||||
sanityCheckTools: bool = True
|
||||
notifySuppressedCommands: InfoWarnNeverEnum = "warn"
|
||||
capabilities: SerialCapabilities = SerialCapabilities()
|
||||
|
||||
resendRatioThreshold: int = 10
|
||||
"""Percentage of resend requests among all sent lines that should be considered critical."""
|
||||
|
||||
resendRatioStart: int = 100
|
||||
ignoreEmptyPorts: bool = False
|
||||
|
||||
encoding: str = "ascii"
|
||||
"""Encoding to use when talking to a machine. `ascii` limits access to characters 0-127, `latin_1` enables access to the "extended" ascii characters 0-255. Other values can be used, see [Python's standard encodings](https://docs.python.org/3/library/codecs.html#standard-encodings)."""
|
||||
|
||||
enableShutdownActionCommand: bool = False
|
||||
"""Whether to enable support for the shutdown action command, allowing the printer to shut down OctoPrint and the system it's running on."""
|
||||
|
||||
# command specific flags
|
||||
triggerOkForM29: bool = True
|
||||
"""Whether to automatically trigger an ok for `M29` (a lot of versions of this command are buggy and the response skips on the ok)."""
|
||||
@@ -1,206 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from enum import Enum
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
CONST_15MIN = 15 * 60
|
||||
CONST_1GB = 1024 * 1024 * 1024
|
||||
CONST_500MB = 500 * 1024 * 1024
|
||||
CONST_200MB = 200 * 1024 * 1024
|
||||
CONST_100KB = 100 * 1024
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ReverseProxyConfig(BaseModel):
|
||||
prefixHeader: Optional[str] = None
|
||||
"""The request header from which to determine the URL prefix under which OctoPrint is served by the reverse proxy."""
|
||||
|
||||
schemeHeader: Optional[str] = None
|
||||
"""The request header from which to determine the scheme (http or https) under which a specific request to OctoPrint was made to the reverse proxy."""
|
||||
|
||||
hostHeader: Optional[str] = None
|
||||
"""The request header from which to determine the host under which OctoPrint is served by the reverse proxy."""
|
||||
|
||||
serverHeader: Optional[str] = None
|
||||
|
||||
portHeader: Optional[str] = None
|
||||
|
||||
prefixFallback: Optional[str] = None
|
||||
"""Use this option to define an optional URL prefix (with a leading /, so absolute to your server's root) under which to run OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse proxy under a different root endpoint than `/` and can't configure said reverse proxy to send a prefix HTTP header (X-Script-Name by default, see above) with forwarded requests."""
|
||||
|
||||
schemeFallback: Optional[str] = None
|
||||
"""Use this option to define an optional forced scheme (http or https) under which to run OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse proxy that also does HTTPS determination but can't configure said reverse proxy to send a scheme HTTP header (X-Scheme by default, see above) with forwarded requests."""
|
||||
|
||||
hostFallback: Optional[str] = None
|
||||
"""Use this option to define an optional forced host under which to run OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse proxy with a different hostname than OctoPrint itself but can't configure said reverse proxy to send a host HTTP header (X-Forwarded-Host by default, see above) with forwarded requests."""
|
||||
|
||||
serverFallback: Optional[str] = None
|
||||
|
||||
portFallback: Optional[str] = None
|
||||
|
||||
trustedDownstream: List[str] = []
|
||||
"""List of trusted downstream servers for which to ignore the IP address when trying to determine the connecting client's IP address. If you have OctoPrint behind more than one reverse proxy you should add their IPs here so that they won't be interpreted as the client's IP. One reverse proxy will be handled correctly by default."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class UploadsConfig(BaseModel):
|
||||
maxSize: int = CONST_1GB
|
||||
"""Maximum size of uploaded files in bytes, defaults to 1GB."""
|
||||
|
||||
nameSuffix: str = "name"
|
||||
"""Suffix used for storing the filename in the file upload headers when streaming uploads."""
|
||||
|
||||
pathSuffix: str = "path"
|
||||
"""Suffix used for storing the path to the temporary file in the file upload headers when streaming uploads."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class CommandsConfig(BaseModel):
|
||||
systemShutdownCommand: Optional[str] = None
|
||||
"""Command to shut down the system OctoPrint is running on."""
|
||||
|
||||
systemRestartCommand: Optional[str] = None
|
||||
"""Command to restart the system OctoPrint is running on."""
|
||||
|
||||
serverRestartCommand: Optional[str] = None
|
||||
"""Command to restart OctoPrint."""
|
||||
|
||||
localPipCommand: Optional[str] = None
|
||||
"""pip command associated with OctoPrint, used for installing plugins and updates, if unset (default) the command will be autodetected based on the current python executable - unless you have a really special setup this is the right way to do it and there should be no need to ever touch this setting."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class OnlineCheckConfig(BaseModel):
|
||||
enabled: Optional[bool] = None
|
||||
"""Whether the online check is enabled. Ships unset, the user will be asked to make a decision as part of the setup wizard."""
|
||||
|
||||
interval: int = CONST_15MIN
|
||||
"""Interval in which to check for online connectivity (in seconds), defaults to 15 minutes."""
|
||||
|
||||
host: str = "1.1.1.1"
|
||||
"""DNS host against which to check, defaults to Cloudflare's DNS."""
|
||||
|
||||
port: int = 53
|
||||
"""DNS port against which to check, defaults to the standard DNS port."""
|
||||
|
||||
name: str = "octoprint.org"
|
||||
"""Host name for which to check name resolution, defaults to OctoPrint's main domain."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class PluginBlacklistConfig(BaseModel):
|
||||
enabled: Optional[bool] = None
|
||||
"""Whether use of the blacklist is enabled. If unset, the user will be asked to make a decision as part of the setup wizard."""
|
||||
|
||||
url: str = "https://plugins.octoprint.org/blacklist.json"
|
||||
"""The URL from which to fetch the blacklist."""
|
||||
|
||||
ttl: int = CONST_15MIN
|
||||
"""Time to live of the cached blacklist, in seconds (default: 15 minutes)."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class DiskspaceConfig(BaseModel):
|
||||
warning: int = CONST_500MB
|
||||
"""Threshold (bytes) after which to consider disk space becoming sparse, defaults to 500MB."""
|
||||
|
||||
critical: int = CONST_200MB
|
||||
"""Threshold (bytes) after which to consider disk space becoming critical, defaults to 200MB."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class PreemptiveCacheConfig(BaseModel):
|
||||
exceptions: List[str] = []
|
||||
"""Which server paths to exclude from the preemptive cache, e.g. `/some/path`."""
|
||||
|
||||
until: int = 7
|
||||
"""How many days to leave unused entries in the preemptive cache config."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class IpCheckConfig(BaseModel):
|
||||
enabled: bool = True
|
||||
"""Whether to enable the check."""
|
||||
|
||||
trustedSubnets: List[str] = []
|
||||
"""Additional non-local subnets to consider trusted, in CIDR notation, e.g. `192.168.1.0/24`."""
|
||||
|
||||
|
||||
class SameSiteEnum(str, Enum):
|
||||
strict = "Strict"
|
||||
lax = "Lax"
|
||||
none = "None"
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class CookiesConfig(BaseModel):
|
||||
secure: bool = False
|
||||
"""Whether to set the `Secure` flag to true on cookies. Only set to true if you are running OctoPrint behind a reverse proxy taking care of SSL termination."""
|
||||
|
||||
samesite: Optional[SameSiteEnum] = None
|
||||
"""`SameSite` setting to use on the cookies. Possible values are `None`, `Lax` and `Strict`. Defaults to unset. Be advised that many browsers now default to `Lax` unless you configure cookies to be set with `Secure` flag set, explicitly set `SameSite` setting here and also serve OctoPrint over https. The `Lax` setting is known to cause with embedding OctoPrint in frames. See also ["Feature: Cookies default to SameSite=Lax"](https://www.chromestatus.com/feature/5088147346030592), ["Feature: Reject insecure SameSite=None cookies"](https://www.chromestatus.com/feature/5633521622188032) and [issue #3482](https://github.com/OctoPrint/OctoPrint/issues/3482)."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ServerConfig(BaseModel):
|
||||
host: Optional[str] = None
|
||||
"""Use this option to define the host to which to bind the server. If unset, OctoPrint will attempt to bind on all available interfaces, IPv4 and v6 unless either is disabled."""
|
||||
|
||||
port: int = 5000
|
||||
"""Use this option to define the port to which to bind the server."""
|
||||
|
||||
firstRun: bool = True
|
||||
"""If this option is true, OctoPrint will show the First Run wizard and set the setting to false after that completes."""
|
||||
|
||||
startOnceInSafeMode: bool = False
|
||||
"""If this option is true, OctoPrint will enable safe mode on the next server start and reset the setting to false"""
|
||||
|
||||
ignoreIncompleteStartup: bool = False
|
||||
"""Set this to true to make OctoPrint ignore incomplete startups. Helpful for development."""
|
||||
|
||||
incompleteStartup: bool = False
|
||||
"""Signals to OctoPrint that the last startup was incomplete. OctoPrint will then startup in safe mode."""
|
||||
|
||||
seenWizards: Dict[str, str] = {}
|
||||
|
||||
secretKey: Optional[str] = None
|
||||
"""Secret key for encrypting cookies and such, randomly generated on first run."""
|
||||
|
||||
heartbeat: int = CONST_15MIN
|
||||
|
||||
reverseProxy: ReverseProxyConfig = ReverseProxyConfig()
|
||||
"""Settings if OctoPrint is running behind a reverse proxy (haproxy, nginx, apache, ...) that doesn't correctly set the [required headers](https://community.octoprint.org/t/reverse-proxy-configuration-examples/1107). These are necessary in order to make OctoPrint generate correct external URLs so that AJAX requests and download URLs work, and so that client IPs are read correctly."""
|
||||
|
||||
uploads: UploadsConfig = UploadsConfig()
|
||||
"""Settings for file uploads to OctoPrint, such as maximum allowed file size and header suffixes to use for streaming uploads. OctoPrint does some nifty things internally in order to allow streaming of large file uploads to the application rather than just storing them in memory. For that it needs to do some rewriting of the incoming upload HTTP requests, storing the uploaded file to a temporary location on disk and then sending an internal request to the application containing the original filename and the location of the temporary file."""
|
||||
|
||||
maxSize: int = CONST_100KB
|
||||
"""Maximum size of requests other than file uploads in bytes, defaults to 100KB."""
|
||||
|
||||
commands: CommandsConfig = CommandsConfig()
|
||||
"""Commands to restart/shutdown octoprint or the system it's running on."""
|
||||
|
||||
onlineCheck: OnlineCheckConfig = OnlineCheckConfig()
|
||||
"""Configuration of the regular online connectivity check."""
|
||||
|
||||
pluginBlacklist: PluginBlacklistConfig = PluginBlacklistConfig()
|
||||
"""Configuration of the plugin blacklist."""
|
||||
|
||||
diskspace: DiskspaceConfig = DiskspaceConfig()
|
||||
"""Settings of when to display what disk space warning."""
|
||||
|
||||
preemptiveCache: PreemptiveCacheConfig = PreemptiveCacheConfig()
|
||||
"""Configuration of the preemptive cache."""
|
||||
|
||||
ipCheck: IpCheckConfig = IpCheckConfig()
|
||||
"""Configuration of the client IP check to warn about connections from external networks."""
|
||||
|
||||
allowFraming: bool = False
|
||||
"""Whether to allow OctoPrint to be embedded in a frame or not. Note that depending on your setup you might have to set SameSite to None, Secure to true and serve OctoPrint through a reverse proxy that enables https for cookies and thus logging in to work."""
|
||||
|
||||
cookies: CookiesConfig = CookiesConfig()
|
||||
"""Settings for further configuration of the cookies that OctoPrint sets (login, remember me, ...)."""
|
||||
@@ -1,19 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class SlicingConfig(BaseModel):
|
||||
enabled: bool = True
|
||||
"""Whether to enable slicing support or not."""
|
||||
|
||||
defaultSlicer: Optional[str] = None
|
||||
"""Default slicer to use."""
|
||||
|
||||
defaultProfiles: Dict[str, str] = {}
|
||||
"""Default slicing profiles per slicer, maps slicer identifier to profile identifier."""
|
||||
@@ -1,31 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class ActionConfig(BaseModel):
|
||||
action: str
|
||||
"""The identifier used internally to identify the action. Set to `divider` to generate a divider in the menu."""
|
||||
|
||||
name: Optional[str] = None
|
||||
"""The name of the action that will be shown on the menu. Must be set if the action is not a divider."""
|
||||
|
||||
command: Optional[str] = None
|
||||
"""The command to execute when the action is selected. Must be set if the action is not a divider."""
|
||||
|
||||
async_: bool = Field(False, alias="async")
|
||||
"""Whether to run the command asynchronously."""
|
||||
|
||||
confirm: Optional[str] = None
|
||||
"""An optional confirmation message to show before executing the command."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class SystemConfig(BaseModel):
|
||||
actions: List[ActionConfig] = []
|
||||
"""A list of system actions to show in the UI."""
|
||||
@@ -1,37 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class TemperatureProfile(BaseModel):
|
||||
name: str
|
||||
"""Name of the profile."""
|
||||
|
||||
extruder: int
|
||||
"""Hotend temperature to set with the profile."""
|
||||
|
||||
bed: int
|
||||
"""Bed temperature to set with the profile."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class TemperatureConfig(BaseModel):
|
||||
profiles: List[TemperatureProfile] = [
|
||||
TemperatureProfile(name="ABS", extruder=210, bed=100),
|
||||
TemperatureProfile(name="PLA", extruder=180, bed=60),
|
||||
]
|
||||
"""Temperature profiles to offer in the UI for quick pre-heating."""
|
||||
|
||||
cutoff: int = 30
|
||||
"""Cut off time for the temperature data, in minutes."""
|
||||
|
||||
sendAutomatically: bool = False
|
||||
"""Whether to send new temperature settings made in the UI automatically."""
|
||||
|
||||
sendAutomaticallyAfter: int = 1
|
||||
"""After what time to send the new temperature settings automatically, in seconds."""
|
||||
@@ -1,35 +0,0 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class TerminalFilterEntry(BaseModel):
|
||||
name: str
|
||||
"""The name of the filter."""
|
||||
|
||||
regex: str
|
||||
"""The regular expression to match. Use [JavaScript regular expressions](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions)."""
|
||||
|
||||
|
||||
DEFAULT_TERMINAL_FILTERS = [
|
||||
TerminalFilterEntry(
|
||||
name="Suppress temperature messages",
|
||||
regex=r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+([PBN]\d+\s+)*)?([BCLPR]|T\d*):-?\d+)",
|
||||
),
|
||||
TerminalFilterEntry(
|
||||
name="Suppress SD status messages",
|
||||
regex=r"(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)",
|
||||
),
|
||||
TerminalFilterEntry(
|
||||
name="Suppress position messages",
|
||||
regex=r"(Send:\s+(N\d+\s+)?M114)|(Recv:\s+(ok\s+)?X:[+-]?([0-9]*[.])?[0-9]+\s+Y:[+-]?([0-9]*[.])?[0-9]+\s+Z:[+-]?([0-9]*[.])?[0-9]+\s+E\d*:[+-]?([0-9]*[.])?[0-9]+).*",
|
||||
),
|
||||
TerminalFilterEntry(name="Suppress wait responses", regex=r"Recv: wait"),
|
||||
TerminalFilterEntry(
|
||||
name="Suppress processing responses",
|
||||
regex=r"Recv: (echo:\s*)?busy:\s*processing",
|
||||
),
|
||||
]
|
||||
@@ -1,107 +0,0 @@
|
||||
__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 pydantic import BaseModel
|
||||
from pydantic_settings import with_attrs_docs
|
||||
|
||||
|
||||
class RatioEnum(str, Enum):
|
||||
sixteen_nine = "16:9"
|
||||
four_three = "4:3"
|
||||
|
||||
|
||||
class TimelapseTypeEnum(str, Enum):
|
||||
off = "off"
|
||||
zchange = "zchange"
|
||||
timed = "timed"
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class TimelapseOptions(BaseModel):
|
||||
interval: Optional[int] = None
|
||||
"""`timed` timelapses only: The interval which to leave between images in seconds."""
|
||||
|
||||
capturePostRoll: Optional[bool] = None
|
||||
"""`timed` timelapses only: Whether to capture the snapshots for the post roll (true) or just copy the last captured snapshot from the print over and over again (false)."""
|
||||
|
||||
retractionZHop: Optional[float] = None
|
||||
"""`zchange` timelapses only: z-hop height during retractions to ignore for capturing snapshots."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class TimelapseConfig(BaseModel):
|
||||
type: TimelapseTypeEnum = "off"
|
||||
"""The timelapse type."""
|
||||
|
||||
fps: int = 25
|
||||
"""The framerate at which to render the movie."""
|
||||
|
||||
postRoll: int = 0
|
||||
"""The number of seconds in the rendered video to add after a finished print. The exact way how the additional images will be recorded depends on timelapse type. `zchange` timelapses will take one final picture and add it `fps * postRoll` times. `timed` timelapses continue to record just like at the beginning, so the recording will continue another `fps * postRoll * interval` seconds. This behaviour can be overridden by setting the `capturePostRoll` option to `false`, in which case the post roll will be created identically to `zchange` mode."""
|
||||
|
||||
options: TimelapseOptions = TimelapseOptions()
|
||||
"""Additional options depending on the timelapse type."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
class WebcamConfig(BaseModel):
|
||||
webcamEnabled: bool = True
|
||||
"""Use this option to enable display of a webcam stream in the UI, e.g. via MJPG-Streamer. Webcam support will be disabled if not set."""
|
||||
|
||||
timelapseEnabled: bool = True
|
||||
"""Use this option to enable timelapse support via snapshot, e.g. via MJPG-Streamer. Timelapse support will be disabled if not set."""
|
||||
|
||||
stream: Optional[str] = None
|
||||
|
||||
streamRatio: RatioEnum = "16:9"
|
||||
|
||||
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."""
|
||||
|
||||
ffmpegThreads: int = 1
|
||||
"""Number of how many threads to instruct ffmpeg to use for encoding."""
|
||||
|
||||
ffmpegVideoCodec: str = "libx264"
|
||||
"""Videocodec to be used for encoding."""
|
||||
|
||||
bitrate: str = "10000k"
|
||||
"""The bitrate to use for rendering the timelapse video. This gets directly passed to ffmpeg."""
|
||||
|
||||
watermark: bool = True
|
||||
"""Whether to include a "created with OctoPrint" watermark in the generated timelapse recordings."""
|
||||
|
||||
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 = (
|
||||
'{ffmpeg} -sseof -1 -i "{input}" -update 1 -q:v 0.7 "{output}"'
|
||||
)
|
||||
|
||||
timelapse: TimelapseConfig = TimelapseConfig()
|
||||
"""The default timelapse settings."""
|
||||
|
||||
cleanTmpAfterDays: int = 7
|
||||
"""After how many days unrendered timelapses will be deleted."""
|
||||
|
||||
cacheBuster: bool = False
|
||||
@@ -40,6 +40,7 @@ from watchdog.observers import Observer
|
||||
from watchdog.observers.polling import PollingObserver
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
import octoprint.filemanager
|
||||
import octoprint.util
|
||||
import octoprint.util.net
|
||||
from octoprint.server import util
|
||||
@@ -70,6 +71,7 @@ app = Flask("octoprint")
|
||||
|
||||
assets = None
|
||||
babel = None
|
||||
limiter = None
|
||||
debug = False
|
||||
safe_mode = False
|
||||
|
||||
@@ -125,10 +127,11 @@ from octoprint.printer.standard import Printer
|
||||
from octoprint.server.util import (
|
||||
corsRequestHandler,
|
||||
corsResponseHandler,
|
||||
csrfRequestHandler,
|
||||
loginFromApiKeyRequestHandler,
|
||||
requireLoginRequestHandler,
|
||||
)
|
||||
from octoprint.server.util.flask import PreemptiveCache
|
||||
from octoprint.server.util.flask import PreemptiveCache, validate_session_signature
|
||||
from octoprint.settings import settings
|
||||
|
||||
VERSION = __version__
|
||||
@@ -185,12 +188,25 @@ def load_user(id):
|
||||
else:
|
||||
sessionid = None
|
||||
|
||||
if session and "usersession.signature" in session:
|
||||
sessionsig = session["usersession.signature"]
|
||||
else:
|
||||
sessionsig = ""
|
||||
|
||||
if sessionid:
|
||||
user = userManager.find_user(userid=id, session=sessionid)
|
||||
# session["_fresh"] is False if the session comes from a remember me cookie,
|
||||
# True if it came from a use of the login dialog
|
||||
user = userManager.find_user(
|
||||
userid=id, session=sessionid, fresh=session.get("_fresh", False)
|
||||
)
|
||||
else:
|
||||
user = userManager.find_user(userid=id)
|
||||
|
||||
if user and user.is_active:
|
||||
if (
|
||||
user
|
||||
and user.is_active
|
||||
and (not sessionid or validate_session_signature(sessionsig, id, sessionid))
|
||||
):
|
||||
return user
|
||||
|
||||
return None
|
||||
@@ -745,6 +761,15 @@ class Server:
|
||||
)
|
||||
}
|
||||
|
||||
only_known_types_validator = {
|
||||
"path_validation": util.tornado.path_validation_factory(
|
||||
lambda path: octoprint.filemanager.valid_file_type(
|
||||
os.path.basename(path)
|
||||
),
|
||||
status_code=404,
|
||||
)
|
||||
}
|
||||
|
||||
valid_timelapse = lambda path: not octoprint.util.is_hidden_path(path) and (
|
||||
octoprint.timelapse.valid_timelapse(path)
|
||||
or octoprint.timelapse.valid_timelapse_thumbnail(path)
|
||||
@@ -839,6 +864,7 @@ class Server:
|
||||
download_permission_validator,
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator,
|
||||
only_known_types_validator,
|
||||
additional_mime_types,
|
||||
),
|
||||
),
|
||||
@@ -1323,7 +1349,7 @@ class Server:
|
||||
):
|
||||
return Locale.negotiate([default_language], LANGUAGES)
|
||||
|
||||
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
|
||||
return Locale.parse(request.accept_languages.best_match(LANGUAGES, default="en"))
|
||||
|
||||
def _setup_heartbeat_logging(self):
|
||||
logger = logging.getLogger(__name__ + ".heartbeat")
|
||||
@@ -1338,6 +1364,8 @@ class Server:
|
||||
timer.start()
|
||||
|
||||
def _setup_app(self, app):
|
||||
global limiter
|
||||
|
||||
from octoprint.server.util.flask import (
|
||||
OctoPrintFlaskRequest,
|
||||
OctoPrintFlaskResponse,
|
||||
@@ -1352,7 +1380,9 @@ class Server:
|
||||
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
|
||||
app.config["REMEMBER_COOKIE_DURATION"] = 90 * 24 * 60 * 60 # 90 days
|
||||
app.config["REMEMBER_COOKIE_HTTPONLY"] = True
|
||||
# REMEMBER_COOKIE_SECURE will be taken care of by our custom cookie handling
|
||||
|
||||
# we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take
|
||||
app.debug = self._debug
|
||||
@@ -1433,6 +1463,18 @@ class Server:
|
||||
|
||||
MarkdownFilter(app)
|
||||
|
||||
from flask_limiter import Limiter
|
||||
from flask_limiter.util import get_remote_address
|
||||
|
||||
app.config["RATELIMIT_STRATEGY"] = "fixed-window-elastic-expiry"
|
||||
|
||||
limiter = Limiter(
|
||||
app,
|
||||
key_func=get_remote_address,
|
||||
enabled=s.getBoolean(["devel", "enableRateLimiter"]),
|
||||
storage_uri="memory://",
|
||||
)
|
||||
|
||||
def _setup_i18n(self, app):
|
||||
global babel
|
||||
global LOCALES
|
||||
@@ -1876,6 +1918,16 @@ class Server:
|
||||
blueprint.before_request(loginFromApiKeyRequestHandler)
|
||||
blueprint.after_request(corsResponseHandler)
|
||||
|
||||
if plugin.is_blueprint_csrf_protected():
|
||||
self._logger.debug(
|
||||
f"CSRF Protection for Blueprint of plugin {name} is enabled"
|
||||
)
|
||||
blueprint.before_request(csrfRequestHandler)
|
||||
else:
|
||||
self._logger.warning(
|
||||
f"CSRF Protection for Blueprint of plugin {name} is DISABLED"
|
||||
)
|
||||
|
||||
if plugin.is_blueprint_protected():
|
||||
blueprint.before_request(requireLoginRequestHandler)
|
||||
|
||||
@@ -2115,8 +2167,8 @@ class Server:
|
||||
"css/bootstrap-slider.css",
|
||||
"css/bootstrap-tabdrop.css",
|
||||
"vendor/font-awesome-3.2.1/css/font-awesome.min.css",
|
||||
"vendor/fontawesome-6.1.1/css/all.min.css",
|
||||
"vendor/fontawesome-6.1.1/css/v4-shims.min.css",
|
||||
"vendor/font-awesome-5.15.1/css/all.min.css",
|
||||
"vendor/font-awesome-5.15.1/css/v4-shims.min.css",
|
||||
"css/jquery.fileupload-ui.css",
|
||||
"css/pnotify.core.min.css",
|
||||
"css/pnotify.buttons.min.css",
|
||||
|
||||
@@ -28,6 +28,7 @@ from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util import (
|
||||
corsRequestHandler,
|
||||
corsResponseHandler,
|
||||
csrfRequestHandler,
|
||||
loginFromApiKeyRequestHandler,
|
||||
loginFromAuthorizationHeaderRequestHandler,
|
||||
noCachingExceptGetResponseHandler,
|
||||
@@ -35,8 +36,10 @@ from octoprint.server.util import (
|
||||
from octoprint.server.util.flask import (
|
||||
get_json_command_from_request,
|
||||
get_remote_address,
|
||||
limit,
|
||||
no_firstrun_access,
|
||||
passive_login,
|
||||
session_signature,
|
||||
)
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
@@ -66,6 +69,7 @@ api.after_request(noCachingExceptGetResponseHandler)
|
||||
api.before_request(corsRequestHandler)
|
||||
api.before_request(loginFromAuthorizationHeaderRequestHandler)
|
||||
api.before_request(loginFromApiKeyRequestHandler)
|
||||
api.before_request(csrfRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
|
||||
# ~~ data from plugins
|
||||
@@ -281,6 +285,11 @@ def serverStatus():
|
||||
|
||||
|
||||
@api.route("/login", methods=["POST"])
|
||||
@limit(
|
||||
"3/minute;5/10 minutes;10/hour",
|
||||
deduct_when=lambda response: response.status_code == 403,
|
||||
error_message="You have made too many failed login attempts. Please try again later.",
|
||||
)
|
||||
def login():
|
||||
data = request.get_json()
|
||||
if not data:
|
||||
@@ -306,6 +315,9 @@ def login():
|
||||
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.session
|
||||
session["usersession.signature"] = session_signature(
|
||||
username, user.session
|
||||
)
|
||||
g.user = user
|
||||
|
||||
login_user(user, remember=remember)
|
||||
|
||||
@@ -25,14 +25,14 @@ def get_permissions():
|
||||
|
||||
@api.route("/access/groups", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def get_groups():
|
||||
return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups)))
|
||||
|
||||
|
||||
@api.route("/access/groups", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def add_group():
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
abort(400, description="Expected content-type JSON")
|
||||
@@ -69,7 +69,7 @@ def add_group():
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def get_group(key):
|
||||
group = groupManager.find_group(key)
|
||||
if group is not None:
|
||||
@@ -80,7 +80,7 @@ def get_group(key):
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["PUT"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def update_group(key):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
abort(400, description="Expected content-type JSON")
|
||||
@@ -113,7 +113,7 @@ def update_group(key):
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def remove_group(key):
|
||||
try:
|
||||
groupManager.remove_group(key)
|
||||
@@ -129,14 +129,14 @@ def remove_group(key):
|
||||
|
||||
@api.route("/access/users", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def get_users():
|
||||
return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users())))
|
||||
|
||||
|
||||
@api.route("/access/users", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def add_user():
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
abort(400, description="Expected content-type JSON")
|
||||
@@ -188,7 +188,7 @@ def get_user(username):
|
||||
|
||||
@api.route("/access/users/<username>", methods=["PUT"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def update_user(username):
|
||||
user = userManager.find_user(username)
|
||||
if user is not None:
|
||||
@@ -223,7 +223,7 @@ def update_user(username):
|
||||
|
||||
@api.route("/access/users/<username>", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def remove_user(username):
|
||||
try:
|
||||
userManager.remove_user(username)
|
||||
@@ -241,7 +241,10 @@ def change_password_for_user(username):
|
||||
if (
|
||||
current_user is not None
|
||||
and not current_user.is_anonymous
|
||||
and (current_user.get_name() == username or current_user.is_admin)
|
||||
and (
|
||||
current_user.get_name() == username
|
||||
or current_user.has_permission(Permissions.ADMIN)
|
||||
)
|
||||
):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
abort(400, description="Expected content-type JSON")
|
||||
@@ -252,7 +255,14 @@ def change_password_for_user(username):
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
if "password" not in data or not data["password"]:
|
||||
abort(400, description="password is missing")
|
||||
abort(400, description="new password is missing")
|
||||
|
||||
if not current_user.has_permission(Permissions.ADMIN) or "current" in data:
|
||||
if "current" not in data or not data["current"]:
|
||||
abort(400, description="current password is missing")
|
||||
|
||||
if not userManager.check_password(username, data["current"]):
|
||||
abort(403, description="Invalid current password")
|
||||
|
||||
try:
|
||||
userManager.change_user_password(username, data["password"])
|
||||
|
||||
@@ -607,6 +607,15 @@ def uploadGcodeFile(target):
|
||||
):
|
||||
abort(409, description="File already exists and noOverwrite was set")
|
||||
|
||||
if (
|
||||
fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage)
|
||||
and not Permissions.FILES_DELETE.can()
|
||||
):
|
||||
abort(
|
||||
403,
|
||||
description="File already exists, cannot overwrite due to a lack of permissions",
|
||||
)
|
||||
|
||||
reselect = printer.is_current_file(futureFullPathInStorage, sd)
|
||||
|
||||
user = current_user.get_name()
|
||||
@@ -1138,42 +1147,55 @@ def gcodeFileCommand(filename, target):
|
||||
if not (is_file or is_folder):
|
||||
abort(400, description=f"Neither file nor folder, can't {command}")
|
||||
|
||||
if command == "copy":
|
||||
# destination already there? error...
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(
|
||||
target, destination
|
||||
):
|
||||
abort(409, description="File or folder does already exist")
|
||||
|
||||
if is_file:
|
||||
fileManager.copy_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.copy_folder(target, filename, destination)
|
||||
|
||||
elif command == "move":
|
||||
with Permissions.FILES_DELETE.require(403):
|
||||
if _isBusy(target, filename):
|
||||
abort(
|
||||
409,
|
||||
description="Trying to move a file or folder that is currently in use",
|
||||
)
|
||||
|
||||
# destination already there AND not ourselves (= display rename)? error...
|
||||
if (
|
||||
_verifyFileExists(target, destination)
|
||||
or _verifyFolderExists(target, destination)
|
||||
) and sanitized_destination != filename:
|
||||
try:
|
||||
if command == "copy":
|
||||
# destination already there? error...
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(
|
||||
target, destination
|
||||
):
|
||||
abort(409, description="File or folder does already exist")
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselect_file()
|
||||
|
||||
if is_file:
|
||||
fileManager.move_file(target, filename, destination)
|
||||
fileManager.copy_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.move_folder(target, filename, destination)
|
||||
fileManager.copy_folder(target, filename, destination)
|
||||
|
||||
elif command == "move":
|
||||
with Permissions.FILES_DELETE.require(403):
|
||||
if _isBusy(target, filename):
|
||||
abort(
|
||||
409,
|
||||
description="Trying to move a file or folder that is currently in use",
|
||||
)
|
||||
|
||||
# destination already there AND not ourselves (= display rename)? error...
|
||||
if (
|
||||
_verifyFileExists(target, destination)
|
||||
or _verifyFolderExists(target, destination)
|
||||
) and sanitized_destination != filename:
|
||||
abort(409, description="File or folder does already exist")
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselect_file()
|
||||
|
||||
if is_file:
|
||||
fileManager.move_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.move_folder(target, filename, destination)
|
||||
|
||||
except octoprint.filemanager.storage.StorageError as e:
|
||||
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
|
||||
abort(
|
||||
415,
|
||||
description=f"Could not {command} {filename} to {destination}, invalid type",
|
||||
)
|
||||
else:
|
||||
abort(
|
||||
500,
|
||||
description=f"Could not {command} {filename} to {destination}",
|
||||
)
|
||||
|
||||
location = url_for(
|
||||
".readGcodeFile",
|
||||
|
||||
@@ -174,7 +174,8 @@ def deleteInstalledLanguagePack(locale, pack):
|
||||
def _unpack_uploaded_zipfile(path, target):
|
||||
with zipfile.ZipFile(path, "r") as zip:
|
||||
# sanity check
|
||||
map(_validate_archive_name, zip.namelist())
|
||||
for info in zip.infolist():
|
||||
_validate_zip_info(info, target)
|
||||
|
||||
# unpack everything
|
||||
zip.extractall(target)
|
||||
@@ -183,16 +184,27 @@ def _unpack_uploaded_zipfile(path, target):
|
||||
def _unpack_uploaded_tarball(path, target):
|
||||
with tarfile.open(path, "r") as tar:
|
||||
# sanity check
|
||||
map(_validate_archive_name, tar.getmembers())
|
||||
for info in tar.getmembers():
|
||||
_validate_tar_info(info, target)
|
||||
|
||||
# unpack everything
|
||||
tar.extractall(target)
|
||||
|
||||
|
||||
def _validate_archive_name(name):
|
||||
if name.startswith("/") or ".." in name:
|
||||
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_zip_info(info, target):
|
||||
_validate_archive_name(info.filename, target)
|
||||
|
||||
|
||||
def _validate_tar_info(info, target):
|
||||
_validate_archive_name(info.name, target)
|
||||
if not (info.isfile() or info.isdir()):
|
||||
raise InvalidLanguagePack("Provided language pack contains invalid file type")
|
||||
|
||||
|
||||
class InvalidLanguagePack(Exception):
|
||||
pass
|
||||
@@ -18,8 +18,7 @@ from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
# ~~ settings
|
||||
|
||||
FOLDER_TYPES = ("uploads", "timelapse", "timelapse_tmp", "logs", "watched")
|
||||
FOLDER_MAPPING = {"timelapseTmp": "timelapse_tmp"}
|
||||
FOLDER_TYPES = ("uploads", "timelapse", "watched")
|
||||
TIMELAPSE_BITRATE_PATTERN = re.compile(r"\d+[KMGTPEZY]?i?B?", flags=re.IGNORECASE)
|
||||
|
||||
|
||||
@@ -269,8 +268,6 @@ def getSettings():
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
"timelapse": s.getBaseFolder("timelapse"),
|
||||
"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
|
||||
"logs": s.getBaseFolder("logs"),
|
||||
"watched": s.getBaseFolder("watched"),
|
||||
},
|
||||
"temperature": {
|
||||
@@ -464,10 +461,7 @@ def _saveSettings(data):
|
||||
|
||||
if "folder" in data:
|
||||
try:
|
||||
folders = {
|
||||
FOLDER_MAPPING.get(folder, folder): path
|
||||
for folder, path in data["folder"].items()
|
||||
}
|
||||
folders = data["folder"]
|
||||
future = {}
|
||||
for folder in FOLDER_TYPES:
|
||||
future[folder] = s.getBaseFolder(folder)
|
||||
|
||||
@@ -43,7 +43,7 @@ def loginFromApiKeyRequestHandler():
|
||||
if loginUserFromApiKey():
|
||||
_flask.g.login_via_apikey = True
|
||||
except InvalidApiKeyException:
|
||||
_flask.abort(403)
|
||||
_flask.abort(403, "Invalid API key")
|
||||
|
||||
|
||||
def loginFromAuthorizationHeaderRequestHandler():
|
||||
@@ -54,7 +54,7 @@ def loginFromAuthorizationHeaderRequestHandler():
|
||||
if loginUserFromAuthorizationHeader():
|
||||
_flask.g.login_via_header = True
|
||||
except InvalidApiKeyException:
|
||||
_flask.abort(403)
|
||||
_flask.abort(403, "Invalid credentials in Basic Authorization header")
|
||||
|
||||
|
||||
class InvalidApiKeyException(Exception):
|
||||
@@ -69,7 +69,7 @@ def loginUserFromApiKey():
|
||||
user = get_user_for_apikey(apikey)
|
||||
if user is None:
|
||||
# invalid API key = no API key
|
||||
return False
|
||||
raise InvalidApiKeyException("Invalid API key")
|
||||
|
||||
return loginUser(user, login_mechanism="apikey")
|
||||
|
||||
@@ -148,6 +148,26 @@ def corsResponseHandler(resp):
|
||||
return resp
|
||||
|
||||
|
||||
def csrfRequestHandler():
|
||||
"""
|
||||
``before_request`` handler for blueprints which checks for CRFS double token on
|
||||
relevant requests & methods.
|
||||
"""
|
||||
from octoprint.server.util.csrf import validate_csrf_request
|
||||
|
||||
if settings().getBoolean(["devel", "enableCsrfProtection"]):
|
||||
validate_csrf_request(_flask.request)
|
||||
|
||||
|
||||
def csrfResponseHandler(resp):
|
||||
"""
|
||||
``after_request`` handler for updating the CSRF cookie on each response.
|
||||
"""
|
||||
from octoprint.server.util.csrf import add_csrf_cookie
|
||||
|
||||
return add_csrf_cookie(resp)
|
||||
|
||||
|
||||
def noCachingResponseHandler(resp):
|
||||
"""
|
||||
``after_request`` handler for blueprints which shall set no caching headers
|
||||
@@ -421,3 +441,23 @@ def require_login(*permissions):
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def validate_local_redirect(url, allowed_paths):
|
||||
"""Validates the given local redirect URL against the given allowed paths.
|
||||
|
||||
An `url` is valid for a local redirect if it has neither scheme nor netloc defined,
|
||||
and its path is one of the given allowed paths.
|
||||
|
||||
Args:
|
||||
url (str): URL to validate
|
||||
allowed_paths (List[str]): List of allowed paths, only paths contained
|
||||
will be considered valid.
|
||||
|
||||
Returns:
|
||||
bool: Whether the `url` passed validation or not.
|
||||
"""
|
||||
from urllib.parse import urlparse
|
||||
|
||||
parsed = urlparse(url)
|
||||
return parsed.scheme == "" and parsed.netloc == "" and parsed.path in allowed_paths
|
||||
@@ -0,0 +1,98 @@
|
||||
"""CSRF double cookie implementation"""
|
||||
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import flask
|
||||
|
||||
from octoprint.server.util.flask import OctoPrintFlaskResponse
|
||||
|
||||
exempt_views = set()
|
||||
|
||||
|
||||
def _get_view_location(view):
|
||||
if isinstance(view, str):
|
||||
return view
|
||||
else:
|
||||
return f"{view.__module__}.{view.__name__}"
|
||||
|
||||
|
||||
def add_exempt_view(view):
|
||||
exempt_views.add(_get_view_location(view))
|
||||
|
||||
|
||||
def is_exempt(view):
|
||||
if not view:
|
||||
return False
|
||||
|
||||
return _get_view_location(view) in exempt_views
|
||||
|
||||
|
||||
def generate_csrf_token():
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
from itsdangerous import URLSafeTimedSerializer
|
||||
|
||||
value = hashlib.sha1(os.urandom(64)).hexdigest()
|
||||
|
||||
secret = flask.current_app.config["SECRET_KEY"]
|
||||
s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token")
|
||||
|
||||
return s.dumps(value)
|
||||
|
||||
|
||||
def validate_csrf_tokens(cookie, header):
|
||||
import hmac
|
||||
|
||||
from itsdangerous import URLSafeTimedSerializer
|
||||
|
||||
if cookie is None or header is None:
|
||||
return False
|
||||
|
||||
secret = flask.current_app.config["SECRET_KEY"]
|
||||
s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token")
|
||||
|
||||
try:
|
||||
# TODO: set max age for values, once we have a REST based heartbeat
|
||||
# that takes care of regular cookie refresh
|
||||
value_cookie = s.loads(cookie)
|
||||
value_header = s.loads(header)
|
||||
return hmac.compare_digest(value_cookie, value_header)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def add_csrf_cookie(response):
|
||||
if not isinstance(response, OctoPrintFlaskResponse):
|
||||
response = flask.make_response(response)
|
||||
|
||||
token = generate_csrf_token()
|
||||
response.set_cookie("csrf_token", token, httponly=False)
|
||||
return response
|
||||
|
||||
|
||||
def validate_csrf_request(request):
|
||||
if request.method in ["GET", "HEAD", "OPTIONS"]:
|
||||
# Irrelevant method for CSRF, bypass
|
||||
return
|
||||
|
||||
session = getattr(flask, "session", {})
|
||||
if len(session) == 0 or session.get("login_mechanism") == "apikey":
|
||||
# empty session, not a browser context
|
||||
return
|
||||
|
||||
if is_exempt(request.endpoint):
|
||||
# marked as exempt, bypass
|
||||
return
|
||||
|
||||
cookie = request.cookies.get("csrf_token", None)
|
||||
header = request.headers.get("X-CSRF-Token", None)
|
||||
|
||||
if not validate_csrf_tokens(cookie, header):
|
||||
flask.abort(400, "CSRF validation failed")
|
||||
|
||||
|
||||
def csrf_exempt(view):
|
||||
add_exempt_view(view)
|
||||
return view
|
||||
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user