Compare commits

..
Author SHA1 Message Date
Gina Häußge d99af420ac 🐛 loginui: fix reload not triggering right after first run setup 2020-02-26 12:01:24 +01:00
Gina Häußge 73c2baa39e 🔖 Preparing release of 1.4.0rc6 2020-02-26 10:08:34 +01:00
Gina Häußge 054df68741 📝 Fix year 2020-02-26 09:13:44 +01:00
Gina Häußge f7756698e9 🐛 Don't protect blueprints before first run setup 2020-02-25 17:03:51 +01:00
Gina Häußge 453ef0cb97 ♻ Remove implicit blueprint protection in favour of explicit one 2020-02-25 17:03:29 +01:00
Gina Häußge 5015422086 🐛 py3 list vs iterator 2020-02-25 15:48:01 +01:00
Gina Häußge 2d85d8acf8 ♻ is_(anonymous|active)() => is_(anonymous|active) 2020-02-25 15:41:38 +01:00
Gina Häußge 2af589a823 ♻ Remove remnants of old login ui 2020-02-25 15:37:51 +01:00
Gina Häußge 20c55f4d3d 🐛 Fix missing protection for blueprint plugins
is_blueprint_protected should mean a requirement of a logged in non
anonymous user. Implemented accordingly. Got forgotten during switch to
granular permission system.
2020-02-25 15:37:50 +01:00
Gina Häußge b7fdc82d30 🐛 Fix buggy implementation of (before|after)_request hooks 2020-02-25 15:37:48 +01:00
Gina Häußge 770ebf2cf9 📝 Docs for new access control situation 2020-02-25 15:34:17 +01:00
Gina Häußge a75c641c18 ♻ Implement login dialog through UiPlugin
Otherwise alternative UIs might still be wide open, and caching and such
was also really painful to solve before.

The LoginUI Plugin is pretty much just a distilled ForceLogin plugin.

Also declared it as hidden so it won't show up/be manageable by the
plugin manager.
2020-02-25 15:33:42 +01:00
Gina Häußge 38c09153ac ♻ Fix deprecated method names 2020-02-24 14:16:09 +01:00
Gina Häußge e30e18e431 📝 Docs for reauthRequired push message 2020-02-24 12:49:12 +01:00
Gina Häußge 249d19f55b 🐛 Reauth for stale sessions instead of active logout
Fixes #3459
2020-02-24 12:49:04 +01:00
Gina Häußge 2e043ecf5b 📝 Explicitly document LineProcessorStream behaviour under py3
Make absolutely clear that processLine will be called with a byte & not
a unicode string.

See #3454
2020-02-18 15:57:01 +01:00
Gina Häußge 831edf234d 🐛 Fix a firmware info reporting bug
It was not reported if firmware detection was disabled, even though one
should not have anything to do with the other.

Not a regression, but considering that it negatively impacts the printer
safety plugin that relies on firmware info it'll go into 1.4.0
regardless.
2020-02-17 17:34:19 +01:00
Gina Häußge b42c753d3f 🐛 Fix a Py3 bug with the self._printer wrapper in plugins 2020-02-17 17:32:20 +01:00
Gina Häußge 924cd5cb4c 🔖 rc/maintenance is now 1.4.0rc6.dev 2020-02-11 14:37:43 +01:00
Gina Häußge 73f7c4d8a1 🔖 Preparing release of 1.4.0rc5 2020-02-10 17:02:07 +01:00
Gina Häußge 10079b8d9d 🐛 PGMR: Fix UI representation of incompatible plugins
Second part of fixing #3442
2020-02-04 15:53:56 +01:00
Gina Häußge c31566a626 🐛 Fix incompatible plugins to be marked as compatible
First part of fixing #3442
2020-02-04 15:52:53 +01:00
Gina Häußge 0cfc7a2976 Merge remote-tracking branch 'origin/staging/maintenance' into staging/maintenance 2020-02-04 13:17:11 +01:00
Gina Häußge de5a10163e 🐛 Reintroduce message backlog on socket
Was present in forcelogin and made sure that plugins triggering a
message on the socket immediately after connect would get through right
after auth.

Without this a lot of plugins out there run into issues, so this is a
backwards compatibility fix for a regression in 1.4.x.

See also #3400
2020-02-04 13:15:44 +01:00
Gina Häußge 0a22c4e66c ♻ Fix a duplicated line of code 2020-01-31 14:28:27 +01:00
Gina Häußge a88d95af77 🐛 Fix autologin
We need to actually try to identify the user just like we used to do
with the forcelogin plugin. Just checking permissions will only work
if we already have a session.

Closes #3434
2020-01-29 11:37:07 +01:00
Gina Häußge 010221ab5b 🐛 Fix handling of unset remote addresses 2020-01-29 11:35:56 +01:00
Gina Häußge 6471a04a86 staging/maintenance is now 1.4.0rc5.dev
And maintenance is now 1.4.1.dev
2020-01-28 15:16:19 +01:00
Gina Häußge 7b2762c590 🐛 Remove accidentally commited debug statement 2020-01-27 18:06:02 +01:00
Gina Häußge de0b97b99c 🐛 Fix first run setup 2020-01-27 17:32:52 +01:00
Gina Häußge 60d2bd1ac1 🔖 Preparing release of 1.4.0rc4 2020-01-27 15:51:27 +01:00
Gina Häußge 4d716647e5 🐛 Fix socket connect timeout handling
Was triggering even though it should have been cleared due to a
self vs this issue.

Also protect against undefined connection deferred.
2020-01-27 15:03:18 +01:00
Gina Häußge 43ab47a260 ✨ pi support: Permission check for API endpoint 2020-01-27 13:46:09 +01:00
Gina Häußge 88ecfbdb65 🐛 Fix another py2 vs 3 issue
Closes #3431
2020-01-27 11:58:17 +01:00
Gina Häußge 8087967683 🐛 Fix behaviour when page cached & server down
E.g. in Firefox reopen tab while server is down - FF will use a cached
copy and for some reason sockjs won't notice that stuff is down. So now
we have a timeout of 5s for initial connection that takes care of that.
2020-01-24 16:54:52 +01:00
Gina Häußge cb43197105 🐛 Fix endpoint in docs 2020-01-24 13:08:10 +01:00
Gina Häußge b1b9329614 ♻ Move /api/access/user to /api/currentuser
Update documentation accordingly.

See also #3418
2020-01-24 13:05:06 +01:00
Gina Häußge 7317814ce0 📝 Document needed permissions & fix some stuff 2020-01-23 13:21:52 +01:00
Gina Häußge 66ef7b66bb 📝 Documentation for the access API 2020-01-22 18:39:32 +01:00
Gina Häußge be3ff5f043 ✨ API endpoint to retrieve info about current user
As suggested by @fieldOfView.

Implements #3418
2020-01-22 14:58:29 +01:00
Gina Häußge c36fa6da90 🐛 Fix readonly group permissions
Those were accidentally stripped.
2020-01-22 14:55:35 +01:00
Gina Häußge aadcf650c7 🐛 Fix UI caching again
Was broken by 3f3cb556a7 in between server
restarts due to the wrong stuff being fetched by the preemptive cache.
2020-01-21 17:26:45 +01:00
Gina Häußge 95c3fa0b04 🐛 Readd requires line that somehow got missing
Addendum to 3f3cb556a7

Closes #3425
2020-01-21 16:03:48 +01:00
Gina Häußge 1d0829a1db 🐛 Introduce ClientAuthed event
May act as entry point for any kind of push messages a plugin might
wish to send to the client after a connect happened. Since depending
on the current permission configuration this might only be possible
once the client has authenticated on the socket, this is required.

Should close #3400
2020-01-21 15:53:52 +01:00
Gina Häußge 8d31d6687e 🐛 Also trigger login dialog eval on permission change
Not just on logout.

Follow-up to #3425
2020-01-21 15:00:20 +01:00
Gina Häußge 3f3cb556a7 🐛 Fix guest access to settings
Needed its own permission, which in turn needed some changes in how the
whole "guest without read permission" situation is handled. I've
reintroduced a custom login view since the main UI would not be able
to fully load up without settings access. Said login view will override
the default UI view if the account in question does not have
Permissions.STATUS and also Permissions.SETTINGS_READ. It pretty much is
the forcelogin plugin from 1.3.x.

Closes #3425
2020-01-21 14:49:46 +01:00
Gina Häußge 4460c8bee0 🐛 env needs to be native strings
So, bytes under py2 and unicode under py3.

Closes #3428
2020-01-20 13:36:02 +01:00
Gina Häußge 89b597a656 🐛 Fix remember me checkbox
Closes #3426
2020-01-17 16:34:13 +01:00
Gina Häußge e1a25a8913 🐛 Fix caching issue for freshly rendered timelapses
Closes #3396
2020-01-16 12:13:38 +01:00
Gina Häußge 482c2f7115 🐛 Fix timelapse progress under Py3
Closes #3409
2020-01-15 16:53:54 +01:00
Gina Häußge 7fa4ebd1ec Merge pull request #3414 from fieldOfView/fix_allows_multiple_needs
Fix checking against multiple Needs on OctoPrintPermission
2020-01-14 12:44:18 +01:00
Gina Häußge 9c3b552aa8 🔥 Remove unused leftover code 2020-01-14 11:24:22 +01:00
Gina Häußge 3229e65a8d ♻ Remove assumptions about UI from permission model
Implements #3419
2020-01-14 11:22:54 +01:00
fieldOfView 7191d39b51 Fix multiple Needs on OctoPrintPermission
fixes #3398
2020-01-03 08:41:59 -08:00
Gina Häußge 58bc5171ee ✏ Adjusted plugin tutorial for py3 2019-12-13 13:43:29 +01:00
Gina Häußge 74f3bc9ae6 🔖 staging/devel is now 1.4.0rc4.dev 2019-12-12 15:01:53 +01:00
Gina Häußge 464d9c0757 🔖 Preparing release of 1.4.0rc3 2019-12-12 13:00:35 +01:00
Gina Häußge 94ae90ab80 ♻ Cleaned up a pre-py3 leftover comment 2019-12-12 12:43:45 +01:00
Gina Häußge 33b89550a4 🐛 Fix a unicode issue under win32
subprocess env must not contain unicode strings but could now after some
py3 related refactorings.
2019-12-12 12:43:13 +01:00
Gina Häußge 9661469532 🐛 Fix some permission bindings
Closes #3388
2019-12-11 15:01:57 +01:00
Gina Häußge b06c222a7d 🐛 Fix checksum calculation in stk500v2 under py3
See #3382
2019-12-11 10:50:40 +01:00
Gina Häußge 9f85b54681 🐛 Convert decoded header to unicode
See #3382
2019-12-11 10:28:32 +01:00
Gina Häußge 5d1ad5d75d 🐛 Add blinker dependency for flask_principal
Was forgotten in 928d62a517
2019-12-10 16:35:07 +01:00
Gina Häußge dc32f955b7 🐛 Fix forwarding of HTTPExceptions on SimpleApiPlugins
Part of #3375
2019-12-10 16:16:40 +01:00
Gina Häußge 220592c267 🐛 IspError should be a proper Exception
Otherwise our try-catch-blocks won't catch it anymore.
2019-12-10 12:56:23 +01:00
Gina Häußge 0faa6879b4 ☂ Resilience against issue in Printoid
Closes #3381
2019-12-10 12:55:47 +01:00
Gina Häußge 71b5de91bf 🐛 Fix 403 response
Dumping string representations of the permission objects doesn't make
sense, and neither does rewriting the error description in the first
place.
2019-12-09 19:06:53 +01:00
Gina Häußge 928d62a517 ♻ Vendoring flask_principal
It no longer seems to be maintained and there's an issue in the code
we need fixed.
2019-12-09 19:06:52 +01:00
Gina Häußge 78bd3b1a52 🐛 "remember" does not need to be set on session
Be able to deal with that.

Follow up to #3370
2019-12-09 19:06:51 +01:00
Gina Häußge b9bab0577b ♻ Remove monkey patch that's no longer needed 2019-12-09 17:32:31 +01:00
Gina Häußge c41551a643 🐛 Fix wrong handling of session protection signal
We should only clear out the identity when the session has actually
been deemed deleted, not just on staleness due to e.g. a client IP
change.

Closes #3370
2019-12-09 17:31:53 +01:00
Gina Häußge 6c92dd1303 🐛 PNotify needs position:fixed
Closes #3377
2019-12-09 14:19:16 +01:00
Gina Häußge 124f01ca2d 🐛 py3: ensure an int as rolling window size
Closes #3371
2019-12-06 13:40:03 +01:00
Gina Häußge 0dece85fa7 🐛 Fix notifications being visible w/ needed login 2019-12-04 15:24:08 +01:00
Gina Häußge caebf90ee9 🐛 Fix short UI flicker before loading animation 2019-12-04 14:37:16 +01:00
Gina Häußge 0c77014903 ☔ Make sure js/css mime types are always correct
Even if we are running on windows and something is borked in the
registry...

Closes #3367
2019-12-03 18:03:11 +01:00
Gina Häußge 231a796200 ☔ Limit legal plugin permission keys 2019-12-03 17:26:29 +01:00
Gina Häußge fe755405e8 📝 Add docs for octoprint.access.permissions hook
As mentioned in #3365
2019-12-03 17:14:00 +01:00
Gina Häußge 2200f2186c 🐛 Fix permissions of global API key
Closes #3365
2019-12-03 14:55:32 +01:00
Gina Häußge b57b7cb606 🐛 appkeys: fix key gen under Python 2
And refactor key generation to be located in ONE central utility method
to avoid issues like that in the future.

Closes #3366
2019-12-03 12:56:14 +01:00
Gina Häußge f2b2496e58 🔖 staging/devel is now 1.4.0rc3.dev 2019-12-02 16:23:02 +01:00
Gina Häußge e603b98d0d 🔖 Preparing release of 1.4.0rc2 2019-12-02 14:11:43 +01:00
Gina Häußge e235fc299f 🐛 Make sure data is set
Closes #3364
2019-12-02 14:07:41 +01:00
Gina Häußge 4f25ed546e 🐛 Only proceed if children is set AND truthy
Closes #3363
2019-12-02 13:55:04 +01:00
Gina Häußge f72b9db6a9 🐛 Fix wrong escape
Closes #3362
2019-12-02 12:24:48 +01:00
Gina Häußge 80e8e33283 🐛 Don't logout always-logged-in AdminUser
If ACL is disabled it doesn't make sense to log it out and it's causing
issues further down the line due to different handling.

Fixes #3361
2019-12-02 12:24:44 +01:00
Gina Häußge 00d0396417 🐛 Fix autologin
Closes #3357
2019-11-29 12:50:16 +01:00
Gina Häußge 59e39662f1 🐛 timelapse: fix accessed event payload field
Closes #3354
2019-11-28 18:02:34 +01:00
Gina Häußge 038e1b9a57 🐛 appkeys: Fix a deprecation warning 2019-11-26 18:42:36 +01:00
Gina Häußge bbefeeeb02 🐛 appkeys: generate string api keys
Instead of binaries.

Closes #3350
2019-11-26 18:35:32 +01:00
Gina Häußge 2801da5c51 💚 Fix unit tests by fixing mocked functions
Closes #3348
2019-11-26 16:22:08 +01:00
Gina Häußge 471dab9406 🐛 Don't try to write None values into upload body
Closes #3349
2019-11-26 15:34:14 +01:00
Gina Häußge 1deb247ce5 🐛 Let functools.wraps do its job
Closes #3348
2019-11-26 15:14:24 +01:00
Gina Häußge 4469a2d84a 🔖 staging/devel is now 1.4.0rc2.dev, devel 1.5.0.dev 2019-11-26 10:36:18 +01:00
Gina Häußge 2da7aa358d 🔖 Preparing release of 1.4.0rc1 2019-11-25 11:57:30 +01:00
Gina Häußge cbb083d7f6 ♻ Do not invalidate / cache on hard reload if printing
Less radical follow-up to #3344 while the kinks for actually needed
UI refreshs are ironed out on that one.
2019-11-25 10:00:03 +01:00
Gina Häußge d68de2c3c7 Revert "Do not refresh on no-cache in request"
This reverts commit 3b1874e
2019-11-25 09:46:50 +01:00
Gina Häußge 454c5e494a Merge pull request #3344 from justfalter/disable-refresh-on-no-cache
Do not refresh on no-cache in request
2019-11-22 12:18:13 +01:00
Mike Ryan 3b1874ea25 Do not refresh on no-cache in request
Remove code that would lead to a refresh upon receiving a
'Cache-Control: no-cache' or 'Pragma: no-cache' in a request. The
purpose of these headers is to invalidate intermdiate proxy caches, not
that of an application server. A refresh in octoprint would lead to
several seconds of high CPU utilization on lower-power systems (like the
Raspberry Pi), leading to stuttering in print jobs.

It is still possible to explicitly cause a refresh by including
`_refresh` in the query parameters of a request.
2019-11-21 08:48:44 -06:00
Gina Häußge e0233dee13 🐛 SWU: Restart after pip update too 2019-11-21 14:27:52 +01:00
Gina Häußge 84a99e1b53 ⬇ Downgrade readthedocs-sphinx-ext
Current versions require jinja2>=2.9 which we can't upgrade to due to
compatibility issues.
2019-11-20 16:02:34 +01:00
Gina Häußge b7e0e89bb4 ⚡️ Precompile markdown & remove changelog
We already have Github's releases with all the changes, we don't need to
keep everything twice.

Instead of the changelog included in the about dialog there's now a link
to the release list, that should suffice.

Implements #3342
2019-11-20 15:35:44 +01:00
Gina Häußge d8c3063813 ⬆️ Update 3rd party deps 2019-11-20 15:30:36 +01:00
Gina Häußge 1485050234 ☔ Add noscript tag
If the user's browser has JS disabled, we should tell them instead of
displaying a non functional UI.

As suggested in https://community.octoprint.org/t/i-forgot-my-octoprint-password-how-can-i-reset-it/215/8?u=foosel
2019-11-15 16:46:06 +01:00
Gina Häußge 6d7721f8f5 ✨ PMGR: More cleanup options
Additional "clean up all leftovers" feature to clean up anything left
over by plugins already uninstalled.

Also takes care of entries in the disabled plugin list now.

See also #3299
2019-11-15 16:28:27 +01:00
Gina Häußge e3ae71eabd 🐛 PMGR: Apparently mtime can sometimes still be None
Handle that.

See https://community.octoprint.org/t/plugins-pip-error-on-fresh-octopi-0-17-0-install/13466
for an example.
2019-11-15 10:43:34 +01:00
Gina Häußge e88041c59e 🐛 PMGR: Remove access attempts on removed field 2019-11-15 10:43:34 +01:00
Gina Häußge e17db4e1cf 📝 SWU: document new pypi_release check type 2019-11-15 10:43:34 +01:00
Gina Häußge 766a64c8f6 Merge pull request #3337 from CapnBry/allowbackanal
Setting to allow gcode analysis to continue during printing
2019-11-12 17:24:14 +01:00
Bryan Mayland 8485d2c9a7 Fix tests failing due to no Settings 2019-11-12 16:07:57 +00:00
Bryan Mayland 397e691a6a Update setting caption for analyzeGcode.runAt 2019-11-12 15:53:06 +00:00
Bryan Mayland 6481f7cf6b webui setting for gcodeAnalysis.runAt 2019-11-12 15:47:54 +00:00
Bryan Mayland 46c527d24a Switch setting to fully control background gcode analysis queueing 2019-11-12 15:28:41 +00:00
Gina Häußge 5392f39cc4 Merge branch 'pr/3335' into devel 2019-11-12 15:28:47 +01:00
Bryan Mayland 4a324b4f5e Setting to allow gcode analysis to continue during printing 2019-11-12 13:49:54 +00:00
Kelly Anderson 2855b0e7a7 Add cbxbiker61 to AUTHORS.md 2019-11-09 00:59:38 -07:00
Kelly Anderson 39e4cd3136 fix another dictionary changed size during iteration exception, possibly triggered only under python3 2019-11-09 00:54:41 -07:00
Gina Häußge 8fefa63c8c 🐛 Fix whitespace issue 2019-11-08 15:15:20 +01:00
Gina Häußge 10532b9118 🐛 SWU: Fix doctest 2019-11-08 14:55:31 +01:00
Gina Häußge 7f2eb470e4 Merge branch 'maintenance' into devel 2019-11-08 14:52:20 +01:00
Gina Häußge 8955b8e0b6 🐛 Fix a unicode bug 2019-11-08 14:48:45 +01:00
Gina Häußge ee9d5048e2 ✨ SWU: Optional pip auto update
Since we can't guarantee for compatibility with future versions of pip
we'll stick to the updater for that being opt-in.
2019-11-08 14:48:29 +01:00
Gina Häußge 09bb74b6c6 ✨ SWU: New check type pypi_release 2019-11-08 14:45:51 +01:00
Gina Häußge 493dddf66e 🐛 to_bytes/to_unicode should pass through None 2019-11-08 14:45:17 +01:00
Gina Häußge 8173f8d0c4 🐛 gcode viewer: Fix swapped G2/G3
Closes #3334
2019-11-08 09:40:09 +01:00
Gina Häußge 01feec47d7 Merge pull request #3330 from dforsi/fix-typos
Fix typos
2019-11-07 12:40:38 +01:00
Daniele Forsi 2b60dbc7e1 Fix typos
Those typos were found with codespell which is available from
https://github.com/lucasdemarchi/codespell.git
2019-11-07 00:02:05 +01:00
Gina Häußge 32f5f36e5a Merge pull request #3328 from balassy/fix/backup-plugin-typo
Fixed a doc typo in the restore command name of the Backup plugin
2019-11-06 19:55:12 +01:00
György Balássy 96294df710 Fixed a typo in the restore command name of the Backup plugin 2019-11-05 22:25:25 +01:00
Gina Häußge ef54cbb148 ☔ Set close_exec flag on serial handle
Possible fix for #3212
2019-11-05 15:41:51 +01:00
Gina Häußge 9cd597a467 🐛 Fix invalid use of 401 response code
Leftovers from fixing #2297.

Fixes #3327
2019-11-05 13:21:49 +01:00
Gina Häußge 2263ebde72 🐛 Fixed ok tracking
Repositioning of clear_to_send clearing removes synchronization issues.

Big thanks to @KevinOConnor for pointing this out!
2019-11-05 12:38:02 +01:00
Gina Häußge 1fd8d597ab Merge pull request #3326 from DominikPalo/feature/support-android-theme-color
Automatically set the toolbar color on Android
2019-11-05 10:57:28 +01:00
Gina Häußge 2aec0b3a75 Merge pull request #3325 from DominikPalo/feature/polish-mac-os-docs
Polish the documentation for macOS (PyCharm setup, macOS naming)
2019-11-05 09:48:47 +01:00
Dominik Palo 47d10a6d3e Set the toolbar color on Android 2019-11-03 11:24:50 +01:00
Dominik Palo ee216ddc93 Merge remote-tracking branch 'upstream/devel' into devel 2019-11-03 09:33:23 +01:00
Dominik Palo 7756d312e2 Update AUTHORS.md 2019-11-03 09:24:51 +01:00
Dominik Palo 19e03eeeb2 Revert a line break 2019-11-03 09:24:51 +01:00
Dominik Palo e73aeba03b Unify macOS naming across docs 2019-11-03 09:23:04 +01:00
Dominik Palo 87f3c5acce Fix documentation for venv step on macOS 2019-11-03 09:19:24 +01:00
Dominik Palo a38a3e67c9 Merge pull request #1 from foosel/maintenance
Maintenance
2019-11-03 09:11:54 +01:00
Gina Häußge 547ae9e13e ♻ SWU: Do not persist check providers
There really is no reason for that
2019-11-01 13:04:20 +01:00
Gina Häußge b031092f07 ✨ PMGR: plugin data cleanup functions
Plugin data can now be cleaned up

  * on a plugin's uninstall through the plugin manager
  * manually through a new action button in the plugin manager

Implements #3299

Ideas for further improvement:

  * Management interface to show "orphaned" plugin data and delete
    on request.
2019-11-01 13:03:47 +01:00
Gina Häußge 6e6dd2c34e 🐛 port can be None 2019-10-31 17:09:49 +01:00
Gina Häußge 759f4f8ea2 🐛 Default checkbox should always be enabled
See #3302
2019-10-31 12:07:31 +01:00
Gina Häußge bee82bcde9 🐛 Treat port=None as port=AUTO on autoconnect
Potential fix for #3267
2019-10-31 11:09:54 +01:00
Gina Häußge 888fb97e66 💡 Clarify Error event in docs
Closes #3210
2019-10-31 09:57:57 +01:00
Gina Häußge 9c775bd899 🐛 Fix overzealous filtering of history entries
Closes #3309
2019-10-30 18:28:53 +01:00
Gina Häußge 4bf3445eef 💡 Fix a doc bug
Closes #3233
2019-10-30 18:23:57 +01:00
Gina Häußge 47b3f51a3f ♻ Speed up the analyser a bit
Closes #3318

Thanks at @jmfrank63 for the heads-up!
2019-10-30 18:10:52 +01:00
Gina Häußge 2e6b85990d 💚 Fix tests 2019-10-30 17:40:49 +01:00
Gina Häußge 30a4b9e9ab Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css
#	src/octoprint/plugins/virtual_printer/virtual.py
2019-10-30 15:59:30 +01:00
Gina Häußge 81a259e51b ☔ virtual printer: parameter existence checks
Closes #3319
2019-10-30 15:45:36 +01:00
Gina Häußge e85e9661e0 🤷‍♀️ PMGR/SWU: Flag to ignore throttle state
Will allow people to circumvent the
shoot-yourself-in-the-foot-countermeasures by editing config.yaml.

If they do that and stuff then fails due to platform instability it's
their problem.
2019-10-30 15:43:52 +01:00
Gina Häußge 1d60250942 🐛 Only detect sd printing on byte pos change
Should fix #3301, or at least make it way less likely to happen.

The problem seems to have been made worse by `M25` not being blocking
on Klipper and thus the SD printing not being guaranteed to have stopped
yet after its return, meaning the following `M26 S0` will be denied,
causing the file position to not be properly reset and hence the issue
to arise in the first place.
2019-10-30 12:47:40 +01:00
Gina Häußge e11463f6ce ♻ Remove stuff deprecated with 1.4.0
See #1852
2019-10-29 13:12:28 +01:00
Gina Häußge 1146a1bb6f ✨ New events UserLogged(In|Out) & modified ClientOpened
On the push socket only available for admin users.

ClientOpened now also get the remoteAddress stripped from the payload
for guests on the push socket.

Implements #783
2019-10-29 12:39:45 +01:00
Gina Häußge 311fdd5aca 🚸 No connection requirement for timelapse config
No, this doesn't mean that you can start timelapses manually or
anything, only that you do not need to be connected to a printer in
order to change the default timelapse configuration.
2019-10-28 18:13:53 +01:00
Gina Häußge 6ddc55bf80 🚸 Fix timelapse progress bar for missing progress
Closes #2713
2019-10-28 18:10:44 +01:00
Gina Häußge 2c930ef069 🚸 allow wrapping on buttons in selection dialogs
Implements #3292
2019-10-25 15:47:18 +02:00
Gina Häußge 3739bbc652 💄 pmgr/swu: dynamic size for scrollables 2019-10-25 14:26:46 +02:00
Gina Häußge 8d544e63f4 ✨ pmgr: more plugin filters
Implements #3288
2019-10-25 14:18:04 +02:00
Gina Häußge 7e4cf6c5dc ✏️ Fix a help text
Closes #3311
2019-10-25 12:56:31 +02:00
Gina Häußge c8d162c999 ✏️ Clarify use of printer profile fields 2019-10-25 11:46:56 +02:00
Gina Häußge 017515dcc1 🚸 Display errors during loading
Also allow disabling loading screen.

Implements #3298
2019-10-24 17:14:33 +02:00
Gina Häußge d8bd684f96 Merge branch 'maintenance' into devel 2019-10-23 14:04:09 +02:00
Gina Häußge aad5c70eb0 🐛 Fix an escaping bug 2019-10-23 14:01:35 +02:00
Gina Häußge ea2f0a9b17 ♻ Minor refactoring & cleanup 2019-10-23 13:39:03 +02:00
Gina Häußge c4131d5e4b 🐛 Fix anonymous users on tornado endpoints
Closes #2779
2019-10-23 13:38:46 +02:00
Gina Häußge 21127bcf2a Merge branch 'maintenance' into devel 2019-10-23 12:30:06 +02:00
Gina Häußge 04da8afb07 Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2019-10-23 12:00:30 +02:00
Gina Häußge c38f06cce2 Merge branch 'staging/maintenance' into maintenance 2019-10-23 11:48:57 +02:00
Gina Häußge 968f952f69 Merge branch 'rc/maintenance' into staging/maintenance 2019-10-22 12:13:00 +02:00
Gina Häußge 8409fdaa48 Merge branch 'rc/maintenance' 2019-10-21 12:27:16 +02:00
Gina Häußge f29e736427 🔖 Preparing release of 1.3.12 2019-10-21 12:26:04 +02:00
Gina Häußge ac3b6f6df8 🐛 Fix broken sv helper 2019-10-14 17:56:45 +02:00
Gina Häußge a4444ccb68 Merge pull request #3305 from RyuzakiKK/fix/systemd_doc
Fix systemd service documentation path
2019-10-14 16:23:51 +02:00
Ludovico de Nittis 270a0dcb1f Fix systemd service documentation path
The previously suggested `service` folder is not available in a canonical
systemd installation. Instead new services should be placed in
`/etc/systemd/system/`
2019-10-11 22:41:58 +02:00
Gina Häußge a889bec4d8 🐛 Solve sorted issues under Python 3.x
sorted does no longer support sorting None values under Python 3. This
patch introduces a utility function that ensures that None values are
replaced by a configurable default value ("" by default) and utilizes
it in places where sorted gets called with a custom sorting key that
can potentially consist of None values.

Closes #3300
2019-10-10 14:54:07 +02:00
Gina Häußge 7ee9bc32eb ☔ Aggressive escaping 2019-10-09 15:51:38 +02:00
Gina Häußge fd62c1fa3d ☔ Set some more headers, remove CDN URL & remove unused JSESSIONID
* Set X-Content-Type-Options to nosniff
  * Set X-Frame-Options to sameorigin (if not configured otherwise)
  * SockJS iframe fallback no longer embeds sockjs library from a CDN
  * SockJS no longer rewrites the unused JSESSIONID cookie
2019-10-08 16:41:42 +02:00
Gina Häußge a445cfe65e Merge pull request #3297 from mkobler/fix-typo
Fix minor typos
2019-10-08 11:21:17 +02:00
Gina Häußge e20a9925dd Merge pull request #3287 from FHeilmann/patch-2
ActionPrompts: More flexibility for selection_command
2019-10-08 11:20:54 +02:00
Gina Häußge 09a4fb2515 🐛 Fix merge error & add escaping
Closes #3296
2019-10-06 18:52:15 +02:00
Gina Häußge cce7389a42 ✨ SWU: More configuration options
Allow to select github_commit tracking, branch and pip target via UI.

Closes #3295
2019-10-06 18:32:19 +02:00
Gina Häußge b138ea7a47 🐛 SWU: Fix OctoPrint version reporting
See #3295
2019-10-06 16:46:34 +02:00
Gina Häußge 3b708ce079 🔗 Fix a link
As mentioned in #3295
2019-10-06 16:45:13 +02:00
Gina Häußge 4441618be5 🐛 Fix a concurrent modification issue 2019-10-06 16:29:37 +02:00
Mike Kobler 0525c9ab40 Fix minor typos 2019-10-05 18:55:15 -05:00
Gina Häußge 0035e7c3ff 🐛 Fix a merge error 2019-10-02 22:34:39 +02:00
Gina Häußge 073060d253 ✨ PMGR: Search box
Implements #3288
2019-09-26 20:26:47 +02:00
Florian Heilmann 55980a1c2c Update AUTHORS.md 2019-09-25 22:12:51 +02:00
Florian Heilmann 852a2cf157 Fix indentation 2019-09-25 22:11:11 +02:00
Florian Heilmann 2e6ee57162 ActionPrompts: More flexibility for selection_command
Allow users to control how and where the choice is inserted into the response by explicitly including "{choice}" in the selection_command
2019-09-25 22:09:20 +02:00
Gina Häußge 5c54f16ece 🐛 Don't trigger pause on SD cancel
Trying to trigger pausing due to the M25 on an SD cancel could lead
to a dead lock, see #3125
2019-09-25 12:05:03 +02:00
Gina Häußge 04a13268ad 🚸 PMGR: Filter for plugin list
We can now filter all/bundled/3rdparty. Should improve overview.
2019-09-24 11:07:45 +02:00
Gina Häußge 49fdac7528 Merge branch 'maintenance' into devel 2019-09-23 15:26:18 +02:00
Gina Häußge 75f6ef4bae Merge branch 'staging/maintenance' into maintenance
# Conflicts:
#	.versioneer-lookup
2019-09-23 15:25:54 +02:00
Gina Häußge 9fd608691b 🔖 staging is now 1.3.12rc4.dev 2019-09-23 15:24:55 +02:00
Gina Häußge a70a45f062 Merge branch 'staging/maintenance' into rc/maintenance 2019-09-23 12:59:49 +02:00
Gina Häußge 61b0845f19 🔖 Preparing release of 1.3.12rc3 2019-09-23 12:55:39 +02:00
Gina Häußge 30d618267f ☔ Protect against broken language packs 2019-09-20 13:20:46 +02:00
Gina Häußge b9665a8af4 🐛 Don't try to trigger M112 on connection errors
Doesn't make sense, we don't HAVE a connection yet.
2019-09-19 10:19:19 +02:00
Gina Häußge 204d212323 Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2019-09-18 14:28:15 +02:00
Gina Häußge 04528a635b 🐛 PMGR: Disable plugin mgmt while printer is busy
Not just when only actively printing.

Closes #3278
2019-09-18 14:27:10 +02:00
Gina Häußge 15522a98b0 🐛 GCODE viewer: get rid of deep clone
Fixes #3277
2019-09-18 13:45:01 +02:00
Gina Häußge db1c18075f ☔ Some more escaping 2019-09-17 17:38:55 +02:00
Gina Häußge 3b556e9d79 Merge branch 'maintenance' into devel 2019-09-17 17:34:34 +02:00
Gina Häußge 8761273636 Merge branch 'staging/maintenance' into maintenance 2019-09-17 17:22:10 +02:00
Gina Häußge 08efe80304 🔖 staging/maintenance is now 1.3.12rc3.dev 2019-09-17 17:21:45 +02:00
Gina Häußge c4258c5bb0 🔖 Preparing release of 1.3.12rc2, part 2 2019-09-17 16:20:44 +02:00
Gina Häußge 58799888b7 🐛 SWU: Fix wrong version check
Fixes #3273
2019-09-17 16:18:07 +02:00
Gina Häußge fb6d57963b 🔖 Preparing release of 1.3.12rc2 2019-09-17 14:19:32 +02:00
Gina Häußge 03f228c0ef ☔ Extend safemode to language packs
Cherry-picked from cc1d88c

Implements #3271
2019-09-16 14:35:04 +02:00
Gina Häußge 93ae368f58 🐛 Escape single/double quotes in l10n strings
Cherry-picked from 72eef3e

Closes #3270
2019-09-16 14:34:21 +02:00
Gina Häußge 378752e155 🐛 GCODE viewer: Fix out-of-sync & slider issue, part 2
Now with all files...

Fixes #3272
2019-09-16 14:32:08 +02:00
Gina Häußge bec307900d 🐛 GCODE viewer: Fix out-of-sync & slider issue
Fixes #3272
2019-09-16 14:27:30 +02:00
Gina Häußge cc1d88c4c8 ☔ Extend safemode to language packs
Implements #3271
2019-09-13 16:04:32 +02:00
Gina Häußge 72eef3e224 🐛 Escape single/double quotes in l10n strings
Closes #3270
2019-09-13 15:42:59 +02:00
Gina Häußge 84f6833597 🚨 Fix unused variable issue 2019-09-12 21:05:00 +02:00
Gina Häußge 2a94abdc49 Merge remote-tracking branch 'origin/devel' into devel 2019-09-12 20:51:06 +02:00
Gina Häußge fab5f34aaa 🔀 Rebuilt CSS 2019-09-12 20:50:46 +02:00
Gina Häußge 76f79e5380 🔀 Migrate forcelogin changes to built-in login 2019-09-12 19:20:55 +02:00
Gina Häußge 1b25029207 🔀 Migrate user CLI to new access control 2019-09-12 17:44:33 +02:00
Gina Häußge 8df2a5436b Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/filemanager/__init__.py
#	src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js
#	src/octoprint/plugins/forcelogin/__init__.py
#	src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
#	src/octoprint/plugins/pluginmanager/__init__.py
#	src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css
#	src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js
#	src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
#	src/octoprint/plugins/tracking/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/views.py
#	src/octoprint/static/js/app/viewmodels/printerstate.js
#	src/octoprint/static/js/app/viewmodels/users.js
#	src/octoprint/timelapse.py
#	src/octoprint/users.py
#	src/octoprint/util/comm.py
2019-09-12 09:30:28 +02:00
Gina Häußge 72f005b7fe 🔖 maintenance is now 1.3.13.dev 2019-09-10 16:55:06 +02:00
Gina Häußge 0eac10d5a6 🔖 staging/maintenance is now 1.3.12rc2.dev 2019-09-10 16:54:20 +02:00
Gina Häußge 2a42f02aec ⬆️ Require newer environment for future upgrades
This is the last version that supports stock OctoPi 0.14, catering
towards the ancient setuptools and pip versions found on it becomes
more and more unjustifiable overhead.
2019-09-10 13:45:18 +02:00
Gina Häußge 7c48cfd0f7 🔖 Preparing 1.3.12rc1 2019-09-09 18:00:13 +02:00
Gina Häußge bba796d551 ☔ errortracking: filter specific callbacks
We don't want to get swamped by third party plugin error messages on
sentry as that costs money.

Blacklist astroprint messages since they caused issues in the past.
2019-09-09 13:51:54 +02:00
Gina Häußge a855f3e62c ☔ Add fqcn of callbacks to exception loggers
Will allow us to filter for them.
2019-09-09 13:45:22 +02:00
Gina Häußge 5079e7e891 🐛 Clear user management dialogs on close 2019-09-09 12:54:03 +02:00
Gina Häußge ddc948fa94 🔖 errortracking: new DSNs for 1.3.12rc1 2019-09-06 17:09:11 +02:00
Gina Häußge f88f2b25ea 🐛 tracking: Only track plugins in pong event 2019-09-06 16:55:27 +02:00
Gina Häußge ea59dab7ab ✨ Optional print start confirmation
Implements #3250
2019-09-05 14:51:51 +02:00
Gina Häußge f0914c2214 🐛 appkeys: empty user_id = unset user_id
Also some more debug logging

Closes #3257
2019-09-05 14:40:40 +02:00
Gina Häußge b3e76c3ecc 🐛 plugin.version can be None, episode 2 2019-09-05 14:25:17 +02:00
Gina Häußge a4d5acb0b8 Merge pull request #3263 from gdombiak/printer_profiles_add_del_events
All printer profile events are now triggered
2019-09-05 09:34:12 +02:00
Gaston Dombiak 79b66f17b6 Events PRINTER_PROFILE_ADDED and PRINTER_PROFILE_DELETED are now triggered 2019-09-04 22:57:17 -07:00
Gina Häußge bcb6c7a1d4 Create SECURITY.md 2019-09-04 18:03:02 +02:00
Gina Häußge 36198c684f 🐛 Fix scoping issue
Closes #3247
2019-09-04 16:22:31 +02:00
Gina Häußge a3a60c5967 ☔ appkeys: better handling of empty request body 2019-09-04 10:59:03 +02:00
Gina Häußge 6df3cb5c12 🐛 plugin.version may be None 2019-09-04 10:33:42 +02:00
Gina Häußge 0611329a6d Merge pull request #3256 from byarmis/fix/byarmis/3253
Resolve error detecting Python version
2019-09-04 10:01:43 +02:00
Gina Häußge 2f90fca5ce Merge pull request #3249 from gdombiak/printer_profile_events
Printer profile events
2019-09-04 09:51:01 +02:00
Ben Yarmis e4e97190da Resolving issue #3253
Added myself to the AUTHORS.md file
2019-08-25 01:48:11 -05:00
Gaston Dombiak 9c748a85b4 removed ' to march master 2019-08-12 20:40:17 -07:00
Gaston Dombiak 78c2199d89 Fire PRINTER_PROFILE_MODIFIED when printer profile was modified 2019-08-12 20:32:42 -07:00
Gina Häußge 0e67906d1e ♻ tracking: Send plugin list only once per day 2019-07-29 17:38:18 +02:00
Gina Häußge 4c602cba2e ☔ Further hardening against corrupt recovery data 2019-07-29 16:55:32 +02:00
Gina Häußge 89255e2ec9 ☔ Harden against corrupt recovery data
Closes #3199
2019-07-29 16:52:05 +02:00
Gina Häußge 372b3662e9 📝 Add docs for printTimeLeftOrigin field
Closes #3203
2019-07-29 16:37:52 +02:00
Gina Häußge e007dbaf4c 🐛 Fix file selection not being cleared on disconnect
Closes #3224
2019-07-29 13:27:08 +02:00
Gina Häußge dbe07af426 Merge pull request #3202 from cbxbiker61/devel
fix RuntimeError: dictionary changed size during iteration
2019-07-25 10:17:45 +02:00
Gina Häußge f67f9b9399 🐛 Fix --admin flag on add command 2019-07-22 15:06:09 +02:00
Gina Häußge c6c5328418 ✨ Add list/activate/deactivate commands 2019-07-22 15:05:51 +02:00
Gina Häußge accbfc2b45 🐛 Fix settings passing 2019-07-22 15:04:27 +02:00
Gina Häußge 9976f2b7a3 🐛 Fix a broken import 2019-07-22 14:00:54 +02:00
Gina Häußge f249563b2c 🐛 At least use configured user manager class
Making the plugin hook work would be a ton of overhead due to the
components dictionary that needs to be supplied to it for user manager
initialization, however at the very least we should support
configuration of the used user manager class.

Both features are rarely used if at all, but we should be aware of this.

Also changed some wording, fixed to unicode and removed redundancy from
the sub commands (e.g. just "add" instead of "add_user") and flags.
2019-07-22 14:00:43 +02:00
Aliaksei Pilko 09e023917c Amend settings ref 2019-07-19 18:08:31 +01:00
Aliaksei Pilko 799b86b287 Update copyright 2019-07-18 15:41:32 +01:00
Aliaksei Pilko ea1bcf8e5d Add user accounts cli
Add forgot password link at login

Update AUTHORS.md
2019-07-17 19:54:21 +01:00
Piotr Usewicz ee93e25ffd Rename currentLine to current_line 2019-07-16 11:02:52 +02:00
Gina Häußge d25f664be3 🐛 printer safety: Anycubic 1.1.2 is already safe
Fix off by one error.

See also https://community.octoprint.org/t/octoprint-tells-me-that-my-printers-firmware-lacks-mandatory-safety-features-what-does-this-mean/350/61
2019-07-16 10:47:42 +02:00
Gina Häußge 3bffe4f7cb Merge pull request #3225 from eyal0/patch-4
Quote arguments in pip install
2019-07-11 11:20:20 +02:00
Eyal f140dd9d44 Quote arguments in pip install
If the argument is not quoted, the shell will interpret the braces.
2019-07-08 21:20:08 -04:00
Gina Häußge d44747b39a 🐛 Fix long_running_command flag for M191
Closes #3220
2019-07-08 11:26:02 +02:00
Gina Häußge f2da9d8d7d Merge pull request #3217 from gdombiak/docs_typo
Fixed typo in chambers documentation
2019-07-05 11:16:24 +02:00
Gaston Dombiak 5483ef7cd4 Fixed typo in chambers documentation 2019-07-04 23:19:35 -07:00
Gina Häußge 85d212ba97 ☔ More resilience against garbage on the line on initial connect
We'll now send the hello command twice, and a third time if we run into
a timeout during initial connect.

Closes #3206
2019-07-02 16:35:57 +02:00
Gina Häußge 44af09580a 🚸 Make clear when GCODE scripts are executed
Closes #3198
2019-07-02 13:56:19 +02:00
Gina Häußge 530fca95e4 ☔ Include wizard flag in etag
Additional protection against #3211 and #3166
2019-07-02 13:48:28 +02:00
Gina Häußge 59ae7e39f2 ☔ Only set relevant cache control headers
We don't want to accidentally overwrite anything again.
2019-07-02 13:43:57 +02:00
Gina Häußge 72167d14d2 🐛 Fix caching headers on / in case of wizards
Revalidation header from ceade46dd7 was
overwriting custom header in case of active wizards, causing the browser
to cache HTML code with enabled wizards.

This fixes this by checking if the headers in question actually need to
be set and aren't already there.
2019-07-02 12:44:29 +02:00
Gina Häußge 2c6568acd1 ✨ Mimetype guessing for the webcam test
Related to #3207
2019-07-01 17:17:34 +02:00
Gina Häußge e27c216a05 Merge branch 'master' into maintenance 2019-06-27 10:19:12 +02:00
Gina Häußge 7b4c148dd7 ✨ tracking: track slicing events
Gives us some numbers the next time someone complains about
slicer support.
2019-06-26 19:27:57 +02:00
Gina Häußge a924520dd6 ✨ tracking: track plugins & versions on startup
Requested feature by plugin developers, will also allow us to compile
stuff like top10 lists.
2019-06-26 18:32:33 +02:00
Kelly Anderson 1c3e463ac6 fix RuntimeError: dictionary changed size during iteration 2019-06-22 18:11:36 -06:00
Gina Häußge e88eb6dd85 ☔ PMGR: Prevent installs while throttled 2019-06-19 15:48:18 +02:00
Gina Häußge 59dfa994bd ☔ SWU: Prevent updates while throttled 2019-06-19 15:41:11 +02:00
Gina Häußge 6959ce4d38 💚 Try to fix doc build by pinning a dep, 2nd try 2019-06-19 11:52:06 +02:00
Gina Häußge 08bc0082cf 💚 Try to fix doc build by pinning a dep 2019-06-19 11:46:53 +02:00
Gina Häußge 6069d74a54 💚 Fix unit tests 2019-06-18 13:35:21 +02:00
Gina Häußge 68ee7030f1 ☔ Send M112 on disconnect due to error (configurable)
Try to disable heaters and such. Might fail, but worth a try at least.
Only do that if we are not SD printing though.
2019-06-17 18:35:44 +02:00
Gina Häußge 81342acccc ☔ Detect endless resend requests & abort
If the printer keeps requesting the same line over and over again,
something is either seriously wrong with the line or with the connection

In any case, log an error and disconnect.
2019-06-17 18:35:44 +02:00
Gina Häußge e029f33901 Merge pull request #3195 from dmweis/patch-2
Fix typo
2019-06-11 10:41:33 +02:00
David Weis 7bd8cff137 Fix typo 2019-06-08 14:14:58 +01:00
Gina Häußge 055dcfa0e1 Merge pull request #3192 from dovecode/translatable-string-fixes
Various translatable text fixes and fixed plugin install message during restore
2019-06-05 13:32:10 +02:00
Nicolai Nielsen 8acf417383 Removed extra curly brace in plugin install message during restore
Fixed plugin install message for UI (never worked!)
Fixed grammar in connectivity initial setup
Added space at end of lines for several multiline messages
2019-06-04 11:47:41 -05:00
Gina Häußge b50e1aee8a 🚨 More consistent whitespace 2019-06-04 15:20:27 +02:00
Gina Häußge c714bce17e Merge pull request #3191 from Flamenco/my_maintenance
Add documentation when target temperature is set to 0
2019-06-04 15:19:23 +02:00
Steven Spungin a9a8e48489 Add new author 2019-06-04 09:00:35 -04:00
Steven Spungin 9dec840818 Add documentation when target temperature is set to 0 2019-06-04 08:57:10 -04:00
Gina Häußge 9af125ca6d 🚨 Consistent whitespace 2019-06-03 13:25:02 +02:00
Gina Häußge 1f4fabe6ef 🐛 PMGR: Refresh data from server if needed on endpoint GET
Closes #3190
2019-06-03 12:17:03 +02:00
Gina Häußge 121f36704d Merge pull request #3184 from dovecode/action_prompt_warning_missing_space
Add space in disable warning message
2019-05-29 18:13:51 +02:00
Nicolai Nielsen 85ff545c07 Add space in disable warning message 2019-05-29 10:10:52 -05:00
Gina Häußge 3662c84de5 Merge branch 'pr/3183' into maintenance 2019-05-28 16:35:00 +02:00
Gina Häußge 79558fdfbf Merge pull request #3179 from dovecode/uninstall_plugin_confirmation
Added confirmation dialog before uninstalling plugin
2019-05-28 16:21:44 +02:00
Nicolai Nielsen 11040f272a Added confirmation dialog before uninstalling plugin
Added confirmation dialog before disabling plugin
Added configuration options to control the confirmation dialogs
Defaults are not to confirm for disabling but confirm for uninstalling
2019-05-27 19:03:29 -05:00
Janne Mäntyharju fa2716c65c Calculate filament usage for all extruders is M605 duplicate/mirror command is used (Issue #3075) 2019-05-27 22:02:34 +03:00
Gina Häußge 768b06e35a ✨ Allow disabling of closing dialogs by click outside
New setting: Settings > Appearance > Close dialogs by clicking outside

Implements #3162
2019-05-27 16:58:45 +02:00
Gina Häußge 0820c23aea Merge pull request #3180 from AndyQ/clear_term_patch
Added button to terminal window to all log window to be cleared out
2019-05-27 16:26:34 +02:00
Gina Häußge 361fbaa366 🐛 pmgr: Smaller height for plugin list
Should work around #3161
2019-05-27 16:22:50 +02:00
Gina Häußge a91359f2af 🚸 Change icon & wording 2019-05-27 16:21:03 +02:00
AndyQ 4bfabf82ae Fixed typo and changed link to clearAllLogs
Both logs (fancy and plain) cleared out at same time
2019-05-27 15:01:14 +01:00
Gina Häußge c90f556fe9 📝 github meta: Clarify devel vs maintenance base 2019-05-27 11:14:31 +02:00
AndyQ 352b190a72 Added button to terminal window to all log window to be cleared out 2019-05-26 12:49:03 +01:00
Gina Häußge e9b0bd9e65 Create FUNDING.yml 2019-05-23 13:08:50 +02:00
Gina Häußge c8ea808d93 🚸 Include seconds in upload date
See #3174
2019-05-21 15:18:24 +02:00
Gina Häußge d40c3e6241 🚸 Add upload date to selected file information
Should make it more clear when an update due to a new upload happens.

Closes #3174
2019-05-21 15:05:28 +02:00
Gina Häußge e94f789b72 🐛 Always report all tools in sharedNozzle setups
Fixes #3177

See also https://community.octoprint.org/t/9620/4
2019-05-21 14:29:15 +02:00
Gina Häußge 9ff44c49a6 🐛 Fix broken tool filtering 2019-05-21 14:20:41 +02:00
Gina Häußge c7b933ba00 🐛 forcelogin: Do not touch static endpoints
Closes #3176
2019-05-21 12:07:39 +02:00
Gina Häußge 6765b25803 🚸 action prompt: show icon for dismissed prompts in navbar 2019-05-21 10:37:47 +02:00
Gina Häußge 59b60f5dad 🐛 action prompt: close & delete prompt on disconnect
As mentioned in #3171
2019-05-20 19:55:10 +02:00
Gina Häußge 2822992843 🚸 action prompt: allow to cancel dialogs
Closes #3171
2019-05-20 19:49:06 +02:00
Gina Häußge 1b82aa859f 🐛 Fix accidental test code commit 2019-05-20 16:48:00 +02:00
Gina Häußge 12be637f85 ✨ Add setting for parity double open workaround
Can now be set to be applied if possibly needed (OS is a Debian Linux),
always or never.

Closes #3169, enhances #3167
2019-05-20 16:46:45 +02:00
Kyle Evans 3bd9d11fc3 comm: Don't open twice on FreeBSD
Originally introduced by PR #673 to fix reconnect issues on pyserial,
OctoPrint will first open the serial port with PARITY_ODD then close it
again and reopen with the desired PARITY_NONE. This works around issues
likely sitting somewhere in the linux tty layer, at least on some
distributions, that don't necessarily exist on other platforms.

Stop doing the workaround on FreeBSD to start with, as this is the only
platform I can effectively test. I suspect MacOS/Windows likely also don't
need to do this.
2019-05-17 22:43:13 -05:00
Gina Häußge e864d6b03e 🚸 Ensure line breaks on copy of terminal contents 2019-05-15 17:35:57 +02:00
Gina Häußge 547db7c1f5 ☔ pmgr: better handling of unexpected repository format
Closes #3157 and Sentry SERVER-116
2019-05-15 17:34:54 +02:00
Gina Häußge d6516e4a4c 🐛 tracking: handle time==None case
Closes #3156 and Sentry SERVER-WR
2019-05-15 15:19:57 +02:00
Gina Häußge 2387b4a771 🐛 backup: make sure exclude is always a list
Closes #3155 and Sentry SERVER-119
2019-05-15 15:15:25 +02:00
Gina Häußge b03d43156d 🐛 Strip interface tags from addresses on local check
Closes #3143 and Sentry SERVER-11B
2019-05-15 13:19:14 +02:00
Gina Häußge 07423712a6 🐛 Fix wrong variable name in exception handler
Closes #3153 & Sentry SERVER-11A
2019-05-15 11:48:45 +02:00
Gina Häußge 81735d07c9 Merge branch 'rc/maintenance' 2019-05-13 14:54:51 +02:00
Gina Häußge 03e328fd13 📝 Fix a documentation issue
Fixes #3117
2019-04-10 17:13:29 +02:00
Gina Häußge 7efcf00baf Merge pull request #3106 from hlovdal/explicit_python_version
README: Use explicit python version for virtualenv
2019-04-05 09:47:52 +02:00
Håkon Løvdal a3254466f7 Whitespace fixes 2019-04-05 01:10:30 +02:00
Håkon Løvdal f8dc504773 Add example of using explicit python version 2019-04-05 01:10:30 +02:00
285 changed files with 12372 additions and 15410 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
# These are supported funding model platforms
github: [foosel]
patreon: foosel
custom: https://octoprint.org/support-octoprint/
+3 -2
View File
@@ -16,8 +16,9 @@ checklist:
made sure your changes don't interfere with current development by
talking it through with the maintainers, e.g. through a
Brainstorming ticket
* [ ] Your PR targets OctoPrint's devel branch, or maintenance if it's
a bug fix for an issue present in the current stable version (no PRs
* [ ] Your PR targets OctoPrint's devel branch if it's a completely
new feature, or maintenance if it's a bug fix or improvement of
existing functionality for the current stable version (no PRs
against master or anything else please)
* [ ] Your PR was opened from a custom branch on your repository
(no PRs from your version of master, maintenance or devel please),
+12 -9
View File
@@ -18,16 +18,19 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.12
# maintenance is currently the branch for preparation of maintenance release 1.4.1
# so are any fix/... and improve/... branches
maintenance 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
fix/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
improve/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
maintenance 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
fix/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
improve/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.11rc4
# staging/maintenance is currently the branch for preparation of 1.4.0rc6
# so is regressionfix/...
staging/maintenance 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
regressionfix/.* 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
staging/maintenance 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
regressionfix/.* 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
# staging/devel is currently inactive (but has the 1.4.0rc6 namespace)
staging/devel 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.5.0-dev for now
.* 1.5.0 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
+10
View File
@@ -105,6 +105,16 @@ date of first contribution):
* [Jack Wilsdon](https://github.com/jackwilsdon)
* [Ryan Finnie](https://github.com/rfinnie)
* [Timur Duehr](https://github.com/tduehr)
* [Nicolai Nielsen](https://github.com/dovecode)
* [Janne Mäntyharju](https://github.com/JanneMantyharju)
* [Steven Spungin](https://github.com/flamenco)
* [Piotr Usewicz](https://github.com/pusewicz)
* [Aliaksei Pilko](https://github.com/aliaksei135)
* [Ben Yarmis](https://github.com/byarmis)
* [Florian Heilmann](https://github.com/FHeilmann)
* [Ludovico de Nittis](https://github.com/RyuzakiKK)
* [Dominik Paľo](https://github.com/DominikPalo)
* [Kelly Anderson](https://github.com/cbxbiker61)
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
+3 -1172
View File
File diff suppressed because it is too large. Load diff
+5 -4
View File
@@ -31,7 +31,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!**
You are currently looking at the source code repository of OctoPrint. If you already installed it
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
might be of more interest for you. You might also want to subscribe to join
might be of more interest for you. You might also want to subscribe to join
[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be
able to help you with any questions you might have.
@@ -39,7 +39,7 @@ able to help you with any questions you might have.
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
[the community forum at community.octoprint.org](https://community.octoprint.org)
and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
@@ -65,14 +65,15 @@ you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your syste
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
2. Change into the OctoPrint folder: `cd OctoPrint`
3. Create a user-owned virtual environment therein: `virtualenv venv`
3. Create a user-owned virtual environment therein: `virtualenv venv` if your system default python version is
python 2.7, otherwise you need to specify the version explicitly, e.g. `virtualenv --python=python2.7 venv`.
4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .`
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
for details.
After installation, please make sure you follow the first-run wizard and set up
access control as necessary.
access control as necessary.
## Dependencies
+11
View File
@@ -0,0 +1,11 @@
# Security Policy
## Supported Versions
Always update to the latest version of OctoPrint to keep up with security patches.
## Reporting a Vulnerability
Email to security@octoprint.org.
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
+20 -12
View File
@@ -6,52 +6,60 @@ thanks to everyone who contributed!
## Patreon Patrons
* Andre Bubel
* Andrew Moorby
* Arnljot Arntsen
* Bjorn Breckenridge
* BigTreeTech
* Boris Hussein
* Brad Jackson
* Christian Petropolis
* Christian Wolf
* COLLE+McVOY
* D Brian Kimmel
* DeltaMaker 3D Printers
* Dennis Breining
* Dorian Gray
* E3D BigBox
* Eric Betts
* Ernesto Martinez
* Franziska Kunsmann
* GadgetAngel
* George Robles
* Greg Holloway
* Hog Duske
* Hugh Blemings
* jean-claude migneault
* Jeff Renfer
* Jefferson Hunt
* Jeremiah Avery
* Joseph Payne
* Joshua Wills
* Justin Kaufman
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Kenneth Jiang
* Kurt Wubbels
* Kyle Menigoz
* LA 3D Printer Repair
* LulzBot®
* Lee Dohm
* Makespace Madrid
* Mark Walker
* Martin Majewski
* Michael Aumock
* Miles Flavel
* Mosaic Manufacturing
* OMER MEHMET SUTAS
* Neil R. Goldberg
* Patrick Glyré
* Patrick McGinnis
* Prof Yuh Wen Chen
* Randy C. Will
* Ranjib Dey
* Richard Michaud
* Rigid3D
* Robert Gusek
* Samer Najia
* Shawn Lewis
* Ronald Griehsler
* Sacha Telgenhof
* sghnsk
* Simon Hallam
* Stefan Krister
* Sven Mueller
* TEVO 3D Printers
* Trent Shumay
* Ulrich Kempken
and 1544 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1764 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
+529
View File
@@ -0,0 +1,529 @@
.. _sec-api-access:
**************
Access control
**************
.. contents::
.. _sec-api-access-permissions:
Permissions
===========
.. _sec-api-access-permissions-list:
List all permissions
--------------------
.. http:get:: /api/access/permissions
Retrieves all permissions available in the system.
Will return a :http:statuscode:`200` with a :ref:`permission list <sec-api-access-datamodel-permissions-list>`
as body.
:status 200: No error
.. _sec-api-access-groups:
Groups
======
.. _sec-api-access-groups-list:
Get group list
--------------
.. http:get:: /api/access/groups
Retrieves all groups registered in the system.
Will return a :http:statuscode:`200` with a :ref:`group list <sec-api-access-datamodel-groups-list>`
as body.
Requires the ``SETTINGS`` permission.
:status 200: No error
.. _sec-api-access-groups-add:
Add a new group
---------------
.. http:post:: /api/access/groups
Adds a new group to the system.
Expects a :ref:`group registration request <sec-api-access-datamodel-groups-addgrouprequest>` as request body.
Will return a :ref:`group list response <sec-api-access-datamodel-groups-list>` on success.
Requires the ``SETTINGS`` permission.
:json key: The group's identifier
:json name: The user's name
:json description: A human readable description of the group
:json permissions: The permissions to assign to the group
:json subgroups: Subgroups assigned to the group
:json default: Whether the group should be assigned to new users by default or not
:status 200: No error
:status 400: If any of the mandatory fields is missing or the request is otherwise
invalid
:status 409: A group with the provided key does already exist
.. _sec-api-access-groups-retrieve:
Retrieve a group
----------------
.. http:get:: /api/access/groups/(string:key)
Retrieves an individual group record.
Will return a :http:statuscode:`200` with a :ref:`group record <sec-api-access-datamodel-groups-grouprecord>`
as body.
Requires the ``SETTINGS`` permission.
:status 200: No error
.. _sec-api-access-groups-modify:
Update a group
--------------
.. http:put:: /api/access/groups/(string:key)
Updates an existing group.
Expects a :ref:`group update request <sec-api-access-datamodel-groups-updategrouprequest>` as request body.
Will return a :ref:`group list response <sec-api-access-datamodel-groups-list>` on success.
Requires the ``SETTINGS`` permission.
:json description: A human readable description of the group
:json permissions: The permissions to assign to the group
:json subgroups: Subgroups assigned to the group
:json default: Whether the group should be assigned to new users by default or not
:status 200: No error
:status 400: If any of the mandatory fields is missing or the request is otherwise
invalid
.. _sec-api-access-groups-delete:
Delete a group
--------------
.. http:delete:: /api/access/groups/(string:key)
Deletes a group.
Will return a :ref:`group list response <sec-api-access-datamodel-groups-list>` on success.
Requires the ``SETTINGS`` permission.
:status 200: No error
.. _sec-api-access-users:
Users
=====
.. _sec-api-access-users-list:
Retrieve a list of users
========================
.. http:get:: /api/access/users
Retrieves a list of all registered users in OctoPrint.
Will return a :http:statuscode:`200` with a :ref:`user list response <sec-api-access-datamodel-users-userlistresponse>`
as body.
Requires the ``SETTINGS`` permission.
:status 200: No error
.. _sec-api-access-users-retrieve:
Retrieve a user
---------------
.. http:get:: /api/access/users/(string:username)
Retrieves information about a user.
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-access-datamodel-users-userrecord>`
as body.
Requires either the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user which to retrieve
:status 200: No error
:status 404: Unknown user
.. _sec-api-access-users-add:
Add a new user
--------------
.. http:post:: /api/access/users
Adds a user to OctoPrint.
Expects a :ref:`user registration request <sec-api-access-datamodel-users-adduserrequest>`
as request body.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-access-users-list>`.
Requires the ``SETTINGS`` permission.
:json name: The user's name
:json password: The user's password
:json active: Whether to activate the account (true) or not (false)
:json admin: Whether to give the account admin rights (true) or not (false)
:status 200: No error
:status 400: If any of the mandatory fields is missing or the request is otherwise
invalid
:status 409: A user with the provided name does already exist
.. _sec-api-access-users-modify:
Update a user
-------------
.. http:put:: /api/access/users/(string:username)
Updates a user record.
Expects a :ref:`user update request <sec-api-access-datamodel-users-updateuserrequest>`
as request body.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-access-users-list>`.
Requires the ``SETTINGS`` permission.
:param username: Name of the user to update
:json admin: Whether to mark the user as admin (true) or not (false), can be left out (no change)
:json active: Whether to mark the account as activated (true) or deactivated (false), can be left out (no change)
:status 200: No error
:status 404: Unknown user
.. _sec-api-access-users-delete:
Delete a user
-------------
.. http:delete:: /api/access/users/(string:username)
Delete a user record.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-access-users-list>`.
Requires the ``SETTINGS`` permission.
:param username: Name of the user to delete
:status 200: No error
:status 404: Unknown user
.. _sec-api-access-users-password:
Change a user's password
------------------------
.. http:put:: /api/access/users/(string:username)/password
Changes the password of a user.
Expects a JSON object with a single property ``password`` as request body.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to change the password for
:json password: The new password to set
:status 200: No error
:status 400: If the request doesn't contain a ``password`` property or the request
is otherwise invalid
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-users-settings-get:
Get a user's settings
---------------------
.. http:get:: /api/access/users/(string:username)/settings
Retrieves a user's settings.
Will return a :http:statuscode:`200` with a JSON object representing the user's
personal settings (if any) as body.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 200: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-users-settings-set:
Update a user's settings
------------------------
.. http:patch:: /api/access/users/(string:username)/settings
Updates a user's settings.
Expects a new settings JSON object to merge with the current settings as
request body.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 204: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-users-apikey-generate:
Regenerate a user's api key
---------------------------
.. http:post:: /api/access/users/(string:username)/apikey
Generates a new API key for the user.
Does not expect a body. Will return the generated API key as ``apikey``
property in the JSON object contained in the response body.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 200: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-users-apikey-delete:
Delete a user's api key
-----------------------
.. http:delete:: /api/access/users/(string:username)/apikey
Deletes a user's personal API key.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 204: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-datamodel:
Data model
==========
.. _sec-api-access-datamodel-permissions:
Permissions
-----------
.. _sec-api-access-datamodel-permissions-list:
Permission list response
~~~~~~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``permissions``
- 0..n
- List of :ref:`permission records <sec-api-datamodel-access-permissions>`
- The list of permissions
.. _sec-api-access-datamodel-groups:
Groups
------
.. _sec-api-access-datamodel-groups-list:
Group list response
~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``groups``
- 0..n
- List of :ref:`group records <sec-api-datamodel-access-groups>`
- The list of groups
.. _sec-api-access-datamodel-groups-addgrouprequest:
Group registration request
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``key``
- 1
- string
- The group's identifier
* - ``name``
- 1
- string
- The group's name
* - ``description``
- 0..1
- string
- The group's description. Set to empty if not provided.
* - ``permissions``
- 1..n
- List of string
- A list of identifier's of permissions to assign to the group
* - ``subgroups``
- 0..n
- List of string
- A list of identifier's of groups to assign to the group as subgroups
* - ``default``
- 0..1
- boolean
- Whether to assign the group to new users by default (true) or not (false, default value)
.. _sec-api-access-datamodel-groups-updategrouprequest:
Group update request
~~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``description``
- 0..1
- string
- The group's description. Set to empty if not provided.
* - ``permissions``
- 1..n
- List of string
- A list of identifier's of permissions to assign to the group
* - ``subgroups``
- 0..n
- List of string
- A list of identifier's of groups to assign to the group as subgroups
* - ``default``
- 0..1
- boolean
- Whether to assign the group to new users by default (true) or not (false, default value)
.. _sec-api-access-datamodel-users:
Users
-----
.. _sec-api-access-datamodel-users-userlistresponse:
User list response
~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``users``
- 0..n
- List of :ref:`user records <sec-api-datamodel-access-users>`
- The list of users
.. _sec-api-access-datamodel-users-adduserrequest:
User registration request
~~~~~~~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- The user's name
* - ``password``
- 1
- string
- The user's password
* - ``active``
- 1
- bool
- Whether to activate the account (true) or not (false)
* - ``groups``
- 0..n
- List of string
- A list of identifiers of groups to assign to the user
* - ``permissions``
- 0..n
- List of string
- A list of identifiers of permissions to assign to the user
.. _sec-api-access-datamodel-users-updateuserrequest:
User update request
~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``active``
- 0..1
- bool
- If present will set the user's active flag to the provided value. True for
activating the account, false for deactivating it.
* - ``groups``
- 0..n
- List of string
- A list of identifiers of groups to assign to the user
* - ``permissions``
- 0..n
- List of string
- A list of identifiers of permissions to assign to the user
+3 -1
View File
@@ -16,6 +16,8 @@ Get connection settings
Retrieve the current connection settings, including information regarding the available baudrates and
serial ports and the current connection state.
Requires the ``STATUS`` permission.
**Example**
.. sourcecode:: http
@@ -81,7 +83,7 @@ Issue a connection command
for the lost acknowledgment should always be properly investigated and removed instead of depending on this
"symptom solver".
Requires user rights.
Requires the ``CONNECTION`` permission.
**Example Connect Request**
+181
View File
@@ -218,6 +218,17 @@ Progress information
- 1
- Integer
- Estimate of time left to print, in seconds
* - ``printTimeLeftOrigin``
- 1
- String
- Origin of the current time left estimate. Can currently be either of:
* ``linear``: based on an linear approximation of the progress in file in bytes vs time
* ``analysis``: based on an analysis of the file
* ``estimate``: calculated estimate after stabilization of linear estimation
* ``average``: based on the average total from past prints of the same model against the same printer profile
* ``mixed-analysis``: mixture of ``estimate`` and ``analysis``
* ``mixed-average``: mixture of ``estimate`` and ``average``
.. _sec-api-datamodel-files:
@@ -469,3 +480,173 @@ References
- URL
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
folders.
.. _sec-api-datamodel-access:
Access control
==============
.. _sec-api-datamodel-access-users:
User record
-----------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- The user's name
* - ``active``
- 1
- bool
- Whether the user's account is active (true) or not (false)
* - ``user``
- 1
- bool
- Whether the user has user rights. Should always be true. Deprecated as of 1.4.0, use the ``users`` group instead.
* - ``admin``
- 1
- bool
- Whether the user has admin rights (true) or not (false). Deprecated as of 1.4.0, use the ``admins`` group instead.
* - ``apikey``
- 0..1
- string
- The user's personal API key
* - ``settings``
- 1
- object
- The user's personal settings, might be an empty object.
* - ``groups``
- 1..n
- List of string
- Groups assigned to the user
* - ``needs``
- 1
- :ref:`Needs object <sec-api-datamodel-access-needs>`
- Effective needs of the user
* - ``permissions``
- 0..n
- List of :ref:`Permissions <sec-api-datamodel-access-permissions>`
- The list of permissions assigned to the user (note: this does not include implicit permissions inherit from groups).
.. _sec-api-datamodel-access-permissions:
Permission record
-----------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``key``
- 1
- string
- The permission's identifier
* - ``name``
- 1
- string
- The permission's name
* - ``dangerous``
- 1
- boolean
- Whether the permission should be considered dangerous due to a high reponsibility (true) or not (false).
* - ``default_groups``
- 1
- List of string
- List of group identifiers for which this permission is enabled by default
* - ``description``
- 1
- string
- Human readable description of the permission
* - ``needs``
- 1
- :ref:`Needs object <sec-api-access-datamodel-general-needs>`
- Needs assigned to the permission
.. _sec-api-datamodel-access-groups:
Group record
------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``key``
- 1
- string
- The group's identifier
* - ``name``
- 1
- string
- The group's name
* - ``description``
- 1
- string
- A human readable description of the group
* - ``permissions``
- 0..n
- List of :ref:`Permissions <sec-api-datamodel-access-permissions>`
- The list of permissions assigned to the group (note: this does not include implicit permissions inherited from
subgroups).
* - ``subgroups``
- 0..n
- List of :ref:`Groups <sec-api-datamodel-access-groups>`
- Subgroups assigned to the group
* - ``needs``
- 1
- :ref:`Needs object <sec-api-datamodel-access-needs>`
- Effective needs of the group
* - ``default``
- 1
- boolean
- Whether this is a default group (true) or not (false)
* - ``removable``
- 1
- boolean
- Whether this group can be removed (true) or not (false)
* - ``changeable``
- 1
- boolean
- Whether this group can be modified (true) or not (false)
* - ``toggleable``
- 1
- boolean
- Whether this group can be assigned to users or other groups (true) or not (false)
.. _sec-api-datamodel-access-needs:
Needs
-----
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``role``
- 0..1
- List of string
- List of ``role`` needs
* - ``group``
- 0..1
- List of string
- List of ``group`` needs
+15 -3
View File
@@ -21,6 +21,8 @@ Retrieve all files
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
Requires the ``FILES_LIST`` permission.
**Example 1**:
Fetch only the files and folders from the root folder.
@@ -250,6 +252,8 @@ Retrieve files from specific location
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
Requires the ``FILES_LIST`` permission.
**Example**:
.. sourcecode:: http
@@ -327,7 +331,7 @@ Upload file or create folder
Returns a :http:statuscode:`201` response with a ``Location`` header set to the management URL of the uploaded
file and an :ref:`Upload Response <sec-api-fileops-datamodel-uploadresponse>` as the body upon successful completion.
Requires user rights.
Requires the ``FILES_UPLOAD`` permission.
**Example for uploading a file**
@@ -504,6 +508,8 @@ Retrieve a specific file's or folder's information
On success, a :http:statuscode:`200` is returned, with a :ref:`file information item <sec-api-datamodel-files-file>`
as the response body.
Requires the ``FILES_LIST`` permission.
**Example**
.. sourcecode:: http
@@ -568,6 +574,8 @@ Issue a file command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires the ``FILES_SELECT`` permission.
slice
Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background
after the response has been sent back to the client. Additional parameters are:
@@ -598,6 +606,8 @@ Issue a file command
Upon success, a status code of :http:statuscode:`202` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
body will be returned.
Requires the ``SLICE`` permission.
copy
Copies the file or folder to a new ``destination`` on the same ``location``. Additional parameters are:
@@ -609,6 +619,8 @@ Issue a file command
Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
body will be returned.
Requires the ``FILES_UPLOAD`` permission.
move
Moves the file or folder to a new ``destination`` on the same ``location``. Additional parameters are:
@@ -622,7 +634,7 @@ Issue a file command
Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
body will be returned.
Requires user rights.
Requires the ``FILES_UPLOAD`` permission.
**Example Select Request**
@@ -773,7 +785,7 @@ Delete file
Returns a :http:statuscode:`204` after successful deletion.
Requires user rights.
Requires the ``FILES_DELETE`` permission.
**Example Request**
+56 -33
View File
@@ -148,8 +148,14 @@ Login
via the ``passive`` flag.
Will return a :http:statuscode:`200` with a :ref:`login response <sec-api-general-datamodel-login>` on successful
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`403` in
case of a username/password mismatch, unknown user or a deactivated account.
.. warning::
Previous versions of this API endpoint did return a :http:statuscode:`401` in case of a username/password
mismatch or an unknown user. That was incompatible with basic authentication since it was a wrong use of
the :http:statuscode:`401` code and got therefore changed as part of a bug fix.
:json passive: If present, performs a passive login only, returning information about the current user that's
active either through an existing session or the used API key
@@ -157,8 +163,7 @@ Login
:json pass: (active login only) Password
:json remember: (active login only) Whether to set a "remember me" cookie on the session
:status 200: Successful login
:status 401: Username/password mismatch or unknown user
:status 403: Deactivated account
:status 403: Username/password mismatch, unknown user or deactivated account
.. _sec-api-general-logout:
@@ -175,6 +180,20 @@ Logout
:status 204: No error
.. _sec-api-general-currentuser:
Current User
============
.. http:get:: /api/currentuser
Retrieves information about the current user.
Will return a :http:statuscode:`200` with a :ref:`current user object <sec-api-general-datamodel-currentuser>`
as body.
:status 200: No error
.. _sec-api-general-datamodel:
Data model
@@ -185,6 +204,30 @@ Data model
Login response
--------------
The Login response is a :ref:`user record <sec-api-datamodel-access-users>` extended by the following fields:
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``session``
- 1
- string
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
* - ``_is_external_client``
- 1
- boolean
- Whether the client that made the request got detected as external from the local network or not.
.. _sec-api-general-datamodel-currentuser:
Current user
------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
@@ -196,32 +239,12 @@ Login response
* - ``name``
- 1
- string
- the user's name/id
* - ``active``
- 1
- boolean
- Whether the user's account is active or not
* - ``admin``
- 1
- boolean
- Whether the user has admin rights or not
* - ``user``
- 1
- boolean
- Whether the user has user rights or not (always ``true``)
* - ``apikey``
- 1
- string or None
- The user's API key, if set
* - ``settings``
- 1
- dict
- The user's settings, if any
* - ``session``
- 1
- string
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
* - ``_is_external_client``
- 1
- boolean
- Whether the client that made the request got detected as external from the local network or not.
- The id of the current user. Unset if guest.
* - ``permissions``
- 0..n
- List of :ref:`permission records <sec-api-datamodel-access-permissions>`
- The effective list of permissions assigned to the user
* - ``groups``
- 0..n
- List of :ref:`permission records <sec-api-datamodel-access-groups>`
- The list of groups assigned to the user
+1 -2
View File
@@ -9,7 +9,6 @@ REST API
general.rst
version.rst
apps.rst
connection.rst
files.rst
job.rst
@@ -21,7 +20,7 @@ REST API
slicing.rst
system.rst
timelapse.rst
users.rst
access.rst
util.rst
wizard.rst
push.rst
+3 -1
View File
@@ -57,7 +57,7 @@ Issue a job command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
Requires the ``PRINT`` permission.
**Example Start Request**
@@ -180,6 +180,8 @@ Retrieve information about the current job
Returns a :http:statuscode:`200` with a :ref:`sec-api-job-datamodel-response` in the body.
Requires the ``STATUS`` permission.
**Example**
.. sourcecode:: http
+1 -1
View File
@@ -6,7 +6,7 @@ Languages
.. note::
All language pack management operations require admin rights.
All language pack management operations require the ``SETTINGS`` permission.
.. contents::
+59 -11
View File
@@ -80,6 +80,8 @@ Retrieve the current printer state
Returns a :http:statuscode:`200` with a :ref:`Full State Response <sec-api-printer-datamodel-fullstate>` in the
body upon success.
Requires the ``STATUS`` permission.
**Example 1**
Include temperature history data, but limit it to two entries.
@@ -241,7 +243,7 @@ Issue a print head command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Jog Request**
@@ -350,7 +352,7 @@ Issue a tool command
Sets the given target temperature on the printer's tools. Additional parameters:
* ``targets``: Target temperature(s) to set, properties must match the format ``tool{n}`` with ``n`` being the
tool's index starting with 0.
tool's index starting with 0. A value of `0` will turn the heater off.
offset
Sets the given temperature offset on the printer's tools. Additional parameters:
@@ -380,7 +382,7 @@ Issue a tool command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Target Temperature Request**
@@ -555,6 +557,8 @@ Retrieve the current tool state
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
Requires the ``STATUS`` permission.
.. note::
If you want both tool and bed temperature information at the same time, take a look at
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
@@ -630,7 +634,7 @@ Issue a bed command
target
Sets the given target temperature on the printer's bed. Additional parameters:
* ``target``: Target temperature to set.
* ``target``: Target temperature to set. A value of `0` will turn the heater off.
offset
Sets the given temperature offset on the printer's bed. Additional parameters:
@@ -645,7 +649,7 @@ Issue a bed command
If no heated bed is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Target Temperature Request**
@@ -714,6 +718,8 @@ Retrieve the current bed state
If no heated bed is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires the ``STATUS`` permission.
.. note::
If you want tool, bed and chamber temperature information at the same time, take a look at
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
@@ -770,7 +776,7 @@ Retrieve the current bed state
Issue a chamber command
=======================
.. http:post:: /api/printer/bed
.. http:post:: /api/printer/chamber
Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands
are:
@@ -778,7 +784,7 @@ Issue a chamber command
target
Sets the given target temperature on the printer's chamber. Additional parameters:
* ``target``: Target temperature to set.
* ``target``: Target temperature to set. A value of `0` will turn the heater off.
offset
Sets the given temperature offset on the printer's chamber. Additional parameters:
@@ -790,10 +796,10 @@ Issue a chamber command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
If no heated chambed is configured for the currently selected printer profile, the resource will return
If no heated chamber is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Target Temperature Request**
@@ -862,6 +868,8 @@ Retrieve the current chamber state
If no heated chamber is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires the ``STATUS`` permission.
.. note::
If you want tool, bed and chamber temperature information at the same time, take a look at
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
@@ -944,7 +952,7 @@ Issue an SD command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Init Request**
@@ -1022,6 +1030,8 @@ Retrieve the current SD state
Returns a :http:statuscode:`200` with an :ref:`SD State Response <sec-api-printer-datamodel-sdstate>` in the body
upon success.
Requires the ``STATUS`` permission.
**Example**
Read the current state of the SD card.
@@ -1058,7 +1068,7 @@ Send an arbitrary command to the printer
If successful returns a :http:statuscode:`204` and an empty body.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example for sending a single command**
@@ -1101,6 +1111,26 @@ Send an arbitrary command to the printer
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
:statuscode 204: No error
.. _sec-api-printer-customcontrols:
Retrieve custom controls
========================
.. http:get:: /api/printer/command/custom
Retrieves the :ref:`custom controls <sec-features-custom_controls>` as configured in
:ref:`config.yaml <sec-configuration-config_yaml>`.
Please refer to the documentation of :ref:`custom controls <sec-features-custom_controls>` on what
data structure to expect here.
Returns a :http:statuscode:`200` with an :ref:`Custom Controls Response <sec-api-printer-datamodel-customcontrols>`
in the body upon success.
Requires the ``CONTROL`` permission.
:statuscode 200: No error
.. _sec-api-printer-datamodel:
Data model
@@ -1211,3 +1241,21 @@ Arbitrary Command Request
- 0..1
- Map of key value pairs
- (only if ``script`` is set) additional template variables to provide to the script renderer
.. _sec-api-printer-datamodel-customcontrols:
Custom Controls Response
------------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``controls``
- 0..n
- List of :ref:`custom controls <sec-features-custom_controls>`
- A list of custom control definitions as defined in ``config.yaml``.
+21 -3
View File
@@ -21,6 +21,8 @@ Retrieve all printer profiles
Returns a :http:statuscode:`200` with a list of :ref:`profiles <sec-api-printerprofiles-datamodel-profile>`.
Requires the ``CONNECTION`` permission.
**Example**
.. sourcecode:: http
@@ -124,6 +126,22 @@ Retrieve all printer profiles
}
.. _sec-api-printerprofiles-get:
Retrieve a single printer profile
=================================
.. http:get:: /api/printerprofiles/(string:identifier)
Retrieves an existing single printer profile.
Returns a :http:statuscode:`200` with a :ref:`profile <sec-api-printerprofiles-datamodel-profile>`.
Requires the ``CONNECTION`` permission.
:statuscode 200: No error
:statuscode 404: The profile does not exist
.. _sec-api-printerprofiles-add:
Add a new printer profile
@@ -143,7 +161,7 @@ Add a new printer profile
Returns a :http:statuscode:`200` with the saved profile as property ``profile``
in the JSON body upon success.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example 1**
@@ -314,7 +332,7 @@ Update an existing printer profile
Returns a :http:statuscode:`200` with the saved profile as property ``profile``
in the JSON body upon success.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example**
@@ -400,7 +418,7 @@ Remove an existing printer profile
Returns a :http:statuscode:`204` an empty body upon success.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example**
+5 -3
View File
@@ -29,6 +29,9 @@ following message types are currently available for usage by 3rd party clients:
* ``connected``: Initial connection information, sent only right after establishing the socket connection. See
:ref:`the payload data model <sec-api-push-datamodel-connected>`.
* ``reauthRequired``: A reauthentication of the current login session is required. The ``reason`` parameter in the
payload defines whether a full active login is necessary (values ``logout`` and ``removed``) or a simple passive
login will suffice (all other values).
* ``current``: Rate limited general state update, payload contains information about the printer's state, job progress,
accumulated temperature points and log lines since last update. OctoPrint will send these updates when new information
is available, but not more often than twice per second in order to not flood the client with messages (e.g.
@@ -51,9 +54,8 @@ OctoPrint's SockJS socket also accepts two commands from the client to the serve
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
existing user session with the socket. That is of special importance to receive
any kind of messages if the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` is enabled
(as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated
clients.
any kind of messages, since the permission system will prevent any kind of status messages to be sent to connected
clients lacking the ``STATUS`` permission.
The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be
obtained from the successful payload of a :ref:`(passive or active) login via the API <sec-api-general-login>`.
+3 -1
View File
@@ -21,6 +21,8 @@ Retrieve current settings
The :ref:`data model <sec-api-settings-datamodel>` is similar to what can be found in
:ref:`config.yaml <sec-configuration-config_yaml>`, see below for details.
Requires the ``SETTINGS_READ`` permission.
.. _sec-api-settings-save:
Save settings
@@ -36,7 +38,7 @@ Save settings
Returns the currently active settings on success, as part of a :http:statuscode:`200` response.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example**
+62 -2
View File
@@ -28,6 +28,8 @@ List All Slicers and Slicing Profiles
Returns a :http:statuscode:`200` response with a :ref:`Slicer list <sec-api-slicing-datamodel-slicerlist>`
as the body upon successful completion.
Requires the ``SLICE`` permission.
**Example**
.. sourcecode:: http
@@ -77,6 +79,8 @@ List Slicing Profiles of a Specific Slicer
Returns a :http:statuscode:`200` response with a :ref:`Profile list <sec-api-slicing-datamodel-profilelist>`
as the body upon successful completion.
Requires the ``SLICE`` permission.
**Example**
.. sourcecode:: http
@@ -121,6 +125,8 @@ Retrieve Specific Profile
Returns a :http:statuscode:`200` response with a :ref:`full Profile <sec-api-slicing-datamodel-profile>`
as the body upon successful completion.
Requires the ``SLICE`` permission.
**Example**
.. sourcecode:: http
@@ -168,7 +174,7 @@ Add Slicing Profile
Returns a :http:statuscode:`201` and an :ref:`abridged Profile <sec-api-slicing-datamodel-profile>` in the body
upon successful completion.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example**
@@ -206,6 +212,31 @@ Add Slicing Profile
:statuscode 201: No error
:statuscode 404: If the ``slicer`` was unknown to the system.
.. _sec-api-slicing-patch:
Update Slicing Profile
======================
.. http:patch:: /api/slicing/(string:slicer)/profiles/(string:key)
Updates the slicing profile identified by ``key`` for the slicer ``slicer``.
Expects a :ref:`profile update request <sec-api-slicing-datamodel-profileupdate>` as body.
Returns a :http:statuscode:`201` and an :ref:`abridged Profile <sec-api-slicing-datamodel-profile>` in the body
upon successful completion.
Requires the ``SETTINGS`` permission.
:param slicer: The identifying key of the slicer for which to update the profile
:param key: The identifying key of the profile to update
:json data: New profile overrides to apply
:json displayName: New display name
:json description: New description
:json default: Whether to make the profile default (true) or not (false) for the slicer
:statuscode 200: No error
:statuscode 404: Slicer or profile do not exist
.. _sec-api-slicing-delete:
Delete Slicing Profile
@@ -216,7 +247,7 @@ Delete Slicing Profile
Delete the slicing profile identified by ``key`` for the slicer ``slicer``. If the profile doesn't exist, the
request will succeed anyway.
Requires admin rights.
Requires the ``SETTINGS`` permission.
:param slicer: The identifying key of the slicer for which to delete the profile
:param key: The identifying key of the profile to delete
@@ -340,3 +371,32 @@ Profile
only the keys differing from the defaults when saving/updating a profile. The keys to be found in here a slicer
specific. Will be left out for list responses.
.. _sec-api-slicing-datamodel-profileupdate:
Profile Update Request
----------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``data``
- 0..1
- Object
- The profile data
* - ``displayName``
- 0..1
- ``string``
- The new display name for the profile
* - ``description``
- 0..1
- ``string``
- The new description for the profile
* - ``default``
- 0..1
- ``boolean``
- Whether to mark the profile as default for the slicer (true) or not (false)
+3 -1
View File
@@ -6,7 +6,7 @@ System
.. note::
All system operations require admin rights.
All system operations require the ``SYSTEM`` permission.
.. _sec-api-system-command-list:
@@ -20,6 +20,8 @@ List all registered system commands
A :http:statuscode:`200` with a :ref:`List all response <sec-api-system-commands-listall>`
will be returned.
Requires the ``SYSTEM`` permission.
**Example**
.. sourcecode:: http
+6 -4
View File
@@ -18,6 +18,8 @@ Retrieve a list of timelapses and the current config
Returns a :ref:`timelapse list <sec-api-timelapse-datamodel-list>` in the
response body.
Requires the ``TIMELAPSE_LIST`` permission.
:param unrendered: If provided and true, also include unrendered timelapses
.. _sec-api-timelapse-delete:
@@ -29,7 +31,7 @@ Delete a timelapse
Delete the timelapse ``filename``.
Requires user rights.
Requires the ``TIMELAPSE_DELETE`` permission.
.. _sec-api-timelapse-render:
@@ -41,7 +43,7 @@ Issue a command for an unrendered timelapse
Current only supports to render the unrendered timelapse ``name`` via the
``render`` command.
Requires user rights.
Requires the ``TIMELAPSE_ADMIN`` permission.
:json command: The command to issue, currently only ``render`` is supported
@@ -54,7 +56,7 @@ Delete an unrendered timelapse
Delete the unrendered timelapse ``name``.
Requires user rights.
Requires the ``TIMELAPSE_DELETE`` permission.
.. _sec-api-timelapse-saveconfig:
@@ -67,7 +69,7 @@ Change current timelapse config
The configuration is expected as the request body.
Requires user rights.
Requires the ``TIMELAPSE_ADMIN`` permission.
.. _sec-api-timelapse-datamodel:
+2 -307
View File
@@ -4,311 +4,6 @@
User
****
.. contents::
.. note::
.. _sec-api-users-list:
Retrieve a list of users
========================
.. http:get:: /api/users
Retrieves a list of all registered users in OctoPrint.
Will return a :http:statuscode:`200` with a :ref:`user list response <sec-api-users-datamodel-userlistresponse>`
as body.
Requires admin rights.
:status 200: No error
.. _sec-api-users-retrieve:
Retrieve a user
===============
.. http:get:: /api/users/(string:username)
Retrieves information about a user.
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-users-datamodel-userrecord>`
as body.
Requires either admin rights or to be logged in as the user.
:param username: Name of the user which to retrieve
:status 200: No error
:status 404: Unknown user
.. _sec-api-users-add:
Add a user
==========
.. http:post:: /api/users
Adds a user to OctoPrint.
Expects a :ref:`user registration request <sec-api-users-datamodel-adduserrequest>`
as request body.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-users-list>`.
Requires admin rights.
:json name: The user's name
:json password: The user's password
:json active: Whether to activate the account (true) or not (false)
:json admin: Whether to give the account admin rights (true) or not (false)
:status 200: No error
:status 400: If any of the mandatory fields is missing or the request is otherwise
invalid
:status 409: A user with the provided name does already exist
.. _sec-api-users-update:
Update a user
=============
.. http:put:: /api/users/(string:username)
Updates a user record.
Expects a :ref:`user update request <sec-api-users-datamodel-updateuserrequest>`
as request body.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-users-list>`.
Requires admin rights.
:param username: Name of the user to update
:json admin: Whether to mark the user as admin (true) or not (false), can be left out (no change)
:json active: Whether to mark the account as activated (true) or deactivated (false), can be left out (no change)
:status 200: No error
:status 404: Unknown user
.. _sec-api-users-delete:
Delete a user
=============
.. http:delete:: /api/users/(string:username)
Delete a user record.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-users-list>`.
Requires admin rights.
:param username: Name of the user to delete
:status 200: No error
:status 404: Unknown user
.. _sec-api-users-resetpassword:
Reset a user's password
=======================
.. http:put:: /api/users/(string:username)/password
Changes the password of a user.
Expects a JSON object with a single property ``password`` as request body.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to change the password for
:json password: The new password to set
:status 200: No error
:status 400: If the request doesn't contain a ``password`` property or the request
is otherwise invalid
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-getsettings:
Retrieve a user's settings
==========================
.. http:get:: /api/users/(string:username)/settings
Retrieves a user's settings.
Will return a :http:statuscode:`200` with a JSON object representing the user's
personal settings (if any) as body.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 200: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-updatesettings:
Update a user's settings
========================
.. http:patch:: /api/users/(string:username)/settings
Updates a user's settings.
Expects a new settings JSON object to merge with the current settings as
request body.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 204: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-generateapikey:
Regenerate a user's personal API key
====================================
.. http:post:: /api/users/(string:username)/apikey
Generates a new API key for the user.
Does not expect a body. Will return the generated API key as ``apikey``
property in the JSON object contained in the response body.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 200: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-deleteapikey:
Delete a user's personal API key
================================
.. http:delete:: /api/users/(string:username)/apikey
Deletes a user's personal API key.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 204: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-datamodel:
Data model
==========
.. _sec-api-users-datamodel-userlistresponse:
User list response
------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``users``
- 0..n
- List of :ref:`user records <sec-api-users-datamodel-userrecord>`
- The list of registered users
.. _sec-api-users-datamodel-userrecord:
User record
-----------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- The user's name
* - ``active``
- 1
- bool
- Whether the user's account is active (true) or not (false)
* - ``user``
- 1
- bool
- Whether the user has user rights. Should always be true.
* - ``admin``
- 1
- bool
- Whether the user has admin rights (true) or not (false)
* - ``apikey``
- 0..1
- string
- The user's personal API key
* - ``settings``
- 1
- object
- The user's personal settings, might be an empty object.
.. _sec-api-users-datamodel-adduserrequest:
User registration request
-------------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- The user's name
* - ``password``
- 1
- string
- The user's password
* - ``active``
- 1
- bool
- Whether to activate the account (true) or not (false)
* - ``admin``
- 0..1
- bool
- Whether to give the user admin rights (true) or not (false or not present)
.. _sec-api-users-datamodel-updateuserrequest:
User update request
-------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``active``
- 0..1
- bool
- If present will set the user's active flag to the provided value. True for
activating the account, false for deactivating it.
* - ``admin``
- 0..1
- bool
- If present will set the user's admin flag to the provided value. True for
admin rights, false for no admin rights.
This API endpoint has been moved and is now part of :ref:`Access Control <sec-api-access-users>`.
+1 -1
View File
@@ -99,7 +99,7 @@ Test paths or URLs
The ``server`` command returns :http:statuscode:`200` with a :ref:`Server test result <sec-api-util-datamodel-servertestresult>`
when the test could be performed. The status code of the response does NOT reflect the test result!
Requires admin rights.
Requires the ``ADMIN`` permission.
**Example 1**
+1 -1
View File
@@ -6,7 +6,7 @@ Wizard
.. note::
All wizard operations require either admin rights or the ``firstRun`` flag to be ``true``.
All wizard operations require either the ``ADMIN`` permission or the ``firstRun`` flag to be ``true``.
.. contents::
+1 -1
View File
@@ -27,7 +27,7 @@ Command line usage
------------------
The Backup Plugin implements a command line interface that allows creation and restoration of backups.
It adds two new commands, ``backup:backup`` and ``backup_restore``.
It adds two new commands, ``backup:backup`` and ``backup:restore``.
.. code-block:: none
+1 -1
View File
@@ -14,7 +14,7 @@ network running Microsoft Windows. You will be able to just double click on the
OctoPrint instance icon in "Networks > Other Devices" in your Windows Explorer,
which will take you directly to the web frontend.
The ZeroConf support allows OctoPrint to announce itself to Safari on MacOS X
The ZeroConf support allows OctoPrint to announce itself to Safari on macOS
on the same network.
Linux users should install `Avahi <http://avahi.org>`_ and can then use one
-35
View File
@@ -1,35 +0,0 @@
.. _sec-bundledplugins-forcelogin:
ForceLogin Plugin
=================
The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous
read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and
instead forces users to log in if they want to get any kind of information from OctoPrint.
.. _fig-bundledplugins-forcelogin:
.. figure:: ../images/bundledplugins-forcelogin-dialog.png
:align: center
:alt: Forced login dialog
OctoPrint's new forced login dialog.
.. warning::
Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam,
it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict
access to your webcam, you'll need to find a way to do so directly on the webcam server which - again -
is not OctoPrint itself.
.. note::
If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable
the ForceLogin Plugin in OctoPrint's plugin manager.
.. _sec-bundledplugins-forcelogin-sourcecode:
Source code
-----------
The source of the ForceLogin plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/forcelogin``.
+1 -1
View File
@@ -14,8 +14,8 @@ Bundled Plugins
backup.rst
discovery.rst
errortracking.rst
forcelogin.rst
logging.rst
loginui.rst
pluginmanager.rst
printer_safety_check.rst
softwareupdate.rst
+66
View File
@@ -0,0 +1,66 @@
.. _sec-bundledplugins-loginui:
Login UI
========
The Login UI plugin has been bundled since OctoPrint 1.4.0 and replaces the ForceLogin plugin bundled with prior
versions since 1.3.10.
If anonymous read-only access is disabled in the :ref:`Access Control settings <sec-features-access_control>`
it provides a stand alone login dialog that gets displayed instead of OctoPrint's regular UI.
.. _fig-bundledplugins-loginui:
.. figure:: ../images/bundledplugins-loginui-dialog.png
:align: center
:alt: Login dialog
OctoPrint's login dialog.
The plugin allows theming of the dialog through :ref:`a plugin hook <sec-bundledplugins-loginui-hooks-theming>`.
.. warning::
Since the plugin is absolutely required for the case of anonymous read-only access because in this case the
UI itself could not even fully initialize due to a lack of permissions required to do so, it is hidden in the plugin
manager and cannot be disabled through that.
.. _sec-bundledplugins-loginui-hooks:
Hooks
-----
.. _sec-bundledplugins-loginui-hooks-theming:
octoprint.plugin.loginui.theming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: loginui_theming_hook(*args, **kwargs)
Support theming of the login dialog, just in case the core UI is themed as well. Use to return a list of additional
CSS file URLs to inject into the login dialog HTML.
Example usage by a plugin:
.. code-block:: python
def loginui_theming():
from flask import url_for
return [url_for("plugin.myplugin.static", filename="css/loginui_theme.css")]
__plugin_hooks__ = {
"octoprint.plugin.loginui.theming": loginui_theming
}
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
url_for like in the example above to be prepared for any configured prefix URLs.
:return: A list of additional CSS URLs to inject into the login dialog.
:rtype: A list of strings.
.. _sec-bundledplugins-loginui-sourcecode:
Source Code
-----------
The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be
found in its source repository under ``src/octoprint/plugins/loginui``.
+4
View File
@@ -196,6 +196,10 @@ Version checks
* ``checkout_folder``: (mandatory) The full path to the folder with a valid git
repository to check.
* ``pypi_release``: Checks `pypi.org <https://pypi.org>`_ for new releases of a specified package.
* ``package``: (mandatory) Name of the package which to check.
* ``command_line``: Uses a provided script to determine whether an update
is available. Additional config parameters:
+5 -3
View File
@@ -5,7 +5,7 @@ config.yaml
If not specified via the command line, the main configuration file ``config.yaml`` for OctoPrint is expected in its
settings folder, which unless defined differently via the command line is located at ``~/.octoprint`` on Linux, at
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on MacOS. If the file is not there,
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on macOS. If the file is not there,
you can just create it - it will only get created by OctoPrint once you save settings that deviate from the default
settings.
@@ -290,6 +290,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# Whether to delete generated web assets on server startup (forcing a regeneration)
clean_on_startup: true
# enable or disable the loading animation
showLoadingAnimation: true
# Settings for the virtual printer
virtualPrinter:
@@ -425,8 +428,7 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# Lines to send on simulated reset
resetLines:
- start
- Marlin: Virtual Marlin!
- "\x80"
- "Marlin: Virtual Marlin!"
- "SD card ok"
# Initial set of prepared oks to use instead of regular ok (e.g. to simulate
+1 -1
View File
@@ -5,7 +5,7 @@ logging.yaml
The logging configuration file ``logging.yaml`` for OctoPrint is expected in its settings folder, which unless defined
differently on the command line is located at ``~/.octoprint`` on Linux, at ``%APPDATA%/OctoPrint`` on Windows and at
``~/Library/Application Support/OctoPrint`` on MacOS.
``~/Library/Application Support/OctoPrint`` on macOS.
You can use it to change the log levels of the individual components within OctoPrint, which might be necessary to help
in debugging issues you are experiencing, or to change the configuration of the logging handlers themselves, e.g. in
+18 -7
View File
@@ -17,21 +17,30 @@ below.
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository:
* Checkout the OctoPrint sources from their Git repository:
* ``git clone -b devel https://github.com/foosel/OctoPrint.git``
* Enter the checked out source folder: ``cd OctoPrint``
* Create virtual environments in the checked out source folder for both Python 2.7 and Python 3.7 to use for
installing and running OctoPrint and its dependencies (this avoids potential versioning issues for the dependencies
with system wide installed instances):
* PY2: ``virtualenv --python=python2 venv2``
* PY3: ``virtualenv --python=python3 venv3``
* PY2: ``virtualenv --python=python2 venv2``
* PY3: ``virtualenv --python=python3 venv3``
* Activate one of the virtual environments:
* PY2: ``source venv2/bin/activate`` (Linux, MacOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* PY3: ``source venv3/bin/activate`` (Linux, MacOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* PY3: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
* ``pip install --upgrade pip``
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
including its regular *and* development and plugin development dependencies:
including its regular *and* development and plugin development dependencies:
* ``pip install -e .[develop,plugins]``
When the virtual environment is activated you can then:
@@ -197,8 +206,10 @@ PyCharm
.......
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
- "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
- **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
- **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." >
"Virtualenv Environment > "Existing Environment", select OctoPrint venv folder (e.g. ``~/devel/OctoPrint/venv``)
- Right click "src" in project tree, mark as source folder
- Add Run/Debug Configuration, select "Python":
+1 -1
View File
@@ -17,7 +17,7 @@ be found in the full :ref:`config.yaml documentation <sec-configuration-config_y
The steps to take are as follows:
* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on MacOS.
* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on macOS.
* Add or extend the ``devel`` section with:
.. code-block:: yaml
+49 -6
View File
@@ -100,20 +100,44 @@ Shutdown
The server is shutting down.
ClientOpened
A client has connected to the web server.
A client has connected to the push socket.
Payload:
* ``remoteAddress``: the remote address (IP) of the client that connected
* ``remoteAddress``: the remote address (IP) of the client that connected. On the push socket only available with
a valid login session.
**Note:** Name changed in version 1.1.0
ClientClosed
A client has disconnected from the webserver
ClientAuthed
A client has authenticated a user session on the push socket.
Payload:
* ``remoteAddress``: the remote address (IP) of the client that disconnected
* ``remoteAddress``: the remote address (IP) of the client that authed. On the push socket only available with a
valid login session.
* ``username``: the name of the user who authed. On the push socket only available with a valid login session.
ClientClosed
A client has disconnected from the push socket.
Payload:
* ``remoteAddress``: the remote address (IP) of the client that disconnected. On the push socket only available
with a valid login session.
UserLoggedIn
A user logged in. On the push socket only available with a valid login session with admin rights.
Payload:
* ``username``: the name of the user who logged in
UserLoggedOut
A user logged out. On the push socket only available with a valid login session with admin rights.
Payload:
* ``username``: the name of the user who logged out
ConnectivityChanged
The server's internet connectivity changed
@@ -151,6 +175,9 @@ Error
An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or
on the connection.
Note that this event will not fire for error messages from the firmware that are handled (and as such recovered from)
either by OctoPrint or a plugin.
Payload:
* ``error``: the error string
@@ -588,6 +615,7 @@ SlicingStarted
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -599,6 +627,7 @@ SlicingDone
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -611,6 +640,7 @@ SlicingCancelled
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -621,6 +651,7 @@ SlicingFailed
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -636,7 +667,7 @@ SlicingProfileAdded
* ``profile``: the profile that was added
SlicingProfileModified
A new slicing profile was modified.
A slicing profile was modified.
Payload:
@@ -661,3 +692,15 @@ SettingsUpdated
This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or
:py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``.
.. _sec-events-available_events-printer_profile:
Printer Profile
---------------
PrinterProfileModified
A printer profile was modified.
Payload:
* ``identifier``: the identifier of the modified printer profile
+39 -4
View File
@@ -3,8 +3,20 @@
Access Control
==============
When Access Control is enabled, anonymous users (not logged in) will only see
the read-only parts of the UI which are the following:
OctoPrint's bundled access control feature allows granular permission control
over which users or user groups are allowed to access which parts of OctoPrint.
The default permissions will deny any kind of access to anonymous (not logged in)
users out of the box.
.. warning::
Please note that OctoPrint does *not* control the webcam and merely embeds it, and
thus also cannot limit access to it. If an anonymous user correctly guesses the
webcam URL, they will thus be able to see it.
If read-only access for anonymous users is enabled, anonymous users will have
read-only access to the following parts of the UI:
* printer state
* available gcode files and stats (upload is disabled)
@@ -16,8 +28,8 @@ the read-only parts of the UI which are the following:
* any components provided through plugins which are enabled for anonymous
users
Logged in users will get access to everything besides the Settings and System
Commands, which are admin-only.
Logged in users without admin flag will be allowed to access everything besides the
Settings and System Commands, which are admin-only.
If Access Control is disabled, everything is directly accessible. **That also
includes all administrative functionality as well as full control over the
@@ -39,6 +51,29 @@ internet or other untrusted networks!).
publicly reachable by everyone with an internet connection, even with access
control enabled.
.. _sec-features-access_control-hooks:
Available Extension Hooks
-------------------------
There are two hooks for plugins to utilize in order to
add new configurable permissions into the system and/or adjust the styling of the
login dialog.
.. _sec-features-access_control-hooks-permissions:
octoprint.access.permissions
............................
See :ref:`here <sec-plugins-hook-permissions>`.
.. _sec-features-access_control-hooks-loginui:
octoprint.plugin.loginui.theming
................................
See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
.. _sec-features-access_control-rerunning_wizard:
Rerunning the wizard
+1 -1
View File
@@ -11,7 +11,7 @@ is clicked.
Unless :ref:`configured otherwise <sec-configuration-config_yaml-folder>`, OctoPrint expects scripts to be located in
the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint``
on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS).
on Windows and ``~/Library/Application Support/OctoPrint`` on macOS).
These GCODE scripts are backed by the templating engine Jinja2, allowing more than just
simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To
+17 -10
View File
@@ -5,19 +5,20 @@ Safe mode
*********
With the advent of support for plugins in OctoPrint, it quickly became apparent that some of the bugs
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins instead of
OctoPrint itself.
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins or language
packs instead of OctoPrint itself.
To allow an easier identification of these cases, OctoPrint 1.3.0 introduced safe mode. Starting
OctoPrint in safe mode disables all plugins that are not bundled with OctoPrint, allowing to easier
identify most cases where a third party plugin is the culprit of an observed issue.
OctoPrint in safe mode disables all plugins (and starting with 1.3.13 also all language packs) that are
not bundled with OctoPrint, allowing to easier identify most cases where a third party plugin or language
pack is the culprit of an observed issue.
Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recovery from cases where
a third party plugin causes the server to not start up or the web interface to not render or function
correctly anymore.
Additionally, OctoPrint allows uninstalling plugins and language packs in this mode, allowing recovery
from cases where a third party addition causes the server to not start up or the web interface to not
render or function correctly anymore.
Whenever reporting an issue with OctoPrint, please always attempt to reproduce it in safe mode as well to
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party plugins.
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party additions.
.. _sec-features-safemode-how:
@@ -73,11 +74,17 @@ When OctoPrint is running in safe mode the following changes to its normal opera
* OctoPrint will not enable any of the installed third party plugins. OctoPrint considers all plugins third
party plugins that do not ship with OctoPrint's sources, so any plugins installed either via `pip` or
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint`` (Windows) and
``~/Library/Application Support/OctoPrint`` (MacOS).
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint/plugins`` (Windows) and
``~/Library/Application Support/OctoPrint/plugins`` (macOS).
* OctoPrint will not enable any of the installed third party language packs. OctoPrint considers all language packs
third party language packs that do not ship with OctoPrint's sources, so any language plugins installed
through the language pack manager within settings and/or stored in the language pack folder at
``~/.octoprint/translations`` (Linux), ``%APPDATA%/OctoPrint/translations`` (Windows) or
``~/Library/Application Support/OctoPrint/translations`` (macOS).
* OctoPrint will still allow to uninstall third party plugins through the built-in Plugin Manager.
* OctoPrint will still allow to disable (bundled) plugins that are still enabled.
* OctoPrint will not allow to enable third party plugins.
* OctoPrint will still allow to manage language packs.
* OctoPrint's web interface will display a notification to remind you that it is running in
safe mode.
File renamed without changes.

Before

Width:  |  Height:  |  Size: 9.6 KiB

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 58 KiB

+1 -1
View File
@@ -42,7 +42,7 @@
To register for all message types, provide ``*`` as the type to register for.
``handler`` is expected to be a function accepting one object parameter ``eventObj``, consisting
of the received message as property ``key`` and the received payload (if any) as property ``data``.
of the received message as property ``event`` and the received payload (if any) as property ``data``.
.. code-block:: javascript
+17 -3
View File
@@ -60,6 +60,7 @@ We'll start at the most basic form a plugin can take - just a few simple lines o
__plugin_name__ = "Hello World"
__plugin_version__ = "1.0.0"
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
__plugin_pythoncompat__ = ">=2.7,<4"
Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup::
@@ -75,7 +76,10 @@ Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you somethin
OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log
entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now.
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now. Additionally
there is ``__plugin_pythoncompat__`` which tells OctoPrint here that your plugin can be run under any Python versions
between 2.7 and 4. That is necessary so that your plugin will be loadable in OctoPrint instances running under either
Python 2 or Python 3, and compatibility to both should be your goal.
.. _sec-plugins-gettingstarted-sayinghello:
@@ -86,7 +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,13
:emphasize-lines: 4-8,14
:linenos:
# -*- coding: utf-8 -*-
@@ -101,6 +105,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
__plugin_name__ = "Hello World"
__plugin_version__ = "1.0.0"
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
and restart OctoPrint. You now get this output in the log::
@@ -284,7 +289,7 @@ of information now defined twice:
The nice thing about our plugin now being a proper Python package is that OctoPrint can and will access the metadata defined
within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__``
and ``__plugin_description__`` from ``__init__.py``:
and ``__plugin_description__`` from ``__init__.py``, but leave ``__plugin_implementation__`` and ``__plugin_pythoncompat__``:
.. code-block:: python
:linenos:
@@ -298,6 +303,7 @@ and ``__plugin_description__`` from ``__init__.py``:
def on_after_startup(self):
self._logger.info("Hello World!")
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
and restart OctoPrint::
@@ -324,6 +330,7 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
self._logger.info("Hello World!")
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
@@ -373,6 +380,7 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
self._logger.info("Hello World!")
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file
@@ -443,6 +451,7 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``:
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Restart OctoPrint. You should see something like this::
@@ -480,6 +489,7 @@ Adjust your plugin's ``__init__.py`` like this:
return dict(url=self._settings.get(["url"]))
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
@@ -590,6 +600,7 @@ again since we don't use that anymore:
]
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we
@@ -693,6 +704,7 @@ like so:
)
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`.
@@ -875,6 +887,7 @@ a reference to our CSS file:
)
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
OctoPrint by default bundles all CSS, JavaScript and LESS files to reduce the amount of requests necessary to fully
@@ -961,6 +974,7 @@ Then adjust our returned assets to include our LESS file as well:
)
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
+112 -42
View File
@@ -200,6 +200,94 @@ Available plugin hooks
.. contents::
:local:
.. _sec-plugins-hook-permissions:
octoprint.access.permissions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: additional_permissions_hook(*args, **kwargs)
Return a list of additional permissions to register in the system on behalf of the plugin. Use this
to add granular permissions to your plugin which can be configured for users and user groups in the general
access control settings of OctoPrint.
Additional permissions must be modelled as ``dict``s with at least a ``key`` and ``name`` field. Possible
fields are as follows:
* ``key``: A key for the permission to be used for referring to it from source code. This will turned uppercase
and prefixed with ``PLUGIN_<PLUGIN IDENTIFIER>_`` before being made available on ``octoprint.access.permissions.Permissions``,
e.g. ``my_permission`` on the plugin with identifier ``example`` turns into ``PLUGIN_EXAMPLE_MY_PERMISSION`` and
can be accessed as ``octoprint.access.permissions.Permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the server and
``permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the ``AccessViewModel`` on the client. Must only contain a-z, A-Z, 0-9 and _.
* ``name``: A human readable name for the permission.
* ``description``: A human readable description of the permission.
* ``permissions``: A list of permissions this permission includes, by key.
* ``roles``: A list of roles this permission includes. Roles are simple strings you define. Usually one role will
suffice.
* ``dangerous``: Whether this permission should be considered dangerous (``True``) or not (``False``)
* ``default_groups``: A list of standard groups this permission should be apply to by default. Standard groups
are ``admins``, ``users``, ``readonly`` and ``guests``
The following example is based on some actual code included in the bundled Application Keys plugin and defines
one additional permission called ``ADMIN`` with a role ``admin`` which is marked as dangerous (since it gives
access to the management to other user's application keys) and by default will only be given to the standard admin
group:
.. code-block:: python
def get_additional_permissions(*args, **kwargs):
return [
dict(key="ADMIN",
name="Admin access",
description=gettext("Allows administrating all application keys"),
roles=["admin"],
dangerous=True,
default_groups=[ADMIN_GROUP])
]
__plugin_hooks__ = {
"octoprint.access.permissions": get_additional_permissions
}
Once registered it can be referenced under the key ``PLUGIN_APPKEYS_ADMIN``.
:return: A list of additional permissions to register in the system.
:rtype: A list of dicts.
.. _sec-plugins-hook-users-factory:
octoprint.access.users.factory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will
be called only once during initial server startup.
The provided ``components`` is a dictionary containing the already initialized system components:
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
* ``event_bus``: The :class:`~octoprint.events.EventManager`
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
:class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage
file ``~/.octoprint/users.yaml``.
:param dict components: System components to use for user manager instance initialization
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
:return: The ``userManager`` instance to use globally.
:rtype: UserManager subclass or None
.. _sec-plugins-hook-accesscontrol-keyvalidator:
octoprint.accesscontrol.keyvalidator
@@ -1014,6 +1102,27 @@ octoprint.filemanager.preprocessor
:return: The `file_object` as passed in or None, or a replaced version to use instead for further processing.
:rtype: AbstractFileWrapper or None
.. _sec-plugins-hook-plugin-loginui-theming:
octoprint.plugin.loginui.theming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
.. _sec-plugins-hook-plugin-pluginmanager-reconnect:
octoprint.plugin.pluginmanager.reconnect_hooks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See :ref:`here <sec-bundledplugins-pluginmanager-hooks-reconnect_hooks>`.
.. _sec-plugins-hook-plugin-softwareupdate-check_config:
octoprint.plugin.softwareupdate.check_config
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See :ref:`here <sec-bundledplugins-softwareupdate-hooks-check_config>`.
.. _sec-plugins-hook-printer-factory:
octoprint.printer.factory
@@ -1185,8 +1294,7 @@ octoprint.server.api.after_request
Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
usage example.
Your plugin might need this to further restrict access to API methods.
.. important::
@@ -1201,8 +1309,7 @@ octoprint.server.api.before_request
Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
usage example.
Your plugin might need this to further restrict access to API methods.
.. important::
@@ -1217,8 +1324,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. See the bundled
"Force Login" plugin for a usage example.
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further.
.. important::
@@ -1342,8 +1448,6 @@ octoprint.server.sockjs.authed
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
@@ -1525,40 +1629,6 @@ octoprint.ui.web.templatetypes
:return: a list of 3-tuples (template type, rule, sorting spec)
:rtype: list
.. _sec-plugins-hook-users-factory:
octoprint.access.users.factory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will
be called only once during initial server startup.
The provided ``components`` is a dictionary containing the already initialized system components:
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
* ``event_bus``: The :class:`~octoprint.events.EventManager`
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
:class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage
file ``~/.octoprint/users.yaml``.
:param dict components: System components to use for user manager instance initialization
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
:return: The ``userManager`` instance to use globally.
:rtype: UserManager subclass or None
.. _sec-plugins-hook-timelapse-capture-pre:
octoprint.timelapse.capture.pre
+1 -1
View File
@@ -166,7 +166,7 @@ Now, the execution order of the ``on_after_startup`` method will be determined b
This will result in the following messages to be generated:
.. code-block:: plain
.. code-block:: none
Plugin B starting up
Plugin C starting up
+5 -6
View File
@@ -11,7 +11,7 @@ import requests
from contextlib import closing
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
nodes, set_source_info, parselinenos, logger, container_wrapper
nodes, parselinenos, logger, container_wrapper
if False:
# For type annotation
@@ -39,11 +39,10 @@ class OnlineIncludeReader(LiteralIncludeReader):
return lines
except (IOError, OSError):
raise IOError(_('Include file %r not found or reading it failed') % filename)
raise IOError('Include file %r not found or reading it failed' % filename)
except UnicodeError:
raise UnicodeError(_('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option') %
(self.encoding, filename))
raise UnicodeError('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option' % (self.encoding, filename))
class OnlineIncludeDirective(LiteralInclude):
@@ -69,7 +68,7 @@ class OnlineIncludeDirective(LiteralInclude):
text, lines = reader.read(location=location)
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
self.set_source_info(retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
elif 'language' in self.options:
+1 -1
View File
@@ -13,5 +13,5 @@ octoprint.init => /etc/init.d/octoprint
## systemd
```
octoprint.service => /etc/systemd/service/octoprint.service
octoprint.service => /etc/systemd/system/octoprint.service
```
+45 -31
View File
@@ -17,6 +17,11 @@ import setuptools
# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported
PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
# Requirements for setup.py
SETUP_REQUIRES = [
"markdown>=3.1,<3.2",
]
# Requirements for our application
INSTALL_REQUIRES = [
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
@@ -27,18 +32,18 @@ INSTALL_REQUIRES = [
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"Flask-Login>=0.4.1,<0.5",
"Flask-Principal>=0.4,<0.5",
"Flask-Babel>=0.12,<0.13",
"Flask-Assets>=0.12,<0.13",
"werkzeug>=0.15.1,<0.16",
"blinker>=1.4,<1.5", # dependency of the now vendor bundled flask_principal
"werkzeug>=0.16,<0.17",
"cachelib>=0.1,<0.2",
"PyYAML>=5.1,<6",
"markdown>=3.0,<3.1",
"markdown>=3.1,<3.2",
"pyserial>=3.4,<3.5",
"netaddr>=0.7.19,<0.8",
"watchdog>=0.9.0,<0.10",
@@ -47,41 +52,42 @@ INSTALL_REQUIRES = [
"pylru>=1.2,<1.3",
"rsa>=4.0,<5",
"pkginfo>=1.5.0.1,<1.6",
"requests>=2.21.0,<3",
"semantic_version>=2.6,<2.7",
"psutil>=5.6.1,<5.7",
"requests>=2.22.0,<3",
"semantic_version>=2.8,<2.9",
"psutil>=5.6.5,<5.7",
"Click>=7,<8",
"awesome-slugify>=1.6.5,<1.7",
"feedparser>=5.2.1,<5.3",
"future>=0.17,<0.18",
"future>=0.18.2,<0.19",
"websocket-client>=0.56,<0.57",
"wrapt>=1.11.1,<1.12",
"emoji>=0.5.1,<0.6",
"wrapt>=1.11.2,<1.12",
"emoji>=0.5.4,<0.6",
"frozendict>=1.2,<1.3",
"sentry-sdk==0.7.7"
"sentry-sdk==0.13.2",
"filetype>=1.0.5,<2"
]
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"futures>=3.2,<3.3",
"futures>=3.3,<3.4",
"monotonic>=1.5,<1.6",
"scandir>=1.10,<1.11",
"chainmap>=1.0.3,<1.1",
"typing>=3.6.6,<4"
"typing>=3.7.4.1,<4"
]
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"appdirs>=1.4.0",
"appdirs>=1.4.3",
]
# Additional requirements for optional install options
EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies
"mock>=2.0.0,<3",
"pytest>=4.2.1,<5.0",
# Testing dependencies - SEE ALSO tox.ini
"mock>=3.0.5,<4",
"pytest==4.6.6",
"pytest-doctest-custom>=1.0.0,<1.1",
"ddt",
@@ -89,10 +95,11 @@ EXTRA_REQUIRES = dict(
"flake8",
# Documentation dependencies
"sphinx>=1.6,<1.7",
"sphinx>=1.8.5,<2",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid>=0.3",
"sphinxcontrib-mermaid>=0.3.1",
"sphinx_rtd_theme",
"readthedocs-sphinx-ext==0.5.17" # Later versions require Jinja >= 2.9
],
# Dependencies for developing OctoPrint plugins
@@ -131,14 +138,14 @@ def read_file_contents(path):
with codecs.open(path, encoding="utf-8") as f:
return f.read()
def data_copy_build_py_factory(files, baseclass):
class data_copy_build_py(baseclass):
def md_to_html_build_py_factory(files, baseclass):
class md_to_html_build_py(baseclass):
files = dict()
def run(self):
import shutil
print("RUNNING md_to_html_build_py")
if not self.dry_run:
for directory, files in self.__class__.files.items():
for directory, files in self.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
@@ -146,16 +153,22 @@ def data_copy_build_py_factory(files, baseclass):
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry
source, dest = entry[0], os.path.join(target_dir, entry[1])
else:
source = dest = entry
shutil.copy(source, os.path.join(target_dir, dest))
source = entry
dest = os.path.join(target_dir, source + ".html")
print("Rendering markdown from {} to {}".format(source, dest))
from markdown import markdownFromFile
markdownFromFile(input=source,
output=dest,
encoding="utf-8")
baseclass.run(self)
return type(data_copy_build_py)(data_copy_build_py.__name__,
(data_copy_build_py,),
dict(files=files))
return type(md_to_html_build_py)(md_to_html_build_py.__name__,
(md_to_html_build_py,),
dict(files=files))
def get_cmdclass():
cmdclass = versioneer.get_cmdclass()
@@ -169,10 +182,9 @@ def get_cmdclass():
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
cmdclass["build_py"] = data_copy_build_py_factory({
cmdclass["build_py"] = md_to_html_build_py_factory({
"octoprint/templates/_data": [
"AUTHORS.md",
"CHANGELOG.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
@@ -191,6 +203,7 @@ def params():
long_description_content_type = "text/markdown"
python_requires = PYTHON_REQUIRES
setup_requires = SETUP_REQUIRES
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
@@ -215,6 +228,7 @@ def params():
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
+10 -40
View File
@@ -233,12 +233,6 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
},
"serial": {
"format": "%(asctime)s - %(message)s"
},
"communication": {
"format": "%(asctime)s - %(name)s - %(message)s"
},
"commdebug": {
"format": "%(asctime)s - %(threadName)s - %(message)s"
}
},
"handlers": {
@@ -256,45 +250,19 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
"backupCount": 6,
"filename": os.path.join(settings.getBaseFolder("logs"), "octoprint.log")
},
"protocolFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"serialFile": {
"class": "octoprint.logging.handlers.SerialLogHandler",
"level": "DEBUG",
"formatter": "communication",
"formatter": "serial",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "protocol.log"),
"delay": True
},
"transportFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"level": "DEBUG",
"formatter": "communication",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "transport.log"),
"delay": True
},
"commDebugFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"level": "DEBUG",
"formatter": "commdebug",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "commdebug.log"),
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"),
"delay": True
}
},
"loggers": {
"PROTOCOL": {
"level": "DEBUG",
"handlers": ["protocolFile"],
"propagate": False
},
"TRANSPORT": {
"level": "DEBUG",
"handlers": ["transportFile"],
"propagate": False
},
"COMMDEBUG": {
"level": "DEBUG",
"handlers": ["commDebugFile"],
"SERIAL": {
"level": "INFO",
"handlers": ["serialFile"],
"propagate": False
},
"octoprint": {
@@ -442,7 +410,9 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
if not startup:
return
sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, x[2], x[0]))
from octoprint.util import sv
sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, sv(x[2]), sv(x[0])))
disabled_list = pm.plugin_disabled_list
already_processed = []
-4
View File
@@ -2,10 +2,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
#import sys
#if sys.version_info[0] >= 3:
# raise RuntimeError("Sorry, OctoPrint does not yet support Python 3")
if __name__ == "__main__":
import octoprint
octoprint.main()
+3 -28
View File
@@ -18,32 +18,7 @@ from octoprint.settings import settings
from octoprint.util import atomic_write
from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP, READONLY_GROUP
from octoprint.access.permissions import Permissions, OctoPrintPermission
from flask_principal import Need, Permission
DEFAULT_ADMIN_PERMISSIONS = [Permissions.ADMIN]
"""Default admin permissions are the legacy permissions from before 1.4.0"""
DEFAULT_USER_PERMISSIONS = [Permissions.STATUS,
Permissions.CONNECTION,
Permissions.WEBCAM,
Permissions.FILES_UPLOAD,
Permissions.FILES_DOWNLOAD,
Permissions.FILES_DELETE,
Permissions.FILES_SELECT,
Permissions.PRINT,
Permissions.MONITOR_TERMINAL,
Permissions.CONTROL,
Permissions.SLICE,
Permissions.TIMELAPSE_LIST,
Permissions.TIMELAPSE_ADMIN]
"""Default user permissions are the legacy permissions from before 1.4.0"""
DEFAULT_GUEST_PERMISSIONS = [Permissions.STATUS,
Permissions.WEBCAM,
Permissions.FILES_DOWNLOAD,
Permissions.TIMELAPSE_LIST,
Permissions.MONITOR_TERMINAL]
"""Default guest permissions are the legacy permissions from before 1.4.0"""
from octoprint.vendor.flask_principal import Need, Permission
GroupNeed = partial(Need, 'group')
@@ -151,8 +126,8 @@ class GroupManager(object):
return [group.key for group in groups]
def _to_groups(self, *groups):
return filter(lambda x: x is not None,
[self._to_group(g) for g in groups])
return list(filter(lambda x: x is not None,
[self._to_group(g) for g in groups]))
def _to_group(self, group):
# noinspection PyCompatibility
+35 -14
View File
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
from future.utils import with_metaclass
from flask import g, abort
from flask_babel import gettext
from flask_principal import Permission, PermissionDenied, RoleNeed, Need
from octoprint.vendor.flask_principal import Permission, PermissionDenied, RoleNeed, Need
from functools import wraps
from collections import OrderedDict, defaultdict
@@ -79,6 +79,22 @@ class OctoPrintPermission(Permission):
def get_description(self):
return self._description
def allows(self, identity):
"""Whether the identity can access this permission.
Overridden from Permission.allows to make sure the Identity provides ALL
required needs instead of ANY required need.
:param identity: The identity
"""
if self.needs and len(self.needs.intersection(identity.provides)) != len(self.needs):
return False
if self.excludes and self.excludes.intersection(identity.provides):
return False
return True
def union(self, other):
"""Create a new OctoPrintPermission with the requirements of the union of this
and other.
@@ -259,8 +275,9 @@ class Permissions(with_metaclass(PermissionsMetaClass)):
default_groups=[ADMIN_GROUP])
STATUS = OctoPrintPermission("Status",
gettext("Allows to gather status information, e.g. job progress, "
"printer state, temperatures, ..."),
gettext("Allows to gather basic status information, e.g. job progress, "
"printer state, temperatures, ... Mandatory for the default UI "
"to work"),
RoleNeed("status"),
default_groups=[USER_GROUP, READONLY_GROUP])
@@ -292,27 +309,26 @@ class Permissions(with_metaclass(PermissionsMetaClass)):
FILES_DOWNLOAD = OctoPrintPermission("File Download",
gettext("Allows users to download files. The GCODE viewer is "
"affected by this as well."),
RoleNeed("files_download"), FILES_LIST,
RoleNeed("files_download"),
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_DELETE = OctoPrintPermission("File Delete",
gettext("Allows users to delete files"),
RoleNeed("files_delete"), FILES_LIST,
RoleNeed("files_delete"),
default_groups=[USER_GROUP])
FILES_SELECT = OctoPrintPermission("File Select",
gettext("Allows to select a file for printing"),
RoleNeed("files_select"), FILES_LIST,
RoleNeed("files_select"),
default_groups=[USER_GROUP])
PRINT = OctoPrintPermission("Print",
gettext("Allows to start, pause and cancel a print job. Includes the \"Select\" "
"permission"),
RoleNeed("print"), FILES_SELECT,
gettext("Allows to start, pause and cancel a print job"),
RoleNeed("print"),
default_groups=[USER_GROUP])
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
gettext("Allows access to the GCODE viewer. Includes the \"File Download\""
"permission."),
RoleNeed("gcodeviewer"), FILES_DOWNLOAD,
gettext("Allows access to the GCODE viewer if the \"File Download\""
"permission is also set."),
RoleNeed("gcodeviewer"),
default_groups=[USER_GROUP, READONLY_GROUP])
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
@@ -351,8 +367,13 @@ class Permissions(with_metaclass(PermissionsMetaClass)):
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP])
SETTINGS = OctoPrintPermission("Settings",
gettext("Allows to manage settings"),
SETTINGS_READ = OctoPrintPermission("Settings Access",
gettext("Allows to read non sensitive settings. Mandatory for the "
"default UI to work."),
RoleNeed("settings_read"),
default_groups=[USER_GROUP, READONLY_GROUP])
SETTINGS = OctoPrintPermission("Settings Admin",
gettext("Allows to manage settings and also to read sensitive settings"),
RoleNeed("settings"),
dangerous=True)
+70 -34
View File
@@ -19,15 +19,18 @@ import logging
# noinspection PyCompatibility
from builtins import range, bytes
from octoprint.settings import settings
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
from octoprint.settings import settings as s
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time, generate_api_key
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.access.permissions import Permissions, OctoPrintPermission
from octoprint.access.groups import GroupChangeListener, Group
from past.builtins import basestring
class UserManager(GroupChangeListener, object):
def __init__(self, group_manager):
def __init__(self, group_manager, settings=None):
self._group_manager = group_manager
self._group_manager.register_listener(self)
@@ -36,6 +39,10 @@ class UserManager(GroupChangeListener, object):
self._sessionids_by_userid = dict()
self._enabled = True
if settings is None:
settings = s()
self._settings = settings
self._login_status_listeners = []
def register_login_status_listener(self, listener):
@@ -48,7 +55,10 @@ class UserManager(GroupChangeListener, object):
if self.enabled:
return AnonymousUser([self._group_manager.guest_group])
else:
return AdminUser([self._group_manager.admin_group])
return AdminUser([self._group_manager.admin_group, self._group_manager.user_group])
def api_user_factory(self):
return ApiUser([self._group_manager.admin_group, self._group_manager.user_group])
@property
def enabled(self):
@@ -92,14 +102,15 @@ class UserManager(GroupChangeListener, object):
try:
listener.on_user_logged_in(user)
except Exception:
self._logger.exception("Error in on_user_logged_in on {!r}".format(listener))
self._logger.exception("Error in on_user_logged_in on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
self._logger.debug("Logged in user: %r" % user)
self._logger.info("Logged in user: {}".format(user.get_id()))
return user
def logout_user(self, user):
if user is None or user.is_anonymous:
def logout_user(self, user, stale=False):
if user is None or user.is_anonymous or isinstance(user, AdminUser):
return
if isinstance(user, LocalProxy):
@@ -118,34 +129,41 @@ class UserManager(GroupChangeListener, object):
pass
if sessionid in self._session_users_by_session:
del self._session_users_by_session[sessionid]
try:
del self._session_users_by_session[sessionid]
except KeyError:
pass
for listener in self._login_status_listeners:
try:
listener.on_user_logged_out(user)
listener.on_user_logged_out(user, stale=stale)
except Exception:
self._logger.exception("Error in on_user_logged_out on {!r}".format(listener))
self._logger.exception("Error in on_user_logged_out on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
self._logger.debug("Logged out user: %r" % user)
self._logger.info("Logged out user: {}".format(user.get_id()))
def _cleanup_sessions(self):
for session, user in self._session_users_by_session.items():
for session, user in list(self._session_users_by_session.items()):
if not isinstance(user, SessionUser):
continue
if user.created + (24 * 60 * 60) < monotonic_time():
self.logout_user(user)
self._logger.info("Cleaning up user session {} for user {}".format(session, user.get_id()))
self.logout_user(user, stale=True)
@staticmethod
def create_password_hash(password, salt=None):
def create_password_hash(password, salt=None, settings=None):
if not salt:
salt = settings().get(["accessControl", "salt"])
if settings is None:
settings = s()
salt = settings.get(["accessControl", "salt"])
if salt is None:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
salt = "".join(choice(chars) for _ in range(32))
settings().set(["accessControl", "salt"], salt)
settings().save()
settings.set(["accessControl", "salt"], salt)
settings.save()
return hashlib.sha512(to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)).hexdigest()
@@ -154,13 +172,16 @@ class UserManager(GroupChangeListener, object):
if not user:
return False
hash = UserManager.create_password_hash(password)
hash = UserManager.create_password_hash(password,
settings=self._settings)
if user.check_password(hash):
# new hash matches, correct password
return True
else:
# new hash doesn't match, but maybe the old one does, so check that!
oldHash = UserManager.create_password_hash(password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW")
oldHash = UserManager.create_password_hash(password,
salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW",
settings=self._settings)
if user.check_password(oldHash):
# old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
self.change_user_password(username, password)
@@ -261,7 +282,8 @@ class UserManager(GroupChangeListener, object):
for user in users:
listener.on_user_modified(user)
except Exception:
self._logger.exception("Error in on_user_modified on {!r}".format(listener))
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
def on_group_subgroups_changed(self, group, added=None, removed=None):
users = self.find_sessions_for(lambda u: group in u.groups)
@@ -271,7 +293,8 @@ class UserManager(GroupChangeListener, object):
for user in users:
listener.on_user_modified(user)
except Exception:
self._logger.exception("Error in on_user_modified on {!r}".format(listener))
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
def _trigger_on_user_modified(self, user):
if isinstance(user, basestring):
@@ -300,14 +323,16 @@ class UserManager(GroupChangeListener, object):
for user in users:
listener.on_user_modified(user)
except Exception:
self._logger.exception("Error in on_user_modified on {!r}".format(listener))
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
def _trigger_on_user_removed(self, username):
for listener in self._login_status_listeners:
try:
listener.on_user_removed(username)
except Exception:
self._logger.exception("Error in on_user_removed on {!r}".format(listener))
self._logger.exception("Error in on_user_removed on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
#~~ Deprecated methods follow
@@ -415,7 +440,7 @@ class LoginStatusListener(object):
def on_user_logged_in(self, user):
pass
def on_user_logged_out(self, user):
def on_user_logged_out(self, user, stale=False):
pass
def on_user_modified(self, user):
@@ -428,13 +453,13 @@ class LoginStatusListener(object):
##~~ FilebasedUserManager, takes available users from users.yaml file
class FilebasedUserManager(UserManager):
def __init__(self, group_manager, path=None):
UserManager.__init__(self, group_manager)
def __init__(self, group_manager, path=None, settings=None):
UserManager.__init__(self, group_manager, settings=settings)
if path is None:
path = settings().get(["accessControl", "userfile"])
path = self._settings.get(["accessControl", "userfile"])
if path is None:
path = os.path.join(settings().getBaseFolder("base"), "users.yaml")
path = os.path.join(s().getBaseFolder("base"), "users.yaml")
self._userfile = path
@@ -537,7 +562,13 @@ class FilebasedUserManager(UserManager):
if username in self._users and not overwrite:
raise UserAlreadyExists(username)
self._users[username] = User(username, UserManager.create_password_hash(password), active, permissions, groups, apikey=apikey)
self._users[username] = User(username,
UserManager.create_password_hash(password,
settings=self._settings),
active,
permissions,
groups,
apikey=apikey)
self._dirty = True
self._save()
@@ -670,7 +701,8 @@ class FilebasedUserManager(UserManager):
if not username in self._users:
raise UnknownUser(username)
passwordHash = UserManager.create_password_hash(password)
passwordHash = UserManager.create_password_hash(password,
settings=self._settings)
user = self._users[username]
if user._passwordHash != passwordHash:
user._passwordHash = passwordHash
@@ -718,7 +750,7 @@ class FilebasedUserManager(UserManager):
raise UnknownUser(username)
user = self._users[username]
user._apikey = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
user._apikey = generate_api_key()
self._dirty = True
self._save()
return user._apikey
@@ -1097,6 +1129,12 @@ class User(UserMixin):
def groups(self):
return list(self._groups)
@property
def effective_permissions(self):
if self._permissions is None:
return []
return list(filter(lambda p: p is not None and self.has_permission(p), Permissions.all()))
@property
def needs(self):
needs = set()
@@ -1115,8 +1153,6 @@ class User(UserMixin):
return self.has_needs(*permission.needs)
def has_needs(self, *needs):
if Permissions.ADMIN in self._permissions:
return True
return set(needs).issubset(self.needs)
def __repr__(self):
+2 -1
View File
@@ -138,9 +138,10 @@ from .dev import dev_commands
from .client import client_commands
from .config import config_commands
from .analysis import analysis_commands
from .user import user_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands])
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
+184
View File
@@ -0,0 +1,184 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import logging
from octoprint import init_settings
from octoprint.cli import get_ctx_obj_option
from octoprint.access.groups import FilebasedGroupManager
from octoprint.access.users import FilebasedUserManager, UnknownUser, UserAlreadyExists
from octoprint.util import get_class, sv
click.disable_unicode_literals_warning = True
#~~ "octoprint user" commands
@click.group()
def user_commands():
pass
@user_commands.group(name="user")
@click.pass_context
def user(ctx):
"""
User management.
Note that this currently only supports managing user accounts stored in the configured user manager, not any
user managers added through plugins and the "octoprint.users.factory" hook.
"""
try:
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
group_manager_name = settings.get(["accessControl", "groupManager"])
try:
clazz = get_class(group_manager_name)
group_manager = clazz()
except AttributeError:
click.echo("Could not instantiate group manager {}, "
"falling back to FilebasedGroupManager!".format(group_manager_name), err=True)
group_manager = FilebasedGroupManager()
ctx.obj.group_manager = group_manager
name = settings.get(["accessControl", "userManager"])
try:
clazz = get_class(name)
user_manager = clazz(group_manager=group_manager, settings=settings)
except Exception:
click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True)
user_manager = FilebasedUserManager(group_manager, settings=settings)
finally:
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
ctx.obj.user_manager = user_manager
except Exception:
click.echo("Could not instantiate user manager", err=True)
return
@user.command(name="list")
@click.pass_context
def list_users_command(ctx):
"""Lists user information"""
users = ctx.obj.user_manager.get_all_users()
_print_list(users)
@user.command(name="add")
@click.argument("username", type=click.STRING, required=True)
@click.password_option("--password", "password", help="Password for the user")
@click.option("-g", "--group", "groups", multiple=True,
help="Groups to set on the user")
@click.option("-p", "--permission", "permissions", multiple=True,
help="Individual permissions to set on the user")
@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False,
help="Adds user to admin group")
@click.pass_context
def add_user_command(ctx, username, password, groups, permissions, is_admin):
"""Add a new user."""
if not groups:
groups = []
if is_admin:
groups.append(ctx.obj.group_manager.admin_group)
try:
ctx.obj.user_manager.add_user(username,
password,
groups=groups,
permissions=permissions,
active=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
except UserAlreadyExists:
click.echo("A user with the name {} does already exist!".format(username), err=True)
@user.command(name="remove")
@click.argument("username", type=click.STRING)
@click.pass_context
def remove_user_command(ctx, username):
"""Remove an existing user."""
confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm",
type=click.STRING)
if confirm.lower() == "yes":
ctx.obj.user_manager.remove_user(username)
click.echo("User {} removed.".format(username))
else:
click.echo("User {} not removed.".format(username))
@user.command(name="password")
@click.argument("username", type=click.STRING)
@click.password_option("--password", "password", help="New password for user")
@click.pass_context
def change_password_command(ctx, username, password):
"""Change an existing user's password."""
try:
ctx.obj.user_manager.change_user_password(username, password)
click.echo("Password changed for user {}.".format(username))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="activate")
@click.argument("username", type=click.STRING)
@click.pass_context
def activate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, True)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="deactivate")
@click.argument("username", type=click.STRING)
@click.pass_context
def deactivate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, False)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
def _print_list(users):
click.echo("{} users registered in the system:".format(len(users)))
for user in sorted(map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))):
click.echo("\t{}".format(_user_to_line(user)))
def _user_to_line(user):
return "{name}" \
"\n\t\tactive: {active}" \
"\n\t\tgroups: {groups}" \
"\n\t\tpermissions: {permissions}".format(name=user.get("name"),
active=user.get("active", "False"),
groups=", ".join(user.get("groups", [])),
permissions=", ".join(user.get("permissions", [])))
-7
View File
@@ -1,7 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
-215
View File
@@ -1,215 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import io
try:
from os import scandir
except ImportError:
from scandir import scandir
from octoprint.settings import settings
from octoprint.util import is_hidden_path
class ConnectionProfile(object):
def __init__(self, id, name=None, printer_profile=None, protocol=None, protocol_parameters=None, transport=None, transport_parameters=None, **kwargs):
self.id = id
self.name = name if name is not None else id
self.printer_profile = printer_profile
self.protocol = protocol
self.protocol_parameters = protocol_parameters
self.transport = transport
self.transport_parameters = transport_parameters
@classmethod
def from_dict(cls, data):
identifier = data.pop("id")
return ConnectionProfile(identifier, **data)
def as_dict(self):
return dict(id=self.id,
name=self.name,
printer_profile=self.printer_profile,
protocol=self.protocol,
protocol_parameters=self.protocol_parameters,
transport=self.transport,
transport_parameters=self.transport_parameters)
class ConnectionProfileManager(object):
@classmethod
def to_profile(cls, data):
return ConnectionProfile.from_dict(data)
def __init__(self):
self._current = None
self._folder = settings().getBaseFolder("connectionProfiles")
self._logger = logging.getLogger(__name__)
def select(self, identifier):
self._current = self.get(identifier)
if self._current is None:
self._logger.error("Profile {} is invalid, cannot select".format(identifier))
return False
return True
def deselect(self):
self._current = None
@property
def current(self):
return self._current
def get_all(self):
return self._load_all()
def get(self, identifier):
try:
if self.exists(identifier):
return self._load_from_path(self._get_profile_path(identifier))
else:
return None
except InvalidProfileError:
return None
def remove(self, identifier):
return self._remove_from_path(self._get_profile_path(identifier))
def save(self, profile, allow_overwrite=False, make_default=False):
self._save_to_path(self._get_profile_path(profile.id),
profile,
allow_overwrite=allow_overwrite)
if make_default:
self.set_default(profile.id)
return self.get(profile.id)
@property
def profile_count(self):
return len(self._load_all_identifiers())
@property
def last_modified(self):
dates = [os.stat(self._folder).st_mtime]
dates += [entry.stat().st_mtime for entry in scandir(self._folder) if entry.name.endswith(".profile")]
return max(dates)
def get_default(self):
default = settings().get(["connectionProfiles", "default"])
if default is not None and self.exists(default):
profile = self.get(default)
if profile is not None:
return profile
else:
self._logger.warning("Default profile {} is invalid".format(default))
return None
def set_default(self, identifier):
all_identifiers = self._load_all_identifiers()
if identifier is not None and identifier not in all_identifiers:
return
settings().set(["connectionProfiles", "default"], identifier)
settings().save()
def get_current_or_default(self):
if self._current is not None:
return self._current
else:
return self.get_default()
def get_current(self):
return self._current
def exists(self, identifier):
if identifier is None:
return False
path = self._get_profile_path(identifier)
return os.path.exists(path) and os.path.isfile(path)
def _load_all(self):
all_identifiers = self._load_all_identifiers()
results = dict()
for identifier, path in all_identifiers.items():
try:
profile = self._load_from_path(path)
except InvalidProfileError:
self._logger.warning("Profile {} is invalid, skipping".format(identifier))
continue
if profile is None:
continue
results[identifier] = profile
return results
def _load_all_identifiers(self):
results = dict()
for entry in scandir(self._folder):
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
continue
if not entry.is_file():
continue
identifier = entry.name[:-len(".profile")]
results[identifier] = entry.path
return results
def _load_from_path(self, path):
if not os.path.exists(path) or not os.path.isfile(path):
return None
import yaml
with io.open(path, 'rt', encoding='utf-8') as f:
data = yaml.safe_load(f)
if data is None or not isinstance(data, dict):
raise InvalidProfileError("Profile is None or not a dict")
return ConnectionProfile.from_dict(data)
def _save_to_path(self, path, profile, allow_overwrite=False):
if os.path.exists(path) and not allow_overwrite:
raise SaveError("Profile {} already exists and overwriting is not allowed".format(profile["id"]))
from octoprint.util import atomic_write
import yaml
try:
with atomic_write(path, mode="wt", max_permissions=0o666) as f:
yaml.safe_dump(profile.as_dict(), f,
default_flow_style=False,
indent=2,
allow_unicode=True)
except Exception as e:
self._logger.exception("Error while trying to save profile {}".format(profile["id"]))
raise SaveError("Cannot save profile {}: {}".format(profile["id"], e))
def _remove_from_path(self, path):
try:
os.remove(path)
return True
except Exception:
return False
def _get_profile_path(self, identifier):
return os.path.join(self._folder, "{}.profile".format(identifier))
class InvalidProfileError(Exception):
pass
class SaveError(Exception):
pass
-573
View File
@@ -1,573 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import copy
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener, ProtocolState, FileManagementProtocolMixin
from octoprint.util.listener import ListenerAware
from abc import ABCMeta, abstractmethod, abstractproperty
from octoprint.util import monotonic_time
from future.utils import with_metaclass
class LastResult(object):
def __init__(self):
self.elapsed = None
self.clean_elapsed = None
self.progress = None
self.pos = None
self.success = None
self.available = False
class Printjob(with_metaclass(ABCMeta, ProtocolListener, ListenerAware)):
parallel = False
"""Job runs parallel to regular communication."""
exclusive = False
"""Job has exclusive claim to communication channel."""
def __init__(self, name=None, user=None, event_data=None):
if event_data is None:
event_data = dict()
super(Printjob, self).__init__()
self._logger = logging.getLogger(__name__)
self._start = None
self._protocol = None
self._printer_profile = None
self._name = name
self._user = user
self._event_data = event_data
self._lost_time = 0
self._last_result = LastResult()
@property
def name(self):
return self._name
@property
def user(self):
return self._user
@property
def size(self):
return None
@property
def pos(self):
return None
@property
def elapsed(self):
return monotonic_time() - self._start if self._start is not None else None
@property
def clean_elapsed(self):
elapsed = self.elapsed
if elapsed is None:
return None
return elapsed - self._lost_time
@property
def last_result(self):
return self._last_result
@property
def progress(self):
size = self.size
pos = self.pos
if pos is None or size is None or size == 0:
return None
return float(pos) / float(size)
@property
def active(self):
return self._start is not None
def add_to_lost_time(self, value):
self._lost_time += value
def can_process(self, protocol):
return False
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
self._last_result = LastResult()
self._start = monotonic_time()
self._user = user
self._protocol = protocol
self._protocol.register_listener(self)
def pause(self, user=None, tags=None, **kwargs):
self.process_job_paused(user=user, tags=tags, **kwargs)
def resume(self, user=None, tags=None, **kwargs):
self.process_job_resumed(user=user, tags=tags, **kwargs)
def cancel(self, error=False, user=None, tags=None, **kwargs):
if error:
self.process_job_failed(**kwargs)
else:
self.process_job_cancelled(user=user, tags=tags, **kwargs)
self._protocol.unregister_listener(self)
self._protocol = None
def get_next(self):
return None
def can_get_content(self):
return False
def get_content_generator(self):
return None
def event_payload(self, incl_last=False):
payload = copy.deepcopy(self._event_data)
payload["owner"] = self._user
elapsed = self.elapsed
if elapsed is None and incl_last and self.last_result.available:
elapsed = self.last_result.elapsed
if elapsed is not None:
payload["time"] = elapsed
return payload
def process_job_started(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_started", self, user=user, tags=tags, **kwargs)
def process_job_done(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_done", self, user=user, tags=tags, **kwargs)
self.report_stats()
self.reset_job()
def process_job_failed(self, **kwargs):
self.notify_listeners("on_job_failed", self, **kwargs)
self.report_stats()
self.reset_job(success=False)
def process_job_cancelled(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_cancelled", self, user=user, tags=tags, **kwargs)
self.report_stats()
self.reset_job(success=False)
def process_job_paused(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_paused", self, user=user, tags=tags, **kwargs)
def process_job_resumed(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_resumed", self, user=user, tags=tags, **kwargs)
def process_job_progress(self):
self.notify_listeners("on_job_progress", self)
def report_stats(self):
elapsed = self.elapsed
if elapsed:
self._logger.info("Job processed in {}s".format(elapsed))
def reset_job(self, success=True):
self._last_result.progress = 1.0 if success else self.progress
self._last_result.pos = self.size if success else self.pos
self._last_result.elapsed = self.elapsed
self._last_result.clean_elapsed = self.clean_elapsed
self._last_result.success = success
self._last_result.available = True
self._start = None
self._lost_time = 0
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
if new_state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) and self.active:
self.cancel(error=True)
class StoragePrintjob(Printjob):
def __init__(self, storage, path_in_storage, *args, **kwargs):
Printjob.__init__(self, *args, **kwargs)
self._storage = storage
self._path_in_storage = path_in_storage
@property
def storage(self):
return self._storage
@property
def path_in_storage(self):
return self._path_in_storage
def event_payload(self, incl_last=False):
payload = Printjob.event_payload(self, incl_last=incl_last)
payload["name"] = self.name
payload["path"] = self.path_in_storage
payload["origin"] = self.storage
return payload
class LocalFilePrintjob(StoragePrintjob):
def __init__(self, path, *args, **kwargs):
encoding = kwargs.pop("encoding", "utf-8")
StoragePrintjob.__init__(self, *args, **kwargs)
if path is None or not os.path.exists(path):
raise ValueError("path must be set to a local file path")
self._path = path
self._encoding = encoding
self._size = os.stat(path).st_size
self._pos = 0
self._read_lines = 0
self._actual_lines = 0
self._cancel_pos = None
self._handle = None
@property
def size(self):
return self._size
@property
def pos(self):
return self._pos
@property
def actual_lines(self):
return self._actual_lines
@property
def read_lines(self):
return self._read_lines
@property
def cancel_pos(self):
return self._cancel_pos
@property
def active(self):
return self._start is not None and self._handle is not None
@property
def path(self):
return self._path
def event_payload(self, incl_last=False):
event_data = StoragePrintjob.event_payload(self, incl_last=incl_last)
event_data["size"] = self.size
return event_data
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs)
from octoprint.util import bom_aware_open
self._handle = bom_aware_open(self._path, encoding=self._encoding, errors="replace")
if position > 0:
self._handle.seek(position)
self._pos = position
self.process_job_started(user=user, tags=tags)
def cancel(self, error=False, user=None, tags=None, **kwargs):
self._cancel_pos = self.pos
super(LocalFilePrintjob, self).cancel(error=error, user=user, tags=tags, **kwargs)
def get_next(self):
from octoprint.util import to_unicode
if self._handle is None:
raise ValueError("File {} is not open for reading" % self._path)
try:
processed = None
while processed is None:
if self._handle is None:
# file got closed just now
self.process_job_done()
return None
line = to_unicode(self._handle.readline())
# we need to manually keep track of our pos here since
# codecs' readline will make our handle's tell not
# return the actual number of bytes read, but also the
# already buffered bytes (for detecting the newlines)
self._pos += len(line)
self._actual_lines += 1
if not line:
self.process_job_done()
return None
processed = self.process_line(line)
self._read_lines += 1
self.process_job_progress()
return processed
except Exception as e:
self.cancel(error=True)
self._logger.exception("Exception while processing line")
raise e
def process_line(self, line):
return line
def close(self):
if self._handle is not None:
try:
self._handle.close()
except Exception:
pass
self._handle = None
def can_get_content(self):
return True
def get_content_generator(self):
from octoprint.util import bom_aware_open
with bom_aware_open(self._path, encoding=self._encoding, error="replace") as f:
for line in f.readline():
yield line
def reset_job(self, success=True):
super(LocalFilePrintjob, self).reset_job(success=success)
self.close()
self._pos = self._read_lines = 0
def report_stats(self):
elapsed = self.elapsed
lines = self._read_lines
if elapsed and lines:
self._logger.info("Job processed in {:.3f}s ({} lines)".format(elapsed, lines))
class LocalGcodeFilePrintjob(LocalFilePrintjob):
def can_process(self, protocol):
return LocalGcodeFilePrintjob in protocol.supported_jobs
def process_line(self, line):
# TODO no dependency on protocol module
from octoprint.comm.protocol.reprap.util import strip_comment
# strip line
processed = line.strip()
# strip comments
processed = strip_comment(processed)
if not len(processed):
return None
# TODO apply offsets
# return result
return processed
class CopyJobMixin(object):
pass
class LocalGcodeStreamjob(LocalGcodeFilePrintjob, CopyJobMixin):
exclusive = True
@classmethod
def from_job(cls, job, remote):
if not isinstance(job, LocalGcodeFilePrintjob):
raise ValueError("job must be a LocalGcodeFilePrintjob")
path = job._path
storage = job._storage
path_in_storage = job._path_in_storage
name = job._name
user = job._user
encoding = job._encoding
event_data = job._event_data
return cls(remote, path, storage, path_in_storage,
name=name, user=user, encoding=encoding, event_data=event_data)
def __init__(self, remote, *args, **kwargs):
super(LocalGcodeStreamjob, self).__init__(*args, **kwargs)
self._remote = remote
@property
def remote(self):
return self._remote
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
super(LocalGcodeStreamjob, self).process(protocol, position=position, user=user, tags=tags, **kwargs)
self._protocol.record_file(self._remote)
def process_job_done(self, user=None, tags=None, **kwargs):
self._protocol.stop_recording_file()
super(LocalGcodeStreamjob, self).process_job_done(user=user, tags=tags, **kwargs)
def process_job_failed(self, **kwargs):
self._protocol.stop_recording_file()
super(LocalGcodeStreamjob, self).process_job_failed(**kwargs)
def process_job_cancelled(self, user=None, tags=None, **kwargs):
self._protocol.stop_recording_file()
self._protocol.delete_file(self.remote)
super(LocalGcodeStreamjob, self).process_job_cancelled(user=user, tags=tags, **kwargs)
def can_process(self, protocol):
from octoprint.comm.protocol import FileStreamingProtocolMixin
return LocalGcodeStreamjob in protocol.supported_jobs and isinstance(protocol, FileStreamingProtocolMixin) and isinstance(protocol, FileManagementProtocolMixin)
def report_stats(self):
elapsed = self.elapsed
lines = self._read_lines
if elapsed and lines:
self._logger.info("Job processed in {:.3f}s ({} lines). Approx. {:.3f} lines/s, {:.3f} ms/line".format(elapsed,
lines,
float(lines) / float(elapsed),
float(elapsed) * 1000.0 / float(lines)))
class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener):
parallel = True
def __init__(self, path, status_interval=2.0, *args, **kwargs):
name = path
if name.startswith("/"):
name = name[1:]
StoragePrintjob.__init__(self,
"sdcard",
name,
name=name,
event_data=dict(name=name,
path=path,
origin="sdcard"))
self._filename = path
self._status_interval = status_interval
self._status_timer = None
self._active = False
self._size = None
self._last_pos = None
@property
def size(self):
return self._size
@property
def pos(self):
return self._last_pos
@property
def active(self):
return self._start is not None and self._active
@property
def status_interval(self):
return self._status_interval
def can_process(self, protocol):
from octoprint.comm.protocol import FileAwareProtocolMixin
return SDFilePrintjob in protocol.supported_jobs and isinstance(protocol, FileAwareProtocolMixin)
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs)
self._protocol.register_listener(self)
self._active = True
self._last_pos = position
self._protocol.start_file_print(self._filename,
position=position,
user=user,
tags=tags,
part_of_job=True,
**kwargs)
self._protocol.start_file_print_status_monitor()
def pause(self, user=None, tags=None, **kwargs):
super(SDFilePrintjob, self).pause(user=user, tags=tags, **kwargs)
self._protocol.pause_file_print(user=user,
tags=tags,
part_of_job=True,
**kwargs)
def resume(self, user=None, tags=None, **kwargs):
super(SDFilePrintjob, self).resume(user=user, tags=tags, **kwargs)
self._protocol.resume_file_print(user=user,
tags=tags,
part_of_job=True,
**kwargs)
def on_protocol_sd_status(self, protocol, pos, total):
self._last_pos = pos
self._size = total
self.process_job_progress()
def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs):
self._size = size
self.process_job_started(**kwargs)
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
self._protocol.stop_file_print_status_monitor(**kwargs)
self.process_job_done(**kwargs)
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
self._protocol.pause_file_print(**kwargs)
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
self._protocol.resume_file_print(**kwargs)
def reset_job(self, success=True):
super(SDFilePrintjob, self).reset_job(success=success)
self._active = False
self._last_pos = None
self._size = None
def event_payload(self, incl_last=False):
payload = Printjob.event_payload(self, incl_last=incl_last)
payload["size"] = self.size
return payload
class PrintjobListener(object):
def on_job_started(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_done(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_failed(self, job, *args, **kwargs):
pass
def on_job_cancelling(self, job, firmware_error=None, *args, **kwargs):
pass
def on_job_cancelled(self, job, cancel_position=None, suppress_script=False, *args, **kwargs):
pass
def on_job_paused(self, job, pause_position=None, suppress_script=False, *args, **kwargs):
pass
def on_job_resumed(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_progress(self, job, *args, **kwargs):
pass
-542
View File
@@ -1,542 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.transport import TransportListener, TransportState
from octoprint.plugin import plugin_manager
from octoprint.util import to_unicode, CountedEvent
from octoprint.util.listener import ListenerAware
from octoprint.settings import SubSettings
import contextlib
import copy
import logging
_registry = dict()
def register_protocols():
from .reprap import ReprapGcodeProtocol
logger = logging.getLogger(__name__)
# stock protocols
register_protocol(ReprapGcodeProtocol)
# more protocols provided by plugins
hooks = plugin_manager().get_hooks("octoprint.comm.protocol.register")
for name, hook in hooks.items():
try:
protocols = hook()
for protocol in protocols:
try:
register_protocol(protocol)
except Exception:
logger.exception("Error while registering protocol class {} for plugin {}".format(protocol, name))
except Exception:
logger.exception("Error executing octoprint.comm.protocol.register hook for plugin {}".format(name))
def register_protocol(protocol_class):
if not hasattr(protocol_class, "key"):
raise ValueError("Protocol class {} is missing key".format(protocol_class))
_registry[protocol_class.key] = protocol_class
def lookup_protocol(key):
return _registry.get(key)
def all_protocols():
return _registry.values()
class Protocol(ListenerAware, TransportListener):
name = None
key = None
supported_jobs = []
@classmethod
def get_connection_options(cls):
return []
@classmethod
def get_settings_defaults(cls):
return dict()
def __init__(self, *args, **kwargs):
super(Protocol, self).__init__()
self._logger = logging.getLogger(__name__)
self._protocol_logger = logging.getLogger("PROTOCOL")
self._state = ProtocolState.DISCONNECTED
self._error = None
self._printer_profile = kwargs.get("printer_profile")
self._plugin_manager = kwargs.get("plugin_manager")
self._event_bus = kwargs.get("event_bus")
self._settings = kwargs.get("settings")
if not isinstance(self._settings, ProtocolSettings):
self._settings = ProtocolSettings(self._settings, self)
self._job = None
self._transport = None
self._job_on_hold = CountedEvent()
self._args = dict()
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@contextlib.contextmanager
def job_put_on_hold(self, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
raise RuntimeError("Could not acquire job_on_hold lock")
self._job_on_hold.set()
try:
yield
finally:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._job_on_hold_cleared()
self._job_on_hold.release()
@property
def job_on_hold(self):
return self._job_on_hold.counter > 0
def set_job_on_hold(self, value, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
return False
try:
if value:
self._job_on_hold.set()
else:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._job_on_hold_cleared()
finally:
self._job_on_hold.release()
return True
@property
def transport(self):
return self._transport
@property
def state(self):
return self._state
@state.setter
def state(self, new_state):
old_state = self._state
if old_state == new_state:
return
self._state = new_state
name = "_on_switching_state_{}".format(new_state)
method = getattr(self, name, None)
if method is not None:
method(old_state)
self.process_protocol_log("--- Protocol state changed from '{}' to '{}'".format(old_state, new_state))
self.notify_listeners("on_protocol_state", self, old_state, new_state)
name = "_on_switched_state_{}".format(new_state)
method = getattr(self, name, None)
if method is not None:
method(old_state)
@property
def error(self):
return self._error
@error.setter
def error(self, new_error):
self._error = new_error
def connect(self, transport, transport_args=None, transport_kwargs=None):
if self.state not in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR):
raise ProtocolAlreadyConnectedError("Already connected, disconnect first")
self.process_protocol_log("--- Protocol {} connecting via transport {}...".format(self,
transport))
if transport_args is None:
transport_args = []
if transport_kwargs is None:
transport_kwargs = dict()
self._transport = transport
self._transport.register_listener(self)
if self._transport.state == TransportState.DISCONNECTED:
self._transport.connect(*transport_args, **transport_kwargs)
self.state = ProtocolState.CONNECTING
def disconnect(self, error=False):
if self.state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR, ProtocolState.DISCONNECTING, ProtocolState.DISCONNECTING_WITH_ERROR):
raise ProtocolNotConnectedError("Already disconnecting or disconnected")
if error:
self.state = ProtocolState.DISCONNECTING_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTING
self.process_protocol_log("--- Protocol {} disconnecting from transport {}...".format(self,
self._transport))
self._transport.unregister_listener(self)
if self._transport.state == TransportState.CONNECTED:
try:
self._transport.disconnect()
except Exception:
self._logger.exception("Error while disconnecting from transport {}".format(self._transport))
error = True
if error:
self.state = ProtocolState.DISCONNECTED_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTED
def process(self, job, position=0, user=None, tags=None, **kwargs):
if not job.can_process(self):
raise ValueError("Job {} cannot be processed with protocol {}".format(job, self))
self._job = job
self._job.register_listener(self)
self.state = ProtocolState.STARTING
self.notify_listeners("on_protocol_job_starting", self, self._job, user=user, tags=tags, **kwargs)
self._job.process(self, position=position, user=user, tags=tags, **kwargs)
def pause_processing(self, user=None, tags=None, **kwargs):
if self._job is None or self.state not in ProtocolState.PROCESSING_STATES:
return
self.state = ProtocolState.PAUSING
self.notify_listeners("on_protocol_job_pausing", self, self._job, user=user, tags=tags, **kwargs)
self._job.pause(user=user, tags=tags)
def resume_processing(self, user=None, tags=None, **kwargs):
if self._job is None or self.state not in (ProtocolState.PAUSING, ProtocolState.PAUSED):
return
self.state = ProtocolState.RESUMING
self.notify_listeners("on_protocol_job_resuming", self, self._job, user=user, tags=tags, **kwargs)
self._job.resume(user=user, tags=tags, **kwargs)
def cancel_processing(self, error=False, user=None, tags=None, **kwargs):
if self._job is not None and self.state in ProtocolState.PROCESSING_STATES + (ProtocolState.PAUSED,):
self.state = ProtocolState.CANCELLING
self.notify_listeners("on_protocol_job_cancelling", self, self._job, user=user, tags=tags, **kwargs)
self._job.cancel(error=error, user=user, tags=tags, **kwargs)
def can_send(self):
return True
def send_commands(self, command_type=None, tags=None, *commands):
pass
def send_script(self, script, context=None, user=None, tags=None):
"""
Sends the specified script/the GCODE script with the specified name.
Args:
script (GcodeScript or unicode): Script or name of the script to send
context (dict): Additional render context
user (str): The user on whose behalf the script is being sent. May be None
tags (set): And tags to send with the script commands. May be None
"""
pass
def repair(self):
pass
def on_job_started(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_started", self, job, *args, **kwargs)
self.state = ProtocolState.PROCESSING
def on_job_paused(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_paused", self, job, *args, **kwargs)
self.state = ProtocolState.PAUSED
def on_job_resumed(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_resumed", self, job, *args, **kwargs)
self.state = ProtocolState.PROCESSING
def on_job_done(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_done", self, job, *args, **kwargs)
self._job_processed(job)
def on_job_cancelled(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_cancelled", self, job, *args, **kwargs)
self._job_processed(job)
def on_job_failed(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_failed", self, job, *args, **kwargs)
self._job_processed(job)
def _job_processed(self, job, *args, **kwargs):
self._job.unregister_listener(self)
self.state = ProtocolState.CONNECTED
def on_transport_disconnected(self, transport, error=None):
self.disconnect(error=error is not None)
def on_transport_log_received_data(self, transport, data):
message = "<<< {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
def on_transport_log_sent_data(self, transport, data):
message = ">>> {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
def on_transport_log_message(self, transport, data):
message = "--- {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
def process_protocol_log(self, message):
self._protocol_logger.info(message)
self.notify_listeners("on_protocol_log", self, message)
def _job_on_hold_cleared(self):
pass
def __str__(self):
return self.__class__.__name__
class ProtocolState(object):
CONNECTING = "connecting"
CONNECTED = "connected"
DISCONNECTING = "disconnecting"
DISCONNECTED = "disconnected"
STARTING = "starting"
PROCESSING = "processing"
FINISHING = "finishing"
CANCELLING = "cancelling"
PAUSING = "pausing"
RESUMING = "resuming"
PAUSED = "paused"
ERROR = "error"
DISCONNECTING_WITH_ERROR = "disconnecting_with_error"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
PROCESSING_STATES = (STARTING, PROCESSING, CANCELLING, PAUSING, RESUMING, FINISHING)
OPERATIONAL_STATES = (CONNECTED, PAUSED) + PROCESSING_STATES
class ProtocolSettings(SubSettings):
def __init__(self, settings, protocol):
SubSettings.__init__(self, settings, ["comm", "protocol", protocol.key],
defaults=protocol.get_settings_defaults())
class ProtocolAlreadyConnectedError(Exception):
pass
class ProtocolNotConnectedError(Exception):
pass
class ThreeAxisProtocolMixin(object):
def move(self, x=None, y=None, z=None, feedrate=None, relative=False, *args, **kwargs):
pass
def home(self, x=False, y=False, z=False, *args, **kwargs):
pass
class MultiToolProtocolMixin(object):
def change_tool(self, tool, *args, **kwargs):
pass
class ThreeDPrinterProtocolMixin(ThreeAxisProtocolMixin, MultiToolProtocolMixin):
def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False, *args, **kwargs):
pass
def set_feedrate_multiplier(self, multiplier, *args, **kwargs):
pass
def set_extrusion_multiplier(self, multiplier, *args, **kwargs):
pass
def set_extruder_temperature(self, temperature, tool=None, wait=False, *args, **kwargs):
pass
def set_bed_temperature(self, temperature, wait=False, *args, **kwargs):
pass
def set_chamber_temperature(self, temperature, wait=False, *args, **kwargs):
pass
class FanControlProtocolMixin(object):
def set_fan_speed(self, speed, *args, **kwargs):
pass
def get_fan_speed(self, speed, *args, **kwargs):
pass
class MotorControlProtocolMixin(object):
def enable_motors(self, *args, **kwargs):
self.set_motor_state(True)
def disable_motors(self, *args, **kwargs):
self.set_motor_state(False)
def set_motor_state(self, enabled, *args, **kwargs):
pass
def get_motor_state(self, *args, **kwargs):
pass
class PowerControlProtocolMixin(object):
def enable_power(self, *args, **kwargs):
self.set_power_state(True)
def disable_power(self, *args, **kwargs):
self.set_power_state(False)
def set_power_state(self, enabled, *args, **kwargs):
pass
def get_power_state(self, *args, **kwargs):
return None
class FileAwareProtocolMixin(object):
def init_file_storage(self, *args, **kwargs):
pass
def eject_file_storage(self, *args, **kwargs):
pass
def list_files(self, *args, **kwargs):
pass
def start_file_print(self, name, position=0, tags=None, *args, **kwargs):
pass
def pause_file_print(self, *args, **kwargs):
pass
def resume_file_print(self, *args, **kwargs):
pass
def get_file_print_status(self, *args, **kwargs):
pass
def start_file_print_status_monitor(self, *args, **kwargs):
pass
def stop_file_print_status_monitor(self, *args, **kwargs):
pass
class FileManagementProtocolMixin(FileAwareProtocolMixin):
def delete_file(self, name, *args, **kwargs):
pass
class FileStreamingProtocolMixin(FileManagementProtocolMixin):
def record_file(self, name, *args, **kwargs):
pass
def stop_recording_file(self, *args, **kwargs):
pass
class ProtocolListener(object):
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
pass
def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs):
pass
def on_protocol_log(self, protocol, message, *args, **kwargs):
pass
def on_protocol_reset(self, protocol, idle, *args, **kwargs):
pass
def on_protocol_job_started(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_pausing(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_paused(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_resuming(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_resumed(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_cancelling(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_finishing(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_done(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_failed(self, protocol, job, *args, **kwargs):
pass
class FileAwareProtocolListener(object):
def on_protocol_file_storage_available(self, protocol, available, *args, **kwargs):
pass
def on_protocol_file_list(self, protocol, files, *args, **kwargs):
pass
def on_protocol_file_status(self, protocol, pos, total, *args, **kwargs):
pass
def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs):
pass
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
pass
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
pass
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
pass
class PositionAwareProtocolListener(object):
def on_protocol_position_all_update(self, protocol, position, *args, **kwargs):
pass
def on_protocol_position_z_update(self, protocol, z, *args, **kwargs):
pass
class FirmwareDataAwareProtocolListener(object):
def on_protocol_firmware_info(self, protocol, info, *args, **kwargs):
pass
def on_protocol_firmware_capability(self, protocol, capability, enabled, capabilities, *args, **kwargs):
pass
File diff suppressed because it is too large. Load diff
@@ -1,93 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import re
from future.utils import with_metaclass
from octoprint.util import pp
_compiled_regex_type = type(re.compile(r"a"))
def _is_compiled_regex(obj):
return isinstance(obj, _compiled_regex_type)
__registry = dict()
def _register_command_class(cls):
__registry[cls.__name__] = cls
def to_command(line, type=None, tags=None, **kwargs):
if isinstance(line, Command):
return line
for cls in __registry.values():
if cls.pattern:
# noinspection PyUnresolvedReferences,PyProtectedMember
if _is_compiled_regex(cls.pattern) and cls.pattern.match(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
elif callable(cls.pattern) and cls.pattern(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
return Command.from_line(line, type=type, tags=tags, **kwargs)
class CommandMetaClass(type):
def __new__(mcs, *args, **kwargs):
c = type.__new__(mcs, *args, **kwargs)
_register_command_class(c)
return c
class Command(with_metaclass(CommandMetaClass, object)):
pattern = None
@classmethod
def from_line(cls, line, type=None, tags=None, **kwargs):
return cls(line, type=type, tags=tags, **kwargs)
def __init__(self, line, type=None, tags=None, **kwargs):
if tags is None:
tags = set()
self.line = line
self.bytes = line.encode("ascii", errors="replace")
self.type = type
self.tags = tags
def __repr__(self):
return "{}({!r},type={!r},tags={})".format(self.__class__.__name__, self.line, self.type, pp(self.tags))
def __str__(self):
return self.line
def __bytes__(self):
return self.bytes
def __key(self):
return self.line, self.type
def __eq__(self, other):
return self.__key() == other.__key()
def __hash__(self):
return hash(self.__key())
def with_type(self, type):
c = copy.deepcopy(self)
c.type = type
return c
def with_tags(self, tags):
if tags is None:
return self
c = copy.deepcopy(self)
c.tags |= tags
return c
@@ -1,40 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.commands import Command
from octoprint.util import pp
class AtCommand(Command):
pattern = staticmethod(lambda x: x.startswith("@"))
@staticmethod
def from_line(line, **kwargs):
split = line.split(None, 1)
if len(split) == 2:
atcommand = split[0]
parameters = split[1]
else:
atcommand = split[0]
parameters = ""
atcommand = atcommand[1:]
return AtCommand(line, atcommand, parameters, **kwargs)
def __init__(self, line, atcommand, parameters, **kwargs):
self.atcommand = atcommand
self.parameters = parameters
super(AtCommand, self).__init__(line, **kwargs)
def __repr__(self):
return "AtCommand({!r},{!r},{!r},type={!r},tags={}".format(self.line,
self.atcommand,
self.parameters,
self.type,
pp(self.tags))
@@ -1,134 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.commands import Command
import re
import string
from octoprint.util import pp
class GcodeCommand(Command):
pattern = staticmethod(lambda x: GcodeCommand.command_regex.match(x))
command_regex = re.compile(r"^\s*((?P<GM>[GM](?P<number>\d+))(\\.(?P<subcode>\d+))?|(?P<T>T(?P<tool>\d+))|(?P<F>F(?P<feedrate>\d+)))")
parameter_regex = re.compile(r"(?P<key>[A-Z])((?P<value>[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))")
possible_params = tuple(string.ascii_lowercase) + ("subcode", "param", "tool", "feedrate", "original")
@staticmethod
def from_line(line, **kwargs):
if isinstance(line, GcodeCommand):
return line
tags = kwargs.get("tags")
if tags is None:
tags = set()
command_type = kwargs.get("type")
line = line.strip()
code = ""
args = dict(original=line, type=command_type, tags=tags)
match = GcodeCommand.command_regex.match(line)
if match is None:
# not a gcode command
return Command.from_line(line, **kwargs)
if match.group("GM"):
code = match.group("GM")
if match.group("subcode"):
args["subcode"] = int(match.group("subcode"))
if match.group(0) != line:
rest = line[len(match.group(0)):]
while True:
matched_param = GcodeCommand.parameter_regex.search(rest)
if not matched_param:
break
key = matched_param.group("key").lower()
if matched_param.group("value"):
value = matched_param.group("value")
if "." in value:
value = float(value)
else:
value = int(value)
else:
value = True
args[key] = value
rest = rest[:matched_param.start()] + rest[matched_param.end():]
rest = rest.lstrip()
if rest:
args["param"] = rest
elif match.group("T"):
code = "T"
args["tool"] = int(match.group("tool"))
elif match.group("F"):
code = "F"
args["feedrate"] = int(match.group("feedrate"))
return GcodeCommand(code, **args)
def __init__(self, code, **kwargs):
self.code = code
self.subcode = kwargs.pop("subcode", None)
self.tool = kwargs.pop("tool", None)
self.feedrate = kwargs.pop("feedrate", None)
self.param = kwargs.pop("param", None)
self.original = kwargs.pop("original", None)
command_type = kwargs.pop("type", None)
tags = kwargs.pop("tags", None)
self.args = kwargs
if self.original is None:
line = self._to_line()
else:
line = self.original
super(GcodeCommand, self).__init__(line, type=command_type, tags=tags)
self._repr = self._to_repr()
def __getattr__(self, item):
if len(item) == 1:
return self.args.get(item, None)
raise AttributeError("'GcodeCommand' object has no attribute '{}'".format(item))
def __repr__(self):
return self._repr
def _to_line(self):
attr = []
for key in string.ascii_lowercase:
value = self.args.get(key, None)
if value is not None:
if value is True:
attr.append(key.upper())
else:
attr.append("{}{!r}".format(key.upper(), value))
attribute_str = " ".join(attr)
return "{}{}{}".format(self.code.upper(), " " + attribute_str if attribute_str else "",
" " + self.param if self.param else "")
def _to_repr(self):
args = [k + "=" + repr(getattr(self, k)) for k in self.possible_params if getattr(self, k, None) is not None]
return "GcodeCommand({!r}{},type={!r},tags={})".format(self.code,
"," + ",".join(args) if args else "",
self.type,
pp(self.tags))
@@ -1,44 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from .generic import * # noqa: F403
from .klipper import * # noqa: F403
from .marlin import * # noqa: F403
from .repetier import * # noqa: F403
from .reprapfirmware import * # noqa: F403
from .smoothieware import * # noqa: F403
from .anet import * # noqa: F403
from .malyan import * # noqa: F403
class FlavorOverride(object):
def __init__(self, flavor, overrides):
self._flavor = flavor
self._overrides = overrides
@property
def flavor(self):
return self._flavor
@flavor.setter
def flavor(self, value):
self._flavor = value
@property
def overrides(self):
return self._overrides
@overrides.setter
def overrides(self, value):
self._overrides = value
def __getattr__(self, item):
try:
return self._overrides[item]
except KeyError:
return getattr(self._flavor, item)
@@ -1,17 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from .repetier import RepetierFlavor
class AnetA8RepetierFlavor(RepetierFlavor):
key = "aneta8repetier"
name = "Anet A8"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "anet_a8" in firmware_name.lower()
@@ -1,706 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
import logging
import time
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
from octoprint.comm.protocol.reprap.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
from octoprint.util import chunks, monotonic_time
from future.utils import with_metaclass
_flavor_registry = dict()
def _register_flavor(cls):
key = getattr(cls, "key", None)
if key and not key in _flavor_registry:
_flavor_registry[key] = cls
def all_flavors():
return _flavor_registry.values()
def lookup_flavor(key):
return _flavor_registry.get(key)
class FlavorMeta(type):
def __new__(mcs, name, bases, class_dict):
cls = type.__new__(mcs, name, bases, class_dict)
_register_flavor(cls)
return cls
class GenericFlavor(with_metaclass(FlavorMeta, object)):
key = "generic"
name = "Generic Flavor"
logger = logging.getLogger(__name__)
unknown_requires_ack = False
unknown_with_checksum = False
always_send_checksum = False
never_send_checksum = False
detect_external_heatups = True
block_while_dwelling = False
trigger_ok_after_resend = "detect"
sd_relative_path = False
checksum_requiring_commands = ["M110"]
long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"]
asynchronous_commands = ["G0", "G1", "G2", "G3"]
blocked_commands = ["M0", "M1"]
pausing_commands = ["M0", "M1", "M25"]
emergency_commands = ["M112", "M108", "M410"]
heatup_abortable = False
regex_resend_linenumber = re.compile(r"(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
regex_temp = re.compile(r"(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*/?\s*(?P<target>%s))?" % (
regex_positive_float_pattern, regex_positive_float_pattern))
"""Regex matching temperature entries in line.
Groups will be as follows:
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
* ``toolnum``: tool number, if provided (int)
* ``actual``: actual temperature (float)
* ``target``: target temperature, if provided (float)
"""
regex_position = re.compile(r"(?P<axis>[XYZE]):(?P<pos>{float})\s*".format(float=regex_float_pattern))
"""Regex for matching position entries in line.
Groups will be as follows:
* ``axis``: axis designator, either ``X``, ``Y``, ``Z`` or ``E`` (str)
* ``pos``: axis position (float)
"""
regex_firmware_splitter = re.compile(r"\s*([A-Z0-9_]+):")
"""Regex to use for splitting M115 responses."""
regex_sd_file_opened = re.compile(r"file opened:\s*(?P<name>.*?)(\s+size:\s*(?P<size>[0-9]+)|$)")
regex_sd_printing_byte = re.compile(r"sd printing byte (?P<current>[0-9]*)/(?P<total>[0-9]*)")
"""Regex matching SD printing status reports.
Groups will be as follows:
* ``current``: current byte position in file being printed
* ``total``: total size of file being printed
"""
##~~ Overrides
_overrides = dict()
@classmethod
def with_overrides(cls, overrides):
return type(b"{}WithOverrides".format(cls.__name__), (cls,), overrides)
##~~ Identifier
@classmethod
def identifier(cls, firmware_name, firmware_info):
return False
##~~ Message matchers
@classmethod
def comm_timeout(cls, line, lower_line, state, flags):
now = monotonic_time()
matches = ((line == "" and now > flags["timeout"]) or (flags["expect_continous_comms"]
and not flags["job_on_hold"]
and not flags["long_running_command"]
and not flags["heating"]
and now > flags["ok_timeout"])) and \
(not cls.block_while_dwelling or not flags["dwelling_until"] or now > flags["dwelling_until"])
continue_further = line != ""
return matches, continue_further
@classmethod
def comm_ok(cls, line, lower_line, state, flags):
matches = lower_line.startswith("ok")
continue_further = not matches \
or cls.message_temperature(line, lower_line, state, flags) \
or cls.message_position(line, lower_line, state, flags) \
or cls.message_firmware_info(line, lower_line, state, flags)
return matches, continue_further
@classmethod
def comm_start(cls, line, lower_line, state, flags):
return lower_line == "start"
@classmethod
def comm_wait(cls, line, lower_line, state, flags):
return lower_line == "wait"
@classmethod
def comm_resend(cls, line, lower_line, state, flags):
return lower_line.startswith("resend") or lower_line.startswith("rs")
@classmethod
def comm_action_command(cls, line, lower_line, state, flags):
return line.startswith("//") and line[2:].strip().startswith("action:")
@classmethod
def comm_error(cls, line, lower_line, state, flags):
return line.startswith("Error:") or line.startswith("!!")
@classmethod
def comm_ignore_ok(cls, line, lower_line, state, flags):
return False
@classmethod
def comm_busy(cls, line, lower_line, state, flags):
return line.startswith("echo:busy:") or line.startswith("busy:")
@classmethod
def error_multiline(cls, line, lower_line, state, flags):
return False
@classmethod
def error_communication(cls, line, lower_line, state, flags):
return "line number" in lower_line or "checksum" in lower_line or "format error" in lower_line or "expected line" in lower_line
@classmethod
def message_temperature(cls, line, lower_line, state, flags):
return "T:" in line or "T0:" in line or "B:" in line
@classmethod
def message_position(cls, line, lower_line, state, flags):
return 'X:' in line and 'Y:' in line and 'Z:' in line
@classmethod
def message_firmware_info(cls, line, lower_line, state, flags):
return "NAME:" in line
@classmethod
def message_firmware_capability(cls, line, lower_line, state, flags):
return lower_line.startswith("cap:")
@classmethod
def message_sd_init_ok(cls, line, lower_line, state, flags):
return "sd card ok" in lower_line
@classmethod
def message_sd_init_fail(cls, line, lower_line, state, flags):
return "sd init fail" in lower_line or "volume.init failed" in lower_line or "openroot failed" in lower_line
@classmethod
def message_sd_file_opened(cls, line, lower_line, state, flags):
return lower_line.startswith("file opened")
@classmethod
def message_sd_file_selected(cls, line, lower_line, state, flags):
return lower_line.startswith("file selected")
@classmethod
def message_sd_begin_file_list(cls, line, lower_line, state, flags):
return lower_line.startswith("begin file list")
@classmethod
def message_sd_end_file_list(cls, line, lower_line, state, flags):
return lower_line.startswith("end file list")
@classmethod
def message_sd_printing_byte(cls, line, lower_line, state, flags):
return "sd printing byte" in lower_line
@classmethod
def message_sd_not_printing(cls, line, lower_line, state, flags):
return "not sd printing" in lower_line
@classmethod
def message_sd_done_printing(cls, line, lower_line, state, flags):
return "done printing file" in lower_line
@classmethod
def message_sd_begin_writing(cls, line, lower_line, state, flags):
return "writing to file" in lower_line
@classmethod
def message_sd_end_writing(cls, line, lower_line, state, flags):
return "done saving file" in lower_line
@classmethod
def message_sd_entry(cls, line, lower_line, state, flags):
return flags["sd_files_temp"] is not None
##~~ Message parsers
@classmethod
def parse_comm_error(cls, line, lower_line, state, flags):
return dict(line=line, lower_line=lower_line)
@classmethod
def parse_comm_timeout(cls, line, lower_line, state, flags):
return dict(line=line, lower_line=lower_line)
@classmethod
def parse_comm_action_command(cls, line, lower_line, state, flags):
action = line[2:].strip()[len("action:"):].strip()
return dict(line=line, lower_line=lower_line, action=action)
@classmethod
def parse_error_communication(cls, line, lower_line, state, flags):
if "line number" in lower_line or "expected line" in lower_line:
error_type = "linenumber"
elif "checksum" in lower_line:
error_type = "checksum"
else:
error_type = "other"
flags["last_communication_error"] = error_type
return dict(error_type=error_type)
@classmethod
def parse_comm_resend(cls, line, lower_line, state, flags):
line_to_resend = None
match = cls.regex_resend_linenumber.search(line)
if match is not None:
line_to_resend = int(match.group("n"))
return dict(linenumber=line_to_resend)
@classmethod
def parse_message_temperature(cls, line, lower_line, state, flags):
"""
Parses the provided temperature line.
The result will be a dictionary mapping from the extruder or bed key to
a tuple with current and target temperature. The result will be canonicalized
with :func:`canonicalize_temperatures` before returning.
Returns:
tuple: a 2-tuple with the maximum tool number and a dict mapping from
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
"""
current_tool = flags["current_tool"]
result = {}
max_tool_num = 0
for match in re.finditer(cls.regex_temp, line):
values = match.groupdict()
tool = values["tool"]
if tool == "T" and "toolnum" in values and values["toolnum"]:
tool_num = int(values["toolnum"])
if tool_num > max_tool_num:
max_tool_num = tool_num
try:
actual = float(values.get("actual", None)) if values.get("actual", None) is not None else None
target = float(values.get("target", None)) if values.get("target", None) is not None else None
result[tool] = actual, target
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
heatup_detected = not lower_line.startswith("ok") and not flags["heating"] and not flags["temperature_autoreporting"]
return dict(max_tool_num=max(max_tool_num, current_tool),
temperatures=cls._canonicalize_temperatures(result, current_tool),
heatup_detected=heatup_detected)
@classmethod
def parse_message_position(cls, line, lower_line, state, flags):
position = dict(x=None, y=None, z=None, e=None)
for match in re.finditer(cls.regex_position, line):
position[match.group("axis").lower()] = float(match.group("pos"))
return dict(position=position)
@classmethod
def parse_message_firmware_info(cls, line, lower_line, state, flags):
data = cls._parse_firmware_line(line)
firmware_name = data.get("FIRMWARE_NAME")
if firmware_name is None:
# Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even
# report its firmware name properly in response to M115. Wonderful - why stick to established
# protocol when you can do your own thing, right?
#
# Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
#
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
name = data.get("NAME")
ver = data.get("VER")
if "malyan" in name.lower() and ver:
firmware_name = name.strip() + " " + ver.strip()
if firmware_name is not None:
firmware_name = firmware_name.strip()
return dict(firmware_name=firmware_name,
data=data)
@classmethod
def parse_message_firmware_capability(cls, line, lower_line, state, flags):
result = cls._parse_capability_line(line)
if not result:
return
cap, enabled = result
return dict(cap=cap, enabled=enabled)
@classmethod
def parse_message_sd_file_opened(cls, line, lower_line, state, flags):
match = cls.regex_sd_file_opened.match(lower_line)
if not match:
return
name = match.group("name")
size = int(match.group("size"))
return dict(name=name, long_name=name, size=size)
@classmethod
def parse_message_sd_entry(cls, line, lower_line, state, flags):
fileinfo = lower_line.rsplit(None, 1)
if len(fileinfo) > 1:
# we might have extended file information here, so let's split filename and size and try to make them a bit nicer
filename, size = fileinfo
try:
size = int(size)
except ValueError:
# whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None
filename = lower_line
size = None
else:
# no extended file information, so only the filename is there and we set size to None
filename = lower_line
size = None
from octoprint.util import filter_non_ascii
if filter_non_ascii(filename):
return None
else:
if not filename.startswith("/"):
# file from the root of the sd -- we'll prepend a /
filename = "/" + filename
return dict(name=filename, long_name=filename, size=int(size) if size is not None else None)
@classmethod
def parse_message_sd_printing_byte(cls, line, lower_line, state, flags):
match = cls.regex_sd_printing_byte.match(lower_line)
if not match:
return None
return dict(current=int(match.group("current")), total=int(match.group("total")))
##~~ Commands
@classmethod
def command_hello(cls):
return cls.command_set_line(0)
@classmethod
def command_get_firmware_info(cls):
return GcodeCommand("M115")
@classmethod
def command_finish_moving(cls):
return GcodeCommand("M400")
@classmethod
def command_get_position(cls):
return GcodeCommand("M114")
@classmethod
def command_get_temp(cls):
return GcodeCommand("M105")
@classmethod
def command_set_line(cls, n):
return GcodeCommand("M110", n=n)
@classmethod
def command_emergency_stop(cls):
return GcodeCommand("M112")
@classmethod
def command_abort_heatup(cls):
return GcodeCommand("M108")
@classmethod
def command_set_extruder_temp(cls, temperature, tool=None, wait=False):
command = "M109" if wait else "M104"
args = dict(s=temperature)
if tool is not None:
args["t"] = tool
return GcodeCommand(command, **args)
@classmethod
def command_set_bed_temp(cls, temperature, wait=False):
return GcodeCommand("M190" if wait else "M140", s=temperature)
@classmethod
def command_set_chamber_temp(cls, temperature, wait=False):
return GcodeCommand("M191" if wait else "M141", s=temperature)
@classmethod
def command_set_relative_positioning(cls):
return GcodeCommand("G91")
@classmethod
def command_set_absolute_positioning(cls):
return GcodeCommand("G90")
@classmethod
def command_move(cls, x=None, y=None, z=None, e=None, f=None):
return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f)
@classmethod
def command_extrude(cls, e=None, f=None):
return cls.command_move(e=e, f=f)
@classmethod
def command_home(cls, x=False, y=False, z=False):
return GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None)
@classmethod
def command_set_tool(cls, tool):
return GcodeCommand("T{}".format(tool))
@classmethod
def command_set_feedrate_multiplier(cls, multiplier):
return GcodeCommand("M220", s=multiplier)
@classmethod
def command_set_extrusion_multiplier(cls, multiplier):
return GcodeCommand("M221", s=multiplier)
@classmethod
def command_set_fan_speed(cls, speed):
return GcodeCommand("M106", s=speed)
@classmethod
def command_set_motors(cls, enable):
return GcodeCommand("M17") if enable else GcodeCommand("M18")
@classmethod
def command_sd_refresh(cls):
return GcodeCommand("M20")
@classmethod
def command_sd_init(cls):
return GcodeCommand("M21")
@classmethod
def command_sd_release(cls):
return GcodeCommand("M22")
@classmethod
def command_sd_select_file(cls, name):
return GcodeCommand("M23", param=name)
@classmethod
def command_sd_start(cls):
return GcodeCommand("M24")
@classmethod
def command_sd_pause(cls):
return GcodeCommand("M25")
@classmethod
def command_sd_resume(cls):
return GcodeCommand("M24")
@classmethod
def command_sd_set_pos(cls, pos):
return GcodeCommand("M26", s=pos)
@classmethod
def command_sd_status(cls):
return GcodeCommand("M27")
@classmethod
def command_sd_begin_write(cls, name):
return GcodeCommand("M28", param=name)
@classmethod
def command_sd_end_write(cls):
return GcodeCommand("M29")
@classmethod
def command_sd_delete(cls, name):
return GcodeCommand("M30", param=name)
@classmethod
def command_autoreport_temperature(cls, interval):
return GcodeCommand("M155", s=interval)
@classmethod
def command_autoreport_sd_status(cls, interval):
return GcodeCommand("M27", s=interval)
@classmethod
def command_busy_protocol_interval(cls, interval):
return GcodeCommand("M113", s=interval)
##~~ Helpers
@classmethod
def _canonicalize_temperatures(cls, parsed, current):
"""
Canonicalizes the temperatures provided in parsed.
Will make sure that returned result only contains extruder keys
like Tn, so always qualified with a tool number.
The algorithm for cleaning up the parsed keys is the following:
* If ``T`` is not included with the reported extruders, return
* If more than just ``T`` is reported:
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
``T`` from the result.
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
* return
Arguments:
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
to canonicalize
current (int): the current active extruder
Returns:
dict: the canonicalized version of ``parsed``
"""
reported_extruders = list(filter(lambda x: x.startswith("T"), parsed.keys()))
if not "T" in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
current_tool_key = "T%d" % current
result = dict(parsed)
if len(reported_extruders) > 1:
if "T0" in reported_extruders:
# Both T and T0 are present, so T contains the current
# extruder's temperature, e.g. for current_tool == 1:
#
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
#
# Same goes if Tc is already present, it will be overwritten:
#
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result[current_tool_key] = result["T"]
del result["T"]
else:
# So T is there, but T0 isn't. That looks like Smoothieware which
# always reports the first extruder T0 as T:
#
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result["T0"] = result["T"]
del result["T"]
else:
# We only have T. That can mean two things:
#
# * we only have one extruder at all, or
# * we are currently parsing a response to M109/M190, which on
# some firmwares doesn't report the full M105 output while
# waiting for the target temperature to be reached but only
# reports the current tool and bed
#
# In both cases it is however safe to just move our T over
# to T<current> in the parsed data, current should always stay
# 0 for single extruder printers. E.g. for current_tool == 1:
#
# T:<T1>
#
# becomes
#
# T1:<T1>
result[current_tool_key] = result["T"]
del result["T"]
return result
@classmethod
def _parse_firmware_line(cls, line):
"""
Parses the provided firmware info line.
The result will be a dictionary mapping from the contained keys to the contained
values.
Arguments:
line (unicode): the line to parse
Returns:
dict: a dictionary with the parsed data
"""
result = dict()
split_line = cls.regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
for key, value in chunks(split_line, 2):
result[key] = value
return result
@classmethod
def _parse_capability_line(cls, line):
"""
Parses the provided firmware capability line.
Lines are expected to be of the format
Cap:<capability name in caps>:<0 or 1>
e.g.
Cap:AUTOREPORT_TEMP:1
Cap:TOGGLE_LIGHTS:0
Args:
line (unicode): the line to parse
Returns:
tuple: a 2-tuple of the parsed capability name and whether it's on (true) or off (false), or None if the line
could not be parsed
"""
line = line.lower()
if line.startswith("cap:"):
line = line[len("cap:"):]
parts = line.split(":")
if len(parts) != 2:
# wrong format, can't parse this
return None
capability, flag = parts
if not flag in ("0", "1"):
# wrong format, can't parse this
return None
return capability.upper(), flag == "1"
@@ -1,19 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "klipper"
name = "Klipper"
unknown_requires_ack = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "klipper" in firmware_name.lower()
@@ -1,21 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MalyanFlavor(GenericFlavor):
key = "malyan"
name = "Malyan"
always_send_checksum = False
block_while_dwelling = True
sd_always_available = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "malyan" in firmware_name.lower()
@@ -1,35 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MarlinFlavor(GenericFlavor):
key = "marlin"
name = "Marlin"
emergency_commands = ["M112", "M108", "M410"]
heatup_abortable = True
class MarlinLegacyFlavor(GenericFlavor):
key = "marlinlegacy"
name = "Legacy Marlin"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "marlin v1" in firmware_name.lower()
class PrusaMarlinFlavor(MarlinFlavor):
key = "prusamarlin"
name = "Marlin: Prusa variant"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "prusa-firmware" in firmware_name.lower() and "marlin" in firmware_name.lower()
@@ -1,94 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors import GenericFlavor
from octoprint.comm.protocol.reprap.util import regex_positive_float_pattern
import re
class RepetierFlavor(GenericFlavor):
key = "repetier"
name = "Repetier"
always_send_checksum = True
identical_resends_countdown = 5
block_while_dwelling = True
detect_external_heatups = False
regex_tempextr = re.compile("targetextr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier.
Groups will be as follows:
* ``toolnum``: number of the extruder to which the target temperature
report belongs (int)
* ``target``: new target temperature (float)
"""
regex_tempbed = re.compile("targetbed:(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier for beds.
Groups will be as follows:
* ``target``: new target temperature (float)
"""
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "repetier" in firmware_name.lower()
@classmethod
def message_temperature(cls, line, lower_line, state, flags):
return GenericFlavor.message_temperature(line, lower_line, state, flags) or "targetextr" in lower_line or "targetbed" in lower_line
@classmethod
def parse_message_temperature(cls, line, lower_line, state, flags):
if "targetextr" in lower_line:
match = cls.regex_tempextr.match(lower_line)
if match is not None:
tool_num = int(match.group("toolnum"))
target = float(match.group("target"))
tool = "T{}".format(tool_num)
temperatures = dict()
temperatures[tool] = (None, target)
return dict(max_tool_num=max(tool_num, flags.get("current_tool", 0)),
temperatures=temperatures,
heatup_detected=False)
elif "targetbed" in lower_line:
match = cls.regex_tempbed.match(lower_line)
if match is not None:
target = float(match.group("target"))
temperatures = dict(bed=(None, target))
return dict(max_tool_num=flags.get("current_tool", 0),
temperatures=temperatures,
heatup_detected=False)
else:
# Repetier sends temperature output on it's own line, so we can't use the
# "no ok in temperature output" metric to detected external heatups
result = GenericFlavor.parse_message_temperature(line, lower_line, state, flags)
result[b"heatup_detected"] = False
return result
##~~ Preprocessors, returning True stops further processing by the protocol
@classmethod
def preprocess_comm_resend(cls, linenumber, state, flags):
if flags.get("resend_swallow_repetitions", False) \
and flags.get("resend_swallow_repetitions_counter", 0) \
and linenumber == flags["resend_requested"] \
and flags["resend_swallow_repetitions_counter"] > 0:
cls.logger.debug("Ignoring resend request for line {}, that is "
"probably a repetition sent by the firmware to "
"ensure it arrives, not a real request"
.format(linenumber))
flags["resend_swallow_repetitions_counter"] -= 1
return True
flags["resend_swallow_repetitions_counter"] = cls.identical_resends_countdown
@@ -1,19 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "reprapfirmware"
name = "RepRapFirmware"
sd_relative_path = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "reprapfirmware" in firmware_name.lower()
@@ -1,13 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "smoothieware"
name = "Smoothieware"
@@ -1,25 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.scripts import Script, UnknownScript
from octoprint.comm.protocol.reprap.util import process_gcode_line
class GcodeScript(Script):
def __init__(self, settings, name, context=None):
def renderer(ctx):
lines = settings.loadScript("gcode", name, context=ctx)
if lines is None:
raise UnknownScript(name)
return lines
super(GcodeScript, self).__init__(name, renderer, context=context)
def render(self, context=None):
script = super(GcodeScript, self).render(context)
return list(filter(lambda x: x is not None and x.strip() != "",
map(lambda x: process_gcode_line(x),
script)))
@@ -1,398 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.commands import Command, to_command
from octoprint.util import PrependableQueue, TypeAlreadyInQueue, CountedEvent
# noinspection PyCompatibility
from past.builtins import basestring
import contextlib
import copy
import logging
import threading
try:
# noinspection PyCompatibility
import queue
except Exception:
# noinspection PyCompatibility
import Queue as queue
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
regex_int_pattern = "\d+"
def strip_comment(line):
if not ";" in line:
# shortcut
return line
escaped = False
result = []
for c in line:
if c == ";" and not escaped:
break
result += c
escaped = (c == "\\") and not escaped
return "".join(result).strip()
def process_gcode_line(line, offsets=None, current_tool=None):
line = strip_comment(line).strip()
if not len(line):
return None
# if offsets is not None:
# line = apply_temperature_offsets(line, offsets, current_tool=current_tool)
return line
def normalize_command_handler_result(command, handler_results, tags_to_add=None):
"""
Normalizes a command handler result.
Handler results can be either ``None``, a single result entry or a list of result
entries.
``None`` results are ignored, the provided ``command``, ``command_type``,
``gcode``, ``subcode`` and ``tags`` are returned in that case (as single-entry list with
one 5-tuple as entry).
Single result entries are either:
* a single string defining a replacement ``command``
* a 1-tuple defining a replacement ``command``
* a 2-tuple defining a replacement ``command`` and ``command_type``
* a 3-tuple defining a replacement ``command`` and ``command_type`` and additional ``tags`` to set
A ``command`` that is ``None`` will lead to the entry being ignored for
the normalized result.
The method returns a list of normalized result entries. Normalized result
entries always are a 4-tuple consisting of ``command``, ``command_type``,
``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
be empty in which case the command is to be suppressed.
Examples:
>>> from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
>>> normalize_command_handler_result(GcodeCommand("M105"), None) # doctest: +ALLOW_UNICODE
[GcodeCommand('M105',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), GcodeCommand("M110")) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110", "lineno_reset"), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type='lineno_reset',tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), []) # doctest: +ALLOW_UNICODE
[]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", None]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), (None, "ignored")]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type='display_message',tags=set()), GcodeCommand('M110',original='M110',type='lineno_reset',tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2'})]
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2', 'tag3'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2', 'tag3'})]
Arguments:
command (Command): The command for which the handler result was
generated
handler_results: The handler result(s) to normalized. Can be either
a single result entry or a list of result entries.
tags_to_add (set of unicode or None): List of tags to add to expanded result
entries
Returns:
(list) - A list of normalized handler result entries, which are
``Command`` instances
"""
original = command
if handler_results is None:
# handler didn't return anything, we'll just continue
return [original]
if not isinstance(handler_results, list):
handler_results = [handler_results, ]
result = []
for handler_result in handler_results:
# we iterate over all handler result entries and process each one
# individually here
if handler_result is None:
# entry is None, we'll ignore that entry and continue
continue
def expand_tags(tags, tags_to_add):
tags = tags.copy()
if tags_to_add and isinstance(tags_to_add, set):
tags |= tags_to_add
return tags
if isinstance(handler_result, basestring):
# entry is just a string, replace command with it
if handler_result != original.line:
# command changed, swap it
command = to_command(handler_result,
type=original.type,
tags=expand_tags(original.tags, tags_to_add))
result.append(command)
elif isinstance(handler_result, Command):
if handler_result != original:
command = copy.copy(handler_result)
command.tags = expand_tags(original.tags, tags_to_add)
result.append(command)
elif isinstance(handler_result, tuple):
# entry is a tuple, extract command and command_type
hook_result_length = len(handler_result)
command_type = original.type
command_tags = original.tags
if hook_result_length == 1:
# handler returned just the command
command_line, = handler_result
elif hook_result_length == 2:
# handler returned command and command_type
command_line, command_type = handler_result
elif hook_result_length == 3:
# handler returned command, command type and additional tags
command_line, command_type, command_tags = handler_result
else:
# handler returned a tuple of an unexpected length, ignore
# and continue
continue
if command_line is None:
# command is None, ignore it and continue
continue
if command_line != original.line or command_type != original.type:
# command or command_type changed, tags need to be rewritten
command_tags = expand_tags(command_tags, tags_to_add)
result.append(to_command(command_line, type=command_type, tags=command_tags))
# reset to original
command = original
return result
class SendToken(CountedEvent):
def __init__(self, value=0, maximum=None, **kwargs):
super(SendToken, self).__init__(value=value, maximum=maximum, **kwargs)
self._ignored = 0
def set(self, ignore=False):
with self._mutex:
if ignore:
self._ignored += 1
self._internal_set(self._counter + 1)
def clear(self, completely=False):
with self._mutex:
if completely:
self._internal_set(0)
self._ignored = 0
else:
if self._ignored > 0:
self._ignored -= 1
self._internal_set(self._counter - 1)
self._internal_set(self._counter - 1)
class LineHistory(object):
def __init__(self, max=None):
self.max = max
self._lines = []
self._mutex = threading.RLock()
self._line_number_lookup = dict()
@property
def lines(self):
with self._mutex:
return [x[0] for x in self._lines]
def append(self, line, line_number=None):
with self._mutex:
self._lines.append((line, line_number))
if line_number is not None:
self._line_number_lookup[line_number] = line
self._cleanup()
def clear(self):
with self._mutex:
self._lines = []
self._line_number_lookup = dict()
def __len__(self):
with self._mutex:
return len(self._lines)
def __getitem__(self, line_number):
with self._mutex:
return self._line_number_lookup[line_number]
def __contains__(self, line_number):
with self._mutex:
return line_number in self._line_number_lookup
def __iter__(self):
return iter(self.lines)
def _cleanup(self):
if len(self._lines) <= self.max:
return
while len(self._lines) > self.max:
_, line_number = self._lines.pop(0)
if line_number is not None:
try:
del self._line_number_lookup[line_number]
except KeyError:
pass
class PositionRecord(object):
_standard_attrs = {"x", "y", "z", "e", "f", "t"}
@classmethod
def valid_e(cls, attr):
if not attr.startswith("e"):
return False
try:
int(attr[1:])
except Exception:
return False
return True
def __init__(self, *args, **kwargs):
attrs = self._standard_attrs | set([key for key in kwargs if self.valid_e(key)])
for attr in attrs:
setattr(self, attr, kwargs.get(attr))
def copy_from(self, other):
# make sure all standard attrs and attrs from other are set
attrs = self._standard_attrs | set([key for key in dir(other) if self.valid_e(key)])
for attr in attrs:
setattr(self, attr, getattr(other, attr))
# delete attrs other doesn't have
attrs = set([key for key in dir(self) if self.valid_e(key)]) - attrs
for attr in attrs:
delattr(self, attr)
def as_dict(self):
attrs = self._standard_attrs | set([key for key in dir(self) if self.valid_e(key)])
return dict((attr, getattr(self, attr)) for attr in attrs)
class TemperatureRecord(object):
def __init__(self):
self._tools = dict()
self._bed = (None, None)
self._chamber = (None, None)
def copy_from(self, other):
self._tools = other.tools
self._bed = other.bed
self._chamber = other.chamber
def set_tool(self, tool, actual=None, target=None):
current = self._tools.get(tool, (None, None))
self._tools[tool] = self._to_new_tuple(current, actual, target)
def set_bed(self, actual=None, target=None):
current = self._bed
self._bed = self._to_new_tuple(current, actual, target)
def set_chamber(self, actual=None, target=None):
current = self._chamber()
self._chamber = self._to_new_tuple(current, actual, target)
@property
def tools(self):
return dict(self._tools)
@property
def bed(self):
return self._bed
@property
def chamber(self):
return self._chamber
def as_dict(self):
result = dict()
tools = self.tools
for tool, data in tools.items():
result["tool{}".format(tool)] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["bed"] = dict(actual=bed[0],
target=bed[1])
chamber = self.chamber
result["chamber"] = dict(actual=chamber[0],
target=chamber[1])
return result
def as_script_dict(self):
result = self.as_dict()
# backwards compatibility
tools = self.tools
for tool, data in tools.items():
result[tool] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["b"] = dict(actual=bed[0],
target=bed[1])
chamber = self.chamber
result["c"] = dict(actual=chamber[0],
target=chamber[1])
return result
@classmethod
def _to_new_tuple(cls, current, actual, target):
if current is None or not isinstance(current, tuple) or len(current) != 2:
current = (None, None)
if actual is None and target is None:
return current
old_actual, old_target = current
if actual is None:
return old_actual, target
elif target is None:
return actual, old_target
else:
return actual, target
@@ -1,194 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.util import PrependableQueue, TypedQueue, TypeAlreadyInQueue
try:
import queue
except ImportError:
import Queue as queue
import contextlib
import logging
import threading
class ScriptQueue(PrependableQueue):
pass
class JobQueue(PrependableQueue):
pass
class CommandQueue(TypedQueue):
def __init__(self, *args, **kwargs):
TypedQueue.__init__(self, *args, **kwargs)
self._unblocked = threading.Event()
self._unblocked.set()
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def get(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.get(self, *args, **kwargs)
def put(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.put(self, *args, **kwargs)
def clear(self):
cleared = []
while True:
try:
cleared.append(TypedQueue.get(self, False))
TypedQueue.task_done(self)
except queue.Empty:
break
return cleared
class SendQueue(PrependableQueue):
def __init__(self, maxsize=0):
PrependableQueue.__init__(self, maxsize=maxsize)
self._unblocked = threading.Event()
self._unblocked.set()
self._resend_queue = PrependableQueue()
self._send_queue = PrependableQueue()
self._lookup = set()
self._resend_active = False
@property
def resend_active(self):
return self._resend_active
@resend_active.setter
def resend_active(self, resend_active):
with self.mutex:
self._resend_active = resend_active
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def prepend(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout)
def put(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout)
def get(self, block=True, timeout=None):
self._unblocked.wait()
item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout)
return item
def clear(self):
cleared = []
while True:
try:
cleared.append(PrependableQueue.get(self, False))
PrependableQueue.task_done(self)
except queue.Empty:
break
return cleared
def _put(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.put(item)
else:
self._send_queue.put(item)
def _prepend(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.prepend(item)
else:
self._send_queue.prepend(item)
def _get(self):
if self.resend_active:
item = self._resend_queue.get(block=False)
else:
try:
item = self._resend_queue.get(block=False)
except queue.Empty:
item = self._send_queue.get(block=False)
_, item_type, _ = item
if item_type is not None:
if item_type in self._lookup:
self._lookup.remove(item_type)
return item
def _qsize(self, len=len):
if self.resend_active:
return self._resend_queue.qsize()
else:
return self._resend_queue.qsize() + self._send_queue.qsize()
class QueueMarker(object):
def __init__(self, callback):
self.callback = callback
def run(self):
if callable(self.callback):
try:
self.callback()
except Exception:
logging.getLogger(__name__).exception("Error while running callback of QueueMarker")
class SendQueueMarker(QueueMarker):
pass
-37
View File
@@ -1,37 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
class Script(object):
def __init__(self, name, renderer, context=None):
if context is None:
context = dict()
self.name = name
self.renderer = renderer
self.context = context
def render(self, context=None):
if context is None:
context = dict()
render_context = dict(self.context)
render_context.update(context)
content = self.renderer(render_context)
if content is None:
return None
return content.split("\n")
class UnknownScript(Exception):
def __init__(self, name, *args, **kwargs):
self.name = name
class InvalidScript(Exception):
pass
-350
View File
@@ -1,350 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.util.parameters import get_param_dict
import copy
import logging
import time
from octoprint.util import monotonic_time
from octoprint.util.listener import ListenerAware
from octoprint.plugin import plugin_manager
from octoprint.settings import SubSettings
_registry = dict()
def register_transports():
from .serialtransport import SerialTransport
from .sockettransport import TcpTransport, SerialOverTcpTransport
logger = logging.getLogger(__name__)
# stock transports
register_transport(SerialTransport)
register_transport(TcpTransport)
register_transport(SerialOverTcpTransport)
# more transports provided by plugins
hooks = plugin_manager().get_hooks("octoprint.comm.transport.register")
for name, hook in hooks.items():
try:
transports = hook()
for transport in transports:
try:
register_transport(transport)
except Exception:
logger.exception("Error while registering transport class {} for plugin {}".format(transport, name))
except Exception:
logger.exception("Error executing octoprint.comm.transport.register hook for plugin {}".format(name))
def register_transport(transport_class):
if not hasattr(transport_class, "key"):
raise ValueError("Transport class {} is missing key".format(transport_class))
_registry[transport_class.key] = transport_class
def lookup_transport(key):
return _registry.get(key)
def all_transports():
return _registry.values()
class Transport(ListenerAware):
name = None
key = None
message_integrity = False
@classmethod
def get_connection_options(cls):
return []
@classmethod
def get_settings_defaults(cls):
return dict()
def __init__(self, *args, **kwargs):
super(Transport, self).__init__()
self._logger = logging.getLogger(__name__)
self._state = TransportState.DISCONNECTED
self._args = dict()
self._printer_profile = kwargs.get("printer_profile")
self._plugin_manager = kwargs.get("plugin_manager")
self._event_bus = kwargs.get("event_bus")
self._settings = kwargs.get("settings")
if not isinstance(self._settings, TransportSettings):
self._settings = TransportSettings(self._settings, self)
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@property
def state(self):
return self._state
@state.setter
def state(self, value):
old_state = self.state
self._state = value
self.notify_listeners("on_transport_log_message", self, "Transport state changed from '{}' to '{}'".format(old_state, value))
def connect(self, **params):
if self.state == TransportState.CONNECTED:
raise TransportAlreadyConnectedError("Already connected, disconnect first")
options = self.get_connection_options()
param_dict = get_param_dict(params, options)
self.create_connection(**param_dict)
self.state = TransportState.CONNECTED
self.notify_listeners("on_transport_connected", self)
def disconnect(self, error=None):
if self.state == TransportState.DISCONNECTED:
raise TransportNotConnectedError("Already disconnected")
success = self.drop_connection()
if not success and not error:
error = "Error disconnecting transport"
if error:
self.state = TransportState.DISCONNECTED_WITH_ERROR
self.notify_listeners("on_transport_log_message", self, error)
else:
self.state = TransportState.DISCONNECTED
self.notify_listeners("on_transport_disconnected", self, error=error)
def create_connection(self, *args, **kwargs):
return True
def drop_connection(self):
return True
def read(self, size=None, timeout=None):
data = self.do_read(size=size, timeout=timeout)
self.notify_listeners("on_transport_log_received_data", self, data)
return data
def write(self, data):
self.do_write(data)
self.notify_listeners("on_transport_log_sent_data", self, data)
@property
def in_waiting(self):
return 0
def do_read(self, size=None, timeout=None):
return b""
def do_write(self, data):
pass
def __str__(self):
return self.__class__.__name__
class TransportState(object):
CONNECTED = "connected"
DISCONNECTED = "disconnected"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
class TransportSettings(SubSettings):
def __init__(self, settings, transport):
self.transport = transport.key
SubSettings.__init__(self, settings, ["comm", "transport", transport.key],
defaults=transport.get_settings_defaults())
class TransportNotConnectedError(Exception):
pass
class TransportAlreadyConnectedError(Exception):
pass
class TransportWrapper(ListenerAware):
unforwarded_handlers = []
"""Allows to explicitly disable certain transport listener handlers on sub classes."""
def __init__(self, transport):
ListenerAware.__init__(self)
self.transport = transport
self.transport.register_listener(self)
# make sure we forward any transport listener calls to our own registered listeners
def forward_handler(name):
def f(*args, **kwargs):
# replace references to self.transport with self
args = [self if arg == self.transport else arg for arg in args]
kwargs = dict((key, self if value == self.transport else value) for key, value in kwargs.items())
# forward
self.notify_listeners(name, *args, **kwargs)
return f
for handler in filter(lambda x: x.startswith("on_transport_"), dir(TransportListener)):
if handler not in self.__class__.unforwarded_handlers:
setattr(self, handler, forward_handler(handler))
def __getattr__(self, item):
return getattr(self.transport, item)
class SeparatorAwareTransportWrapper(TransportWrapper):
unforwarded_handlers = ["on_transport_log_received_data"]
"""We have read overwritten and hence send our own received_data notification."""
def __init__(self, transport, terminator):
TransportWrapper.__init__(self, transport)
self.terminator = terminator
self._buffered = bytearray()
def read(self, size=None, timeout=None):
start = monotonic_time()
termlen = len(self.terminator)
data = self._buffered
while True:
# make sure we always read everything that is waiting
data += bytearray(self.transport.read(self.transport.in_waiting))
# check for terminator, if it's there we have found our line
termpos = data.find(self.terminator)
if termpos >= 0:
# line: everything up to and incl. the terminator
line = data[:termpos + termlen]
# buffered: everything after the terminator
self._buffered = data[termpos + termlen:]
received = bytes(line)
self.notify_listeners("on_transport_log_received_data", self, received)
return received
# check if timeout expired
if timeout and monotonic_time() > start + timeout:
break
# if we arrive here we so far couldn't read a full line, wait for more data
c = self.transport.read(1)
if not c:
# EOF
break
# add to data and loop
data += c
self._buffered = data
raise TimeoutTransportException()
def __str__(self):
return "SeparatorAwareTransportWrapper({}, separator={})".format(self.transport, self.terminator)
class LineAwareTransportWrapper(SeparatorAwareTransportWrapper):
def __init__(self, transport):
SeparatorAwareTransportWrapper.__init__(self, transport, b"\n")
def __str__(self):
return "LineAwareTransportWrapper({})".format(self.transport)
class PushingTransportWrapper(TransportWrapper):
def __init__(self, transport, name=b"PushingTransportWrapper.receiver_loop", timeout=None):
super(PushingTransportWrapper, self).__init__(transport)
self.name = name
self.timeout = timeout
self._receiver_active = False
self._receiver_thread = None
@property
def active(self):
return self._receiver_active
def connect(self, **kwargs):
self.transport.connect(**kwargs)
import threading
self._receiver_active = True
self._receiver_thread = threading.Thread(target=self._receiver_loop, name=self.name)
self._receiver_thread.daemon = True
self._receiver_thread.start()
def disconnect(self):
self._receiver_active = False
self.transport.disconnect()
def wait(self):
self._receiver_thread.join()
def _receiver_loop(self):
while self._receiver_active:
try:
data = self.transport.read(timeout=self.timeout)
self.notify_listeners("on_transport_data_pushed", self, data)
except TimeoutTransportException as ex:
self.notify_listeners("on_transport_data_exception", self, ex)
except Exception:
if self._receiver_active:
raise
def __str__(self):
return "PushingTransportWrapper({})".format(self.transport)
class TransportListener(object):
def on_transport_connected(self, transport):
pass
def on_transport_disconnected(self, transport, error=None):
pass
def on_transport_log_sent_data(self, transport, data):
pass
def on_transport_log_received_data(self, transport, data):
pass
def on_transport_log_message(self, transport, data):
pass
class PushingTransportWrapperListener(object):
def on_transport_data_pushed(self, transport, data):
pass
def on_transport_data_exception(self, transport, exception):
pass
class TransportException(Exception):
pass
class TimeoutTransportException(TransportException):
pass
class EofTransportException(TransportException):
pass
@@ -1,206 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.transport import Transport, LineAwareTransportWrapper, PushingTransportWrapper
from octoprint.comm.util.parameters import TextType, IntegerType, ChoiceType, SuggestionType, BooleanType, Value
import serial
import logging
class SerialTransport(Transport):
name = "Serial Connection"
key = "serial"
message_integrity = False
suggested_baudrates = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
unix_port_patterns = ["/dev/ttyUSB*", "/dev/ttyACM*", "/dev/tty.usb*",
"/dev/cu.*", "/dev/cuaU*", "/dev/rfcomm*"]
max_write_passes = 5
@classmethod
def for_additional_ports_and_baudrates(cls, additional_ports, additional_baudrates):
patterns = SerialTransport.unix_port_patterns
if additional_ports:
patterns += additional_ports
baudrates = SerialTransport.suggested_baudrates
if additional_baudrates:
baudrates += additional_baudrates
return type(cls.__name__ + b"WithAdditionalPorts",
(cls,),
{b"unix_port_patterns": patterns,
b"suggested_baudrates": baudrates})
@classmethod
def get_connection_options(cls):
return [
SuggestionType("port", "Port", cls.get_available_serial_ports(), lambda value: Value(value)),
SuggestionType("baudrate", "Baudrate", cls.get_available_baudrates(), lambda value: Value(value), default=0),
IntegerType("write_timeout", "Write Timeout (sec)", min=1, default=10, advanced=True),
BooleanType("exclusive", "Exclusive access", default=True, advanced=True),
ChoiceType("parity", "Parity",
[Value(serial.PARITY_NONE, "none"),
Value(serial.PARITY_ODD, "odd"),
Value(serial.PARITY_EVEN, "even")],
default=serial.PARITY_NONE, advanced=True)
]
@classmethod
def get_available_serial_ports(cls):
import sys
if sys.platform == "win32":
# windows
from serial.tools.list_ports import comports
ports = comports()
else:
# posix
import glob
devices = [device
for pattern in cls.unix_port_patterns
for device in glob.glob(pattern)]
plat = sys.platform.lower()
if plat[:5] == "linux":
# linux
from serial.tools.list_ports_linux import SysFS
ports = [info
for info in [SysFS(d) for d in devices]
if info.subsystem != "platform"]
else:
# other posix systems
from serial.tools import list_ports_common
ports = [list_ports_common.ListPortInfo(d) for d in devices]
port_values = [Value(None, title="Auto detect")] + sorted([Value(port.device, title=port.description) for port in ports], key=lambda x: x.title)
return port_values
@classmethod
def get_available_baudrates(cls):
return [Value(0, title="Auto detect")] + \
sorted([Value(baudrate) for baudrate in cls.suggested_baudrates], key=lambda x: x.title, reverse=True)
def __init__(self, *args, **kwargs):
super(SerialTransport, self).__init__()
self.serial_factory = kwargs.get("serial_factory", None)
self._logger = logging.getLogger(__name__)
self._serial = None
self._closing = False
def create_connection(self, **kwargs):
factory = self.serial_factory
if self.serial_factory is None:
factory = self._default_serial_factory
self._closing = False
self._serial = factory(**kwargs)
self.set_current_args(**kwargs)
return True
def drop_connection(self):
error = False
if self._serial is not None:
self._closing = True
try:
if callable(getattr(self._serial, "cancel_read", None)):
self._serial.cancel_read()
except Exception:
self._logger.exception("Error while cancelling pending reads from the serial port")
try:
if callable(getattr(self._serial, "cancel_write", None)):
self._serial.cancel_write()
except Exception:
self._logger.exception("Error while cancelling pending writes to the serial port")
try:
self._serial.close()
except Exception:
self._logger.exception("Error while closing the serial port")
error = True
self._serial = None
return not error
def do_read(self, size=None, timeout=None):
return self._serial.read(size=size)
def do_write(self, data):
written = 0
passes = 0
def try_to_write(d):
result = self._serial.write(d)
if result is None or not isinstance(result, int):
# probably some plugin not returning the written bytes, assuming all of them
return len(data)
else:
return result
while written < len(data):
to_send = data[written:]
old_written = written
try:
written += try_to_write(to_send)
except serial.SerialTimeoutException:
self._logger.warn("Serial timeout while writing to serial port, trying again.")
try:
# second try
written += try_to_write(to_send)
except Exception:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
except Exception:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
if old_written == written:
passes += 1
if passes > self.max_write_passes:
message = "Could not write anything to the serial port in {} tries, something appears to be " \
"wrong with the printer communication".format(self.max_write_passes)
self._logger.error(message)
self.disconnect(error=message)
break
@property
def in_waiting(self):
return getattr(self._serial, "in_waiting", 0)
def _default_serial_factory(self, **kwargs):
return serial.Serial(port=kwargs.get("port"),
baudrate=kwargs.get("baudrate"),
exclusive=kwargs.get("exclusive"),
parity=kwargs.get("parity"),
write_timeout=kwargs.get("write_timeout", 10) * 1000)
def __str__(self):
return "SerialTransport"
if __name__ == "__main__":
# list ports
ports = SerialTransport.get_available_serial_ports()
for port in ports:
print(port.title + ": " + port.value)
@@ -1,65 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.transport import Transport, LineAwareTransportWrapper
from octoprint.comm.util.parameters import TextType, IntegerType
import socket
class TcpTransport(Transport):
name = "TCP Connection"
key = "tcpsocket"
message_integrity = True
@classmethod
def get_connection_options(cls):
return [
TextType("host", "Host"),
IntegerType("port", "Port", min=1, max=65535)
]
def __init__(self):
super(TcpTransport, self).__init__()
self._socket = None
def create_connection(self, host=None, port=None):
if host is None:
raise ValueError("host must not be None")
if port is None:
raise ValueError("port must not be None")
self._socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
self._socket.connect((host, port))
self.set_current_args(host=host, port=port)
return True
def drop_connection(self):
try:
self._socket.close()
return True
except Exception:
self._logger.exception("Error closing socket")
return False
def do_read(self, size=None, timeout=None):
if size is None:
size = 16
return self._socket.recv(size)
def do_write(self, data):
self._socket.sendall(data)
def __str__(self):
return "TcpTransport"
class SerialOverTcpTransport(TcpTransport):
name = "Serial Connection over TCP"
key = "serialovertcpsocket"
message_integrity = False
View File
Whitespace-only changes.
-194
View File
@@ -1,194 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from past.builtins import unicode
def get_param_dict(data, options):
options_by_name = dict((option.name, option) for option in options)
result = dict()
for key, value in data.items():
if not key in options_by_name:
continue
option = options_by_name[key]
result[key] = option.convert(value)
return result
class ParamType(object):
type = "generic"
def __init__(self, name, title, default=None, advanced=False, help=None):
self.name = name
self.title = title
self.default = default
self.advanced = advanced
self.help = help
def as_dict(self):
return dict(name=self.name,
title=self.title,
default=self.default,
advanced=self.advanced,
help=self.help,
type=self.type)
def convert(self, value):
return value
def __repr__(self):
return "{}(".format(self.__class__.__name__) \
+ ", ".join(["{}={!r}".format(key, value) for key, value in self.__dict__.items() if not key.startswith("_")]) + ")"
class TextType(ParamType):
type = "text"
def convert(self, value):
if isinstance(value, bytes):
value = value.decode("utf-8", "replace")
return value
class IntegerType(ParamType):
type = "integer"
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
self.min = min
self.max = max
self.unit = unit
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(min=self.min,
max=self.max,
unit=self.unit))
return result
def convert(self, value):
try:
value = int(value)
except ValueError:
raise ValueError("value {!r} is not a valid integer".format(value))
if self.min is not None and value < self.min:
raise ValueError("value {} is less than minimum valid value {}".format(value, self.min))
if self.max is not None and value > self.max:
raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max))
return value
class FloatType(ParamType):
type = "float"
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
self.min = min
self.max = max
self.unit = unit
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(min=self.min,
max=self.max,
unit=self.unit))
return result
def convert(self, value):
try:
value = float(value)
except ValueError:
raise ValueError("value {!r} is not a valid float".format(value))
if self.min is not None and value < self.min:
raise ValueError("value {} is less than minimum valid value {}".format(value, self.min))
if self.max is not None and value > self.max:
raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max))
return value
class BooleanType(ParamType):
type = "boolean"
def convert(self, value):
try:
value = bool(value)
except ValueError:
raise ValueError("value {!r} is not a valid boolean".format(value))
return value
class ChoiceType(ParamType):
type = "choice"
def __init__(self, name, title, choices, **kwargs):
self.choices = choices
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(choices=list(map(lambda x: x.as_dict(), self.choices))))
return result
class SmallChoiceType(ChoiceType):
type = "smallchoice"
class SuggestionType(ParamType):
type = "suggestion"
def __init__(self, name, title, suggestions, factory, **kwargs):
self.suggestions = suggestions
self.factory = factory
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(suggestions=list(map(lambda x: x.as_dict(), self.suggestions))))
return result
class ListType(ParamType):
type = "list"
def __init__(self, name, title, factory, **kwargs):
self.factory = factory
ParamType.__init__(self, name, title, **kwargs)
def convert(self, value):
if isinstance(value, unicode):
items = map(unicode.strip, value.split(","))
elif isinstance(value, list):
items = value
else:
raise ValueError("value {!r} must be either a comma-separated string or a list".format(value))
return list(map(self.factory, items))
class ParamGroup(ParamType):
type = "group"
def __init__(self, name, title, params, help=None, advanced=False):
ParamType.__init__(self, name, title, help=help, advanced=advanced)
self.params = params
def as_dict(self):
result = ParamType.as_dict(self)
result["params"] = [x.as_dict() for x in self.params]
return result
def convert(self, value):
if not isinstance(value, dict):
raise ValueError("value {!r} must be a dict".format(value))
return dict((k, v.convert()) for k, v in value.items())
class Value(object):
def __init__(self, value, title=None, help=None):
self.value = value
self.title = title if title else value
self.help = help
def as_dict(self):
return dict(value=self.value,
title=self.title,
help=self.help)
+6 -8
View File
@@ -46,6 +46,12 @@ class Events(object):
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
CLIENT_AUTHED = "ClientAuthed"
CLIENT_DEAUTHED = "ClientDeauthed"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
USER_LOGGED_OUT = "UserLoggedOut"
# File management
UPLOAD = "Upload"
@@ -227,14 +233,6 @@ class EventManager(object):
q.put((event, payload))
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
# TODO v1.4.0 Remove again
import copy
legacy_payload = copy.deepcopy(payload)
legacy_payload["type"] = "gcode"
q.put((event, legacy_payload))
def subscribe(self, event, callback):
"""
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
+34 -27
View File
@@ -16,11 +16,12 @@ from octoprint.events import eventManager, Events
from .destinations import FileDestinations
from .analysis import QueueEntry, AnalysisQueue
from .storage import LocalFileStorage
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
from octoprint.util import get_fully_qualified_classname as fqcn
from collections import namedtuple
# noinspection PyCompatibility
from past.builtins import basestring
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
@@ -224,6 +225,7 @@ class FileManager(object):
import octoprint.settings
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
self._analyzeGcode = octoprint.settings.settings().get(["gcodeAnalysis", "runAt"])
def initialize(self, process_backlog=False):
self.reload_plugins()
@@ -231,6 +233,10 @@ class FileManager(object):
self.process_backlog()
def process_backlog(self):
# only check for a backlog if gcodeAnalysis is 'idle' or 'always'
if self._analyzeGcode == "never":
return
def worker():
self._logger.info("Adding backlog items from all storage types to analysis queue...".format(**locals()))
for storage_type, storage_manager in self._storage_managers.items():
@@ -330,16 +336,18 @@ class FileManager(object):
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
try:
if _error:
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
reason=_error))
eventManager().fire(Events.SLICING_FAILED, dict(slicer=slicer_name,
stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
reason=_error))
elif _cancelled:
eventManager().fire(Events.SLICING_CANCELLED, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location))
eventManager().fire(Events.SLICING_CANCELLED, dict(slicer=slicer_name,
stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location))
else:
source_meta = self.get_metadata(source_location, source_path)
hash = source_meta.get("hash", "n/a")
@@ -357,11 +365,12 @@ class FileManager(object):
printer_profile=printer_profile, analysis=_analysis)
end_time = octoprint.util.monotonic_time()
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
time=end_time - start_time))
eventManager().fire(Events.SLICING_DONE, dict(slicer=slicer_name,
stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
time=end_time - start_time))
if callback is not None:
if callback_args is None:
@@ -382,7 +391,8 @@ class FileManager(object):
slicer = self._slicing_manager.get_slicer(slicer_name)
start_time = octoprint.util.monotonic_time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name,
"stl": source_path,
"stl_location": source_location,
"gcode": dest_path,
"gcode_location": dest_location,
@@ -428,7 +438,8 @@ class FileManager(object):
try:
callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
except Exception:
self._logger.exception("Exception while pushing slicing progress")
self._logger.exception("Exception while pushing slicing progress",
extra=dict(callback=fqcn(callback)))
if progress_int:
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
@@ -602,9 +613,6 @@ class FileManager(object):
name=dst_name))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def create_print_job(self, destination, path, user=None):
return self._storage(destination).create_print_job(path, user=user)
def has_analysis(self, destination, path):
return self._storage(destination).has_analysis(path)
@@ -619,13 +627,10 @@ class FileManager(object):
def log_print(self, destination, path, timestamp, print_time, success, printer_profile):
try:
try:
if success:
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
else:
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
except NotImplementedError:
pass
if success:
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
else:
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path))
except NoSuchStorage:
# if there's no storage configured where to log the print, we'll just not log it
@@ -663,6 +668,8 @@ class FileManager(object):
try:
with io.open(self._recovery_file, 'rt', encoding='utf-8') as f:
data = yaml.safe_load(f)
if not isinstance(data, dict) or not all(map(lambda x: x in data, ("origin", "path", "pos", "date"))):
raise ValueError("Invalid recovery data structure")
return data
except Exception:
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
+12 -10
View File
@@ -19,6 +19,7 @@ import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import monotonic_time
from octoprint.util import get_fully_qualified_classname as fqcn
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
@@ -109,14 +110,15 @@ class AnalysisQueue(object):
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
callback(entry, result)
try:
callback(entry, result)
except:
self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback),
extra=dict(callback=fqcn(callback)))
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"result": result,
# TODO: deprecated, remove in a future release
"file": entry.path})
"result": result})
class AbstractAnalysisQueue(object):
"""
@@ -174,7 +176,10 @@ class AbstractAnalysisQueue(object):
(False, default)
"""
if high_priority:
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry))
return
elif high_priority:
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
prio = self.__class__.HIGH_PRIO
else:
@@ -255,10 +260,7 @@ class AbstractAnalysisQueue(object):
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"type": entry.type,
# TODO deprecated, remove in 1.4.0
"file": entry.path})
"type": entry.type})
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -20,7 +21,6 @@ except ImportError:
from octoprint.util import atomic_write
from contextlib import contextmanager
# noinspection PyCompatibility
from past.builtins import basestring
from emoji import demojize
@@ -30,10 +30,417 @@ import octoprint.filemanager
from octoprint.util import is_hidden_path, to_unicode, to_bytes
from . import Storage, StorageError
class StorageInterface(object):
"""
Interface of storage adapters for OctoPrint.
"""
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
yield
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
Args:
path (str or None): Path for which to determine the subtree's last modification date. If left out or
set to None, defatuls to storage root.
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
the whole ``path``'s subtree (True).
Returns: (float) The last modification date of the indicated subtree
"""
raise NotImplementedError()
def file_in_path(self, path, filepath):
"""
Returns whether the file indicated by ``file`` is inside ``path`` or not.
:param string path: the path to check
:param string filepath: path to the file
:return: ``True`` if the file is inside the path, ``False`` otherwise
"""
return NotImplementedError()
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def folder_exists(self, path):
"""
Returns whether the folder indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the folder exists, ``False`` otherwise
"""
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"name": "some_folder",
"path": "some_folder",
"type": "folder",
"children": {
"some_sub_folder": {
"name": "some_sub_folder",
"path": "some_folder/some_sub_folder",
"type": "folder",
"typePath": ["folder"],
"children": { ... }
},
"some_file.gcode": {
"name": "some_file.gcode",
"path": "some_folder/some_file.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"name": "test.gcode",
"path": "test.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"name": "test.stl",
"path": "test.stl",
"type": "model",
"typePath": ["model", "stl"],
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
do one step down into sub folders to be able to populate the ``children``.
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
"""
raise NotImplementedError()
def copy_folder(self, source, destination):
"""
Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
def move_folder(self, source, destination):
"""
Moves the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
def remove_file(self, path):
"""
Removes the file at ``path``
Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param string path: path of the file to remove
"""
raise NotImplementedError()
def copy_file(self, source, destination):
"""
Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
def move_file(self, source, destination):
"""
Moves the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
raise NotImplementedError()
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
referring to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
raise NotImplementedError()
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
raise NotImplementedError()
def canonicalize(self, path):
"""
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
implementation must separate those if necessary.
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
of stripping any invalid characters.
Args:
path: the path to canonicalize
Returns:
a 2-tuple containing the canonicalized path and file name
"""
return self.sanitize(path)
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
raise NotImplementedError()
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
raise NotImplementedError()
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class LocalFileStorage(Storage):
class StorageError(Exception):
UNKNOWN = "unknown"
INVALID_DIRECTORY = "invalid_directory"
INVALID_FILE = "invalid_file"
INVALID_SOURCE = "invalid_source"
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
BaseException.__init__(self)
self.message = message
self.cause = cause
if code is None:
code = StorageError.UNKNOWN
self.code = code
class LocalFileStorage(StorageInterface):
"""
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
@@ -59,7 +466,7 @@ class LocalFileStorage(Storage):
text = demojize(text, delimiters=("", ""))
return cls._SLUGIFY(text)
def __init__(self, basefolder, create=False, key="local"):
def __init__(self, basefolder, create=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
if necessary and ``create`` is set to ``True``.
@@ -442,17 +849,6 @@ class LocalFileStorage(Storage):
metadata = self.get_metadata(path)
return "analysis" in metadata
def create_print_job(self, path, user=None):
from octoprint.comm.job import LocalGcodeFilePrintjob
return LocalGcodeFilePrintjob(self.path_on_disk(path),
"local",
self.path_in_storage(path),
name=self.path_in_storage(path),
user=user,
event_data=dict(path=path,
name=self.split_path(path)[1],
origin="local"))
def get_metadata(self, path):
path, name = self.sanitize(path)
return self._get_metadata_entry(path, name)
@@ -1,457 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
class Storage(object):
"""
Interface of storage adapters for OctoPrint.
"""
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
# noinspection PyUnreachableCode
yield
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
# noinspection PyUnreachableCode
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
Args:
path (str or None): Path for which to determine the subtree's last modification date. If left out or
set to None, defatuls to storage root.
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
the whole ``path``'s subtree (True).
Returns: (float) The last modification date of the indicated subtree
"""
raise NotImplementedError()
def file_in_path(self, path, filepath):
"""
Returns whether the file indicated by ``file`` is inside ``path`` or not.
:param string path: the path to check
:param string filepath: path to the file
:return: ``True`` if the file is inside the path, ``False`` otherwise
"""
return NotImplementedError()
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def folder_exists(self, path):
"""
Returns whether the folder indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the folder exists, ``False`` otherwise
"""
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"name": "some_folder",
"path": "some_folder",
"type": "folder",
"children": {
"some_sub_folder": {
"name": "some_sub_folder",
"path": "some_folder/some_sub_folder",
"type": "folder",
"typePath": ["folder"],
"children": { ... }
},
"some_file.gcode": {
"name": "some_file.gcode",
"path": "some_folder/some_file.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"name": "test.gcode",
"path": "test.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"name": "test.stl",
"path": "test.stl",
"type": "model",
"typePath": ["model", "stl"],
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
do one step down into sub folders to be able to populate the ``children``.
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
"""
raise NotImplementedError()
def copy_folder(self, source, destination):
"""
Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
def move_folder(self, source, destination):
"""
Moves the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
def remove_file(self, path):
"""
Removes the file at ``path``
Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param string path: path of the file to remove
"""
raise NotImplementedError()
def copy_file(self, source, destination):
"""
Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
def move_file(self, source, destination):
"""
Moves the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
def create_print_job(self, path, user=None):
"""
Retrieves the :class:`~octoprint.job.PrintJob` instance
to use for printing ``path``.
"""
raise NotImplementedError()
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
raise NotImplementedError()
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
referring to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
raise NotImplementedError()
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
raise NotImplementedError()
def add_history(self, path, data):
"""
Adds a history entry for the given ``path``.
:param path: path of the file for which to add the history entry
:param data: history entry
"""
raise NotImplementedError()
def update_history(self, path, index, data):
"""
Updates the history entry for ``path`` at ``index``.
:param path: path of the file for which to update the history entry
:param index: index
:param data: history entry
"""
raise NotImplementedError()
def remove_history(self, path, index):
"""
Removes the history entry for ``path`` at ``index``.
:param path: path of the file for which to remove the history entry
:param index: index
"""
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
raise NotImplementedError()
def canonicalize(self, path):
"""
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
implementation must separate those if necessary.
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
of stripping any invalid characters.
Args:
path: the path to canonicalize
Returns:
a 2-tuple containing the canonicalized path and file name
"""
return self.sanitize(path)
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
raise NotImplementedError()
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
raise NotImplementedError()
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class StorageError(Exception):
UNKNOWN = "unknown"
INVALID_DIRECTORY = "invalid_directory"
INVALID_FILE = "invalid_file"
INVALID_SOURCE = "invalid_source"
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
BaseException.__init__(self)
self.message = message
self.cause = cause
if code is None:
code = StorageError.UNKNOWN
self.code = code
@@ -1,14 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import Storage, StorageError
class PrinterSDStorage(Storage):
def create_print_job(self, path, user=None):
from octoprint.comm.job import SDFilePrintjob
return SDFilePrintjob("/" + path, user=user)
+8 -5
View File
@@ -107,7 +107,7 @@ class MultiStream(io.RawIOBase):
their contents in the order they are provided to the constructor.
Arguments:
*streams (io.IOBase): One or more streams to concatenate.
*streams (io.RawIOBase): One or more streams to concatenate.
"""
def __init__(self, *streams):
io.RawIOBase.__init__(self)
@@ -159,10 +159,12 @@ class LineProcessorStream(io.RawIOBase):
While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method
:meth:`.process_line` for each read line.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that
``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need
to do the decoding yourself.
Arguments:
input_stream (io.IOBase): The stream to process on the fly.
input_stream (io.RawIOBase): The stream to process on the fly.
"""
def __init__(self, input_stream):
@@ -220,10 +222,11 @@ class LineProcessorStream(io.RawIOBase):
wrapper `input_stream`.
Arguments:
line (str): The line as read from `self.input_stream`
line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and
bytes under Python 3)
Returns:
str or None: The processed version of the line (might also be multiple lines), or None if the line is to be
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
stripped from the processed stream.
"""
return line
+8 -7
View File
@@ -62,23 +62,23 @@ class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
pass
class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
do_rollover = dict()
do_rollover = False
suffix_template = "%Y-%m-%d_%H-%M-%S"
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
@classmethod
def on_open_connection(cls, logger):
cls.do_rollover[logger] = True
def on_open_connection(cls):
cls.do_rollover = True
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(CommunicationLogHandler, self).__init__(*args, **kwargs)
super(SerialLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
def shouldRollover(self, record):
return self.do_rollover.pop(record.name, False)
return self.do_rollover
def getFilesToDelete(self):
"""
@@ -107,6 +107,8 @@ class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFil
os.remove(path)
def doRollover(self):
self.do_rollover = False
if self.stream:
self.stream.close()
self.stream = None
@@ -123,7 +125,6 @@ class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFil
if not self.delay:
self.stream = self._open()
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, *args, **kwargs):
super(RecordingLogHandler, self).__init__(*args, **kwargs)
+121 -8
View File
@@ -23,7 +23,7 @@ import os
import logging
import threading
from octoprint.settings import settings as s, SubSettings
from octoprint.settings import settings as s
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin
from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules
@@ -230,7 +230,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
error_callback(plugin._identifier, plugin, exc)
class PluginSettings(SubSettings):
class PluginSettings(object):
"""
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
@@ -315,15 +315,78 @@ class PluginSettings(SubSettings):
"""
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
self.settings = settings
self.plugin_key = plugin_key
SubSettings.__init__(self, settings, ["plugins", plugin_key],
defaults=defaults,
get_preprocessors=get_preprocessors,
set_preprocessors=set_preprocessors)
if self.defaults is not None:
if defaults is not None:
self.defaults = dict(plugins=dict())
self.defaults["plugins"][plugin_key] = defaults
self.defaults["plugins"][plugin_key]["_config_version"] = None
else:
self.defaults = None
if get_preprocessors is None:
get_preprocessors = dict()
self.get_preprocessors = dict(plugins=dict())
self.get_preprocessors["plugins"][plugin_key] = get_preprocessors
if set_preprocessors is None:
set_preprocessors = dict()
self.set_preprocessors = dict(plugins=dict())
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
def prefix_path_in_args(args, index=0):
result = []
if index == 0:
result.append(self._prefix_path(args[0]))
result.extend(args[1:])
else:
args_before = args[:index - 1]
args_after = args[index + 1:]
result.extend(args_before)
result.append(self._prefix_path(args[index]))
result.extend(args_after)
return result
def add_getter_kwargs(kwargs):
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.get_preprocessors)
return kwargs
def add_setter_kwargs(kwargs):
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.set_preprocessors)
return kwargs
self.access_methods = dict(
has =("has", prefix_path_in_args, add_getter_kwargs),
get =("get", prefix_path_in_args, add_getter_kwargs),
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
get_boolean=("getBoolean", prefix_path_in_args, add_getter_kwargs),
set =("set", prefix_path_in_args, add_setter_kwargs),
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
remove =("remove", prefix_path_in_args, lambda x: x)
)
self.deprecated_access_methods = dict(
getInt ="get_int",
getFloat ="get_float",
getBoolean="get_boolean",
setInt ="set_int",
setFloat ="set_float",
setBoolean="set_boolean"
)
def _prefix_path(self, path=None):
if path is None:
path = list()
return ['plugins', self.plugin_key] + path
def global_has(self, path, **kwargs):
return self.settings.has(path, **kwargs)
@@ -415,3 +478,53 @@ class PluginSettings(SubSettings):
filename += ".log"
return os.path.join(self.settings.getBaseFolder("logs"), filename)
@deprecated("PluginSettings.get_plugin_data_folder has been replaced by OctoPrintPlugin.get_plugin_data_folder",
includedoc="Replaced by :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`",
since="1.2.0")
def get_plugin_data_folder(self):
path = os.path.join(self.settings.getBaseFolder("data"), self.plugin_key)
if not os.path.isdir(path):
os.makedirs(path)
return path
def get_all_data(self, **kwargs):
merged = kwargs.get("merged", True)
asdict = kwargs.get("asdict", True)
defaults = kwargs.get("defaults", self.defaults)
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
kwargs.update(dict(
merged=merged,
asdict=asdict,
defaults=defaults,
preprocessors=preprocessors
))
return self.settings.get(self._prefix_path(), **kwargs)
def clean_all_data(self):
self.settings.remove(self._prefix_path())
def __getattr__(self, item):
all_access_methods = list(self.access_methods.keys()) + list(self.deprecated_access_methods.keys())
if item in all_access_methods:
decorator = None
if item in self.deprecated_access_methods:
new = self.deprecated_access_methods[item]
decorator = deprecated("{old} has been renamed to {new}".format(old=item, new=new), stacklevel=2)
item = new
settings_name, args_mapper, kwargs_mapper = self.access_methods[item]
if hasattr(self.settings, settings_name) and callable(getattr(self.settings, settings_name)):
orig_func = getattr(self.settings, settings_name)
if decorator is not None:
orig_func = decorator(orig_func)
def _func(*args, **kwargs):
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
_func.__name__ = to_native_str(item)
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
return _func
return getattr(self.settings, item)
+36 -6
View File
@@ -39,7 +39,7 @@ import pkginfo
from past.builtins import unicode
from octoprint.util import to_unicode
from octoprint.util import to_unicode, sv
from octoprint.util.version import is_python_compatible, get_python_version_string
try:
@@ -130,6 +130,14 @@ class PluginInfo(object):
Bundled plugins will automatically be assumed to be compatible.
"""
attr_hidden = '__plugin_hidden__'
"""
Module attribute from which to determine if the plugin's hidden or not.
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
and similar places.
"""
attr_hooks = '__plugin_hooks__'
""" Module attribute from which to retrieve the plugin's provided hooks. """
@@ -444,10 +452,22 @@ class PluginInfo(object):
default=">=2.7,<3",
incl_metadata=True)
@property
def hidden(self):
"""
Hidden flag.
Returns:
bool: Whether the plugin should be flagged as hidden or not
"""
return self._get_instance_attribute(self.__class__.attr_hidden,
default=False,
incl_metadata=True)
@property
def hooks(self):
"""
Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defiend in
Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defined in
:attr:`attr_hooks` if available, otherwise an empty dictionary is returned.
Returns:
@@ -600,6 +620,16 @@ class PluginInfo(object):
result[key] = a.value.args[0].s
break
for key in (self.__class__.attr_hidden,):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Name) and a.value.id in ("True", "False"):
result[key] = bool(a.value.id)
break
except SyntaxError:
self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key))
self.invalid_syntax = True
@@ -1008,7 +1038,7 @@ class PluginManager(object):
# 1st pass: loading the plugins
for name, plugin in added.items():
try:
if not plugin.blacklisted and not plugin.forced_disabled:
if not plugin.blacklisted and not plugin.forced_disabled and not plugin.incompatible:
self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
except PluginNeedsRestart:
pass
@@ -1022,7 +1052,7 @@ class PluginManager(object):
# 2nd pass: enabling those plugins that need enabling
for name, plugin in added.items():
try:
if plugin.loaded and not plugin.forced_disabled:
if plugin.loaded and not plugin.forced_disabled and not plugin.incompatible:
if plugin.blacklisted:
self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin))
continue
@@ -1585,7 +1615,7 @@ class PluginManager(object):
sorting_value = None
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
return sorting_value is None, sorting_value, not plugin_info.bundled if plugin_info else True, impl[0]
return sorting_value is None, sv(sorting_value), not plugin_info.bundled if plugin_info else True, sv(impl[0])
return [impl[1] for impl in sorted(result, key=sort_func)]
@@ -1672,7 +1702,7 @@ class PluginManager(object):
def _sort_hooks(self, hook):
self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
key=lambda x: (x[0] is None, x[0], x[1], x[2]))
key=lambda x: (x[0] is None, sv(x[0]), sv(x[1]), sv(x[2])))
def _get_callback_and_order(self, hook):
if callable(hook):
+4 -1
View File
@@ -1391,9 +1391,12 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
# noinspection PyMethodMayBeStatic
def is_blueprint_protected(self):
"""
Whether a login session is needed to access the blueprint if the forcelogin plugin is enabled or not. Requiring
Whether a login session by a registered user is needed to access the blueprint's endpoints. Requiring
a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files
are always accessible.
If you want your blueprint's endpoints to have specific permissions, return ``False`` for this and do your
permissions checks explicitly.
"""
return True
@@ -82,6 +82,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
def on_event(self, event, payload):
if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
elif event == Events.DISCONNECTED:
self._close_prompt()
#~ SettingsPlugin
@@ -218,15 +220,18 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
return
self._close_prompt()
self._printer.commands(["{command} S{choice}".format(command=self._command,
choice=choice)])
if "{choice}" in self._command:
self._printer.commands([self._command.format(choice=choice)])
else:
self._printer.commands(["{command} S{choice}".format(command=self._command,
choice=choice)])
__plugin_name__ = "Action Command Prompt Support"
__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection"
__plugin_author__ = "Gina Häußge"
__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger"
"confirmation or selection prompts in OctoPrint")
" confirmation or selection prompts in OctoPrint")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = ActionCommandPromptPlugin()
__plugin_hooks__ = {
@@ -5,7 +5,17 @@ $(function() {
self.loginState = parameters[0];
self.access = parameters[1];
self._modal = undefined;
self.modal = ko.observable(undefined);
self.text = ko.observable();
self.buttons = ko.observableArray([]);
self.active = ko.pureComputed(function() {
return self.text() !== undefined;
});
self.visible = ko.pureComputed(function() {
return self.modal() !== undefined;
});
self.requestData = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
@@ -16,26 +26,35 @@ $(function() {
self.fromResponse = function(data) {
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
self._showPrompt(data.text, data.choices);
self.text(data.text);
self.buttons(data.choices);
self.showPrompt();
} else {
self.text(undefined);
self.buttons([]);
}
};
self._showPrompt = function(text, buttons) {
self.showPrompt = function() {
var text = self.text();
var buttons = self.buttons();
var opts = {
title: gettext("Message from your printer"),
message: text,
selections: buttons,
maycancel: true, // see #3171
onselect: function(index) {
if (index > -1) {
self._select(index);
}
},
onclose: function() {
self._modal = undefined;
self.modal(undefined);
}
};
self._modal = showSelectionDialog(opts)
self.modal(showSelectionDialog(opts));
};
self._select = function(index) {
@@ -43,8 +62,9 @@ $(function() {
};
self._closePrompt = function() {
if (self._modal) {
self._modal.modal("hide");
var modal = self.modal();
if (modal) {
modal.modal("hide");
}
};
@@ -60,10 +80,14 @@ $(function() {
switch (data.action) {
case "show": {
self._showPrompt(data.text, data.choices);
self.text(data.text);
self.buttons(data.choices);
self.showPrompt();
break;
}
case "close": {
self.text(undefined);
self.buttons([]);
self._closePrompt();
break;
}
@@ -74,6 +98,7 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: ActionCommandPromptViewModel,
dependencies: ["loginStateViewModel", "accessViewModel"]
dependencies: ["loginStateViewModel", "accessViewModel"],
elements: ["#navbar_plugin_action_command_prompt"]
});
});
@@ -0,0 +1,3 @@
<a id="navbar_show_prompt" class="pull-right" style="display: none" href="javascript:void(0)" data-bind="click: function() { showPrompt(); }, visible: active() && !visible()" title="{{ _('Message from your printer')|edq }}">
<i class="fa fa-commenting-o"></i>
</a>
@@ -242,6 +242,9 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
return NO_CONTENT
def is_blueprint_protected(self):
return False
##~~ EventHandlerPlugin
def on_event(self, event, payload):
@@ -1,3 +1,3 @@
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements')|edq }}">
<i class="fa" data-bind="css: {'fa-bell-o': !unread(), 'fa-bell': unread()}"></i>
</a>
+24 -6
View File
@@ -7,7 +7,7 @@ import os
import yaml
import io
import time
from binascii import hexlify
import uuid
from collections import defaultdict
from flask_babel import gettext
@@ -15,12 +15,11 @@ import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, no_firstrun_access
from octoprint.server import NO_CONTENT, current_user, admin_permission
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
from octoprint.util import atomic_write, monotonic_time, ResettableTimer, generate_api_key
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
@@ -45,6 +44,12 @@ class PendingDecision(object):
user_id=self.user_id,
user_token=self.user_token)
def __repr__(self):
return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id,
self.app_token,
self.user_id,
self.user_token)
class ReadyDecision(object):
def __init__(self, app_id, app_token, user_id):
@@ -56,6 +61,11 @@ class ReadyDecision(object):
def for_pending(cls, pending, user_id):
return cls(pending.app_id, pending.app_token, user_id)
def __repr__(self):
return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id,
self.app_token,
self.user_id)
class ActiveKey(object):
def __init__(self, app_id, api_key, user_id):
@@ -76,6 +86,11 @@ class ActiveKey(object):
def for_internal(cls, internal, user_id):
return cls(internal["app_id"], internal["api_key"], user_id)
def __repr__(self):
return u"ActiveKey({!r}, {!r}, {!r})".format(self.app_id,
self.api_key,
self.user_id)
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
@@ -135,12 +150,15 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if data is None:
return flask.make_response("Missing key request", 400)
if not "app" in data:
return flask.make_response("No app name provided", 400)
app_name = data["app"]
user_id = None
if "user" in data:
if "user" in data and data["user"]:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
@@ -362,7 +380,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
for user_id, data in self._keys.items():
if any(filter(lambda x: x.api_key == api_key, data)):
if self._user_manager.enabled:
return self._user_manager.findUser(userid=user_id)
return self._user_manager.find_user(userid=user_id)
elif user_id == "_admin" or user_id == "dummy":
# dummy = backwards compatible
return self._user_manager.anonymous_user_factory()
@@ -380,7 +398,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
return result
def _generate_key(self):
return hexlify(os.urandom(16))
return generate_api_key()
def _load_keys(self):
with self._keys_lock:
@@ -52,7 +52,7 @@ $(function() {
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
perform);
};
@@ -68,7 +68,7 @@ $(function() {
self.promptForAccess = function(app, token) {
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
message = _.sprintf(message, {app: app});
message = _.sprintf(message, {app: _.escape(app)});
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
return new PNotify({
title: gettext("Access Request"),
@@ -210,7 +210,7 @@ $(function() {
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
perform);
};
@@ -258,11 +258,11 @@ $(function() {
handler = function(key) {
return OctoPrint.plugins.appkeys.revokeKey(key)
.done(function() {
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: _.escape(key)}), true);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key});
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText});
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: _.escape(key)});
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: _.escape(key), error: _.escape(jqXHR.responseText)});
deferred.notify(short, long, false);
});
};
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff. Show more