Compare commits

..
108 Commits
Author SHA1 Message Date
Gina Häußge f377de636e 🐛 Fix handling of % in timelapse filenames
Switched all replacement logic to {} style format strings, which means
we no longer need to escape % internally. Only escaping it in one single
place now, before pacing the capture file pattern to ffmpeg, as THAT
uses % style formatting.

Closes #4505
2022-06-29 11:24:43 +02:00
Christian 0af5972a28 🐛 Fix skip dialog in wizard popping up twice (#4561)
* remove show.bs.tab listener which triggered twice the innerTabShown

* add myself in the authors files
2022-06-28 14:35:37 +02:00
Gina Häußge 18b0565ea6 🐛 swu: Fix multiple credentials saving
We make sure to check if any of the credentials
we support are contained in the incoming settings
data and if so set that, and only that, on our
plugin settings, instead of overwriting the
stored credentials with just those that changed.

See #4540
2022-06-28 11:19:31 +02:00
JoveToo 306e513ee3 ✨ GCodeViewer: in-memory compression (#4435)
Individual commits:

* Add last position cache
* Must be lower than percentage of next level.
* Fully working version with jsonc compression
* Switch to pako.js for both speed and efficiency
* compressed code is now an instance of Uint8Array
* Temporary fix for rebuildLayerPercentageLookup and purgeEmptyLayers
* Fix merge issues
* Fix prettier
* Fix prettier
* Calculate empty layers and percentage of layer in doAnalyse
* Delete all state when doing clear()
* Delete all state when doing clear()
* Add options to control compression. Allow to enable compression from the warning page.
* Do not always turn on compression by default.
* Correctly calculate the rendererEmptyLayers array.
* Only show "force compression" if compression is not already enabled.
* pre-commit fixes
* Use correct index and fix merge issues.
* Add some comments.
* Update src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 (Co-authored-by: Gina Häußge <gina@octoprint.org>)
* Move "Skip to this" up and make the threshold dependent on alwaysCompress setting.
* Remove redundant "Skip to this" (Co-authored-by: Gina Häußge <gina@octoprint.org>)
2022-06-27 16:57:16 +02:00
Gina Häußge bfe40f0c74 👷 More work on DeploySentinel integration 2022-06-27 13:55:17 +02:00
CoReYe eaad6350fd Fixed typo (#4553) 2022-06-27 10:19:54 +02:00
Charlie Powell 151c38a515 🐛 gcodeInterpreter: Avoid ZeroDivisionError with firmware retraction (#4555)
Closes #4554
2022-06-27 10:09:11 +02:00
GitHub Nightly Merge Action 41d11d8a75 Merge branch 'master' into maintenance 2022-06-24 00:11:53 +00:00
Gina Häußge 3087548664 👷 Add DeploySentinel to e2e tests
Got sponsored access, might help debug the
test flakyness.
2022-06-23 16:33:19 +02:00
Gina Häußge 2e1ec42c5b 👷‍♂️ Needs to run against pull_request_target 2022-06-23 10:50:06 +02:00
GitHub Nightly Merge Action 2259d25153 Merge branch 'master' into maintenance 2022-06-22 00:14:34 +00:00
Gina Häußge c3531bc5b4 💄 GCV: Fix settings markup. 2022-06-21 15:29:11 +02:00
Gina Häußge 6bddada8c2 👷‍♂️ Add task labeling 2022-06-21 10:12:53 +02:00
GitHub Nightly Merge Action 2b092a9899 Merge branch 'master' into maintenance 2022-06-21 00:12:10 +00:00
Gina Häußge 008292ce60 Use org wide secret 2022-06-20 15:56:07 +02:00
Gina Häußge 01f24e6cea 👷‍♂️ Add issues/PRs to backlog automatically 2022-06-20 15:49:00 +02:00
Gina Häußge 8174a8e16b 🐛 Fix version of pydantic-settings, 2nd try 2022-06-09 13:08:09 +02:00
Gina Häußge 9a18fa0f24 🐛 Fix version of pydantic-settings 2022-06-09 13:04:10 +02:00
Gina Häußge 8a8c0b16a2 ♻️ Migrate default settings to pydantic model
Currently using pydantic-settings for with_attrs_docs decorator
to retrieve doc strings as descriptions. Should be replaced with
vendored utility.
2022-06-09 12:43:22 +02:00
Billy Richardson 10ec9cd4e4 ✅ Add more unit tests for helpers.js (#4536) 2022-06-08 12:03:23 +02:00
Federico Nembrini 64ad527753 ✨ Record last fan speed (#4531)
* Add fan speed record to record last, pause and cancel fan speed
Update doc.

* Replace fan speed record with simple fan speed variable
Update doc.
2022-06-07 13:43:50 +02:00
luzpaz 999ccac230 ✏️ Fix misc. typos (#4533)
Found via `codespell -q 3 -S *.po`
2022-05-31 14:18:38 +02:00
Billy Richardson e8be86c15f ✅ Add a few unit tests for helpers.js (#4529) 2022-05-31 14:17:27 +02:00
Billy Richardson fe84605f24 👷 Add JS QUnit tests to build workflow with node-qunit-puppeteer (#4534) 2022-05-31 14:16:47 +02:00
GitHub Nightly Merge Action 5931d4493d Merge branch 'master' into maintenance 2022-05-30 13:00:08 +00:00
Gina Häußge 53b9b61857 👷 Only trigger release jobs on main repo 2022-05-30 14:51:54 +02:00
Gina Häußge e2349b4565 👷 Ignore errors on Discord hook & e2e
e2e are too flaky, discord hook might be unconfigured in a fork.
2022-05-30 14:45:16 +02:00
Charlie Powell c491f4fedc ⬆️ Bump wrapt to fix Python 3.11 compatibility (#4530)
Fully tested on 3.7, 3.10 and 3.11 - any issues that did exist appear to have been resolved.
2022-05-30 11:04:51 +02:00
JoveToo cd7f44cb57 There are not files with \r-only line endings (#4450) 2022-05-25 16:01:31 +02:00
Gina Häußge 9491db60da Merge branch 'maintenance' of github.com:OctoPrint/OctoPrint into maintenance 2022-05-24 12:24:17 +02:00
Gina Häußge 7aa5cab728 Merge branch 'master' into maintenance 2022-05-24 12:24:11 +02:00
Gina Häußge 260a1aef11 🔖 Preparing release of 1.8.1 2022-05-24 10:55:31 +02:00
Franck Nijhof 9a8dde1650 Use lazy logging in octoprint. (#4512) 2022-05-24 10:32:53 +02:00
Franck Nijhof 6709f9ca3c Migrate black configuration to pyproject.toml (#4511) 2022-05-24 10:28:42 +02:00
Franck Nijhof d56e8302c7 Update black to 22.3.0 (#4510) 2022-05-24 10:27:54 +02:00
Gina Häußge 866c9a20d7 🐛 Fix a redirect loop on login
If guest/anonymous users where configured with read-only rights,
the login dialog would enter a redirect loop due to require_login_with
not recognizing anonymous use with permissions as valid.

Fixes #4516
2022-05-24 10:26:57 +02:00
Gina Häußge 77904a71b4 🔒️ Fix an XSS issue in the user/group delete confirmation
Requires admin rights to exploit in any way.
With OctoPrint 1.8.0 all cookies with credentials
are http-only and thus not targetable (to my
knowledge) by this.

CVSS:3.1/AV:L/AC:H/PR:N/UI:R/S:U/C:L/I:N/A:N, Severity Low
2022-05-19 13:08:16 +02:00
Gina Häußge 89fbcfd214 🐛 Gracefully handle errors scanning /dev
Solves an issue with Octo4a on some Android devices.
2022-05-19 09:38:00 +02:00
Gina Häußge 26aac1701f 🔖 staging/bugfix is 1.8.1.dev 2022-05-19 09:25:03 +02:00
Gina Häußge 4daa5f61fb Merge branch 'maintenance' of github.com:OctoPrint/OctoPrint into maintenance 2022-05-17 13:42:15 +02:00
Gina Häußge 158a5c2522 Merge branch 'master' into maintenance 2022-05-17 13:38:49 +02:00
Gina Häußge f430257d70 Merge branch 'rc/maintenance' 2022-05-16 14:58:38 +02:00
Gina Häußge d2a9aaceda 🔖 Preparing release of 1.8.0 2022-05-16 14:55:05 +02:00
Gina Häußge 8ca327669c 🔒️ XSS in webcam stream URL test in Chrome
Apparently Chrome will happily create URL objects from
what is actually HTML tags. So now we will also
URI encode the stream URL prior to embedding in the page.
2022-05-12 18:58:16 +02:00
Gina Häußge d1fca86636 🥅 Better error handling 2022-05-12 10:58:08 +02:00
Gina Häußge 4d9e86ca0f 🐛 We also recognize webrtcs: for webcam streams
Thanks for the heads-up, @cp2004
2022-05-12 10:57:39 +02:00
Gina Häußge 6d259d7e6f 🔒️ Fix XSS in webcam stream test 2022-05-11 16:40:07 +02:00
Gina Häußge 5ef16773c8 🔒️ Escape requested user id
Fixes an XSS issue.
2022-05-11 13:03:40 +02:00
Gina Häußge 8087528e4a 🔒️ Sanitize and validate login redirect
Fixes an XSS and an open redirect issue.
2022-05-11 13:02:52 +02:00
Charlie Powell 0cf869a6fe ⏫ Upgrade to FontAwesome 6 (#4484)
* ⬆️ Initial FA6 upgrade

Only broken icon noticed so far is announcements header.

Strangely, the plugin manager 'Install' buttons have regained their plus signs.

* Allow plugins to use new FA5/6 icon styles in sidebar

Adds some backwards compatibility testing to allow new icons to work. Icons can be specified with either `fas fa-<icon>` or just `<icon` to use `fa fa-<icon>`. Both will work.

* 🔥 Remove plugin manager plus icon

It was gone for a while, I think I prefer the look of the button without it. No need to have an icon next to it IMO.

* ⬆️ Upgrade to FA 6.1.1

* ◀️ Add back v4 compatibility

And fix preloading V3....

* 🐛 Correct icon style

* 🐛 Fix font preload

Changed to fix dual loading in this PR, but I did it wrong. Now properly fixed.
2022-05-11 10:52:53 +02:00
Gina Häußge 700034d028 🔒️ Set remember_me cookie http only 2022-05-10 20:56:48 +02:00
GitHub Nightly Merge Action 500729607d Merge branch 'master' into maintenance 2022-05-04 09:29:15 +00:00
Gina Häußge 885ca31168 👷‍♂️ Fix nightly merge
The action needed an upgrade due to a behaviour change in latest git.
2022-05-04 11:28:25 +02:00
Jefferey Neuffer cafd480642 🐛 Don't block unused keys when keyboard control is active (#4483)
Allows to still use keys such as F5 for refresh, etc. while keyboard control is open, rather than swallowing every possible key combination.
2022-05-02 16:49:27 +01:00
Billy Richardson 1a5de41a0f 🐛 Remove use of HTML entity degree symbol in temperature title attribute (#4490)
* Use unicode degree symbol in title attribute
2022-05-02 16:40:13 +01:00
Billy Richardson 64c21ba8f0 ✏️ Documentation spelling fixes (#4497) 2022-04-24 17:21:13 +01:00
Billy Richardson 671829a4f1 ✏️ Fix minor spelling issue (#4492) 2022-04-22 18:31:30 +01:00
Gina Häußge e5af809795 Merge branch 'staging/maintenance' into maintenance 2022-04-12 16:22:15 +02:00
Gina Häußge 53dbde2ef9 🔖 staging/maintenance is now 1.8.0rc6.dev 2022-04-12 16:21:41 +02:00
Gina Häußge 45598764e6 🔖 Preparing release of 1.8.0rc5 2022-04-12 15:30:56 +02:00
Gina Häußge 2ecc1c944f 🥅 Only use the first value pair for a temp sensor
This protects against lines from the printer like

  T:210.04 /210.00 B:52.00 /52.00 @:85 B:1234.0 /1234.0

We've seen *so* much weird stuff out there in firmware, let's better
be safe rather than sorry and rule out latter values from overwriting
former values just in case.
2022-04-12 14:26:55 +02:00
Gina Häußge d81504c12e 🐛 Fix folder saving & config migration
Settings._config has been turned into a read-only view by the
recent refactoring of the settings hierarchy. Refactored our use
as needed to still function and added deprecated decorator to
getter and setter property to communicate this change in behaviour.

_config wasn't documented, so it is not part of the official API and
thus this doesn't qualify as a breaking change, however there might
be plugins there that went beyond the documented API and use it in
some way (possibly even stuff I have written in the past), so
best give them a heads-up.

Closes #4486
2022-04-11 16:51:22 +02:00
tommywienert d1c96cbb37 ✏️ Replace 'mm/s' with 'mm/min' in docs (#4470) 2022-04-07 13:07:35 +01:00
Jamie 9ec00f9471 ✏️ Tiny documentation typo, timeouts -> timeout (#4468) 2022-04-07 13:00:23 +01:00
Gina Häußge 2e4af01b0f ⬆️ Upgrade flask-login & werkzeug
Closes #4477
2022-04-06 12:31:42 +02:00
Gina Häußge a0128a3a39 Merge branch 'staging/maintenance' into maintenance 2022-04-05 14:50:02 +02:00
Gina Häußge 302ccc087b 🔖 staging/maintenance is now 1.8.0rc5.dev 2022-04-05 14:49:48 +02:00
Gina Häußge c5b095a8b9 🔖 Preparing release of 1.8.0rc4 2022-04-05 13:25:05 +02:00
Gina Häußge f4b4f50cfd 🐛 Fix handling of invalid intermittend values
We not only ignore None values on our subkey paths, we ignore
anything that isn't a dict we can further level down in.

Closes #4479
2022-04-04 19:02:44 +02:00
Gina Häußge fe2d176221 ⬆️ Upgrade Sphinx et al
And adjust docs to build error free under the new versions too.
2022-03-30 16:03:22 +02:00
Gina Häußge 7a124d1861 Merge branch 'staging/maintenance' into maintenance 2022-03-29 14:06:37 +02:00
Gina Häußge 9faec6e982 🔖 staging/maintenance is now 1.8.0rc4.dev 2022-03-29 14:05:23 +02:00
Gina Häußge 3c478036ae Merge branch 'master' into staging/maintenance 2022-03-29 11:19:35 +02:00
Gina Häußge 76e87ba813 💚 Pin click in pre-commit black
See psf/black#2964

To be replaced by an update of black et al in dev branches.
2022-03-29 11:19:16 +02:00
Gina Häußge ad32bbfdb8 🐛 Add back accidentally removed flask-login req 2022-03-29 10:55:15 +02:00
Gina Häußge ccd5fa56a2 📌 Pin werkzeug to 2.0.x for now
Apparently werkzeug removes stuff on minor releases and that just
broke flask-login 0.5. A newer version isn't out yet, so we pin to
a lower version of werkzeug for 1.8.0 and will then see what to do
with this situation for 1.9 and later (potentially even vendor
flask-login as it appears pretty dead currently).
2022-03-29 10:38:04 +02:00
Gina Häußge 24b5b3a857 🐛 Fix potential race condition in webassets
Could trigger when reloading page while preliminary cache
was being done, causing an internal server error
on page load, immediately fixed by a second reload.

Seems to be caused by the change in webasset handling
in 1.8.0, hence considering this a regression.

Fix consists of switching to a thread-safe in-memory
manifest storage.
2022-03-28 16:42:46 +02:00
Gina Häußge 3be85646cd 🔖 Preparing release of 1.8.0rc3 2022-03-28 14:27:38 +02:00
Gina Häußge 54207abbe1 ⬆️ Require latest version of the PiSupport plugin 2022-03-28 11:23:35 +02:00
Gina Häußge 37bc874131 ⬆️ pre-commit: upgrade flake8-bugbear & fix issues 2022-03-23 10:55:12 +01:00
Gina Häußge bf96e6321f Merge branch 'staging/maintenance' into maintenance 2022-03-23 10:24:55 +01:00
Gina Häußge 4c4721518c Merge branch 'master' into staging/maintenance 2022-03-23 10:24:02 +01:00
Gina Häußge 772f9f95da 📌 pre-commit: Pin flake8 bugbear
The new version will cause pre-commit to fail, we need to fix
the newly detected issues but not on frozen code (like master
or to a degree the RCs).
2022-03-23 10:23:18 +01:00
Gina Häußge a8b6483b8c Merge branch 'master' into maintenance 2022-03-23 08:42:16 +01:00
Gina Häußge a2f490ef9a Merge branch 'maintenance' of github.com:OctoPrint/OctoPrint into maintenance 2022-03-23 08:39:32 +01:00
Gina Häußge 34e935bd0b 🐛 GCV: Moves may be arcs too
Closes #4471
2022-03-22 17:09:21 +01:00
Gina Häußge 6728a17448 🚸 Re-enable connect dialog w/ no serial ports
Apparently disabling it if no serial ports are currently
known to the client breaks certain workflows for people.

So this is a short-term solution to fix things for them, while
technically non-sensical (why offer to connect if we don't see
anything to connect to?) So in 1.9.0 this should rather be
solved by adding some form of platform agnostic (!) auto-refresh,
either regular polling while no port is detected, or even
watchdog enabled event based refresh. See #4473.
2022-03-22 12:07:59 +01:00
Zack Lewis 7bc2a79642 ✏️ Spelling correction in software update docs (#4466)
* Spelling Correction

supplyting -> supplying

* Update AUTHORS.md
2022-03-17 22:32:24 +00:00
Gina Häußge 8c9536f323 🐛 GCV: Send the final layer to the UI as well
Closes #4463
2022-03-17 14:28:16 +01:00
GitHub Nightly Merge Action 1695dd45b9 Merge branch 'master' into maintenance 2022-03-17 00:10:16 +00:00
Charlie Powell 594b660bb6 :pencil2 2022-03-16 21:44:03 +00:00
Gina Häußge 635d6179e3 Merge branch 'staging/maintenance' into maintenance 2022-03-16 11:53:51 +01:00
Gina Häußge 23f90060c6 🔖 staging/maintenance is now 1.8.0rc3.dev 2022-03-16 11:53:23 +01:00
Gina Häußge 76c5924532 ⬆️ Force upgrade PiSupport to 2022.3.1+
Not 2021.3.1... 🤦‍♀️
2022-03-16 10:45:52 +01:00
Gina Häußge 6fc2edcc1f 🚸 Expose serial.ignoreEmptyPorts on UI
Closes #4460
2022-03-15 19:30:41 +01:00
Gina Häußge 056eb122f3 🐛 Fix some more less 4 incompatibilities 2022-03-15 18:27:06 +01:00
Gina Häußge 33cef57551 🐛 GCV: Fix layer transmission logic
Only ever send *completed* layers to the frontend. Otherwise in case of
zHops and such we risk sending incomplete layers and missing whole
command segments in the process.

Closes #4459
2022-03-15 17:42:01 +01:00
Gina Häußge 9563e898ba 🐛 GCV: Don't try to iterate empty models 2022-03-15 17:39:51 +01:00
Gina Häußge 3816c95678 🐛 Fix get_by_path for empty default dicts & local keys
Closes #4458
2022-03-15 14:36:55 +01:00
Gina Häußge df3b3420ab 🐛 Fix custom temperature handling
* Fix too broad regex
  * Fix lack of error handling in case of reserved identifier

All of these got already introduced in 1.4.1, but now with #4388
they are WAY more likely to pop up (e.g. in garbage lines too) and
completely nuke the connection.

Closes #4456
2022-03-15 12:38:11 +01:00
Gina Häußge 6cd87d1c84 🔖 Preparing of 1.8.0rc2 2022-03-14 18:08:40 +01:00
Gina Häußge fd125e3569 ⬆️ Upgrade outdated sentry-sdk 2022-03-14 18:08:03 +01:00
Gina Häußge 6033ca9a8f 📝 appkeys: Add docs for new auth dialog workflow 2022-03-14 16:26:25 +01:00
Gina Häußge 091edac818 🔖 make staging/maintenance actually be 1.8.0rc2.dev 2022-03-14 15:59:07 +01:00
Gina Häußge e59fab10f8 🥅 More resilience against template plugin bugs
* Don't crash if template is set to None
  * In general catch any error while processing plugin template
    configs and ignore plugin completely.

Closes #4453
2022-03-14 15:17:34 +01:00
Gina Häußge 7f348146cb 🐛 Fix handling of integer keys in the settings
Closes #4454
2022-03-14 14:46:55 +01:00
Gina Häußge 1de39fc9d5 🔖 maintenance is now 1.9.0.dev 2022-03-14 12:30:36 +01:00
Gina Häußge 4a3b50cd3e 🔖 staging/maintenance is now 1.8.0rc2.dev 2022-03-14 12:29:32 +01:00
155 changed files with 22786 additions and 17616 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
name: Add issues/PRs to backlog automatically
on:
issues:
types:
- opened
- transferred
pull_request_target:
types:
- opened
jobs:
add-to-project:
name: Add issue or PR to OctoPrint Backlog project
runs-on: ubuntu-latest
steps:
- uses: actions/add-to-project@main
with:
project-url: https://github.com/orgs/OctoPrint/projects/6
github-token: ${{ secrets.BACKLOG_PROJECT_ACCESS }}
+22 -3
View File
@@ -65,6 +65,19 @@ jobs:
run: |
pytest
test-js-unit:
name: 🧪 JavaScript unit tests
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- 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
test-install:
name: 🧪 Installation tests
needs: build
@@ -96,6 +109,7 @@ jobs:
name: 🧪 E2E tests
needs: build
runs-on: ubuntu-latest
continue-on-error: true
steps:
- name: ⬇ Checkout code
uses: actions/checkout@v2
@@ -125,6 +139,10 @@ jobs:
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
@@ -141,10 +159,11 @@ jobs:
publish-on-testpypi:
name: 📦 Publish on TestPyPI
if: github.event_name == 'release'
if: github.event_name == 'release' && github.repository == 'OctoPrint/OctoPrint'
needs:
- pre-commit
- test-unit
- test-js-unit
- test-install
- test-e2e
runs-on: ubuntu-latest
@@ -163,7 +182,7 @@ jobs:
publish-on-pypi:
name: 📦 Publish tagged releases to PyPI
if: github.event_name == 'release'
if: github.event_name == 'release' && github.repository == 'OctoPrint/OctoPrint'
needs: publish-on-testpypi
runs-on: ubuntu-latest
steps:
@@ -179,7 +198,7 @@ jobs:
notify-custopizer-build:
name: 📧 Notify OctoPi-UpToDate
if: github.event_name == 'release'
if: github.event_name == 'release' && github.repository == 'OctoPrint/OctoPrint'
needs: publish-on-pypi
runs-on: ubuntu-latest
steps:
+6 -1
View File
@@ -28,6 +28,11 @@ jobs:
labels = labels.filter(label => label !== 'triage');
setLabels = true;
}
if (context.payload.issue.title.match(/\[task\]/i)) {
labels.push('task');
labels = labels.filter(label => label !== 'triage');
setLabels = true;
}
if (labels.length === 0) {
labels.push('triage');
@@ -37,7 +42,7 @@ jobs:
}
case 'closed': {
if (labels.includes('bug') || labels.includes('request') || labels.includes('improvement')) {
if (labels.includes('bug') || labels.includes('request') || labels.includes('improvement') || labels.includes('task')) {
labels.push('done');
setLabels = true;
}
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
fetch-depth: 0
- name: 🔀 Merge master into maintenance
uses: robotology/gh-action-nightly-merge@v1.3.2
uses: robotology/gh-action-nightly-merge@v1.3.3
with:
stable_branch: "master"
development_branch: "maintenance"
@@ -24,7 +24,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: 🔀 Merge maintenance into devel
uses: robotology/gh-action-nightly-merge@v1.3.2
uses: robotology/gh-action-nightly-merge@v1.3.3
with:
stable_branch: "maintenance"
development_branch: "devel"
+4
View File
@@ -31,12 +31,14 @@ jobs:
run: |
pip install .
- 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:${{ matrix.branch }}` was successful"
- name: 📧 Discord failure notification
continue-on-error: true
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
@@ -65,12 +67,14 @@ jobs:
run: |
pip install https://github.com/OctoPrint/OctoPrint/archive/${{ steps.latest.outputs.release }}.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"
- name: 📧 Discord failure notification
continue-on-error: true
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
+4 -3
View File
@@ -43,16 +43,17 @@ repos:
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 22.1.0
rev: 22.3.0
hooks:
- id: black
args: ["--config", "black.toml"]
additional_dependencies:
- click==8.0.4
- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.2
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear
- flake8-bugbear==22.3.20
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.5.1
hooks:
+10 -10
View File
@@ -18,21 +18,21 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.8.0
# maintenance is currently the branch for preparation of maintenance release 1.9.0
# so are any fix/... and improve/... branches
maintenance 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
fix/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
improve/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
maintenance 1.9.0 fa2c4680cca0d1d6b46e6c1ed68ceea4d9b79afb pep440-dev
fix/.* 1.9.0 fa2c4680cca0d1d6b46e6c1ed68ceea4d9b79afb pep440-dev
improve/.* 1.9.0 fa2c4680cca0d1d6b46e6c1ed68ceea4d9b79afb pep440-dev
# staging/bugfix is the branch for preparation of the 1.7.4 bugfix release
# staging/bugfix is the branch for preparation of the 1.8.1 bugfix release
# so are any bug/... branches
staging/bugfix 1.7.4 59cbfadf8922d85b9df40f8d0173e8c21724c3b8 pep440-dev
bug/.* 1.7.4 59cbfadf8922d85b9df40f8d0173e8c21724c3b8 pep440-dev
staging/bugfix 1.8.1 d2a9aacedacf2b582faca462d6e915f88676a3d5 pep440-dev
bug/.* 1.8.1 d2a9aacedacf2b582faca462d6e915f88676a3d5 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.7.0rc4
# staging/maintenance is currently the branch for preparation of 1.8.0rc6
# so is regressionfix/...
staging/maintenance 1.7.0rc4 f31194f75365787f3eb5da61a24f2f8620111f4f pep440-dev
regressionfix/.* 1.7.0rc4 f31194f75365787f3eb5da61a24f2f8620111f4f pep440-dev
staging/maintenance 1.8.0rc6 45598764e6c7f6257de87a98d15964209ddc9e09 pep440-dev
regressionfix/.* 1.8.0rc6 45598764e6c7f6257de87a98d15964209ddc9e09 pep440-dev
# staging/devel is currently inactive (but has the 1.4.1rc4 namespace)
staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev
+3
View File
@@ -164,6 +164,9 @@ date of first contribution):
* [Shell M. Shrader](https://github.com/synman)
* [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
+8 -4
View File
@@ -8,6 +8,7 @@ thanks to everyone who contributed!
* 3D-TECH
* 3DPrinterOS
* Al Mucci
* Arnljot Arntsen
* Artillery 3D
* Ash King
@@ -20,6 +21,7 @@ thanks to everyone who contributed!
* Christian Wolf
* Christian Würthner
* Christoph Sigrist
* Craig Parker
* Creality3D
* David Bounds
* DeltaMaker 3D Printers
@@ -34,7 +36,9 @@ thanks to everyone who contributed!
* Hog Duske
* Itay Shem-tov
* James Mackay
* Jeff Green
* Jeff Moe
* jeffiel
* Jeremy Cole
* Joshua Wills
* Julian Melo
@@ -45,16 +49,15 @@ thanks to everyone who contributed!
* Kurt Wubbels
* Kyle Menigoz
* Lachlan Bell
* Lee Dohm
* Lefteris Lertas
* LulzBot
* Makespace Madrid
* Mark Walker
* Matt Van Itallie
* Michael Aumock
* Mike Kershaw
* Miles Flavel
* Mosaic Manufacturing
* Nat Friedman
* Norman Jaffe
* Peopoly
* Pete Barnwell
@@ -66,6 +69,7 @@ thanks to everyone who contributed!
* Richard Stocks
* Robert Gusek
* Ronald Griehsler
* Sean Jensen-Grey
* Sebastien Andrivet
* Stefan Krister
* Steve Dougherty
@@ -74,7 +78,7 @@ thanks to everyone who contributed!
* The Spaghetti Detective
* TJ Horner
* Trent Shumay
* Ulderico Cirello
* Ulrich Kempken
* Yehuda Katz
and 2298 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
and 2279 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
+1
View File
@@ -28,6 +28,7 @@
* [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
+2 -2
View File
@@ -2,11 +2,11 @@
[jinja2: src/octoprint/templates/**.jinja2]
silent=false
extensions=jinja2.ext.autoescape, jinja2.ext.with_, webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch
extensions=webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch
[jinja2: src/octoprint/plugins/**.jinja2]
silent=false
extensions=jinja2.ext.autoescape, jinja2.ext.with_, webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch
extensions=webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch
[javascript: src/octoprint/static/js/app/**.js]
extract_messages = gettext, ngettext
-27
View File
@@ -1,14 +1,3 @@
/* 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;
@@ -42,19 +31,3 @@
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;
}
+1 -1
View File
@@ -649,7 +649,7 @@ Permission record
* - ``dangerous``
- 1
- boolean
- Whether the permission should be considered dangerous due to a high reponsibility (true) or not (false).
- Whether the permission should be considered dangerous due to a high responsibility (true) or not (false).
* - ``default_groups``
- 1
- List of string
+2
View File
@@ -627,9 +627,11 @@ 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``
+2 -2
View File
@@ -76,7 +76,7 @@ Change current timelapse config
.. http:post:: /api/timelapse
Save a new :ref:`timelapse configuration <sec-api-timelapse-datamodel-config>` to use for the next print. Set the optional ``save`` flag in the
configuration to ``true`` in order to make the new configuration persist accross restarts.
configuration to ``true`` in order to make the new configuration persist across restarts.
The configuration is expected as the request body.
@@ -220,7 +220,7 @@ Timelapse configuration
* - ``save``
- 1
- bool
- Optional flag to be included when when saving a configuration to make the configuration persist accross restarts
- Optional flag to be included when when saving a configuration to make the configuration persist across restarts
Further fields are timelapse type specific, see below for details.
-9
View File
@@ -1,9 +0,0 @@
.. _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
View File
@@ -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 wil fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist``
type included in this list, the test will 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.
+126 -7
View File
@@ -45,10 +45,11 @@ of the following steps:
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
3. The App sends an :ref:`Authorization request <sec-bundledplugins-appkey-datamodel-authrequest>` to the Server to start the
authorization process.
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
4. The Server triggers a confirmation dialog for the User on the Webinterface (unused here) and returns an endpoint to the
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`
and an :ref:`Authorization response <sec-bundledplugins-appkey-datamodel-authresponse>` (unused here).
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
signals that no decision has been made yet.
6. The User either accepts or denies the access request which makes the Webinterface send a
@@ -116,6 +117,98 @@ of the following steps:
end
.. _sec-bundledplugins-appkeys-workflow-authdialog:
Workflow with redirect to auth dialog
-------------------------------------
.. versionadded:: 1.8.0
Instead of asking the user to open the full blown OctoPrint interface to confirm the request,
since OctoPrint 1.8.0 there also exists the alternative of redirecting the user to a
basic auth dialog that allows logging in and confirming the request in a light-weight
dialog. To implementat that, follow these steps:
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
enters their username which is also their user ID into the App.
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
3. The App sends an :ref:`Authorization request <sec-bundledplugins-appkey-datamodel-authrequest>` to the Server to start the
authorization process.
4. The Server triggers a confirmation dialog for the User on the Webinterface (unused here) and returns an endpoint to the
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`
and an :ref:`Authorization response <sec-bundledplugins-appkey-datamodel-authresponse>`.
5. The App opens a browser window with the provided `auth_dialog` URL for the user to log in and confirm the request. At the
same time the App also uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
signals that no decision has been made yet.
6. The User logs in and either accepts or denies the access request which makes the auth dialog send a
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
an HTTP :http:statuscode:`404`.
.. mermaid::
sequenceDiagram
participant User
participant App
participant Auth Dialog
participant Server
note over User, Server: Step 1, 2 & 3
User->>App: enters URL of instance to connect to and optional user_id
App->>Server: GET /plugin/appkeys/probe
alt Workflow unsupported
Server->>App: 404
App->>User: alternative workflow, copy-paste key manually
else Workflow supported
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
note over User, Server: Step 4
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>, auth_dialog: <auth_dialog>
note over User, Server: Step 5
App-->>Auth Dialog: open new browser window with auth_dialog URL
loop Poll for decision
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 202
end
note over User, Server: Step 6 & 7
User->>Auth Dialog: Logs in
alt User accepts
User-->>Auth Dialog: Allow access
Auth Dialog->>Server: POST /plugin/appkeys/decision/<user_token>, (True)
Server->>Auth Dialog: 204
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 200, api_key
else User denies
User-->>Auth Dialog: Deny access
Auth Dialog->>Server: POST /plugin/appkeys/decision/<user_token>, (False)
Server->>Auth Dialog: 204
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 404
end
end
.. _sec-bundledplugins-appkeys-api:
API
@@ -144,7 +237,7 @@ Start authorization process
Starts the authorization process.
Expects a :ref:`Key request <sec-bundledplugins-appkey-datamodel-keyrequest>` as request body.
Expects a :ref:`Authorization request <sec-bundledplugins-appkey-datamodel-authrequest>` as request body.
The ``app`` parameter should be a human readable identifier to use
for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively,
@@ -156,6 +249,9 @@ Start authorization process
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
is logged in on.
Returns a :ref:`Authorization response <sec-bundledplugins-appkey-datamodel-authresponse>`
and HTTP :http:statuscode:`201` with the ``Location`` header set to the endpoint to poll for a decision.
:json app: application identifier to use for the request, case insensitive
:json user: optional user id to restrict the decision to the specified user
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
@@ -287,10 +383,10 @@ Issue an application key command
Data model
----------
.. _sec-bundledplugins-appkey-datamodel-keyrequest:
.. _sec-bundledplugins-appkey-datamodel-authrequest:
Key request
...........
Authorization request
.....................
.. list-table::
:widths: 15 5 10 30
@@ -309,6 +405,29 @@ Key request
- str
- User identifier/name to restrict the request to
.. _sec-bundledplugins-appkey-datamodel-authresponse:
Authorization response
......................
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``app_token``
- 1
- str
- Application token to use to poll for the decision.
* - ``auth_dialog``
- 1
- str
- An URL with which a dedicated auth dialog can be used for the user to log into
and authorize the request.
.. _sec-bundledplugins-appkey-datamodel-keyresponse:
Key response
-6
View File
@@ -1,6 +0,0 @@
.. _sec-bundledplugins-loginui:
Login UI
========
The Login UI plugin's functionality has been merged into OctoPrint's core as of OctoPrint 1.4.2.
+1 -1
View File
@@ -560,7 +560,7 @@ Global credentials
.. versionadded:: 1.5.0
Starting with OctoPrint 1.5.0, the Software Update Plugin supports supplyting a GitHub
Starting with OctoPrint 1.5.0, the Software Update Plugin supports supplying a GitHub
API token to use for the ``github_release`` and ``github_commit`` version check types,
to work around possible rate limit problems if a lot of checks are to be made from a single
external IP. You may create a `personal access token <https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token>`_
+4 -8
View File
@@ -43,6 +43,7 @@ extensions = [
"sphinx.ext.napoleon",
"sphinxcontrib.mermaid",
"sphinx.ext.intersphinx",
"sphinx_rtd_theme"
]
todo_include_todos = True
intersphinx_mapping = {
@@ -108,7 +109,7 @@ exclude_patterns = ["_build"]
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
pygments_style = "stata-dark"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
@@ -122,19 +123,14 @@ 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()]
+5
View File
@@ -451,6 +451,11 @@ 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.
enforceReallyUniversalFilenames: false
.. _sec-configuration-config_yaml-folder:
-4
View File
@@ -329,10 +329,6 @@ 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",
+1 -1
View File
@@ -216,7 +216,7 @@ There many configuration options via ``config.yaml`` for the virtual printer tha
# Enable virtual EEPROM
# If enabled, a file `eeprom.json` will be created in the plugin data folder
# to enable settings persistence across connections. Enables M500/1/2/4 commmands
# to enable settings persistence across connections. Enables M500/1/2/4 commands
# And a selection of other settings commands. Responses modeled on Marlin 2.0
enable_eeprom: true
+3 -3
View File
@@ -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 follwing command:
On OctoPi (or another Linux distribution) you can use the following command:
.. code-block::
@@ -133,7 +133,7 @@ Example: Your PC has an IP address of ``192.168.23.42`` and a subnet mask of
The easy way: Using the OctoPrint-AutoLoginConfig plugin
........................................................
The easist way to configure AutoLogin is to install the
The easiest way to configure AutoLogin is to install the
`OctoPrint-AutoLoginConfig plugin <https://plugins.octoprint.org/plugins/autologin_config/>`_
via the plugin manager.
@@ -189,7 +189,7 @@ further down there's also a dedicated list of steps for OctoPi specifically.
4. Restart OctoPrint, check that everything works.
This will automatically log you in as the user you specified whenver you connect to
This will automatically log you in as the user you specified whenever you connect to
OctoPrint from an address in the address range (e.g. a device on your local network).
OctoPi specific steps
+1 -1
View File
@@ -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/s.
confirm: You are about to move the X axis right by 10mm with 3000mm/min.
commands:
- G91
- G1 X10 F3000
+4
View File
@@ -84,6 +84,8 @@ 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``)
@@ -99,6 +101,7 @@ 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``
@@ -109,6 +112,7 @@ 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``
+2 -27
View File
@@ -55,7 +55,6 @@ 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"
@@ -91,8 +90,7 @@ 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: 4-8,14
:linenos:
:emphasize-lines: 1-5,11
import octoprint.plugin
@@ -120,7 +118,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 :ref:`python logger <logging>` ready to be
one of those being a fully instantiated :py:mod:`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>``.
@@ -270,7 +268,6 @@ 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"
@@ -278,7 +275,6 @@ 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"
@@ -290,7 +286,6 @@ 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
@@ -313,7 +308,6 @@ 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
@@ -359,7 +353,6 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
.. code-block:: python
:emphasize-lines: 4
:linenos:
import octoprint.plugin
@@ -376,7 +369,6 @@ 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>
@@ -423,7 +415,6 @@ 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
@@ -455,7 +446,6 @@ Adjust your plugin's ``__init__.py`` like this:
.. code-block:: python
:emphasize-lines: 12-13
:linenos:
import octoprint.plugin
@@ -478,7 +468,6 @@ 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>
@@ -515,7 +504,6 @@ 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">
@@ -537,7 +525,6 @@ 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>
@@ -560,7 +547,6 @@ again since we don't use that anymore:
.. code-block:: python
:emphasize-lines: 12-16
:linenos:
import octoprint.plugin
@@ -618,7 +604,6 @@ 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">
@@ -655,7 +640,6 @@ like so:
.. code-block:: python
:emphasize-lines: 6,19-22
:linenos:
import octoprint.plugin
@@ -693,7 +677,6 @@ Then we'll create our custom `Knockout <http://knockoutjs.com/documentation/intr
like so:
.. code-block:: javascript
:linenos:
$(function() {
function HelloWorldViewModel(parameters) {
@@ -768,7 +751,6 @@ 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">
@@ -807,7 +789,6 @@ 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%;
@@ -818,7 +799,6 @@ 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">
@@ -833,7 +813,6 @@ a reference to our CSS file:
.. code-block:: python
:emphasize-lines: 23
:linenos:
import octoprint.plugin
@@ -916,7 +895,6 @@ Then adjust our returned assets to include our LESS file as well:
.. code-block:: python
:emphasize-lines: 24
:linenos:
import octoprint.plugin
@@ -966,7 +944,6 @@ 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>
@@ -995,7 +972,6 @@ 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>
@@ -1025,7 +1001,6 @@ 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>
-2
View File
@@ -11,7 +11,6 @@ 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
@@ -42,7 +41,6 @@ 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
+3 -30
View File
@@ -26,7 +26,6 @@ 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")
@@ -75,7 +74,6 @@ 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
@@ -95,7 +93,6 @@ 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
@@ -120,7 +117,6 @@ hook called ``octoprint.plugin.ordertest.callback``:
And these three plugins defining handlers for that hook:
.. code-block:: python
:linenos:
:caption: oneorderedhook.py
import logging
@@ -135,7 +131,6 @@ And these three plugins defining handlers for that hook:
}
.. code-block:: python
:linenos:
:caption: anotherorderedhook.py
import logging
@@ -150,7 +145,6 @@ And these three plugins defining handlers for that hook:
}
.. code-block:: python
:linenos:
:caption: yetanotherhook.py
import logging
@@ -237,7 +231,7 @@ octoprint.access.permissions
.. code-block:: python
from octoprint.access import ADMIN_GROUP
def get_additional_permissions(*args, **kwargs):
return [
dict(key="ADMIN",
@@ -316,7 +310,6 @@ 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>`_
@@ -350,7 +343,6 @@ 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>`_
@@ -543,7 +535,6 @@ 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>`__
@@ -594,7 +585,6 @@ 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>`__
@@ -749,7 +739,6 @@ 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>`_
@@ -792,7 +781,6 @@ 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>`_
@@ -831,7 +819,6 @@ 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>`_
@@ -868,7 +855,6 @@ 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>`_
@@ -877,7 +863,6 @@ 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>`_
@@ -918,7 +903,6 @@ 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>`_
@@ -984,7 +968,6 @@ 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':
@@ -1043,7 +1026,6 @@ 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"]
@@ -1078,7 +1060,6 @@ 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
@@ -1111,7 +1092,6 @@ octoprint.filemanager.extension_tree
and ``s3g``:
.. code-block:: python
:linenos:
def support_x3g_machinecode(*args, **kwargs):
return dict(
@@ -1152,7 +1132,6 @@ 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>`_
@@ -1454,7 +1433,7 @@ octoprint.server.http.access_validator
Allows adding additional access validators to the default tornado routers.
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further.
Your plugin might need to this to restrict access to downloads and webcam snapshots further.
.. important::
@@ -1496,7 +1475,6 @@ 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>`_
@@ -1556,7 +1534,6 @@ 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>`_
@@ -1846,24 +1823,20 @@ 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>`_
@@ -1938,7 +1911,7 @@ octoprint.timelapse.capture.post
Perform specific actions after capturing a timelapse frame.
``filename`` will be the path of the frame that should have been saved.
``sucesss`` indicates whether the capture was successful or not.
``success`` indicates whether the capture was successful or not.
:param str filename: The path of the frame that should have been saved.
:param boolean success: Indicates whether the capture was successful or not.
-5
View File
@@ -26,7 +26,6 @@ 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():
@@ -79,7 +78,6 @@ 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
@@ -95,7 +93,6 @@ 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
@@ -116,7 +113,6 @@ 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
@@ -138,7 +134,6 @@ 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
+2 -2
View File
@@ -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 unter both Python 2 and Python 3, you should add the corresponding
To make your code behave the same in that regard in both Python 2 and Python 3, you should add the corresponding
future import:
.. code-block:: python
@@ -336,7 +336,7 @@ As a summary, follow this checklist to migrate your plugin to be compatible to b
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
* Thorougly test your plugin under Python 3. Pay special attention to any kind of string handling issues, integer
* Thoroughly test your plugin under Python 3. Pay special attention to any kind of string handling issues, integer
division, relative imports from your plugin package and how the results of ``map``, ``filter`` and ``zip`` are
used in your code, as those have proven to be the biggest issues during past migrations.
* Once everything works under both Python versions and you've prepared a new release of your plugin (don't forget to
View File
File renamed without changes.
+12 -9
View File
@@ -31,7 +31,7 @@ SETUP_REQUIRES = []
bundled_plugins = [
"OctoPrint-FileCheck>=2021.2.23",
"OctoPrint-FirmwareCheck>=2021.10.11",
"OctoPrint-PiSupport>=2021.3.1",
"OctoPrint-PiSupport>=2022.3.28",
]
core_deps = [
"cachelib>=0.2,<0.3",
@@ -42,7 +42,7 @@ core_deps = [
"filetype>=1.0.7,<2",
"Flask-Assets>=2.0,<3",
"Flask-Babel>=2.0,<3",
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"Flask-Login>=0.6,<0.7", # breaking changes can happen on minor version increases
"flask>=2,<3",
"frozendict>=2.0,<3",
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
@@ -58,13 +58,16 @@ core_deps = [
"requests>=2.26.0,<3",
"sarge==0.1.6",
"semantic_version>=2.8.5,<3",
"sentry-sdk>=1.3.1,<2",
"sentry-sdk>=1.5.7,<2",
"tornado>=6.0.4,<7",
"watchdog>=1,<2",
"websocket-client>=1.2.1,<2",
"wrapt>=1.13.3,<1.14",
"werkzeug>=2.1,<2.2", # breaking changes can happen on minor version increases
"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
@@ -96,11 +99,11 @@ EXTRA_REQUIRES = {
"plugins": ["cookiecutter>=1.7.2,<1.8"],
# Dependencies for building the documentation
"docs": [
"readthedocs-sphinx-ext",
"sphinx_rtd_theme",
"sphinx>=3,<4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"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",
],
}
+28 -28
View File
@@ -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 {}, ignoring it".format(implementation._identifier),
"Error while trying to migrate settings for " "plugin %s, ignoring it",
implementation._identifier,
extra={"plugin": implementation._identifier},
)
@@ -526,13 +526,16 @@ def init_custom_events(plugin_manager):
event, prefix=f"plugin_{name}_"
)
logger.debug(
'Registered event {} of plugin {} as Events.{} = "{}"'.format(
event, name, constant, value
)
'Registered event %s of plugin %s as Events. %s = "%s"',
event,
name,
constant,
value,
)
except Exception:
logger.exception(
f"Error while retrieving custom event list from plugin {name}",
"Error while retrieving custom event list from plugin %s",
name,
extra={"plugin": name},
)
@@ -661,7 +664,7 @@ def init_pluginsystem(
disabled_from_overlays[name] = (disabled_plugins, order)
settings_overlays[name] = overlay
logger.debug(f"Found settings overlay on plugin {name}")
logger.debug("Found settings overlay on plugin %s", name)
def handle_plugins_loaded(
startup=False, initialize_implementations=True, force_reload=None
@@ -686,24 +689,22 @@ def init_pluginsystem(
if addon in already_processed:
logger.info(
"Plugin {} wants to disable plugin {}, but that was already processed".format(
name, addon
)
"Plugin %s wants to disable plugin %s, but that was already processed",
name,
addon,
)
if addon not in already_processed and addon not in disabled_list:
disabled_list.append(addon)
logger.info(
"Disabling plugin {} as defined by plugin {}".format(
addon, name
)
"Disabling plugin %s as defined by plugin %s", 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(f"Added settings overlay from plugin {name}")
logger.info("Added settings overlay from plugin %s", name)
pm.on_plugin_loaded = handle_plugin_loaded
pm.on_plugins_loaded = handle_plugins_loaded
@@ -756,22 +757,22 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
if "pluginversions" in entry:
logger.debug(
"Blacklisted plugin: {}, versions: {}".format(
entry["plugin"], ", ".join(entry["pluginversions"])
)
"Blacklisted plugin: %s, versions: %s",
entry["plugin"],
", ".join(entry["pluginversions"]),
)
for version in entry["pluginversions"]:
result.append((entry["plugin"], version))
elif "versions" in entry:
logger.debug(
"Blacklisted plugin: {}, versions: {}".format(
entry["plugin"], ", ".join(entry["versions"])
)
"Blacklisted plugin: %s, versions: %s",
entry["plugin"],
", ".join(entry["versions"]),
)
for version in entry["versions"]:
result.append((entry["plugin"], f"=={version}"))
else:
logger.debug("Blacklisted plugin: {}".format(entry["plugin"]))
logger.debug("Blacklisted plugin: %s", entry["plugin"])
result.append(entry["plugin"])
return result
@@ -808,9 +809,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
)
except Exception as e:
logger.info(
"Unable to fetch plugin blacklist from {}, proceeding without it: {}".format(
url, e
)
"Unable to fetch plugin blacklist from %s, proceeding without it: %s",
url,
e,
)
return result
@@ -832,10 +833,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
if blacklist:
logger.info(
"Blacklist processing done, "
"adding {} blacklisted plugin versions: {}".format(
len(blacklist), format_blacklist(blacklist)
)
"Blacklist processing done, adding %s blacklisted plugin versions: %s",
len(blacklist),
format_blacklist(blacklist),
)
else:
logger.info("Blacklist processing done")
+2 -6
View File
@@ -500,7 +500,7 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
:widths: 5 95
* - icon
- Icon to use for the sidebar header, should be the name of a Font Awesome icon without the leading ``icon-`` part.
- 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``.
* - 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,12 +631,10 @@ 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>`_
@@ -1191,7 +1189,6 @@ class SimpleApiPlugin(OctoPrintPlugin):
Take this example of a plugin registered under plugin identifier ``mysimpleapiplugin``:
.. code-block:: python
:linenos:
import octoprint.plugin
@@ -1327,7 +1324,6 @@ 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
@@ -1428,7 +1424,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
# 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 [member for member in dir(self) if not member.startswith("_")]:
for member in [x for x in dir(self) if not x.startswith("_")]:
f = getattr(self, member)
if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules:
@@ -95,7 +95,7 @@ class ActionCommandNotificationPlugin(
{
"type": "sidebar",
"name": gettext("Printer Notifications"),
"icon": "bell-o",
"icon": "far fa-bell",
"styles_wrapper": ["display: none"],
"template_header": "action_command_notification_sidebar_header.jinja2",
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
@@ -18,10 +18,10 @@ from octoprint.util.version import (
)
SENTRY_URL_SERVER = (
"https://87d311e64fdc40f096a1049d99307bf5@o118517.ingest.sentry.io/1373987"
"https://f4265899b96044f3a31e6414c315a0d1@o118517.ingest.sentry.io/1373987"
)
SENTRY_URL_COREUI = (
"https://91516ad9a76c47409b02734cbe8492c5@o118517.ingest.sentry.io/1374096"
"https://2f33808cb0cb4027afd005c35eebfeb4@o118517.ingest.sentry.io/1374096"
)
SETTINGS_DEFAULTS = {
@@ -1,2 +1,3 @@
/*! @sentry/browser 5.18.1 (b1261aab) | https://github.com/getsentry/sentry-javascript */
var Sentry=function(t){var n=function(t,r){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var r in n)n.hasOwnProperty(r)&&(t[r]=n[r])})(t,r)};function r(t,r){function e(){this.constructor=t}n(t,r),t.prototype=null===r?Object.create(r):(e.prototype=r.prototype,new e)}var e=function(){return(e=Object.assign||function(t){for(var n,r=1,e=arguments.length;r<e;r++)for(var i in n=arguments[r])Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i]);return t}).apply(this,arguments)};function i(t){var n="function"==typeof Symbol&&t[Symbol.iterator],r=0;return n?n.call(t):{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}}}function o(t,n){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var e,i,o=r.call(t),u=[];try{for(;(void 0===n||n-- >0)&&!(e=o.next()).done;)u.push(e.value)}catch(t){i={error:t}}finally{try{e&&!e.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return u}function u(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(o(arguments[n]));return t}var c,a,s;!function(t){t[t.None=0]="None",t[t.Error=1]="Error",t[t.Debug=2]="Debug",t[t.Verbose=3]="Verbose"}(c||(c={})),(a=t.Severity||(t.Severity={})).Fatal="fatal",a.Error="error",a.Warning="warning",a.Log="log",a.Info="info",a.Debug="debug",a.Critical="critical",function(t){t.fromString=function(n){switch(n){case"debug":return t.Debug;case"info":return t.Info;case"warn":case"warning":return t.Warning;case"error":return t.Error;case"fatal":return t.Fatal;case"critical":return t.Critical;case"log":default:return t.Log}}}(t.Severity||(t.Severity={})),(s=t.Status||(t.Status={})).Unknown="unknown",s.Skipped="skipped",s.Success="success",s.RateLimit="rate_limit",s.Invalid="invalid",s.Failed="failed",function(t){t.fromHttpCode=function(n){return n>=200&&n<300?t.Success:429===n?t.RateLimit:n>=400&&n<500?t.Invalid:n>=500?t.Failed:t.Unknown}}(t.Status||(t.Status={}));var f=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(t,n){return t.__proto__=n,t}:function(t,n){for(var r in n)t.hasOwnProperty(r)||(t[r]=n[r]);return t});var h=function(t){function n(n){var r=this.constructor,e=t.call(this,n)||this;return e.message=n,e.name=r.prototype.constructor.name,f(e,r.prototype),e}return r(n,t),n}(Error);function v(t){switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return E(t,Error)}}function l(t){return"[object ErrorEvent]"===Object.prototype.toString.call(t)}function d(t){return"[object DOMError]"===Object.prototype.toString.call(t)}function p(t){return"[object String]"===Object.prototype.toString.call(t)}function y(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function m(t){return"[object Object]"===Object.prototype.toString.call(t)}function b(t){return"undefined"!=typeof Event&&E(t,Event)}function w(t){return"undefined"!=typeof Element&&E(t,Element)}function g(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function E(t,n){try{return t instanceof n}catch(t){return!1}}function x(t,n){return void 0===n&&(n=0),"string"!=typeof t||0===n?t:t.length<=n?t:t.substr(0,n)+"..."}function j(t,n){if(!Array.isArray(t))return"";for(var r=[],e=0;e<t.length;e++){var i=t[e];try{r.push(String(i))}catch(t){r.push("[value cannot be serialized]")}}return r.join(n)}function k(t,n){return!!p(t)&&(r=n,"[object RegExp]"===Object.prototype.toString.call(r)?n.test(t):"string"==typeof n&&-1!==t.indexOf(n));var r}function S(){return"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}var T={};function O(){return S()?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:T}function _(){var t=O(),n=t.crypto||t.msCrypto;if(void 0!==n&&n.getRandomValues){var r=new Uint16Array(8);n.getRandomValues(r),r[3]=4095&r[3]|16384,r[4]=16383&r[4]|32768;var e=function(t){for(var n=t.toString(16);n.length<4;)n="0"+n;return n};return e(r[0])+e(r[1])+e(r[2])+e(r[3])+e(r[4])+e(r[5])+e(r[6])+e(r[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=16*Math.random()|0;return("x"===t?n:3&n|8).toString(16)})}function D(t){if(!t)return{};var n=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!n)return{};var r=n[6]||"",e=n[8]||"";return{host:n[4],path:n[5],protocol:n[2],relative:n[5]+r+e}}function R(t){if(t.message)return t.message;if(t.exception&&t.exception.values&&t.exception.values[0]){var n=t.exception.values[0];return n.type&&n.value?n.type+": "+n.value:n.type||n.value||t.event_id||"<unknown>"}return t.event_id||"<unknown>"}function I(t){var n=O();if(!("console"in n))return t();var r=n.console,e={};["debug","info","warn","error","log","assert"].forEach(function(t){t in n.console&&r[t].__sentry_original__&&(e[t]=r[t],r[t]=r[t].__sentry_original__)});var i=t();return Object.keys(e).forEach(function(t){r[t]=e[t]}),i}function N(t,n,r){t.exception=t.exception||{},t.exception.values=t.exLine truncated
/*! @sentry/browser 6.18.2 (22f518e) | https://github.com/getsentry/sentry-javascript */
var Sentry=function(t){var n=function(t,r){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])},n(t,r)};function r(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function i(){this.constructor=t}n(t,r),t.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var i,e=function(){return e=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++)for(var e in n=arguments[r])Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=n[e]);return t},e.apply(this,arguments)};function o(t){var n="function"==typeof Symbol&&Symbol.iterator,r=n&&t[n],i=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function u(t,n){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var i,e,o=r.call(t),u=[];try{for(;(void 0===n||n-- >0)&&!(i=o.next()).done;)u.push(i.value)}catch(t){e={error:t}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return u}function a(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(u(arguments[n]));return t}t.Severity=void 0,(i=t.Severity||(t.Severity={})).Fatal="fatal",i.Error="error",i.Warning="warning",i.Log="log",i.Info="info",i.Debug="debug",i.Critical="critical";var c={};function s(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:c}var f=Object.prototype.toString;function h(t){switch(f.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return x(t,Error)}}function v(t,n){return f.call(t)==="[object "+n+"]"}function d(t){return v(t,"ErrorEvent")}function l(t){return v(t,"DOMError")}function p(t){return v(t,"String")}function y(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function m(t){return v(t,"Object")}function b(t){return"undefined"!=typeof Event&&x(t,Event)}function w(t){return"undefined"!=typeof Element&&x(t,Element)}function g(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function x(t,n){try{return t instanceof n}catch(t){return!1}}function E(t,n){try{for(var r=t,i=[],e=0,o=0,u=" > ".length,a=void 0;r&&e++<5&&!("html"===(a=_(r,n))||e>1&&o+i.length*u+a.length>=80);)i.push(a),o+=a.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return"<unknown>"}}function _(t,n){var r,i,e,o,u,a=t,c=[];if(!a||!a.tagName)return"";c.push(a.tagName.toLowerCase());var s=n&&n.length?n.filter((function(t){return a.getAttribute(t)})).map((function(t){return[t,a.getAttribute(t)]})):null;if(s&&s.length)s.forEach((function(t){c.push("["+t[0]+'="'+t[1]+'"]')}));else if(a.id&&c.push("#"+a.id),(r=a.className)&&p(r))for(i=r.split(/\s+/),u=0;u<i.length;u++)c.push("."+i[u]);var f=["type","name","title","alt"];for(u=0;u<f.length;u++)e=f[u],(o=a.getAttribute(e))&&c.push("["+e+'="'+o+'"]');return c.join("")}var j=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(t,n){return t.__proto__=n,t}:function(t,n){for(var r in n)Object.prototype.hasOwnProperty.call(t,r)||(t[r]=n[r]);return t});var k=function(t){function n(n){var r=this.constructor,i=t.call(this,n)||this;return i.message=n,i.name=r.prototype.constructor.name,j(i,r.prototype),i}return r(n,t),n}(Error),S=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/;function O(t,n){void 0===n&&(n=!1);var r=t.host,i=t.path,e=t.pass,o=t.port,u=t.projectId;return t.protocol+"://"+t.publicKey+(n&&e?":"+e:"")+"@"+r+(o?":"+o:"")+"/"+(i?i+"/":i)+u}function T(t){return"user"in t&&!("publicKey"in t)&&(t.publicKey=t.user),{user:t.publicKey||"",protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function D(t){var n="string"==typeof t?function(t){var n=S.exec(t);if(!n)throw new k("Invalid Sentry Dsn: "+t);var r=u(n.slice(1),6),i=r[0],e=r[1],o=r[2],a=void 0===o?"":o,c=r[3],s=r[4],f=void 0===s?"":s,h="",v=r[5],d=v.split("/");if(d.length>1&&(h=d.slice(0,-1).join("/"),v=d.pop()),v){var l=v.match(/^\d+/);l&&(v=l[0])}return T({host:c,pass:a,path:h,projectId:v,port:f,protocol:i,publicKey:e})}(t):T(t);return n}var R=["fatal","error","warning","log","info","debug","critical"],N=s(),I="Sentry Logger ";function M(t){var n=s();if(!("console"in n))return t();var r=n.console,i={};["debug","info","warn","error","log","assert"].forEach((function(t){t in n.console&&r[t].__sentry_original__&&(i[t]=r[t],r[t]=r[t].__sentry_original__)}));var e=t();return Object.keys(i).forEach((function(t){r[t]=i[t]})),e}var q=function(){function t(){this.t=!1}return t.prototype.disable=function(){this.t=!1},t.prototype.enable=function(){this.t=!0},t.prototype.log=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];this.t&&M((function(){var n;(n=N.console).log.apply(n,a([I+"[Log]:Line truncated
//# sourceMappingURL=bundle.min.js.map
@@ -17,6 +17,7 @@ class GcodeviewerPlugin(
"js/viewer/ui.js",
"js/viewer/reader.js",
"js/viewer/renderer.js",
"js/viewer/pako.js",
]
return {
@@ -47,6 +48,8 @@ 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,6 +8,7 @@ $(function () {
self.sizeThresholdStr = undefined;
self.mobileSizeThresholdStr = undefined;
self.compressionSizeThresholdStr = undefined;
self.ui_progress_busy = ko.observable(false);
self.ui_progress_percentage = ko.observable();
@@ -83,6 +84,7 @@ $(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);
@@ -127,7 +129,12 @@ $(function () {
var reader = {
purgeEmptyLayers: self.reader_hideEmptyLayers(),
ignoreOutsideBed: self.reader_ignoreOutsideBed()
ignoreOutsideBed: self.reader_ignoreOutsideBed(),
alwaysCompress:
self.settings.settings.plugins.gcodeviewer.alwaysCompress(),
compressionSizeThreshold:
self.settings.settings.plugins.gcodeviewer.compressionSizeThreshold(),
forceCompression: self.reader_forceCompression()
};
if (additionalReaderOptions) {
_.extend(reader, additionalReaderOptions);
@@ -170,6 +177,7 @@ $(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;
@@ -360,6 +368,9 @@ $(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");
@@ -396,6 +407,13 @@ $(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();
@@ -435,6 +453,7 @@ $(function () {
self.reader_hideEmptyLayers(true);
self.reader_ignoreOutsideBed(true);
self.reader_forceCompression(false);
};
self.clear = function () {
@@ -522,10 +541,6 @@ $(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
@@ -935,6 +950,7 @@ $(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,7 +7,6 @@
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};
@@ -39,11 +38,31 @@ GCODE.gCodeReader = (function () {
},
ignoreOutsideBed: false,
g90InfluencesExtruder: false,
bedZ: 0
bedZ: 0,
alwaysCompress: false,
compressionSizeThreshold: 0,
forceCompression: false
};
// 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;
@@ -81,17 +100,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 (
rendererModel[layer][middle].percentage == key ||
(rendererModel[layer][middle].percentage <= key &&
rendererModel[layer][middle + 1].percentage > key)
cmds[middle].percentage == key ||
(cmds[middle].percentage <= key && cmds[middle + 1].percentage > key)
)
return middle;
if (rendererModel[layer][middle].percentage > key) {
if (cmds[middle].percentage > key) {
upper = middle - 1;
} else {
lower = middle + 1;
@@ -108,7 +127,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, rendererModel[layer].length - 1, key);
var cmd = searchInCmds(layer, 0, GCODE.renderer.getLayer(layer).length - 1, key);
// remember last position
cachedLayer = layer;
@@ -117,49 +136,51 @@ GCODE.gCodeReader = (function () {
return {layer: layer, cmd: cmd};
};
var sanitizeModel = function (m) {
var cleanModel = function (m) {
if (!m) return [];
return _.filter(m, function (layer) {
return !!layer;
});
};
var purgeEmptyLayers = function (m) {
return _.filter(m, function (layer) {
return (
!!layer &&
layer.length > 0 &&
_.find(layer, function (cmd) {
return cmd && cmd.extrude;
}) !== undefined
);
});
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 rebuildLayerPercentageLookup = function (m) {
var result = [];
for (var i = 0; i < m.length - 1; i++) {
// start is first command of current layer
var start = m[i].length ? m[i][0].percentage : -1;
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 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 (m[j].length) {
end = m[j][0].percentage;
break;
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];
break;
}
}
result[i] = [start, end];
}
result[i] = [start, end];
// final start-end-pair is start percentage of last layer and 100%
result[result.length] = [rendererPercentageByLayer[m.length - 1], 100];
}
// final start-end-pair is start percentage of last layer and 100%
result[m.length - 1] = m[m.length - 1].length
? [m[m.length - 1][0].percentage, 100]
: [-1, -1];
layerPercentageLookup = result;
};
@@ -179,6 +200,8 @@ GCODE.gCodeReader = (function () {
maxZ: undefined
};
rendererModel = undefined;
rendererEmptyLayers = undefined;
rendererPercentageByLayer = undefined;
layerPercentageLookup = undefined;
cachedLayer = undefined;
cachedCmd = undefined;
@@ -206,6 +229,12 @@ 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: {
@@ -216,7 +245,8 @@ GCODE.gCodeReader = (function () {
bed: gCodeOptions["bed"],
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"],
bedZ: gCodeOptions["bedZ"]
bedZ: gCodeOptions["bedZ"],
compress: mustCompress
}
}
});
@@ -235,14 +265,11 @@ GCODE.gCodeReader = (function () {
},
passDataToRenderer: function () {
var m = sanitizeModel(model);
if (gCodeOptions["purgeEmptyLayers"]) m = purgeEmptyLayers(m);
rendererModel = cleanModel(model);
rebuildLayerPercentageLookup(rendererModel);
rendererModel = m;
rebuildLayerPercentageLookup(m);
GCODE.renderer.doRender(m, 0);
return m;
GCODE.renderer.doRender(rendererModel, 0);
return rendererModel;
},
processLayersFromWorker: function (msg) {
@@ -262,6 +289,8 @@ GCODE.gCodeReader = (function () {
speedsByLayer = msg.speedsByLayer;
printTime = msg.printTime;
printTimeByLayer = msg.printTimeByLayer;
emptyLayers = msg.emptyLayers;
percentageByLayer = msg.percentageByLayer;
},
getLayerFilament: function (z) {
@@ -288,8 +317,8 @@ GCODE.gCodeReader = (function () {
getGCodeLines: function (layer, fromSegments, toSegments) {
var result = {
first: model[layer][fromSegments].gcodeLine,
last: model[layer][toSegments].gcodeLine
first: GCODE.renderer.getLayer(layer)[fromSegments].gcodeLine,
last: GCODE.renderer.getLayer(layer)[toSegments].gcodeLine
};
return result;
},
@@ -99,6 +99,32 @@ 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"]) {
@@ -162,13 +188,15 @@ 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 = model[layer];
var cmds = getLayer(layer);
var firstExtrusion;
var i;
@@ -858,7 +886,7 @@ GCODE.renderer = (function () {
if (!model || !model[layerNum]) return;
var cmds = model[layerNum];
var cmds = getLayer(layerNum);
var x, y;
//~~ find our initial prevX/prevY tuple
@@ -875,7 +903,7 @@ GCODE.renderer = (function () {
// previous layer exists, use last x/y as prevX/prevY
prevX = undefined;
prevY = undefined;
var prevModelLayer = model[layerNum - 1];
var prevModelLayer = getLayer(layerNum - 1);
for (i = prevModelLayer.length - 1; i >= 0; i--) {
if (prevX === undefined && prevModelLayer[i].x !== undefined) {
prevX = prevModelLayer[i].x;
@@ -1042,7 +1070,14 @@ GCODE.renderer = (function () {
if (renderOptions["showMoves"] && !isNotCurrentLayer) {
// move => draw line from (prevX, prevY) to (x, y) in move color
ctx.lineWidth = lineWidthFactor;
ctx.lineTo(x, y);
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);
}
}
} else if (cmd.extrude) {
if (cmd.retract == 0) {
@@ -1340,11 +1375,14 @@ GCODE.renderer = (function () {
},
getLayerNumSegments: function (layer) {
if (model) {
return model[layer] ? model[layer].length : 1;
return model[layer] ? getLayer(layer).length : 1;
} else {
return 1;
}
},
getLayer: function (layer) {
return getLayer(layer);
},
clear: function () {
offsetModelX = 0;
offsetModelY = 0;
@@ -1355,6 +1393,7 @@ GCODE.renderer = (function () {
speeds = [];
speedsByLayer = {};
modelInfo = undefined;
layerCache = [];
this.doRender([], 0);
},
@@ -1372,7 +1411,7 @@ GCODE.renderer = (function () {
speeds = modelInfo.speeds;
speedsByLayer = modelInfo.speedsByLayer;
if (model[layerNum]) {
toProgress = model[layerNum].length;
toProgress = getLayer(layerNum).length;
}
}
@@ -1394,7 +1433,7 @@ GCODE.renderer = (function () {
if (!model || !model[layerNum]) {
return "-1";
}
var cmds = model[layerNum];
var cmds = getLayer(layerNum);
for (var i = 0; i < cmds.length; i++) {
if (cmds[i].prevZ !== undefined) return cmds[i].prevZ;
}
@@ -36,6 +36,22 @@ 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 = [];
@@ -46,6 +62,7 @@ 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]];
}
@@ -85,7 +102,9 @@ var sendAnalyzeDone = function () {
layerTotal: model.length,
speeds: speeds,
speedsByLayer: speedsByLayer,
printTimeByLayer: printTimeByLayer
printTimeByLayer: printTimeByLayer,
percentageByLayer: percentageByLayer,
emptyLayers: emptyLayers
}
});
};
@@ -97,8 +116,10 @@ var purgeLayers = function () {
if (!model[i]) {
purge = true;
} else {
for (var j = 0; j < model[i].length; j++) {
if (model[i][j].extrude) purge = false;
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;
}
}
if (!purge) {
@@ -155,7 +176,13 @@ 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;
@@ -288,7 +315,16 @@ 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();
@@ -303,6 +339,7 @@ var analyzeModel = function () {
var doParse = function () {
var argChar, numSlice;
var activeLayer = undefined;
var sendLayer = undefined;
var sendMultiLayer = [];
var lastSend = 0;
@@ -599,7 +636,6 @@ var doParse = function () {
}
layer = model.length;
sendLayer = layer;
prevZ = z;
}
@@ -610,6 +646,9 @@ 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,
@@ -634,49 +673,68 @@ var doParse = function () {
};
if (zLift) {
// Insert zLift moves for later processing
// Insert zLift moves for later processing - they might be part of
// the active layer still
zLiftMoves.push({
command: command,
layer: layer
});
} else if (zLiftMoves.length > 0) {
// there's something to be checked in the Z-lift cache
if (prevZ < maxLiftZ) {
zLiftMoves.forEach(function (zLiftMove) {
// move command from move layer...
model[zLiftMove.layer].splice(
model[layer].indexOf(zLiftMove.command),
1
);
// ... to z-lift layer
model[zLiftLayer].push(zLiftMove.command);
});
} else {
if (zLiftMoves.length > 0) {
// 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);
});
// clean up empty layers at the end of the model
var spliceFrom = undefined;
for (var l = model.length - 1; l > 0; l--) {
if (model[l].length > 0) break;
spliceFrom = l;
}
if (spliceFrom !== undefined) {
model.splice(spliceFrom, model.length - spliceFrom);
// clean up empty layers at the end of the model
var spliceFrom = undefined;
for (var l = model.length - 1; l > 0; l--) {
if (model[l].length > 0) break;
spliceFrom = l;
}
if (spliceFrom !== undefined) {
model.splice(spliceFrom, model.length - spliceFrom);
}
// finally determine the new active layer
if (prevZ === zLiftZ) {
// initial lifted on layer if we are back at a prior height
layer = zLiftLayer;
} else {
// new layer if this a new z, just lower than max z-lift
model[model.length] = [];
layer = model.length - 1;
}
}
// finally determine the new active layer
if (prevZ === zLiftZ) {
// initial lifted on layer if we are back at a prior height
layer = zLiftLayer;
} else {
// new layer if this a new z, just lower than max z-lift
model[model.length] = [];
layer = model.length - 1;
}
// clear up cached Z-lift moves
zLiftMoves = [];
zLiftZ = undefined;
maxLiftZ = undefined;
zLiftLayer = undefined;
}
// have we progressed a layer?
if (activeLayer === undefined || layer > activeLayer) {
// the formerly active layer is now done and can be sent
sendLayer = activeLayer;
// the current layer is the new active layer
activeLayer = layer;
}
// clear up cached Z-lift moves
zLiftMoves = [];
zLiftZ = undefined;
maxLiftZ = undefined;
zLiftLayer = undefined;
}
model[layer].push(command);
@@ -694,10 +752,19 @@ var doParse = function () {
sendMultiLayer = [];
sendMultiLayerZ = [];
}
sendMultiLayer[sendMultiLayer.length] = sendLayer;
if (sendMultiLayer.indexOf(sendLayer) === -1) {
sendMultiLayer.push(sendLayer);
}
sendLayer = undefined;
}
}
// we are done, send the final layer
if (sendMultiLayer.indexOf(activeLayer) === -1) {
sendMultiLayer.push(activeLayer);
}
sendLayersToParent(sendMultiLayer, 100);
};
@@ -710,6 +777,7 @@ 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,17 +1,22 @@
<h3>{{ _("GCode Viewer") }}</h3>
<form class="form-horizontal" onsubmit="return false;">
<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">{{ _('GCode Viewer file size threshold') }}</label>
<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">
<div class="input-append">
<input type="text" class="input-mini text-right" data-bind="value: sizeThresholdStr" id="settings-gcodeviewer-featureSizeThreshold">
</div>
<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>
<div class="controls">
<input type="text" class="input-mini text-right" data-bind="value: sizeThresholdStr" id="settings-gcodeviewer-featureSizeThreshold">
<span class="help-inline">{{ _('on desktop')}}</span>
</div>
<div class="controls">
<div class="input-append">
<input type="text" class="input-mini text-right" data-bind="value: mobileSizeThresholdStr">
</div>
<input type="text" class="input-mini text-right" data-bind="value: mobileSizeThresholdStr">
<span class="help-inline">{{ _('on mobile')}}</span>
</div>
<div class="controls">
@@ -20,13 +25,29 @@
</span>
</div>
</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>
<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>
</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>
</form>
@@ -134,7 +134,26 @@
Are you sure you want to visualize this file nevertheless?
</p>{% endtrans %}
<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>
<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>
</div>
@@ -97,7 +97,7 @@ def map_repository_entry(entry):
entry["compatibility"]["python"]
)
else:
# we default to only assume py2 compatiblity for now
# we default to only assume py2 compatibility for now
result["is_compatible"]["python"] = is_python_compatible(">=2.7,<3")
return result
@@ -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; } }"><i class="fas fa-add"></i> <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; } }"><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,7 +773,9 @@ class SoftwareUpdatePlugin(
def on_settings_save(self, data):
# ~~ plugin settings
for key in self.get_settings_defaults():
defaults = self.get_settings_defaults()
for key in defaults:
if key in (
"checks",
"cache_ttl",
@@ -783,6 +785,7 @@ class SoftwareUpdatePlugin(
"octoprint_checkout_folder",
"octoprint_type",
"octoprint_release_channel",
"credentials",
):
continue
if key in data:
@@ -912,6 +915,14 @@ 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
@@ -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 insuffient disk space, OctoPrint requires
To reduce the likelihood of running into update problems due to insufficient disk space, OctoPrint requires
a minimum of {{ min_free_storage }} free disk space in various locations:
</p>
{% endtrans %}
+4 -4
View File
@@ -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/s
- Speed of the X axis in mm/min
* - ``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/s
- Speed of the Y axis in mm/min
* - ``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/s
- Speed of the Z axis in mm/min
* - ``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/s
- Speed of the E axis in mm/min
* - ``axes.e.inverted``
- ``bool``
- Whether a positive value change extrudes (False, default) or retracts (True) filament
+2
View File
@@ -0,0 +1,2 @@
__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"
+54
View File
@@ -0,0 +1,54 @@
__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()
@@ -0,0 +1,52 @@
__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."""
+18
View File
@@ -0,0 +1,18 @@
__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."""
+164
View File
@@ -0,0 +1,164 @@
__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."""
+86
View File
@@ -0,0 +1,86 @@
__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."""
+55
View File
@@ -0,0 +1,55 @@
__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
+29
View File
@@ -0,0 +1,29 @@
__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."""
+40
View File
@@ -0,0 +1,40 @@
__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."""
+45
View File
@@ -0,0 +1,45 @@
__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."""
+49
View File
@@ -0,0 +1,49 @@
__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."""
@@ -0,0 +1,34 @@
__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."""
+19
View File
@@ -0,0 +1,19 @@
__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."""
@@ -0,0 +1,12 @@
__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] = []
@@ -0,0 +1,13 @@
__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."""
+31
View File
@@ -0,0 +1,31 @@
__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()
+238
View File
@@ -0,0 +1,238 @@
__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)."""
+206
View File
@@ -0,0 +1,206 @@
__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, ...)."""
+19
View File
@@ -0,0 +1,19 @@
__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."""
+31
View File
@@ -0,0 +1,31 @@
__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."""
@@ -0,0 +1,37 @@
__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."""
@@ -0,0 +1,35 @@
__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",
),
]
+107
View File
@@ -0,0 +1,107 @@
__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
+8 -4
View File
@@ -1352,6 +1352,7 @@ class Server:
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
app.config["REMEMBER_COOKIE_HTTPONLY"] = True
# we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take
app.debug = self._debug
@@ -1944,6 +1945,8 @@ class Server:
global assets
global pluginManager
from octoprint.server.util.webassets import MemoryManifest # noqa: F401
util.flask.fix_webassets_filtertool()
base_folder = self._settings.getBaseFolder("generated")
@@ -1955,7 +1958,8 @@ class Server:
for entry, recreate in (
("webassets", True),
(".webassets-cache", False), # no longer used, but clean up just in case
# no longer used, but clean up just in case
(".webassets-cache", False),
(".webassets-manifest.json", False),
):
path = os.path.join(base_folder, entry)
@@ -2042,7 +2046,7 @@ class Server:
# few seconds for regeneration in development, if it means we can get rid of
# a whole monkey patch and in internal use of pickle with non-tamperproof files
assets.cache = False
assets.manifest = "json:.webassets-manifest.json"
assets.manifest = "memory"
UpdaterType = type(util.flask.SettingsCheckUpdater)(
util.flask.SettingsCheckUpdater.__name__,
@@ -2111,8 +2115,8 @@ class Server:
"css/bootstrap-slider.css",
"css/bootstrap-tabdrop.css",
"vendor/font-awesome-3.2.1/css/font-awesome.min.css",
"vendor/font-awesome-5.15.1/css/all.min.css",
"vendor/font-awesome-5.15.1/css/v4-shims.min.css",
"vendor/fontawesome-6.1.1/css/all.min.css",
"vendor/fontawesome-6.1.1/css/v4-shims.min.css",
"css/jquery.fileupload-ui.css",
"css/pnotify.core.min.css",
"css/pnotify.buttons.min.css",
+1
View File
@@ -490,6 +490,7 @@ def _saveSettings(data):
s.setBaseFolder(folder, future[folder])
except Exception:
logger.exception("Something went wrong while saving a folder path")
abort(400, description="At least one of the configured folders is invalid")
if "api" in data:
-3
View File
@@ -378,9 +378,6 @@ def require_login_with(permissions=None, user_id=None):
):
requires_login = False
if current_user.is_anonymous:
requires_login = True
if permissions is not None and not has_permissions(*permissions):
requires_login = True
login_kwargs["permissions"] = ",".join([x.key for x in permissions])
+1 -2
View File
@@ -41,8 +41,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
"""Recursively yield DirEntry objects for given directory."""
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
for entry in _recursive_scandir(entry.path):
yield entry
yield from _recursive_scandir(entry.path)
else:
yield entry
+18
View File
@@ -6,6 +6,7 @@ import gzip
import logging
import os
import re
import threading
from urllib import parse as urlparse
import webassets.filter.cssrewrite.urlpath as urlpath
@@ -14,6 +15,7 @@ from webassets.filter import Filter
from webassets.filter.cssrewrite.base import PatternRewriter
from webassets.filter.rjsmin import rjsmin
from webassets.merge import BaseHunk, MemoryHunk
from webassets.version import Manifest
def replace_url(source_url, output_url, url):
@@ -207,3 +209,19 @@ class JsPluginBundle(Bundle):
(hunk, lambda x: x.replace("\n", "\n ")),
MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_SUFFIX.format(plugin=self.plugin)),
)
class MemoryManifest(Manifest):
id = "memory"
def __init__(self, *args, **kwargs):
self.manifest = {}
self._lock = threading.RLock()
def remember(self, bundle, ctx, version):
with self._lock:
self.manifest[bundle.output] = version
def query(self, bundle, ctx):
with self._lock:
return self.manifest.get(bundle.output, None)
+31 -10
View File
@@ -8,6 +8,7 @@ import logging
import os
import re
from collections import defaultdict
from urllib.parse import urlparse
from flask import (
Response,
@@ -150,9 +151,9 @@ def _valid_status_for_cache(status_code):
return 200 <= status_code < 400
def _add_additional_assets(hook):
def _add_additional_assets(hook_name):
result = []
for name, hook in pluginManager.get_hooks(hook).items():
for name, hook in pluginManager.get_hooks(hook_name).items():
try:
assets = hook()
if isinstance(assets, (tuple, list)):
@@ -170,7 +171,16 @@ def _add_additional_assets(hook):
def login():
from flask_login import current_user
redirect_url = request.args.get("redirect", request.script_root + url_for("index"))
default_redirect_url = request.script_root + url_for("index")
redirect_url = request.args.get("redirect", default_redirect_url)
parsed = urlparse(redirect_url) # check if redirect url is valid
if parsed.scheme != "" or parsed.netloc != "":
_logger.warning(
f"Got an invalid redirect URL with the login attempt, misconfiguration or attack attempt: {redirect_url}"
)
redirect_url = default_redirect_url
permissions = sorted(
filter(
lambda x: x is not None and isinstance(x, OctoPrintPermission),
@@ -1223,9 +1233,17 @@ def fetch_template_data(refresh=False):
for var_name, var_value in vars.items():
plugin_vars["plugin_" + name + "_" + var_name] = var_value
includes = _process_template_configs(
name, implementation, configs, template_rules
)
try:
includes = _process_template_configs(
name, implementation, configs, template_rules
)
except Exception:
_logger.exception(
"Error while processing template configs for plugin {}, ignoring it".format(
name
),
extra={"plugin": name},
)
if not wizard_required or wizard_ignored:
includes["wizard"] = list()
@@ -1483,11 +1501,14 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
)
return None
if "template" not in data:
data["template"] = rule["template"](name)
data["template"] = implementation.template_folder_key + "/" + data["template"]
if data.get("template"):
data["template"] = implementation.template_folder_key + "/" + data["template"]
else:
data["template"] = (
implementation.template_folder_key + "/" + rule["template"](name)
)
if "template_header" in data:
if data.get("template_header"):
data["template_header"] = (
implementation.template_folder_key + "/" + data["template_header"]
)
@@ -31,9 +31,11 @@ from collections.abc import KeysView
from yaml import YAMLError
from octoprint.schema.config import Config
from octoprint.util import (
CaseInsensitiveSet,
atomic_write,
deprecated,
dict_merge,
fast_deepcopy,
generate_api_key,
@@ -85,393 +87,9 @@ def settings(init=False, basedir=None, configfile=None, overlays=None):
return _instance
default_settings = {
"serial": {
"port": None,
"baudrate": None,
"exclusive": True,
"lowLatency": False,
"autoconnect": False,
"log": False,
"timeout": {
"detectionFirst": 10,
"detectionConsecutive": 2,
"connection": 10,
"communication": 30,
"communicationBusy": 3,
"temperature": 5,
"temperatureTargetSet": 2,
"temperatureAutoreport": 2,
"sdStatus": 1,
"sdStatusAutoreport": 1,
"posAutoreport": 5,
"resendOk": 0.5,
"baudrateDetectionPause": 1.0,
"positionLogWait": 10.0,
},
"maxCommunicationTimeouts": {"idle": 2, "printing": 5, "long": 5},
"maxWritePasses": 5,
"additionalPorts": [],
"additionalBaudrates": [],
"blacklistedPorts": [],
"blacklistedBaudrates": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"],
"blockedCommands": ["M0", "M1"],
"ignoredCommands": [],
"pausingCommands": ["M0", "M1", "M25"],
"emergencyCommands": ["M112", "M108", "M410"],
"checksumRequiringCommands": ["M110"],
"helloCommand": "M110 N0",
"disconnectOnErrors": True,
"ignoreErrorsFromFirmware": False,
"terminalLogSize": 20,
"lastLineBufferSize": 50,
"logResends": True,
"supportResendsWithoutOk": "detect",
"logPositionOnPause": True,
"logPositionOnCancel": False,
"abortHeatupOnCancel": True,
"waitForStartOnConnect": False,
"alwaysSendChecksum": False,
"neverSendChecksum": False,
"sendChecksumWithUnknownCommands": False,
"unknownCommandsNeedAck": False,
"sdRelativePath": False,
"sdAlwaysAvailable": False,
"sdLowerCase": False,
"sdCancelCommand": "M25",
"maxNotSdPrinting": 2,
"swallowOkAfterResend": True,
"repetierTargetTemp": False,
"externalHeatupDetection": True,
"supportWait": True,
"ignoreIdenticalResends": False,
"identicalResendsCountdown": 7,
"supportFAsCommand": False,
"firmwareDetection": True,
"blockWhileDwelling": False,
"useParityWorkaround": "detect",
"maxConsecutiveResends": 10,
"sendM112OnError": True,
"disableSdPrintingDetection": False,
"ackMax": 1,
"sanityCheckTools": True,
"notifySuppressedCommands": "warn",
"capabilities": {
"autoreport_temp": True,
"autoreport_sdstatus": True,
"autoreport_pos": True,
"busy_protocol": True,
"emergency_parser": True,
"extended_m20": True,
},
"resendRatioThreshold": 10,
"resendRatioStart": 100,
"ignoreEmptyPorts": False,
"encoding": "ascii",
"enableShutdownActionCommand": False,
# command specific flags
"triggerOkForM29": True,
},
"server": {
"host": None,
"port": 5000,
"firstRun": True,
"startOnceInSafeMode": False,
"ignoreIncompleteStartup": False,
"incompleteStartup": False,
"seenWizards": {},
"secretKey": None,
"heartbeat": 15 * 60, # 15 min
"reverseProxy": {
"prefixHeader": None,
"schemeHeader": None,
"hostHeader": None,
"serverHeader": None,
"portHeader": None,
"prefixFallback": None,
"schemeFallback": None,
"hostFallback": None,
"serverFallback": None,
"portFallback": None,
"trustedDownstream": [],
},
"uploads": {
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
"nameSuffix": "name",
"pathSuffix": "path",
},
"maxSize": 100 * 1024, # 100 KB
"commands": {
"systemShutdownCommand": None,
"systemRestartCommand": None,
"serverRestartCommand": None,
"localPipCommand": None,
},
"onlineCheck": {
"enabled": None,
"interval": 15 * 60, # 15 min
"host": "1.1.1.1",
"port": 53,
"name": "octoprint.org",
},
"pluginBlacklist": {
"enabled": None,
"url": "https://plugins.octoprint.org/blacklist.json",
"ttl": 15 * 60, # 15 min
},
"diskspace": {
"warning": 500 * 1024 * 1024, # 500 MB
"critical": 200 * 1024 * 1024, # 200 MB
},
"preemptiveCache": {"exceptions": [], "until": 7},
"ipCheck": {"enabled": True, "trustedSubnets": []},
"allowFraming": False,
"cookies": {"secure": False, "samesite": None},
},
"webcam": {
"webcamEnabled": True,
"timelapseEnabled": True,
"stream": None,
"streamRatio": "16:9",
"streamTimeout": 5,
"streamWebrtcIceServers": ["stun:stun.l.google.com:19302"],
"snapshot": None,
"snapshotTimeout": 5,
"snapshotSslValidation": True,
"ffmpeg": None,
"ffmpegThreads": 1,
"ffmpegVideoCodec": "libx264",
"bitrate": "10000k",
"watermark": True,
"flipH": False,
"flipV": False,
"rotate90": False,
"ffmpegCommandline": '{ffmpeg} -framerate {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"',
"ffmpegThumbnailCommandline": '{ffmpeg} -sseof -1 -i "{input}" -update 1 -q:v 0.7 "{output}"',
"timelapse": {
"type": "off",
"options": {},
"postRoll": 0,
"fps": 25,
},
"cleanTmpAfterDays": 7,
"cacheBuster": False,
},
"gcodeAnalysis": {
"maxExtruders": 10,
"throttle_normalprio": 0.01,
"throttle_highprio": 0.0,
"throttle_lines": 100,
"runAt": "idle", # 'never', 'idle', 'always'
"bedZ": 0.0,
},
"feature": {
"temperatureGraph": True,
"sdSupport": True,
"keyboardControl": True,
"pollWatched": False,
"modelSizeDetection": True,
"rememberFileFolder": False,
"printStartConfirmation": False,
"printCancelConfirmation": True,
"uploadOverwriteConfirmation": True,
"autoUppercaseBlacklist": ["M117", "M118"],
"g90InfluencesExtruder": False,
"enforceReallyUniversalFilenames": False,
},
"folder": {
"uploads": None,
"timelapse": None,
"timelapse_tmp": None,
"logs": None,
"virtualSd": None,
"watched": None,
"plugins": None,
"slicingProfiles": None,
"printerProfiles": None,
"scripts": None,
"translations": None,
"generated": None,
"data": None,
},
"temperature": {
"profiles": [
{"name": "ABS", "extruder": 210, "bed": 100},
{"name": "PLA", "extruder": 180, "bed": 60},
],
"cutoff": 30,
"sendAutomatically": False,
"sendAutomaticallyAfter": 1,
},
"printerProfiles": {"default": None},
"printerParameters": {"pauseTriggers": []},
"appearance": {
"name": "",
"color": "default",
"colorTransparent": False,
"colorIcon": True,
"defaultLanguage": "_default",
"showFahrenheitAlso": False,
"fuzzyTimes": True,
"closeModalsWithClick": True,
"showInternalFilename": True,
"components": {
"order": {
"navbar": [
"settings",
"systemmenu",
"plugin_announcements",
"plugin_logging_seriallog",
"plugin_logging_plugintimingslog",
"plugin_pi_support",
"login",
],
"sidebar": [
"plugin_firmware_check_warning",
"plugin_firmware_check_info",
"connection",
"state",
"files",
],
"tab": [
"temperature",
"control",
"plugin_gcodeviewer",
"terminal",
"timelapse",
],
"settings": [
"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",
],
"usersettings": ["access", "interface"],
"wizard": [
"plugin_softwareupdate_update",
"plugin_backup",
"plugin_corewizard_acl",
"plugin_corewizard_onlinecheck",
],
"about": [
"about",
"plugin_pi_support",
"supporters",
"authors",
"changelog",
"license",
"thirdparty",
"plugin_pluginmanager",
],
"generic": [],
},
"disabled": {
"navbar": [],
"sidebar": [],
"tab": [],
"settings": [],
"usersettings": [],
"generic": [],
},
},
},
"controls": [],
"system": {"actions": []},
"accessControl": {
"salt": None,
"userManager": "octoprint.access.users.FilebasedUserManager",
"groupManager": "octoprint.access.groups.FilebasedGroupManager",
"permissionManager": "octoprint.access.permissions.PermissionManager",
"userfile": None,
"groupfile": None,
"autologinLocal": False,
"localNetworks": ["127.0.0.0/8", "::1/128"],
"autologinAs": None,
"trustBasicAuthentication": False,
"checkBasicAuthenticationPassword": True,
"trustRemoteUser": False,
"remoteUserHeader": "REMOTE_USER",
"addRemoteUsers": False,
},
"slicing": {"enabled": True, "defaultSlicer": None, "defaultProfiles": {}},
"events": {"enabled": True, "subscriptions": []},
"api": {"key": None, "allowCrossOrigin": False, "apps": {}},
"terminalFilters": [
{
"name": "Suppress temperature messages",
"regex": r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+([PBN]\d+\s+)*)?([BCLPR]|T\d*):-?\d+)",
},
{
"name": "Suppress SD status messages",
"regex": r"(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)",
},
{
"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]+).*",
},
{"name": "Suppress wait responses", "regex": r"Recv: wait"},
{
"name": "Suppress processing responses",
"regex": r"Recv: (echo:\s*)?busy:\s*processing",
},
],
"plugins": {"_disabled": [], "_forcedCompatible": [], "_sortingOrder": {}},
"scripts": {
"gcode": {
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0",
"snippets": {
"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 %}",
},
}
},
"estimation": {
"printTime": {
"statsWeighingUntil": 0.5,
"validityRange": 0.15,
"forceDumbFromPercent": 0.3,
"forceDumbAfterMin": 30,
"stableThreshold": 60,
}
},
"devel": {
"stylesheet": "css",
"cache": {"enabled": True, "preemptive": True},
"webassets": {
"bundle": True,
"clean_on_startup": True,
"minify": True,
"minify_plugins": False,
},
"useFrozenDictForPrinterState": True,
"showLoadingAnimation": True,
"sockJsConnectTimeout": 30,
"pluginTimings": False,
},
}
# TODO: This is a temporary solution to get the default settings from the pydantic model.
_config = Config()
default_settings = _config.dict(by_alias=True)
"""The default settings of the core application."""
valid_boolean_trues = CaseInsensitiveSet(True, "true", "yes", "y", "1", 1)
@@ -563,7 +181,7 @@ class HierarchicalChainMap:
items = []
for k, v in d.items():
new_key = parent_key + _CHAINMAP_SEP + k if parent_key else k
new_key = parent_key + _CHAINMAP_SEP + str(k) if parent_key else str(k)
if v and isinstance(v, dict):
items.extend(HierarchicalChainMap._flatten(v, new_key).items())
else:
@@ -577,16 +195,30 @@ class HierarchicalChainMap:
if d is None:
return {}
result = dict()
result = {}
for key, value in d.items():
if not key.startswith(prefix):
continue
subkeys = key[len(prefix) :].split(_CHAINMAP_SEP)
current = result
path = []
for subkey in subkeys[:-1]:
if subkey not in current or current[subkey] is None:
# we only need that for logging in case of data weirdness below
path.append(subkey)
# make sure the subkey is in the current dict, and that it is a dict
if subkey not in current:
current[subkey] = {}
elif not isinstance(current[subkey], dict):
logging.getLogger(__name__).warning(
f"There is a non-dict value on the path to {key} at {path!r}, ignoring."
)
current[subkey] = {}
# go down a level
current = current[subkey]
current[subkeys[-1]] = value
return result
@@ -631,27 +263,26 @@ class HierarchicalChainMap:
current = self._chainmap
key = self._path_to_key(path)
prefix = key + _CHAINMAP_SEP
if key in current:
if key in current and not any(k.startswith(prefix) for k in current.keys()):
# found it, return
return current[key]
# if we arrived here we might be trying to grab a dict, look for children
key = key + _CHAINMAP_SEP
# TODO 2.0.0 remove this & make 'merged' the default
if not merged and hasattr(current, "maps"):
# we do something a bit odd here: if merged is not true, we don't include the
# full contents of the key. Instead, we only include the contents of the key
# on the first level where we find the value.
for layer in current.maps:
if any(k.startswith(key) for k in layer):
if any(k.startswith(prefix) for k in layer):
current = layer
break
result = self._unflatten(
{k: v for k, v in current.items() if k.startswith(key)}, prefix=key
{k: v for k, v in current.items() if k.startswith(prefix)}, prefix=prefix
)
if not result:
raise KeyError("Could not find entry for " + str(path))
@@ -796,7 +427,7 @@ class Settings:
serial:
port: "/dev/ttyACM0"
baudrate: 250000
timeouts:
timeout:
communication: 20.0
temperature: 5.0
sdStatus: 1.0
@@ -849,7 +480,6 @@ class Settings:
self._map = HierarchicalChainMap({}, default_settings)
self.load_overlays(overlays)
self._config = None
self._dirty = False
self._dirty_time = 0
self._last_config_hash = None
@@ -1112,7 +742,7 @@ class Settings:
@property
def config_yaml(self):
return yaml.dump(self._config)
return yaml.dump(self.config)
@property
def config_hash(self):
@@ -1127,10 +757,28 @@ class Settings:
return self._last_config_hash
@property
def _config(self):
def config(self):
"""
A view of the local config as stored in config.yaml
Does not support modifications, they will be thrown away silently. If you need to
modify anything in the settings, utilize the provided set and remove methods.
"""
return self._map.top_map
@property
@deprecated(
"Settings._config has been deprecated and is a read-only view. Please use Settings.config or the set & remove methods instead.",
since="1.8.0",
)
def _config(self):
return self.config
@_config.setter
@deprecated(
"Setting of Settings._config has been deprecated. Please use the set & remove methods instead and get in touch if you have a usecase they don't cover.",
since="1.8.0",
)
def _config(self, value):
self._map.top_map = value
@@ -1161,11 +809,14 @@ class Settings:
# ~~ load and save
def load(self, migrate=False):
config = None
mtime = None
if os.path.exists(self._configfile) and os.path.isfile(self._configfile):
with open(self._configfile, encoding="utf-8", errors="replace") as f:
try:
self._config = yaml.load_from_file(file=f)
self._mtime = self.last_modified
config = yaml.load_from_file(file=f)
mtime = self.last_modified
except YAMLError as e:
details = str(e)
@@ -1185,8 +836,11 @@ class Settings:
)
# changed from else to handle cases where the file exists, but is empty / 0 bytes
if not self._config or not isinstance(self._config, dict):
self._config = {}
if not config or not isinstance(config, dict):
config = {}
self._map.top_map = config
self._mtime = mtime
if migrate:
self._migrate_config()
@@ -1280,7 +934,7 @@ class Settings:
def _migrate_config(self, config=None, persist=False):
if config is None:
config = self._config
config = self._map.top_map
persist = True
dirty = False
@@ -1302,6 +956,9 @@ class Settings:
dirty = migrate(config) or dirty
if dirty and persist:
self._map.top_map = (
config # we need to write it back here or the changes will be lost
)
self.save(force=True)
def _migrate_gcode_scripts(self, config):
@@ -1820,7 +1477,7 @@ class Settings:
permissions=0o600,
max_permissions=0o666,
) as configFile:
yaml.save_to_file(self._config, file=configFile)
yaml.save_to_file(self._map.top_map, file=configFile)
self._dirty = False
except Exception:
self._logger.exception("Error while saving config.yaml!")
@@ -2059,10 +1716,7 @@ class Settings:
folder = default_folder
try:
del self._config["folder"][type]
if not len(self._config["folder"]):
del self._config["folder"]
self._mark_dirty()
self.remove(["folder", type])
self.save()
except KeyError:
pass
@@ -2257,23 +1911,12 @@ class Settings:
currentPath = self.getBaseFolder(type)
defaultPath = self._get_default_folder(type)
if (
(path is None or path == defaultPath)
and "folder" in self._config
and type in self._config["folder"]
):
del self._config["folder"][type]
if not self._config["folder"]:
del self._config["folder"]
self._mark_dirty()
if path is None or path == defaultPath:
self.remove(["folder", type])
elif (path != currentPath and path != defaultPath) or force:
if validate:
_validate_folder(path, check_writable=True, deep_check_writable=True)
if "folder" not in self._config:
self._config["folder"] = {}
self._config["folder"][type] = path
self._mark_dirty()
self.set(["folder", type], path, force=force)
def saveScript(self, script_type, name, script):
script_folder = self.getBaseFolder("scripts")
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #fff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #fff, #e6e6e6);background-image:-o-linear-gradient(top, #fff, #e6e6e6);background-image:linear-gradient(to bottom, #fff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:65 / 100;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #08c, #04c);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#04c));background-image:-webkit-linear-gradient(top, #08c, #04c);background-image:-o-linear-gradient(top, #08c, #04c);background-image:linear-gradient(to bottom, #08c, #04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)Line truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #fff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #fff, #e6e6e6);background-image:-o-linear-gradient(top, #fff, #e6e6e6);background-image:linear-gradient(to bottom, #fff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #08c, #04c);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#04c));background-image:-webkit-linear-gradient(top, #08c, #04c);background-image:-o-linear-gradient(top, #08c, #04c);background-image:linear-gradient(to bottom, #08c, #04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btnLine truncated
+84 -34
View File
@@ -652,13 +652,25 @@ function cleanTemperature(temp, offThreshold) {
return temp;
}
function formatTemperature(temp, showF, offThreshold) {
function formatTemperature(temp, showF, offThreshold, returnUnicode) {
if (temp === undefined || !_.isNumber(temp)) return "-";
if (offThreshold !== undefined && temp < offThreshold) return gettext("off");
var degreeSymbol = "&deg;";
if (returnUnicode !== undefined && returnUnicode) {
degreeSymbol = "\u00B0";
}
if (showF) {
return _.sprintf("%.1f&deg;C (%.1f&deg;F)", temp, (temp * 9) / 5 + 32);
return _.sprintf(
"%.1f%sC (%.1f%sF)",
temp,
degreeSymbol,
(temp * 9) / 5 + 32,
degreeSymbol
);
} else {
return _.sprintf("%.1f&deg;C", temp);
return _.sprintf("%.1f%sC", temp, degreeSymbol);
}
}
@@ -1485,7 +1497,7 @@ var sizeObservable = function (observable) {
var getQueryParameterByName = function (name, url) {
// from http://stackoverflow.com/a/901144/2028598
if (!url) {
url = window.location.href;
url = fetchWindowLocation().href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
@@ -1542,41 +1554,75 @@ var copyToClipboard = function (text) {
temp.remove();
};
var determineWebcamStreamType = function (streamUrl) {
if (streamUrl) {
if (streamUrl.startsWith("webrtc")) {
return "webrtc";
}
var getExternalHostUrl = function () {
var loc = fetchWindowLocation();
var port = "";
if (
(loc.protocol === "http:" && loc.port !== "80") ||
(loc.protocol === "https:" && loc.port !== "443")
) {
port = ":" + loc.port;
}
return loc.protocol + "//" + loc.hostname + port;
};
var lastDotPosition = streamUrl.lastIndexOf(".");
var firstQuotationSignPosition = streamUrl.indexOf("?");
if (
lastDotPosition != -1 &&
firstQuotationSignPosition != -1 &&
lastDotPosition >= firstQuotationSignPosition
) {
throw "Malformed URL. Cannot determine stream type.";
}
var validateWebcamUrl = function (streamUrl) {
if (!streamUrl) {
return false;
}
// If we have found a dot, try to extract the extension.
if (lastDotPosition > -1) {
if (firstQuotationSignPosition > -1) {
var extension = streamUrl.slice(
lastDotPosition + 1,
firstQuotationSignPosition - 1
);
} else {
var extension = streamUrl.slice(lastDotPosition + 1);
}
if (extension.toLowerCase() == "m3u8") {
return "hls";
}
}
// By default, 'mjpg' is the stream type.
return "mjpg";
var lower = streamUrl.toLowerCase();
var toParse = streamUrl;
if (lower.startsWith("//")) {
// protocol relative
toParse = fetchWindowLocation().protocol + streamUrl;
} else if (lower.startsWith("/")) {
// host relative
toParse = getExternalHostUrl() + streamUrl;
} else if (
lower.startsWith("http:") ||
lower.startsWith("https:") ||
lower.startsWith("webrtc:") ||
lower.startsWith("webrtcs:")
) {
// absolute & supported protocol
toParse = streamUrl;
} else {
return false;
}
try {
return new URL(toParse);
} catch (e) {
return false;
}
};
var determineWebcamStreamType = function (streamUrl) {
if (!streamUrl) {
throw "Empty streamUrl. Cannot determine stream type.";
}
var parsed = validateWebcamUrl(streamUrl);
if (!parsed) {
throw "Invalid streamUrl. Cannot determine stream type.";
}
if (parsed.protocol === "webrtc:" || parsed.protocol === "webrtcs:") {
return "webrtc";
}
var lastDotPosition = parsed.pathname.lastIndexOf(".");
if (lastDotPosition !== -1) {
var extension = parsed.pathname.substring(lastDotPosition + 1);
if (extension.toLowerCase() === "m3u8") {
return "hls";
}
}
// By default, 'mjpg' is the stream type.
return "mjpg";
};
var saveToLocalStorage = function (key, data) {
@@ -1705,3 +1751,7 @@ var startWebRTC = function (videoElement, streamUrl, iceServers) {
negotiateWebRTC(streamUrl);
return pc;
};
var fetchWindowLocation = function () {
return window.location;
};
@@ -324,7 +324,7 @@ $(function () {
title: gettext("Are you sure?"),
message: _.sprintf(
gettext('You are about to delete the user "%(name)s".'),
{name: user.name}
{name: _.escape(user.name)}
),
proceed: gettext("Delete"),
onproceed: function () {
@@ -656,7 +656,7 @@ $(function () {
title: gettext("Are you sure?"),
message: _.sprintf(
gettext('You are about to delete the group "%(name)s".'),
{name: group.name}
{name: _.escape(group.name)}
),
proceed: gettext("Delete"),
onproceed: function () {
@@ -40,7 +40,8 @@ $(function () {
self.isLoading = ko.observable(undefined);
self.enableConnect = ko.pureComputed(function () {
return self.enablePort() || !self.isErrorOrClosed();
//return self.enablePort() || !self.isErrorOrClosed();
return true; // enable always for now, until we have an auto refresh in 1.9.0
});
self.buttonText = ko.pureComputed(function () {
@@ -573,7 +573,7 @@ $(function () {
}
// Determine stream type and switch to corresponding webcam.
var streamType = determineWebcamStreamType(self.settings.webcam_streamUrl());
var streamType = self.settings.webcam_streamType();
if (streamType == "mjpg") {
self._switchToMjpgWebcam();
} else if (streamType == "hls") {
@@ -728,9 +728,12 @@ $(function () {
// z home
button = $("#control-zhome");
break;
default:
case 9: // prevent tab key from removing focus from webcam
event.preventDefault();
return false;
default:
// don't prevent other keys
return true;
}
if (button === undefined) {
@@ -760,7 +763,7 @@ $(function () {
return;
}
var newSrc = self.settings.webcam_streamUrl();
var newSrc = self.settings.webcam_streamUrlEscaped();
if (currentSrc != newSrc) {
if (self.settings.webcam_cacheBuster()) {
if (newSrc.lastIndexOf("?") > -1) {
@@ -797,10 +800,10 @@ $(function () {
typeof video.canPlayType != undefined &&
video.canPlayType("application/vnd.apple.mpegurl") == "probably"
) {
video.src = self.settings.webcam_streamUrl();
video.src = self.settings.webcam_streamUrlEscaped();
} else if (Hls.isSupported()) {
self.hls = new Hls();
self.hls.loadSource(self.settings.webcam_streamUrl());
self.hls.loadSource(self.settings.webcam_streamUrlEscaped());
self.hls.attachMedia(video);
}
@@ -836,7 +839,7 @@ $(function () {
if (self.webRTCPeerConnection == null) {
self.webRTCPeerConnection = startWebRTC(
video,
self.settings.webcam_streamUrl(),
self.settings.webcam_streamUrlEscaped(),
self.settings.webcam_streamWebrtcIceServers()
);
}
@@ -865,7 +868,7 @@ $(function () {
// If we found the rotation container, the view is rotated 90 degrees. This
// means we need to manually calculate the player dimensions and apply them
// to the rotation target where height = width and width = height (to
// accomodate the rotation). The target is centered in the container and
// accommodate the rotation). The target is centered in the container and
// rotated around its center, so after we manually resized the container
// everything will layout nicely.
if (rotationContainer && player.videoWidth && player.videoHeight) {
@@ -250,6 +250,7 @@ $(function () {
self.serial_ackMax = ko.observable(undefined);
self.serial_resendRatioThreshold = ko.observable(100);
self.serial_resendRatioStart = ko.observable(100);
self.serial_ignoreEmptyPorts = ko.observable(undefined);
self.serial_enableShutdownActionCommand = ko.observable(undefined);
self.folder_uploads = ko.observable(undefined);
@@ -311,13 +312,20 @@ $(function () {
self.webcam_ffmpegPathOk(false);
self.webcam_ffmpegPathBroken(false);
};
self.webcam_streamUrlEscaped = ko.pureComputed(function () {
return encodeURI(self.webcam_streamUrl());
});
self.webcam_streamType = ko.pureComputed(function () {
try {
return determineWebcamStreamType(self.webcam_streamUrl());
return determineWebcamStreamType(self.webcam_streamUrlEscaped());
} catch (e) {
return "";
}
});
self.webcam_streamValid = ko.pureComputed(function () {
var url = self.webcam_streamUrlEscaped();
return !url || validateWebcamUrl(url);
});
self.server_onlineCheckText = ko.observable();
self.server_onlineCheckOk = ko.observable(false);
@@ -438,7 +446,8 @@ $(function () {
self.testWebcamStreamUrlBusy = ko.observable(false);
self.testWebcamStreamUrl = function () {
if (!self.webcam_streamUrl()) {
var url = self.webcam_streamUrlEscaped();
if (!url) {
return;
}
@@ -449,24 +458,31 @@ $(function () {
var text = gettext(
"If you see your webcam stream below, the entered stream URL is ok."
);
var streamType = self.webcam_streamType();
var streamType;
try {
streamType = self.webcam_streamType();
} catch (e) {
streamType = "";
}
var webcam_element;
var webrtc_peer_connection;
if (streamType == "mjpg") {
webcam_element = $('<img src="' + self.webcam_streamUrl() + '">');
} else if (streamType == "hls") {
if (streamType === "mjpg") {
webcam_element = $('<img src="' + url + '">');
} else if (streamType === "hls") {
webcam_element = $(
'<video id="webcam_hls" muted autoplay style="width: 100%"/>'
);
video_element = webcam_element[0];
if (video_element.canPlayType("application/vnd.apple.mpegurl")) {
video_element.src = self.webcam_streamUrl();
video_element.src = url;
} else if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(self.webcam_streamUrl());
hls.loadSource(url);
hls.attachMedia(video_element);
}
} else if (isWebRTCAvailable() && streamType == "webrtc") {
} else if (isWebRTCAvailable() && streamType === "webrtc") {
webcam_element = $(
'<video id="webcam_webrtc" muted autoplay playsinline controls style="width: 100%"/>'
);
@@ -474,7 +490,7 @@ $(function () {
webrtc_peer_connection = startWebRTC(
video_element,
self.webcam_streamUrl(),
url,
self.webcam_streamWebrtcIceServers()
);
} else {
@@ -270,7 +270,7 @@ var bootstrapWizardCreate = function(element, options) {
// remove the existing handlers
$('a[data-toggle="tab"]', $navigation).off('click', innerTabClick);
$('a[data-toggle="tab"]', $navigation).off('show show.bs.tab', innerTabShown);
$('a[data-toggle="tab"]', $navigation).off('show', innerTabShown);
// reset elements based on current state of the DOM
$navigation = element.find('ul:first', element);
@@ -278,7 +278,7 @@ var bootstrapWizardCreate = function(element, options) {
// re-add handlers
$('a[data-toggle="tab"]', $navigation).on('click', innerTabClick);
$('a[data-toggle="tab"]', $navigation).on('show show.bs.tab', innerTabShown);
$('a[data-toggle="tab"]', $navigation).on('show', innerTabShown);
obj.fixNavigationButtons();
};
@@ -303,7 +303,8 @@ var bootstrapWizardCreate = function(element, options) {
$('a[data-toggle="tab"]', $navigation).on('click', innerTabClick);
// attach to both show and show.bs.tab to support Bootstrap versions 2.3.2 and 3.0.0
$('a[data-toggle="tab"]', $navigation).on('show show.bs.tab', innerTabShown);
// Note: removing show.bs.tab in the listener stops to trigger twice the method innerTabShown
$('a[data-toggle="tab"]', $navigation).on('show', innerTabShown);
};
$.fn.bootstrapWizard = function(options) {
//expose methods
+1 -1
View File
@@ -41,7 +41,7 @@ $(function () {
// system commands
self.systemCommands = ko.observableArray([]);
// systen info
// system info
self.systemInfo = ko.observableArray([]);
// printer
+2 -2
View File
@@ -21,8 +21,8 @@
// Optional: Group multiple button groups together for a toolbar
.btn-toolbar {
font-size: 0; // Hack to remove whitespace that results from using inline-block
margin-top: @baseLineHeight / 2;
margin-bottom: @baseLineHeight / 2;
margin-top: (@baseLineHeight / 2);
margin-bottom: (@baseLineHeight / 2);
> .btn + .btn,
> .btn-group + .btn,
> .btn + .btn-group {
+2 -2
View File
@@ -24,8 +24,8 @@ code {
// Blocks of code
pre {
display: block;
padding: (@baseLineHeight - 1) / 2;
margin: 0 0 @baseLineHeight / 2;
padding: ((@baseLineHeight - 1) / 2);
margin: 0 0 (@baseLineHeight / 2);
font-size: @baseFontSize - 1; // 14px to 13px
line-height: @baseLineHeight;
word-break: break-all;
+5 -5
View File
@@ -81,7 +81,7 @@ input[type="color"],
display: inline-block;
height: @baseLineHeight;
padding: 4px 6px;
margin-bottom: @baseLineHeight / 2;
margin-bottom: (@baseLineHeight / 2);
font-size: @baseFontSize;
line-height: @baseLineHeight;
color: @gray;
@@ -399,7 +399,7 @@ select:focus:invalid {
.help-block {
display: block; // account for any element using help-block
margin-bottom: @baseLineHeight / 2;
margin-bottom: (@baseLineHeight / 2);
}
.help-inline {
@@ -416,7 +416,7 @@ select:focus:invalid {
.input-append,
.input-prepend {
display: inline-block;
margin-bottom: @baseLineHeight / 2;
margin-bottom: (@baseLineHeight / 2);
vertical-align: middle;
font-size: 0; // white space collapse hack
white-space: nowrap; // Prevent span and input from separating
@@ -617,7 +617,7 @@ input.search-query {
// Margin to space out fieldsets
.control-group {
margin-bottom: @baseLineHeight / 2;
margin-bottom: (@baseLineHeight / 2);
}
// Legend collapses margin, so next element is responsible for spacing
@@ -666,7 +666,7 @@ legend + .control-group {
.input-prepend,
.input-append {
+ .help-block {
margin-top: @baseLineHeight / 2;
margin-top: (@baseLineHeight / 2);
}
}
// Move over buttons in .form-actions to align with .controls
+2 -2
View File
@@ -376,7 +376,7 @@
// Opacity
.opacity(@opacity) {
opacity: @opacity / 100;
opacity: (@opacity / 100);
filter: ~"alpha(opacity=@{opacity})";
}
@@ -679,7 +679,7 @@
// Vertically center elements in the navbar.
// Example: an element has a height of 30px, so write out `.navbarVerticalAlign(30px);` to calculate the appropriate top margin.
.navbarVerticalAlign(@elementHeight) {
margin-top: (@navbarHeight - @elementHeight) / 2;
margin-top: ((@navbarHeight - @elementHeight) / 2);
}
// Grid System
+1 -1
View File
@@ -77,7 +77,7 @@ sub {
img {
/* Responsive images (ensure images don't scale beyond their parents) */
max-width: 100%; /* Part 1: Set a maxium relative to the parent */
max-width: 100%; /* Part 1: Set a maximum relative to the parent */
width: auto\9; /* IE7-8 need help adjusting responsive images */
height: auto; /* Part 2: Scale the height according to the width, otherwise you get stretching */
+3 -3
View File
@@ -6,7 +6,7 @@
// -------------------------
p {
margin: 0 0 @baseLineHeight / 2;
margin: 0 0 (@baseLineHeight / 2);
}
.lead {
margin-bottom: @baseLineHeight;
@@ -160,7 +160,7 @@ h4 small {
ul,
ol {
padding: 0;
margin: 0 0 @baseLineHeight / 2 25px;
margin: 0 0 (@baseLineHeight / 2) 25px;
}
ul ul,
ul ol,
@@ -204,7 +204,7 @@ dt {
font-weight: bold;
}
dd {
margin-left: @baseLineHeight / 2;
margin-left: (@baseLineHeight / 2);
}
// Horizontal layout (like forms)
.dl-horizontal {
File diff suppressed because it is too large. Load diff
@@ -1,5 +0,0 @@
/*!
* Font Awesome Free 5.15.1 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
*/
.fa,.fab,.fad,.fal,.far,.fas{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}.fa-lg{font-size:1.33333em;line-height:.75em;vertical-align:-.0667em}.fa-xs{font-size:.75em}.fa-sm{font-size:.875em}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:2.5em;padding-left:0}.fa-ul>li{position:relative}.fa-li{left:-2em;position:absolute;text-align:center;width:2em;line-height:inherit}.fa-border{border:.08em solid #eee;border-radius:.1em;padding:.2em .25em .15em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.fab.fa-pull-left,.fal.fa-pull-left,.far.fa-pull-left,.fas.fa-pull-left{margin-right:.3em}.fa.fa-pull-right,.fab.fa-pull-right,.fal.fa-pull-right,.far.fa-pull-right,.fas.fa-pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s linear infinite;animation:fa-spin 2s linear infinite}.fa-pulse{-webkit-animation:fa-spin 1s steps(8) infinite;animation:fa-spin 1s steps(8) infinite}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scaleX(-1);transform:scaleX(-1)}.fa-flip-vertical{-webkit-transform:scaleY(-1);transform:scaleY(-1)}.fa-flip-both,.fa-flip-horizontal.fa-flip-vertical,.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)"}.fa-flip-both,.fa-flip-horizontal.fa-flip-vertical{-webkit-transform:scale(-1);transform:scale(-1)}:root .fa-flip-both,:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270{-webkit-filter:none;filter:none}.fa-stack{display:inline-block;height:2em;line-height:2em;position:relative;vertical-align:middle;width:2.5em}.fa-stack-1x,.fa-stack-2x{left:0;position:absolute;text-align:center;width:100%}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-500px:before{content:"\f26e"}.fa-accessible-icon:before{content:"\f368"}.fa-accusoft:before{content:"\f369"}.fa-acquisitions-incorporated:before{content:"\f6af"}.fa-ad:before{content:"\f641"}.fa-address-book:before{content:"\f2b9"}.fa-address-card:before{content:"\f2bb"}.fa-adjust:before{content:"\f042"}.fa-adn:before{content:"\f170"}.fa-adversal:before{content:"\f36a"}.fa-affiliatetheme:before{content:"\f36b"}.fa-air-freshener:before{content:"\f5d0"}.fa-airbnb:before{content:"\f834"}.fa-algolia:before{content:"\f36c"}.fa-align-center:before{content:"\f037"}.fa-align-justify:before{content:"\f039"}.fa-align-left:before{content:"\f036"}.fa-align-right:before{content:"\f038"}.fa-alipay:before{content:"\f642"}.fa-allergies:before{content:"\f461"}.fa-amazon:before{content:"\f270"}.fa-amazon-pay:before{content:"\f42c"}.fa-ambulance:before{content:"\f0f9"}.fa-american-sign-language-interpreting:before{content:"\f2a3"}.fa-amilia:before{content:"\f36d"}.fa-anchor:before{content:"\f13d"}.fa-android:before{content:"\f17b"}.fa-angellist:before{content:"\f209"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-down:before{content:"\f107"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angry:before{content:"\f556"}.fa-angrycreative:before{content:"\f36e"}.fa-angular:before{content:"\f420"}.fa-ankh:before{content:"\f644"}.fa-app-store:before{content:"\f36f"}.fa-app-store-ios:before{content:"\f370"}.fa-apper:before{content:"\f371"}.fa-apple:before{content:"\f179"}.fa-apple-alt:before{content:"\f5d1"}.fa-apple-pay:before{content:"\f415"}.fa-archive:before{content:"\f187"}.fa-archway:before{content:"\f557"}.fa-arrow-alt-circle-down:before{content:"\f358"}.fa-arrow-alt-circle-left:before{content:"\f359"}.fa-arrow-alt-circle-right:before{content:"\f35a"}.fa-arrow-alt-circle-up:before{content:"\f35b"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-ciLine truncated
@@ -1,5 +0,0 @@
/*!
* Font Awesome Free 5.15.1 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
*/
.fa.fa-glass:before{content:"\f000"}.fa.fa-meetup{font-family:"Font Awesome 5 Brands";font-weight:400}.fa.fa-star-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-star-o:before{content:"\f005"}.fa.fa-close:before,.fa.fa-remove:before{content:"\f00d"}.fa.fa-gear:before{content:"\f013"}.fa.fa-trash-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-trash-o:before{content:"\f2ed"}.fa.fa-file-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-file-o:before{content:"\f15b"}.fa.fa-clock-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-clock-o:before{content:"\f017"}.fa.fa-arrow-circle-o-down{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-arrow-circle-o-down:before{content:"\f358"}.fa.fa-arrow-circle-o-up{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-arrow-circle-o-up:before{content:"\f35b"}.fa.fa-play-circle-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-play-circle-o:before{content:"\f144"}.fa.fa-repeat:before,.fa.fa-rotate-right:before{content:"\f01e"}.fa.fa-refresh:before{content:"\f021"}.fa.fa-list-alt{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-dedent:before{content:"\f03b"}.fa.fa-video-camera:before{content:"\f03d"}.fa.fa-picture-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-picture-o:before{content:"\f03e"}.fa.fa-photo{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-photo:before{content:"\f03e"}.fa.fa-image{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-image:before{content:"\f03e"}.fa.fa-pencil:before{content:"\f303"}.fa.fa-map-marker:before{content:"\f3c5"}.fa.fa-pencil-square-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-pencil-square-o:before{content:"\f044"}.fa.fa-share-square-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-share-square-o:before{content:"\f14d"}.fa.fa-check-square-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-check-square-o:before{content:"\f14a"}.fa.fa-arrows:before{content:"\f0b2"}.fa.fa-times-circle-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-times-circle-o:before{content:"\f057"}.fa.fa-check-circle-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-check-circle-o:before{content:"\f058"}.fa.fa-mail-forward:before{content:"\f064"}.fa.fa-expand:before{content:"\f424"}.fa.fa-compress:before{content:"\f422"}.fa.fa-eye,.fa.fa-eye-slash{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-warning:before{content:"\f071"}.fa.fa-calendar:before{content:"\f073"}.fa.fa-arrows-v:before{content:"\f338"}.fa.fa-arrows-h:before{content:"\f337"}.fa.fa-bar-chart{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-bar-chart:before{content:"\f080"}.fa.fa-bar-chart-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-bar-chart-o:before{content:"\f080"}.fa.fa-facebook-square,.fa.fa-twitter-square{font-family:"Font Awesome 5 Brands";font-weight:400}.fa.fa-gears:before{content:"\f085"}.fa.fa-thumbs-o-up{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-thumbs-o-up:before{content:"\f164"}.fa.fa-thumbs-o-down{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-thumbs-o-down:before{content:"\f165"}.fa.fa-heart-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-heart-o:before{content:"\f004"}.fa.fa-sign-out:before{content:"\f2f5"}.fa.fa-linkedin-square{font-family:"Font Awesome 5 Brands";font-weight:400}.fa.fa-linkedin-square:before{content:"\f08c"}.fa.fa-thumb-tack:before{content:"\f08d"}.fa.fa-external-link:before{content:"\f35d"}.fa.fa-sign-in:before{content:"\f2f6"}.fa.fa-github-square{font-family:"Font Awesome 5 Brands";font-weight:400}.fa.fa-lemon-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-lemon-o:before{content:"\f094"}.fa.fa-square-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-square-o:before{content:"\f0c8"}.fa.fa-bookmark-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-bookmark-o:before{content:"\f02e"}.fa.fa-facebook,.fa.fa-twitter{font-family:"Font Awesome 5 Brands";font-weight:400}.fa.fa-facebook:before{content:"\f39e"}.fa.fa-facebook-f{font-family:"Font Awesome 5 Brands";font-weight:400}.fa.fa-facebook-f:before{content:"\f39e"}.fa.fa-github{font-family:"Font Awesome 5 Brands";font-weight:400}.fa.fa-credit-card{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-feed:before{content:"\f09e"}.fa.fa-hdd-o{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-hdd-o:before{content:"\f0a0"}.fa.fa-hand-o-right{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-hand-o-right:before{content:"\f0a4"}.fa.fa-hand-o-left{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-hand-o-left:before{content:"\f0a5"}.fa.fa-hand-o-up{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-hand-o-up:before{content:"\f0a6"}.fa.fa-hand-o-down{font-family:"Font Awesome 5 Free";font-weight:400}.fa.fa-hand-o-down:before{content:"\f0a7"}.fa.fa-arrows-alt:before{content:"\f31e"}.fa.fa-group:before{content:"\f0c0"}.fa.fa-chain:before{content:"\f0c1"}.fa.fa-scissorsLine truncated
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more