Compare commits

...
Author SHA1 Message Date
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 4b04e8fd79 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
2019-05-14 11:22:35 +02:00
Gina Häußge 2edd2ba887 Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2019-05-14 11:21:19 +02:00
Gina Häußge fcef3a1bbd Merge branch 'staging/maintenance' into maintenance 2019-05-14 11:21:01 +02:00
Gina Häußge d1d24dba9a Merge branch 'rc/maintenance' into staging/maintenance 2019-05-14 11:18:37 +02:00
Gina Häußge 81735d07c9 Merge branch 'rc/maintenance' 2019-05-13 14:54:51 +02:00
Gina Häußge 2c640ff8b8 🔖 Preparing release of 1.3.11 2019-05-13 13:52:32 +02:00
Gina Häußge 0331a25ae3 📝 Reflect API key changes in docs
Closes #3121
2019-05-13 12:55:25 +02:00
Gina Häußge 326422013a Merge pull request #3147 from esver/autofocus
Add autocofus to the username in the login plugin
2019-05-13 11:23:37 +02:00
Olivier Esver 9b4da62e69 Add autocofus to the username in the login plugin 2019-05-11 20:53:51 +02:00
Gina Häußge c0096c41a0 Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/cli/plugins.py
#	src/octoprint/events.py
#	src/octoprint/filemanager/__init__.py
#	src/octoprint/logging/__init__.py
#	src/octoprint/plugins/announcements/__init__.py
#	src/octoprint/plugins/appkeys/__init__.py
#	src/octoprint/plugins/forcelogin/__init__.py
#	src/octoprint/plugins/forcelogin/static/js/main.js
#	src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
#	src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css
#	src/octoprint/plugins/printer_safety_check/__init__.py
#	src/octoprint/plugins/softwareupdate/__init__.py
#	src/octoprint/plugins/virtual_printer/virtual.py
#	src/octoprint/printer/__init__.py
#	src/octoprint/printer/estimation.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/__init__.py
#	src/octoprint/server/api/settings.py
#	src/octoprint/server/api/system.py
#	src/octoprint/server/apps/__init__.py
#	src/octoprint/server/util/__init__.py
#	src/octoprint/server/util/flask.py
#	src/octoprint/server/util/sockjs.py
#	src/octoprint/server/views.py
#	src/octoprint/settings.py
#	src/octoprint/slicing/__init__.py
#	src/octoprint/static/js/app/helpers.js
#	src/octoprint/static/js/app/main.js
#	src/octoprint/static/js/app/viewmodels/settings.js
#	src/octoprint/static/js/app/viewmodels/temperature.js
#	src/octoprint/templates/dialogs/settings/accesscontrol.jinja2
#	src/octoprint/templates/dialogs/settings/api.jinja2
#	src/octoprint/templates/initscript.jinja2
#	src/octoprint/templates/tabs/control.jinja2
#	src/octoprint/timelapse.py
#	src/octoprint/users.py
#	src/octoprint/util/comm.py
#	src/octoprint/util/gcodeInterpreter.py
#	src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py
#	src/octoprint/vendor/sockjs/tornado/transports/websocket.py
#	translations/messages.pot
2019-05-10 17:13:55 +02:00
Gina Häußge b46a66caa8 ♻ Slight refactoring... 2019-05-09 15:40:51 +02:00
Gina Häußge 6711813fef Merge pull request #3134 from tduehr/remote
Remote user support
2019-05-09 15:23:37 +02:00
Timur Duehr 7726e5c04e review fixes 2019-05-09 15:14:51 +02:00
Timur Duehr 495d99fbe9 Add support for remote users 2019-05-09 15:14:36 +02:00
Gina Häußge a35b7cddf2 🐛 Only add response text if there is one 2019-05-09 15:08:48 +02:00
Gina Häußge f2af5e8b86 💬 Change wording to reflect more potential error cases
Closes #3133
2019-05-09 14:59:00 +02:00
Gina Häußge 289c3a4d0f 🐛 Fix handling of Empty exception in send loop
Closes #3096
2019-05-09 13:39:56 +02:00
Gina Häußge 4cb67fe72c ☔ Don't allow NaN in generated JSON output on APIs
See also #3022
2019-05-08 17:52:27 +02:00
Gina Häußge b79fc94a4e ☔ Protect against NaN & Inf in GCODE
Also cleanup broken metadata entries that contain invalid json.

Fixes #3022
2019-05-08 17:49:53 +02:00
Gina Häußge fca626a3d6 ✨ Support tags on GCODE script hook
Also add `plugin:<plugin id>` to script parts from plugins.

Implements #3101
2019-05-08 16:55:18 +02:00
Gina Häußge f5a04973c4 🐛 Fix emergency codes not jumping queues
Fixes #3104
2019-05-07 15:10:18 +02:00
Gina Häußge 1c9ff91bae ♻️ Make emergency codes configurable 2019-05-07 15:09:41 +02:00
Gina Häußge e1e521300b 🐛 Only do autologin if not actively logged out
Fixes #3142
2019-05-07 13:11:33 +02:00
Gina Häußge c1e8bc717a 🐛 gcodeviewer: fix layers vanishing on rerender
Fixes #3143
2019-05-07 12:33:19 +02:00
Gina Häußge 22d7392769 🔊 gcodeviewer: Increase logging 2019-05-07 11:09:42 +02:00
Gina Häußge 904e7d2ecd 🐛 gcode viewer: do not invert axes
The axis inversion is only relevant to the control panel (depends on
how the print head is positioned), NOT the rendition of the GCODE.

Fixes #3137
2019-05-03 17:26:55 +02:00
Gina Häußge b3173386ae 🐛 modals: re-add missing minHeight support 2019-05-03 16:44:38 +02:00
Gina Häußge 1e3b8dfb2c Merge pull request #3131 from rfinnie/multiple-events
[Request] Allow subscriptions of multiple events
2019-05-03 16:08:46 +02:00
Gina Häußge 94d172ab67 Merge branch 'maintenance' into multiple-events 2019-05-03 15:57:50 +02:00
Gina Häußge 7dac6ca433 Merge pull request #3126 from jackwilsdon/toggle-search-filtering
Add option for disabling filters on search results
2019-05-03 15:32:51 +02:00
Ryan Finnie 9aeeb5fecc Allow subscriptions of multiple events
events > subscriptions[] > event may be either a string (existing
functionality) or now a list of strings.  If a list, the subscriptions
are treated the same for each event in the list.

To make it possible for command subscriptions to determine which event
was triggered, a {__eventname} substitution has been added.
2019-04-24 10:11:09 -07:00
Gina Häußge 52f65b469d Merge branch 'staging/maintenance' into maintenance 2019-04-24 16:29:20 +02:00
Gina Häußge 0843c0fbc7 📝 Reflect API key changes in docs
Closes #3121
2019-04-24 16:26:10 +02:00
Jack Wilsdon 11607fbc73 Add jackwilsdon to author list 2019-04-20 15:53:55 +01:00
Jack Wilsdon 1521b76090 Add option for disabling filters on search results 2019-04-20 15:24:06 +01:00
Gina Häußge a33a7b4d67 Merge branch 'staging/maintenance' into maintenance 2019-04-11 15:25:12 +02:00
Gina Häußge c00fdbf73b 🔖 staging/maintenance is now 1.3.11rc4.dev 2019-04-11 15:21:39 +02:00
Gina Häußge af32858549 🔖 Preparing release of 1.3.11rc3, part 2 2019-04-11 12:21:24 +02:00
Gina Häußge d1104ddbae 🐛 Fix file list refresh after SD list update 2019-04-11 12:14:59 +02:00
Gina Häußge e2519abbbe ✨ Add setting for exclusive comm port flag
Just in case there are issues with that on some setups as first RC seem
to indicate, we make it toggleable.
2019-04-11 12:14:38 +02:00
Gina Häußge 967b3bbff8 🔖 Preparing release of 1.3.11rc3 2019-04-10 17:38:17 +02:00
Gina Häußge 9721aec32a 🐛 printer safety: Fix for unicode issues
Fixes #3090
2019-04-10 17:15:59 +02:00
Gina Häußge 68952c20bd ⏪ Switch lines read from serial back to bytes
While long term we want to have unicode here, the rest of the code
is not even remotely prepared for handling utf-8 strings as visible in
the large amount of unicode issues visible in sentry.

So for now we go back to byte objects and fix #3091 differently
2019-04-10 17:15:58 +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 9775d99feb 🔇 error tracking: mute tornado's WebSocketErrors 2019-04-10 12:03:45 +02:00
Gina Häußge bfcff9a1cd 🐛 Fix some potential encoding errors 2019-04-10 12:03:31 +02:00
Gina Häußge 5ca286f4e3 🔇 error tracking: mute ispErrors 2019-04-10 11:39:02 +02:00
Gina Häußge 7dae700215 🐛 sockjs-tornado: Handle websocket errors 2019-04-09 17:32:29 +02:00
Gina Häußge 58806a3d00 🔧 error tracking: update DSNs 2019-04-09 17:22:16 +02:00
Gina Häußge 72cc1afb45 🐛 Refresh connection tab on disconnect
That way we'll hopefully notice vanishing/changed ports.

Potential fix for #3111, waiting for test results from @arhi
2019-04-09 17:00:57 +02:00
Gina Häußge 323131cbc5 ☔ Harden against estimation exceptions 2019-04-09 16:56:17 +02:00
Gina Häußge f389773036 ☔ Make sure rolling window is at least 1
See #3116
2019-04-09 16:56:02 +02:00
Gina Häußge 0a04043922 🐛 Fix potential division by zero
Fixes #3116
2019-04-09 16:55:35 +02:00
Gina Häußge 84fa3b6073 🐛 Don't log empty lines
See also #3115
2019-04-09 11:07:11 +02:00
Gina Häußge d6576306b0 🐛 Add missing rstrip
Fixes #3115
2019-04-09 11:06:04 +02:00
Gina Häußge 8970fb42b1 ✨ error tracking: further filtering 2019-04-08 14:08:57 +02:00
Gina Häußge 55e8cc1118 ☔ more type annotations 2019-04-08 13:05:27 +02:00
Gina Häußge 43e2f79575 🐛 Fix a unicode issue
Fixes #3109
2019-04-08 13:05:02 +02:00
Gina Häußge 132e2cb244 🐛 virtual printer: Fix handling of closed connection
Closes #3114
2019-04-08 12:24:24 +02:00
Gina Häußge de6d1afdd6 ✨ Add flag to ignore incomplete startup
See https://github.com/foosel/OctoPrint/issues/3103#issuecomment-480612935
2019-04-08 12:12:00 +02:00
Gina Häußge 0a1cc68a6b ♻ error tracking: minor restructuring 2019-04-05 18:36:50 +02:00
Gina Häußge f1309dad1d ✨ error tracking: filter all exceptions triggered in plugins
The new extra parameter passed to exception loggers throughout
OctoPrint allows even more aggressive filtering to reduce the noise
further.
2019-04-05 17:48:52 +02:00
Gina Häußge b353c4eee2 ✨ extra logging parameter to add plugin identifier
Will allow to identify logged exceptions originating from calling
plugins, but also log plugin identifiers directly in the log message
if so desired.
2019-04-05 17:47:36 +02:00
Gina Häußge 34c30ed73f 🐛 Fix wrong textual representation of STARTING state
See comment/log files in #3104
2019-04-05 16:23:11 +02:00
Gina Häußge c28faa8032 ☔ SWU: empty restart command == unset 2019-04-05 15:37:25 +02:00
Gina Häußge 8da5bb2d42 🐛 Fix bug in port detection
Closes #3108
2019-04-05 15:19:58 +02:00
Gina Häußge 54c885f1ad ☔ Prevent issues if hash is n/a
Apparently it can happen that no hash is available for an STL file.
See SERVER-TQ in Sentry.

So let's be a bit more careful here.

Closes #3107
2019-04-05 10:24:41 +02:00
Gina Häußge 65fe048ade ☔ error tracking: ignore RequestExceptions
We don't want to get error events every time someone's net connection
goes down or the webcam is misconfigured.
2019-04-05 10:17:12 +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
Gina Häußge 3574c2ddf9 🐛 virtual printer: Fix yet another unicode issue
Closes #3105
2019-04-04 19:05:17 +02:00
Gina Häußge 1dc0f1fb31 ☔ Define empty UI_API_KEY to be backwards compatible
Some plugins rely on this to be defined, let's give them some more time
to update.
2019-04-04 18:55:24 +02:00
Gina Häußge 30ddbfd324 Merge branch 'staging/maintenance' into maintenance 2019-04-04 17:12:01 +02:00
Gina Häußge 5c522d86ca Merge remote-tracking branch 'origin/staging/maintenance' into staging/maintenance 2019-04-04 17:09:11 +02:00
Gina Häußge f785c8180b 🔖 staging/maintenance is now 1.3.11rc3.dev 2019-04-04 17:08:33 +02:00
Gina Häußge 18e7d2b72a 🔖 Preparing release of 1.3.11rc2 2019-04-04 14:26:01 +02:00
Gina Häußge 410c3ee5f6 ☔ error tracking: ignore errors from packed_plugins.js 2019-04-04 14:12:19 +02:00
Gina Häußge 48825fd4c2 ⬆ error tracking: update js sentry sdk 2019-04-04 14:11:30 +02:00
Gina Häußge ff9c83ea25 ☔ Don't confuse users with pip's "OMG PY2.7 IS EOL!!1!" message
We know that python 2.7 is about to reach end of life. We are making
preparations for this in the devel branch. We don't need pip going
around and alarming our users about something they cannot solve, and
which pretty much is already solved anyhow.

So we nuke this stupid message present in current pip versions. Hard.

See also #2988
2019-04-04 11:51:16 +02:00
Gina Häußge 2c18a40dcb ⬆ Update bootstrap modal
Fixes #3095
2019-04-01 14:47:42 +02:00
Gina Häußge 0b6dd7e76e 🐛 backup: exclude timelapse_tmp if timelapse is excluded
Fixes #3098
2019-04-01 14:28:40 +02:00
Gina Häußge d68c7bfc67 ☔ More resilience against platform startup issues
Might solve problems like #3100, but that is only a shot in the dark at
this point.
2019-04-01 13:57:29 +02:00
Gina Häußge c879ad27f4 ♻ Turn lines read from serial into unicode
Backported from devel branch.

Should also fix #3091
2019-04-01 13:56:19 +02:00
Gina Häußge d1914824c6 🐛 Don't read returncode on async commands 2019-03-29 17:43:45 +01:00
Gina Häußge 79196eeaf7 🔇 Match up log level 2019-03-29 17:37:02 +01:00
Gina Häußge 6491db730d ☔ Harden against broken configs
See Sentry issue SERVER-BF
2019-03-29 17:22:00 +01:00
Gina Häußge bd07cda205 ✨ error tracking: support ignoring specific exceptions
We are not interested in any SerialExceptions raised in the comm layer
due to people ripping out cables or having otherwise broken comms.
2019-03-29 16:38:15 +01:00
Gina Häußge 9c7ca0ab7a ✏ Add thanks to sentry.io 2019-03-29 16:34:48 +01:00
Gina Häußge c4da5d6764 🔇 Some changes in what gets reported as error 2019-03-29 15:27:16 +01:00
Gina Häußge 47187c233d 🐛 Default value for self._errorValue 2019-03-29 15:08:44 +01:00
Gina Häußge 982ed793d9 📈 error tracking: change DSNs 2019-03-29 14:32:34 +01:00
Gina Häußge 718306073e ♻ error tracking: Restrict what gets tracked
We are only interested in

  * Exceptions that are
  * logged either in octoprint.* or tornado.* and not from third party
    plugins or unhandled

Implements #3094
2019-03-29 14:12:23 +01:00
Gina Häußge df6e94f7a3 🐛 Better validation of tool parameter on /api/printer/tool
Fixes #3092
2019-03-28 20:21:44 +01:00
Gina Häußge 1a2739c640 🐛 Fix /api/printer/tool endpoint
Fixes #3090

Fixes SERVER-24
2019-03-28 19:58:42 +01:00
Gina Häußge 9d318a4031 ☔ More hardening against invalid language packs
See issue SERVER-G in Sentry
2019-03-28 14:44:37 +01:00
Gina Häußge 292d608b97 🐛 Fix missing _chamberTemp definition
Closes #3089
2019-03-28 13:38:33 +01:00
Gina Häußge 2d7cb40633 🐛 Fix for plugin vars that contain unicode
ETag calculation could otherwise fall flat on its face.

Fixes #3088
2019-03-28 13:18:55 +01:00
Gina Häußge ce9315850f 🔖 maintenance is now 1.3.12.dev 2019-03-28 12:25:22 +01:00
Gina Häußge b8dbc627cb 🔖 staging/maintenance is now 1.3.11rc2.dev 2019-03-28 12:23:25 +01:00
Gina Häußge 73df8c2407 🔖 Preparing release of 1.3.11rc1, part 2 2019-03-28 10:54:19 +01:00
Gina Häußge 55ec8b1809 🐛 Partial revert of always sending SettingsUpdated event
It was causing a ton of issues with backend code using `Settings.save`
to persist changes outside of REST API calls, triggering configuration
update dialogs in the frontend way too often and when not needed.

Added a flag instead to cause the `save` method to trigger an event and
setting that to False by default. Settings REST API uses it, other
callees in e.g. plugin code will be able to as well in the future if
necessary.

It would be cleaner to always trigger this event and adjust calling code
and frontend code to compensate, but with third party plugins out there
this is not going to happen reliably so we go this route.
2019-03-28 10:52:15 +01:00
Gina Häußge 33eba705bf 🐛 invalid API key = no API key 2019-03-27 17:05:30 +01:00
Gina Häußge 9ec3a6ae7a ➖ Remove python-dateutil dependency
It's no longer installable from source under OctoPi 0.14 due to an
unpinned setup_requires dependency on setuptools_scm, and since we still
have to support that installation scenario that is a problem. Thankfully
it's only used in the plugin manager for parsing the notice date, and
we can just use datetime.strptime for that.
2019-03-27 14:34:13 +01:00
Gina Häußge ec2ba63425 🔖 Preparing release of 1.3.11rc1 2019-03-26 14:58:45 +01:00
Gina Häußge 6097222b7b ♻ Remove onWizardPreventSettingsRefreshDialog
Makes the whole wizard stuff less complex.
2019-03-26 14:46:06 +01:00
Gina Häußge 40396847e3 ⬆ werkzeug.contrib.cache is now cachelib 2019-03-26 10:12:58 +01:00
Gina Häußge a296574c70 🐛 Fix handling of invalid API keys 2019-03-25 11:31:56 +01:00
Gina Häußge 547962f4bc 🐛 Fix login via Authorization header 2019-03-25 11:31:41 +01:00
Gina Häußge 1d2ceefb72 🐛 appkeys: Fix in case of disabled access control
Closes #3071
2019-03-22 19:45:22 +01:00
Gina Häußge 3d4422021e ⬆ Updated various dependencies
Closes #3074
2019-03-22 18:52:16 +01:00
Gina Häußge 3b5c11a2bb ✏ Typo 2019-03-20 14:28:35 +01:00
Gina Häußge 4908d94c97 🐛 Fix initialization of temperature graph
Was broken by #3072 & followup work
2019-03-20 13:09:58 +01:00
Gina Häußge 17a7e508c3 ♻ Remove UI_API_KEY & API disabling
With the inclusion of the ForceLogin plugin that doesn't serve a real
purpose anymore in most cases, and it was only ever more of a rate
limiting feature than an actual security measure anyhow. Plus it lead to
a ton of false security alarms along the lines of "OMG UI_API_KEY IN THE
SOCKET HANDSHAKE, PWNED!!1!".

On stock installations, the behaviour will be unchanged since the
ForceLogin plugin prevents any kind of API access without authentication
that isn't the login request itself, including access to blueprint
plugin endpoints that do not specify that they are unprotected.

If a user decides to disable the ForceLogin plugin but keep access
control enabled, anonymous API access will now be possible without API
key or the need to fetch the current UI API Key from the server via the
websocket or the source code of the index page. This is a change
compared to earlier behaviour, but with a very limited impact as as
mentioned the UI API Key was so far also easily obtainable either via
the websocket or by parsing a fresh copy of the HTML page.

If the user decides to disable access control, there's no change
compared to previous behaviour.

Disabling the API - which was so far the only real use case for having
the UI API Key in the first place apart from basic rate limiting - has
also been removed. Allowing this only made things horribly complex as
the default frontend fully depends on the API's availability. Users
who do not wish third parties to have access to the API should
simply leave the ForceLogin plugin enabled.
2019-03-19 17:14:19 +01:00
Gina Häußge 0069c94d35 🐛 forcelogin: add favicon meta tags 2019-03-19 16:55:02 +01:00
Gina Häußge 99e7824913 🐛 Fix some outdated links to the forum 2019-03-19 15:00:10 +01:00
Gina Häußge ceade46dd7 🐛 Fix caching headers on main view
Clients/browsers should be instructed to always revalidate against the
server in order to prevent any kind of old content to be served.

See https://community.octoprint.org/t/cant-login-to-the-web-interface/7908/17?u=foosel
2019-03-19 14:48:45 +01:00
Gina Häußge bc66d29d02 🐛 Fix reporting back of active port & baudrate
Closes #2859
2019-03-19 13:24:00 +01:00
Gina Häußge 9ea1074b03 ✨ Process watched folder on startup
Implements #2462
2019-03-19 11:52:32 +01:00
Gina Häußge 6e069211cc Merge remote-tracking branch 'origin/maintenance' into maintenance 2019-03-18 17:06:26 +01:00
Gina Häußge 8d3befb01f ✨ Support for heated chamber fw capabilities
Chamber temperatures reported via M105 will only be parsed if the
fw reports chamber capabilities (through Cap:CHAMBER_TEMPERATURE:1) or
the currently selected printer profile has a heated chamber configured.
This is to avoid incompatibility issues with firmware variants that
might already use the C parameter for something else (which might be the
case since we don't have a reliable well defined standard that people
need to adhere to...)

Chamber temperature commands M141 and M191 will only be allowed to be
sent if the selected printer profile has a heated chamber configured.
This mirrors the behaviour for the bed temperature commands M140 and
M190 and heated bed configuration.

Display of chamber data in the graph will only happen if the printer
profile has a heated chamber configured.

Implements one workflow behind #321
2019-03-18 16:51:12 +01:00
Gina Häußge 42a6cab92e Merge pull request #3072 from Fabi0San/maint/temperature
Hides temperature tab if the machine has no heated bed nor extruders.
2019-03-18 12:57:35 +01:00
Gina Häußge 083e424529 ✏️ Fix a typo in the german translation
Closes #3061
2019-03-17 13:27:16 +01:00
Gina Häußge d5eefcd1a5 🐛 virtual: fix homing 2019-03-16 09:40:55 +01:00
Gina Häußge c1670d03c8 🐛 virtual: fix parsing of negative coordinates
Closes #3080
2019-03-16 09:29:04 +01:00
Gina Häußge b2637eb06a 🐛 Fix refactoring error 2019-03-13 15:09:27 +01:00
Gina Häußge 47179f2956 ☔ forcelogin: Never handle the UI if ACL is disabled
The following `passive_login` should always succeed if ACL is disabled
and hence this *should* not have caused issues, but considering

https://community.octoprint.org/t/cant-login-to-the-web-interface/7908/3

it might have after all, so better be safe than sorry here.
2019-03-13 15:09:02 +01:00
Gina Häußge d64b8512ab 💄 PGMR, SWU: Use scrollables instead of pagination 2019-03-12 17:02:14 +01:00
Gina Häußge 602ec5c495 🐛 Only use page size from local storage if configured
Should be a conscious decision by whoever uses ItemListHelper since
otherwise the size can never be changed again to a new default.

Follow-up to #2620
2019-03-12 16:52:17 +01:00
Gina Häußge a63ee9355e 🎨 Fix some linter warnings 2019-03-12 16:47:55 +01:00
Gina Häußge e44ae7a024 💚 Fix broken unit test
Who broke the test? That's right... me 😕
2019-03-12 16:26:14 +01:00
Gina Häußge 76ad332287 ♻ Use monotonic_time for relative times
Timeouts, durations and such shouldn't depend on the non-monotonic
system clock but instead use a monotonic time source.
2019-03-12 16:03:58 +01:00
Gina Häußge 93ab7bb089 Merge branch 'pr/3073' into maintenance 2019-03-12 13:57:08 +01:00
Gina Häußge b4e7e73e29 ♻ Use length of tool array for visibility
No need for an additional variable to keep in sync.
2019-03-12 13:56:53 +01:00
Gina Häußge 92ad53a9ec ♻ Use ko computed for visibility state 2019-03-12 13:42:45 +01:00
Gina Häußge 21c9c51858 ♻ Backport some more pieces from devel 2019-03-12 13:40:58 +01:00
Gina Häußge 38a321e175 ✨ Add configurable list of blocked and pausing commands
Instead of a boolean option to block sending of M0 *and* M1 and
hardcoding them and M25 to pause an ongoing print, we now have two lists
for blocked commands and pausing commands respectively.

Blocked by default: M0 and M1.

Pausing by default: M0, M1 and M25.

Implements #2970
2019-03-12 12:16:23 +01:00
Gina Häußge 32050c31ae 🐛 Only process pause if we aren't already pausing
Also don't process a pause if we are cancelling. "isPrinting" is too
broad here, so we use explicit states.
2019-03-12 12:12:24 +01:00
Gina Häußge f020fc1bc6 ✨ Add ipv4- and ipv6-only command line flags
-4 or --ipv4 will behave as if "--host 0.0.0.0" (or any other specific
v4 address) was supplied and only bind the server socket to v4. It will
be ignored if a v6 address is set to bind to.

-6 or --ipv6 will only bind the server socket to v6 instead of dual
stack on both v4 and v6. It will be ignored if a v4 address is set to
bind to.

Implements #2904
2019-03-11 17:21:28 +01:00
Gina Häußge a1e8694073 🐛 Don't change to PRINTING state on resume if not RESUMING
See #2955
2019-03-11 16:02:20 +01:00
Gina Häußge e748b52098 🐛 Don't change to PAUSED state if not PAUSING
Fixes #2955
2019-03-11 15:34:11 +01:00
Gina Häußge aab629d80e 🎨 except: => except Exception: 2019-03-06 15:10:38 +01:00
Gina Häußge 4e2afbc170 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/filemanager/storage.py
#	src/octoprint/util/__init__.py
#	src/octoprint/util/comm.py
2019-03-06 14:49:42 +01:00
Gina Häußge 8668c6200a ✨ Decorator for timing methods
Probably mostly helpful during development...
2019-03-06 13:53:53 +01:00
Gina Häußge e01f391b30 ⚡ More intelligent use of copy & deepcopy
Improves performance of file manipulation, especially in cases with a
lot of files in the folder, without the added complexity of fully
decoupling metadata file serialization from general processing.

Better fix for #3057
2019-03-06 13:44:45 +01:00
Gina Häußge 92618362e1 💚 Forgot to adjust the tests for d071684 2019-03-05 17:01:10 +01:00
Gina Häußge d071684d41 ♻ Remove old metadata.yaml files
Were deprecated and supposed to be removed with 1.3.10, we'll do it with
1.3.11.
2019-03-05 16:53:30 +01:00
Gina Häußge 7d0bd6a339 ☔ Remove stale entries from metadata
If a file no longer exists on disk for whatever reason it also doesn't
need to be kept in metadata.json.

See also #3057

Cherry-picked from 15d3b2ca
2019-03-05 16:20:13 +01:00
Fabi0San 1b5a654a2d Hide Tool section in Control for machines with no extruders. Such as Lasers. 2019-03-04 19:00:08 -08:00
FabioSan f0ee7f343e Hides temperature tab if the machine has no heated bed nor extruders. 2019-03-04 18:34:55 -08:00
Gina Häußge 3e16f0901a Merge remote-tracking branch 'origin/maintenance' into maintenance 2019-03-01 11:21:01 +01:00
Gina Häußge 8866ed716d ☔ Better resilience against invalid SD status reports 2019-03-01 11:20:45 +01:00
Gina Häußge cf16392e18 💚 Ignore vendor path for tests & fix 2.7 tests 2019-02-28 17:05:13 +01:00
Gina Häußge 34e4a20866 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/plugins/__init__.py
#	src/octoprint/plugins/tracking/__init__.py
2019-02-28 16:40:04 +01:00
Gina Häußge 0f157d3747 ♻ Load bundled plugins under octoprint.plugins.*
Makes more sense than putting them into sys.modules as <identifier>,
which also can cause conflicts (e.g. in the case of octoprint.plugins
.logging which then suddenly gets found instead of the built-in crucial
logging module).
2019-02-28 16:37:09 +01:00
Gina Häußge 1b3a8acf0d ♻ Work around deprecation of imp
After two days of trying to make the plugin loading work completely,
including loading bundled templates etc, using only native importlib
methods, I've finally given up and bundled the (deprecated) imp module
for Python 3+ which relies on importlib but does some magic I've yet to
figure out which makes stuff just work.

Replacing imp completely with something more slim is something for
another day, for now we want to get stuff to work under Py3 with as
little warnings as possible.
2019-02-28 16:07:07 +01:00
Gina Häußge fdb4e75241 Merge pull request #3066 from fieldOfView/fix_docs_job_state
Add missing documentation about state in `jobs` endpoint
2019-02-28 12:34:35 +01:00
Gina Häußge 4dbb24ecd7 📝 state is not a sub data model but a string 2019-02-28 12:26:25 +01:00
fieldOfView a15e2de251 Fix datamodel structure 2019-02-28 12:17:35 +01:00
fieldOfView c652bed871 Add missing documentation about state in jobs endpoint 2019-02-28 11:40:22 +01:00
Gina Häußge 1ed6730400 🔊 Improved logging in case of plugin syntax errors 2019-02-27 16:11:00 +01:00
Gina Häußge dde99736e4 📝 Fix an error in the docs 2019-02-27 14:32:37 +01:00
Gina Häußge 334f2c35f9 ✨ Allow to ignore compatibility for plugins
Adding a plugin's identifier to the list plugins._forcedCompatible in
config.yaml will make OctoPrint ignore its python compatibility status,
e.g.

    plugins:
      _forcedCompatible:
      - myplugin

This might be helpful for plugin authors during development but should
NOT be used in production!

See also #2722
2019-02-27 14:28:35 +01:00
Gina Häußge aacd59ae78 ☔ Log exceptions while parsing the AST 2019-02-27 13:43:01 +01:00
Gina Häußge 253a38c32d ♻ gcode => printables 2019-02-26 15:31:22 +01:00
Gina Häußge e08becbb4c Merge pull request #3055 from AndyQ/show_current_layer
Added ability to preview the current layer to be drawn
2019-02-26 13:54:43 +01:00
Gina Häußge 09a043b393 🐛 tracking: fix handling of missing print time
See also #3063
2019-02-26 13:50:35 +01:00
Gina Häußge 058dbd0c2e 🐛 virtual: fix regexes again 2019-02-22 18:46:45 +01:00
Gina Häußge 54c8923087 🐛 virtual: fix some str/bytes issues
Threw some type annotations into it while at it. Should make the IDE
become angry at such problems in the future.
2019-02-22 18:29:36 +01:00
Gina Häußge 1025f0be43 💚 Revert "🎨 Remove unnecessary import"
This reverts commit 295b96f259.
2019-02-22 13:31:36 +01:00
Gina Häußge 295b96f259 🎨 Remove unnecessary import
Already included in the next line
2019-02-22 12:53:18 +01:00
Gina Häußge adea0db344 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/util/__init__.py
2019-02-22 12:48:52 +01:00
Gina Häußge 0c4f4383e3 ♻ Introduce type hints
For now we'll only use them to have our IDEs scream at us...
2019-02-22 11:44:45 +01:00
Gina Häußge 9f2821fe96 👷 ALLOW_UNICODE and custom pretty printer in doctests
We could also have set ALLOW_UNICODE globally, but this way we might
catch situations where we definitely do not expect mixed results between
py2 and py3.
2019-02-21 15:36:10 +01:00
Gina Häußge dcc1148863 👷 Switching from nose to pytest 2019-02-21 15:34:07 +01:00
Gina Häußge e972026ad0 🚸 PMGR: show message if plugin repo list is empty
E.g. due to filters or compatibility issues.
2019-02-20 18:11:08 +01:00
Gina Häußge 6592be63f8 ✨ PMGR: Support python compatibility flag in plugin repo 2019-02-20 18:10:59 +01:00
Gina Häußge 8b5626e49c 💚 Fix unit tests under Py3 2019-02-20 16:28:06 +01:00
Gina Häußge be4a931e32 ✨ Add Python 3 compat control property
As discussed in #2722
2019-02-20 16:14:12 +01:00
Gina Häußge 548da0d64f Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/environment.py
2019-02-20 15:33:15 +01:00
Gina Häußge 45aa26f13e ♻ Add central methods for getting python version 2019-02-20 15:32:07 +01:00
Gina Häußge 25f26170ff Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/plugins/printer_safety_check/__init__.py
#	tests/filemanager/test_filemanager.py
2019-02-20 15:10:25 +01:00
Gina Häußge 4a64bc6023 Merge branch 'improve/moreFlexiblePrinterSafetyChecks' into maintenance
# Conflicts:
#	src/octoprint/plugins/printer_safety_check/__init__.py
2019-02-20 14:41:09 +01:00
Gina Häußge 8e6773d19f 🐛 printer_safety_check: Fix some issues with new implementation 2019-02-20 14:39:21 +01:00
Gina Häußge dfcddea581 🎨 Fix some whitespace issues 2019-02-19 13:28:15 +01:00
Gina Häußge ff59e275bf Merge branch 'improve/errortracking_plugin' into maintenance 2019-02-19 13:11:38 +01:00
Gina Häußge 0f8f1ec8e0 ✨ Finalize first version of errortracking plugin
Also add docs for that & the Anonymous Usage Tracking plugin.
2019-02-19 13:11:25 +01:00
AndyQ 0e302d440f Added ability to preview the current layer to be drawn
If selected, the current layer is drawn at 30% opacity and then the progress is drawn over the top at 100%
Added additional checkbox on GCodeView page to include current layer as preview
2019-02-18 11:28:41 +01:00
Gina Häußge 980616519d Merge pull request #3054 from rgriebl/master
Fix python version detection on Debian testing/unstable
2019-02-18 10:46:56 +01:00
Gina Häußge 434751634f Merge pull request #3053 from AndyQ/MultipleFiliament_fix
Fixed error in GCode viewer where multiple filaments available (e.g. …
2019-02-18 10:44:33 +01:00
Robert Griebl c35708a422 Fix python version detection on Debian testing/unstable
The current 2.7 Python binary on Debian returns "2.7.15+" as its version, which
is not PEP440 compliant. Tthere is no feedback at all from Debian maintainers
regarding the bug report as of now:
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=914072

This patch makes sure to drop any trailing '+' character in a version string.

Fixes #3049
2019-02-18 00:37:08 +01:00
AndyQ 64464a38ce Fixed error in GCode viewer where multiple filaments available (e.g. using Prusa MMU2), but only using a filament that isn't the first one
e.g. filament 4
2019-02-17 11:57:13 +00:00
Gina Häußge 0e482151fd Merge pull request #3051 from CapnBry/unfuzzy-timetips
Always show unfuzzy times for total print time and time left in tooltip
2019-02-14 15:59:34 +01:00
Gina Häußge c5bf58e1cc ♻️ == -> === 2019-02-14 15:56:09 +01:00
Bryan Mayland 38b7be0142 Fix whitespace 2019-02-14 14:52:24 +00:00
Bryan Mayland 28a515ba6a Always show unfuzzy times for total print time and time left in tooltip 2019-02-14 14:41:01 +00:00
Gina Häußge b6b562399e 💥 Remove deprecated AppSessionManager
Has been replaced by the bundled AppKeys plugin and its workflow.
Deprecation will be announced in 1.3.11.
2019-02-13 17:04:31 +01:00
Gina Häußge 3654512085 🐛 Fix mysteriously broken unit tests 2019-02-13 16:42:21 +01:00
Gina Häußge e7dbd804ce ♻ Use to_unicode instead
See #2722
2019-02-13 16:35:00 +01:00
Gina Häußge 7fd03265d4 🐛 Work around for jsonify calls with bytes
See #2722
2019-02-13 16:32:34 +01:00
Gina Häußge 369679bae5 🐛 Work around CPython bug bpo-29097 2019-02-13 16:12:28 +01:00
Gina Häußge 27e1f2e6e7 🐛 Fix package collection
As mentioned in #2722

See also razerraz@d269c36
2019-02-13 15:26:15 +01:00
Gina Häußge 109cbeea6a 🐛 Fix slicing permission 2019-02-13 15:21:37 +01:00
Gina Häußge 606199dcc9 Merge branch 'maintenance' into devel
# Conflicts:
#	tests/filemanager/test_filemanager.py
2019-02-13 14:56:40 +01:00
Gina Häußge 38868303da 🐛 Fix tests 2019-02-13 14:55:48 +01:00
Gina Häußge 75b5fe198f Merge branch 'maintenance' into devel
# Conflicts:
#	AUTHORS.md
#	src/octoprint/_version.py
#	src/octoprint/plugins/backup/__init__.py
#	src/octoprint/plugins/cura/__init__.py
#	src/octoprint/plugins/cura/profile.py
#	src/octoprint/plugins/cura/templates/cura_settings.jinja2
#	src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/api/files.py
#	src/octoprint/server/util/tornado.py
#	src/octoprint/server/views.py
#	src/octoprint/users.py
#	src/octoprint/util/__init__.py
#	versioneer.py
2019-02-13 14:28:06 +01:00
Gina Häußge fe65f18f78 💥 Unbundling the cura plugin
It lives on as curalegacy at

  https://github.com/OctoPrint/OctoPrint-CuraLegacy

which will be added to the plugin repository once the first RC of 1.3.11
lands.

Due to this change, the general handling of STL files has also changed
slightly. They will no longer be supported by upload out of the box
unless a SlicerPlugin is available (which will now by default extend the
extension tree with STL files, unless overwritten). As a consequence of
that the file type filters in the file list have also been adjusted to
only show up if there are additional file types to filter for.
2019-02-13 13:41:44 +01:00
Gina Häußge e1e302f93d ✨ Allow slicing while printing on multi core systems
If we don't know the number of cores or the number is less than two we
the old behaviour still applies.

Implements #1938
2019-02-13 12:06:32 +01:00
Gina Häußge 1cea388481 🐛 Fix _version.py generation 2019-02-12 13:53:20 +01:00
Gina Häußge 14a3d903d7 Merge remote-tracking branch 'origin/maintenance' into maintenance 2019-02-12 13:46:35 +01:00
Gina Häußge 34d6a6f8ce ⬆ Update versioneer & generated file 2019-02-12 12:29:00 +01:00
Gina Häußge 6a03532ea7 ♻ Backport py3 compat for versioneer 2019-02-12 12:25:41 +01:00
Gina Häußge 649bfdbe37 Merge branch 'master' into maintenance 2019-02-12 12:18:31 +01:00
Gina Häußge 8ce2290d63 📝 Improve docs for connection API
See #3043
2019-02-12 12:07:55 +01:00
Gina Häußge b1413abfff Merge pull request #3045 from akraus53/patch-1
I fixed a few typos in the German translation
2019-02-12 12:02:42 +01:00
Alexander Kraus 772914f38c Fixed a few typos
I hope this is the correct Branch....
2019-02-11 22:54:04 +01:00
Gina Häußge c6b4eee437 🐛 treat pausing as paused for resume handling
See MarlinFirmware/Marlin#13039 and #2955
2019-02-11 18:21:32 +01:00
Gina Häußge e67f72ce3d 🐛 paused action must not trigger *any* local processing
That includes sending M400 and M114 to capture the pause position.

See MarlinFirmware/Marlin#13039
2019-02-11 18:19:47 +01:00
Gina Häußge de6da3f360 Merge branch 'master' into maintenance 2019-02-11 10:08:54 +01:00
Gina Häußge b744c341eb 💬 discourse.octoprint.org => community.octoprint.org 2019-02-11 09:58:39 +01:00
Gina Häußge 697af69e97 Merge branch 'master' into maintenance 2019-02-08 17:06:59 +01:00
Gina Häußge 601451a3f1 ✨ Setting to disable fuzzy estimates
Implements #3040
2019-02-08 16:44:25 +01:00
Gina Häußge 81d523b73d ♻ Backport to_str -> to_bytes from devel
Add unit tests.
2019-02-08 14:39:07 +01:00
Gina Häußge deacd9c188 Merge pull request #3041 from Microtome/add-klipper-to-firmware-autodetect
Add support for klipper in firmware autodetect
2019-02-08 14:02:37 +01:00
Gina Häußge 3c5aa60d2b 🐛 Some more unicode vs bytes fixes 2019-02-07 18:35:35 +01:00
Daniel Joyce 6e0024149e Add support for klipper firmware autodetect 2019-02-07 07:36:11 -08:00
Gina Häußge 1b876f1cf3 ♻ Only depend on chainmap and scandir under py2 2019-02-07 16:31:43 +01:00
Gina Häußge 580e5f5122 🐛 It's time.monotonic in py3, not monotonic.monotonic 2019-02-07 15:40:31 +01:00
Gina Häußge 22f6a38f0a ♻ Universal wheel and related setup.py adjustments
Also make sure that our environment specific dependencies get recorded
to the wheel so that we don't have to build in the same environment as
the software will run later (consider this work towards a PyPI release
that might also be backported).
2019-02-07 15:28:01 +01:00
Gina Häußge 620aa4dfe0 📝 README adjustment to state Py3 support 2019-02-07 12:35:53 +01:00
Gina Häußge dd3b318327 Merge branch 'pr/3036' into maintenance 2019-02-07 12:07:13 +01:00
Gina Häußge 1ccc787222 📝 docs: grammar 2019-02-07 11:57:21 +01:00
Gina Häußge f8e7ae7436 Merge branch 'py23' of github.com:smurfix/OctoPrint into pr/3032 2019-02-07 11:56:16 +01:00
Gina Häußge 3ae284d9a7 Merge branch 'devel' into pr/3032 2019-02-07 11:51:41 +01:00
Gina Häußge caf5be562e 🐛 Workaround for "Request.is_xhr deprecated" warning 2019-02-07 11:51:09 +01:00
Gina Häußge 069e83c63c Merge pull request #3039 from Microtome/improve-backup-filename
Improve backup filename, fix for #3030
2019-02-07 11:43:02 +01:00
Daniel Joyce 0cf345f29b Fix bug where if no plugins are installed, restore fails
* When no plugins are installed, backup does not create a
  plugin_list.json file.
* Restore then fails when it tries to read the missing file.
* Add check to ensure plugin_list.json exists before restoring
  from backup.
2019-02-06 21:06:19 -08:00
Daniel Joyce 0fda153d60 Provide a better name for backup files, use utility function for consistent name 2019-02-06 20:45:07 -08:00
Matthias Urlichs c01a34f358 fix grammar, simplify instructions
A "pip" alias that points to the correct version is part of the venv.

"activate" auto-deactivates the previous venv.
2019-02-06 18:46:53 +01:00
Gina Häußge deee737660 🐛 Raise no exception in case of missing wheel metadata
That's normal for plugins that were installed as eggs instead of wheels
and we don't want to raise the error in this case. If we also don't find
egg metadata we'll log a warning anyhow.

Any other exceptions will be raised though.
2019-02-06 18:36:00 +01:00
Gina Häußge 8425c7b973 Merge branch 'py23' of github.com:smurfix/OctoPrint into pr/3032 2019-02-06 18:13:57 +01:00
Gina Häußge 1e42db040d 📝 docs: some rewording re dev environment 2019-02-06 18:12:44 +01:00
Matthias Urlichs e2d4b64510 superfluous "import io" 2019-02-06 17:29:19 +01:00
Gina Häußge 61136edeea ✅ Add tox.ini 2019-02-06 17:19:28 +01:00
Gina Häußge 7614ef40d3 🐛 Fix repeatability of doctests under py2 2019-02-06 17:07:50 +01:00
Gina Häußge 935639a51a 🐛 Fix json file writing
Apparently json.dump produces mixed bytes/unicode content. So now we use
json.dumps wrapped in to_bytes and that's it.
2019-02-06 16:51:54 +01:00
Gina Häußge ec689e3939 🐛 Fix versioneer 2019-02-06 16:35:32 +01:00
Hannappel 84f95b1099 Fixes creating of groups 2019-02-06 16:08:15 +01:00
Gina Häußge fd8788dd34 ♻ More error resilience for encoding issues in config.yaml
Normally I'd say, broken files are broken files, but since in case of an
encoding error in config.yaml the server won't come up anymore we are
erring on the side of caution here and running with errors="replace"
2019-02-06 16:06:56 +01:00
Gina Häußge 32a8646135 ♻ codecs.open -> io.open
The general consensus regarding codecs.open appears to be that it's only
left in Python 3 for backwards compatibility (which I find kind funny
but I digress...) and that io.open should be used instead for Py2.6+
since it's available and behaving the same in both versions. So that's
what we do here.
2019-02-06 16:05:09 +01:00
Gina Häußge 09cc7cf5f7 🐛 Fix unicode vs bytes issues for atomic_write
NamedTemporaryFile doesn't support the encoding parameter under py2.
However, without it specifying text mode defaults to ascii, causing some
issues especially with config files containing utf-8.

By swapping NamedTemporaryFile for mkstemp and a custom io.open call
(parameterized according to the open mode) we can support a proper
encoding aware atomic_write.
2019-02-06 16:03:32 +01:00
Gina Häußge 496e9f0ec4 ✅ Add unit test for pip caller initialization 2019-02-06 13:11:03 +01:00
Gina Häußge 18b2ecd64c 🐛 Fix unicode vs bytes issues in PipCaller
* environment for subprocess needs native str (at least under win)
  * when reading a text file we should also be writing one inside the
    test balloon
2019-02-06 12:53:23 +01:00
Gina Häußge cc6f61c62e 🐛 discovery: fix unicode vs bytes issues in SSDP 2019-02-06 12:00:16 +01:00
Matthias Urlichs de149613cb Run flake8 tests only once 2019-02-05 18:13:44 +01:00
Matthias Urlichs a7ca374955 Fix additional flake8 nits 2019-02-05 17:54:09 +01:00
Daniel Joyce 61ac8430d6 Added self to Authors file 2019-02-05 08:46:58 -08:00
Daniel Joyce 6b4dfcb960 Support opening serial port in exclusive mode.
* Slight cleanup and refactoring
2019-02-05 08:46:44 -08:00
Matthias Urlichs d7d3272905 Merge errors fixed 2019-02-05 17:43:31 +01:00
Matthias Urlichs 9eb29a8ce0 found another unnecessary list-ification 2019-02-05 17:41:30 +01:00
Matthias Urlichs bf16bd1180 Merge py23 from devel 2019-02-05 17:36:07 +01:00
Matthias Urlichs 7b5315383b Add wildcard import for compatibility 2019-02-05 17:35:25 +01:00
Matthias Urlichs 72729ad418 fix speling an move to docstring 2019-02-05 17:34:57 +01:00
Matthias Urlichs e6f902cbe7 add logging 2019-02-05 17:34:45 +01:00
Matthias Urlichs 9b14f32279 take PY3 from existing declaration 2019-02-05 17:34:27 +01:00
Matthias Urlichs 7ad4d75588 fixed merge errors 2019-02-05 17:34:15 +01:00
Gina Häußge 5a623b486c ✅ Adding flake8 to CI 2019-02-05 17:28:44 +01:00
Gina Häußge 920283cf87 Merge branch 'devel' into pr/3032
# Conflicts:
#	src/octoprint/access/groups.py
#	src/octoprint/static/css/octoprint.css
2019-02-05 17:08:24 +01:00
Gina Häußge becd16b892 🐛 Fix a test 2019-02-05 16:08:40 +01:00
Gina Häußge f59c1ce804 ⬆ Upgrade Flask-Login dependency
It used to be 0.3.0+, some merge in the past must have broken that.
2019-02-05 15:58:15 +01:00
Gina Häußge c71972c0f8 ♻ Explicitly add admin group to plugin permissions
Admin only access by default for these was implied by not having them
added to one of the three major default groups, making it explicit is
more clear though.
2019-02-05 15:58:15 +01:00
Gina Häußge 47a9a40ec9 ✨ permissions: Groups can now have subgroups
That way we can easily provide a Read Only group that allows read-only
access and which can then be added to the Guest group by users who
desire anonymous read-only access, similar to disabling the forcelogin
plugin in 1.3.10+
2019-02-05 15:58:15 +01:00
Matthias Urlichs 5c1fffc3d0 comm: more str vs. bytes (esp. baudrate detect) 2019-02-05 14:30:23 +01:00
Matthias Urlichs fe090cc6cc Virtual printer: str vs. bytes 2019-02-05 14:29:27 +01:00
Matthias Urlichs ab3c4ab66c Don't compare with None 2019-02-05 14:29:04 +01:00
Matthias Urlichs 1d6b7244b5 Bah. That glob-import-removal was overzealous. 2019-02-04 21:33:35 +01:00
Matthias Urlichs ea17566aba some more unused variables 2019-02-04 21:13:19 +01:00
Matthias Urlichs 315ed57916 Another missing import 2019-02-04 21:12:20 +01:00
Matthias Urlichs 1014582b4b removed wildcard imports 2019-02-04 21:10:11 +01:00
Matthias Urlichs cf77053901 missing imports 2019-02-04 21:10:04 +01:00
Matthias Urlichs f040482b18 don't assign to an unused variable 2019-02-04 21:09:27 +01:00
Matthias Urlichs 523fadd930 Don't shadow globals 2019-02-04 21:08:32 +01:00
Matthias Urlichs 97d0fbd2c9 Don't compare with bool values 2019-02-04 21:07:53 +01:00
Matthias Urlichs 3b820f6848 Scoping error: py3 deletes exceptions after their except: block 2019-02-04 21:02:32 +01:00
Matthias Urlichs e8b9f385b4 "has_key" is deprecated 2019-02-04 20:54:54 +01:00
Matthias Urlichs 95bc1006a0 Fix undefined "autologin_as" and "local_networks" 2019-02-04 20:49:49 +01:00
Matthias Urlichs 14ef17163f Don't compare with None 2019-02-04 20:44:57 +01:00
Matthias Urlichs 9a1bd8af87 These are numbers so unicode() is not necessary 2019-02-04 20:35:00 +01:00
Matthias Urlichs a292a12c4a The lastline buffer has bytes
This reduces required work because we only need to convert back when
resending
2019-02-04 20:35:00 +01:00
Matthias Urlichs 200a3ef4eb replaced a bunch of map() with generator expressions 2019-02-04 20:35:00 +01:00
Matthias Urlichs 88582beb55 grammar ;-) 2019-02-04 20:29:22 +01:00
Matthias Urlichs 6d7c8bbda6 More backslashes 2019-02-04 20:13:06 +01:00
Matthias Urlichs 9a7f92174a forgot to replace a unicode=str instance 2019-02-04 20:13:06 +01:00
Gina Häußge 61431c0df3 Merge remote-tracking branch 'origin/master' 2019-02-04 18:48:10 +01:00
Matthias Urlichs a301fc6da9 Merge remote-tracking branch 'origin/devel' into py23 2019-02-04 18:44:23 +01:00
Gina Häußge cc0b63cbb9 📝 Fix a formatting issue
No events are about to be removed in 1.4.0, only the payload fields
marked as deprecated. And for some reason ReST doesn't appear to allow
including that piece of information within the `deprecated` directive,
so now we have a slightly different way of expressing it...
2019-02-04 18:40:57 +01:00
Matthias Urlichs e08dc0b5aa missed importing "long" from past.builtins 2019-02-04 17:04:33 +01:00
Matthias Urlichs a368a7f1c9 comm: we already have a logger. Use it. 2019-02-04 17:04:01 +01:00
Gina Häußge 020403dc54 💬 Correct typo in german translation
Closes #3029
2019-02-04 14:43:12 +01:00
Matthias Urlichs 6a601d4f8e clean_ansi: accept strings 2019-02-04 14:33:57 +01:00
Gina Häußge 7a3b370469 🐛 Fix earlier merge error
New permission system does handle disabled ACL slightly differently.
2019-02-04 14:30:02 +01:00
Matthias Urlichs e676d53e9f Fix the remaining docstr tests
Sets are annoying to test:
(a) their repr() is different
(b) they might get re-ordered.
2019-02-04 14:15:09 +01:00
Matthias Urlichs 40b231f692 fix TagStripper for py2 2019-02-04 14:14:55 +01:00
Matthias Urlichs 86664fdb39 super() doesn't work in Py2. Yech. 2019-02-04 13:58:56 +01:00
Matthias Urlichs 4ebb5cf42d more native_str 2019-02-04 13:38:31 +01:00
Matthias Urlichs e8bee435af forgotten import 2019-02-04 13:33:46 +01:00
Matthias Urlichs 082f977f7a Disable unicode strings in github_release
I am too lazy to fix all the doctests
2019-02-04 13:32:34 +01:00
Matthias Urlichs 237a2c0add Make the HTML tag stripper 2.7 compatible
convert_charrefs defaults to True on Py3.5 ff.
2019-02-04 13:20:47 +01:00
Matthias Urlichs 2e47f49f7a Make to_native_str() decode bytes
used for doctests
2019-02-04 13:14:32 +01:00
Matthias Urlichs 05919363e1 De-ANSIfication needs to run on bytes. 2019-02-04 13:14:01 +01:00
Matthias Urlichs 7c8547555c double escapes vs. raw strings. Ugh. 2019-02-04 13:13:30 +01:00
Matthias Urlichs ce0c77f0bf Travis: run on xenial distro 2019-02-04 13:13:09 +01:00
Matthias Urlichs aec041b014 Fix unicode woes in doctests 2019-02-04 13:00:54 +01:00
Matthias Urlichs 58b32803df Tell Travis to also test py3.6 and py3.7 2019-02-04 12:49:11 +01:00
Matthias Urlichs 6d447f8408 unicode woes for funcion __name__/__qualname__ 2019-02-04 12:47:44 +01:00
Matthias Urlichs 54d359f730 Don't spew a stack trace if vcgencmd doesn't work / exist 2019-02-04 11:34:05 +01:00
Matthias Urlichs 4d9f0fca41 Unicode woes for serial seending 2019-02-04 11:24:25 +01:00
Matthias Urlichs 41146c2b7c another hash 2019-02-04 11:23:08 +01:00
Matthias Urlichs 99d7157cb7 Missing translation 2019-02-03 19:10:27 +01:00
Matthias Urlichs c8b5662ff2 a bunch of bytes 2019-02-03 19:02:10 +01:00
Matthias Urlichs b781681e0f There's no 'file' in Py3 2019-02-03 19:01:47 +01:00
Matthias Urlichs 5edeecdc8c Py3 codecs.open doesn't like mode='t' 2019-02-03 19:01:07 +01:00
Matthias Urlichs f82ec61463 restore setup.py
Incompatibility with Jinja 2.10
2019-02-03 19:00:29 +01:00
Matthias Urlichs 372a8d2ea8 Feedparser: avoid warning due to their workaround
see Feedparser issues 328 and 310
2019-02-03 17:39:12 +01:00
Matthias Urlichs 9c5d1dec59 don't apply str.lower() to unicode 2019-02-03 17:39:01 +01:00
Matthias Urlichs feff5e0978 type() vs. unicode, again 2019-02-03 17:25:39 +01:00
Matthias Urlichs 019bf5acd4 use past.builtins.unicode 2019-02-03 17:19:46 +01:00
Matthias Urlichs 717aafee08 TODO catch this sphinx error in a reasonable way 2019-02-03 16:39:31 +01:00
Matthias Urlichs 67c5a5e168 went through "except Exception:" with a fine comb 2019-02-03 16:39:01 +01:00
Matthias Urlichs 6310afa261 owchie to_native 2019-02-03 16:36:20 +01:00
Matthias Urlichs cd6ae6e47b setup 2 unicode_literals 2019-02-03 16:35:48 +01:00
Matthias Urlichs b01e1c269d owchie to_native 2019-02-03 16:35:12 +01:00
Matthias Urlichs 49fb0f87d5 Clean up Py2-vs.Py3 imports 2019-02-03 16:32:00 +01:00
Matthias Urlichs 8956e7a173 actually purge logger entries 2019-02-03 15:55:49 +01:00
Matthias Urlichs 9fa20f0e52 rename to_str to to_bytes 2019-02-03 14:54:28 +01:00
Matthias Urlichs 6bf8384c35 Kill of u"" (visual clutter) 2019-02-03 14:25:41 +01:00
Matthias Urlichs 1dacbc35bf Use unicode_literals __future__ 2019-02-03 14:09:57 +01:00
Matthias Urlichs 7522dbed1d serial readline: bytes 2019-02-03 14:06:06 +01:00
Matthias Urlichs d433c919ec more bare except: 2019-02-03 14:02:41 +01:00
Matthias Urlichs a6f701802f Simplify: set([GEN]) → set(GEN) 2019-02-01 17:33:32 +01:00
Matthias Urlichs e03feeb7ac checked "basestring" 2019-02-01 17:23:08 +01:00
Matthias Urlichs 00068114a1 Unicode oops 2019-02-01 17:15:42 +01:00
Matthias Urlichs 6a7e11eb7c items not values 🙄 2019-02-01 17:14:27 +01:00
Matthias Urlichs 6f987577f4 missed hash_update 2019-02-01 17:14:10 +01:00
Matthias Urlichs 819d690bc3 Merge devel into py23 2019-02-01 16:50:56 +01:00
Gina Häußge dbfe487f13 Merge branch 'maintenance' into devel 2019-02-01 15:12:42 +01:00
Gina Häußge 21a82bbdb6 🐛 Fix enableWebcam render kwarg
Was using the wrong setting name.
2019-02-01 15:10:28 +01:00
Gina Häußge 47e9afa811 ♻ Use new named registration params for UiStateVM 2019-02-01 14:58:02 +01:00
Gina Häußge f9edea0c2c 🐛 Fix duplicate auth request on socket
Merge error.
2019-02-01 14:57:11 +01:00
Gina Häußge 8ef3d1dcad 🐛 Fix reload loop on first setup
Removed the forcelogin plugin since it's obsolete in 1.4.0 thanks to
the granular permission system anyhow.
2019-02-01 14:56:48 +01:00
Gina Häußge fcfef25c93 🐛 Fix first run wizard again
Necessary requests were wrongfully denied after initial setup of a user
account due to hasBeenCustomized still being used and its deprecated
wrapper wrapping the always False implementation in the UserManager base
class instead of the adjusted one in the FileBasedUserManager. Evil bug.
2019-02-01 14:45:38 +01:00
Gina Häußge 604d2f7811 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/server/views.py
#	src/octoprint/templates/dialogs/settings/api.jinja2
2019-02-01 11:12:29 +01:00
Gina Häußge 727fd12939 🚸 CORS change needs restart to take effect 2019-02-01 10:55:24 +01:00
Gina Häußge 100fe5f290 🐛 Allow disabling CORS headers on SockJS endpoints
Fixes 2) of #3024
2019-02-01 10:40:37 +01:00
Matthias Urlichs a721256204 AssertEquals is deprecated 2019-01-31 20:10:30 +01:00
Matthias Urlichs 24d2efd3ce Merge devel into py23 2019-01-31 20:08:40 +01:00
Gina Häußge 1acf69cb6d 🐛 Add CORS headers to tornado endpoints (if enabled)
Fixes 1) of #3024
2019-01-31 17:38:10 +01:00
Gina Häußge 3815c340a8 ☔ Protect against corrupt language packs 2019-01-31 17:07:10 +01:00
Gina Häußge 5e8220055f 🐛 Fix merge error 2019-01-31 14:44:46 +01:00
Gina Häußge 38eff3fe6f Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/server/api/system.py
2019-01-31 14:07:14 +01:00
Gina Häußge 4e47ecabf8 🐛 Fix duped log entries 2019-01-31 13:57:05 +01:00
Gina Häußge c36a378b60 Merge branch 'hotfix/documentation_error' into maintenance 2019-01-30 15:08:41 +01:00
Gina Häußge 9a7ebde76b 📝 Fix documentation for firmware info & capability plugin hooks 2019-01-30 15:02:32 +01:00
Gina Häußge c23bafd788 ☔ Protect against callback errors in decorators on default view 2019-01-30 14:36:53 +01:00
Gina Häußge 1aea92a5f1 ☔ Protect against invalid preemptive cache config data
Fixes #3023
2019-01-30 14:36:52 +01:00
Gina Häußge df9617ac1e 🔀 Merge branch 'maintenance' into devel 2019-01-30 11:27:30 +01:00
Gina Häußge 0b23417f45 🐛 Add missing asset that got lost during a merge
Fixes #3021
2019-01-29 16:48:07 +01:00
Matthias Urlichs 828ba56952 list()-ify keys(), values() and items()
where required. At some places it's not.

Also, "if foo in some_dict.keys()" is unnecessarily slow.
Replaced with "if foo in some_dict".

I left "for key in some_dict.keys()" alone;
"for key in some_dict" is equivalent but not always obvious.
2019-01-28 21:55:44 +01:00
Matthias Urlichs 63723baf07 list()-ify map() and filter()
where required. At some places it's not.
2019-01-28 21:55:44 +01:00
Matthias Urlichs b60b20d784 Clean up example code 2019-01-28 21:06:35 +01:00
Matthias Urlichs 1e0bdc8b8c octoprint => octoprint serve
for the trivial case of starting "run" without arguments
2019-01-28 20:36:02 +01:00
Matthias Urlichs b47b39af99 missing import 2019-01-28 20:36:02 +01:00
Matthias Urlichs 6bc4d8fca4 TODO: TypeError is too unspecific
This might need better error filtering, assuming that we need it in the
first place. For now, remove entirely.
2019-01-28 20:36:02 +01:00
Matthias Urlichs 1e01e587f3 another missing comma 2019-01-28 20:36:02 +01:00
Matthias Urlichs d8f5dd701b another tab 2019-01-28 20:36:02 +01:00
Matthias Urlichs bee609a316 more list() 2019-01-28 20:36:02 +01:00
Gina Häußge fb38c396e8 Merge pull request #3010 from HarlemSquirrel/maintenance-disk-usage
Add system usage API endpoint
2019-01-28 18:33:38 +01:00
Gina Häußge 904b3c6cf5 🔧 Adjust default regex of temperature terminal filter (2nd try)
Should no longer match lines like

    FIRMWARE_NAME:Marlin 1.1.7-C2 (Github) SOURCE_CODE_URL:https://github.com/Robo3D/Marlin-C2 PROTOCOL_VERSION:C2 MACHINE_TYPE:RoboC2 EXTRUDER_COUNT:1 UUID:cede2a2f-41a2-4748-9b12-c55c62f367ff EMERGENCY_CODES:M108,M112,M410

but should pass unit tests.

Fixes #2945
2019-01-28 18:20:03 +01:00
Gina Häußge 7f2b79bcd5 ⏪ Revert "🔧 Adjust default regex of temperature terminal filter"
This reverts commit dd692d6
2019-01-28 18:02:46 +01:00
Gina Häußge dd692d6f30 🔧 Adjust default regex of temperature terminal filter
Should no longer match lines like

    FIRMWARE_NAME:Marlin 1.1.7-C2 (Github) SOURCE_CODE_URL:https://github.com/Robo3D/Marlin-C2 PROTOCOL_VERSION:C2 MACHINE_TYPE:RoboC2 EXTRUDER_COUNT:1 UUID:cede2a2f-41a2-4748-9b12-c55c62f367ff EMERGENCY_CODES:M108,M112,M410

Fixes #2945
2019-01-28 17:56:10 +01:00
Gina Häußge 5d021d76a0 ✨ action_command_prompt: PROMPT_SUPPORT capability support
Allow configuration of whether to enable the plugin if firmware support
is detected, always or never. Handle PROMPT_SUPPORT capability report
accordingly.

See MarlinFirmware/Marlin#12982
2019-01-28 17:41:01 +01:00
Matthias Urlichs 5794a347f1 Added myself to AUTHORS ;-) 2019-01-28 15:08:40 +01:00
Gina Häußge 2db230549e ✨ action_command_prompt: signal prompt support on connect (default off)
Note: Has to be enabled manually for now as long as we cannot detect
that the firmware indeed has support for M876.

See MarlinFirmware/Marlin#12982
2019-01-28 14:50:40 +01:00
Gina Häußge 01484b630a ✨ action_command_prompt: EMERGENCY_PARSER support (default off)
Note: Has to be enabled manually for now as long as we cannot detect
that the firmware indeed has support for M876 and hence has it as part
of the EMERGENCY_PARSER.

See MarlinFirmware/Marlin#12982
2019-01-28 14:32:10 +01:00
Matthias Urlichs 5d8535cb9c Test string must be Unicode 2019-01-28 14:14:23 +01:00
Matthias Urlichs 21d3622c2e fix dependency (TEMP) 2019-01-28 14:14:23 +01:00
Matthias Urlichs 008cde6ef6 octoprint.user => octoprint.access.user 2019-01-28 14:14:23 +01:00
Matthias Urlichs 4df57cd8fe Fix DeprecationWarning about using __plugin_implementations__ 2019-01-28 14:14:23 +01:00
Matthias Urlichs f53380c04e superfluous (and deprecated) import 2019-01-28 14:14:23 +01:00
Matthias Urlichs 8af45e2f21 need to list-ify OS matches 2019-01-28 14:14:23 +01:00
Matthias Urlichs 0da47858fa Escaping woes 2019-01-28 14:14:23 +01:00
Matthias Urlichs abfffa3231 Remove deprecated unittest.TestCase.assertDictContainsSubset 2019-01-28 14:14:23 +01:00
Matthias Urlichs e056ccdf29 Testing: exception args 2019-01-28 14:14:23 +01:00
Matthias Urlichs e334d8b073 Testing: file modes 2019-01-28 14:14:23 +01:00
Matthias Urlichs f1673c148f str vs utf 2019-01-28 14:14:23 +01:00
Matthias Urlichs ae5a1dc6dc Don't base your exceptions on BaseException 2019-01-28 14:14:23 +01:00
Matthias Urlichs 7fcc3551ca We need text mode for JSON and YAML 2019-01-28 14:14:23 +01:00
Matthias Urlichs f3fdac7e5a Use raw strings for all regexps.
No exceptions please.
2019-01-28 14:14:23 +01:00
Gina Häußge d8088887e1 🐛 Fix bug introduced in bd58138acf 2019-01-28 13:45:09 +01:00
Gina Häußge 379411cea7 🔧 action_command_prompt: M876 as default command
See MarlinFirmware/Marlin#12982
2019-01-28 13:10:00 +01:00
Gina Häußge 5e953c12a1 💬 Rewording 2019-01-28 13:07:34 +01:00
Gina Häußge bd58138acf 🎨 Refactored for better code reuse 2019-01-28 13:05:27 +01:00
Gina Häußge 44b4c6cc40 🐛 sleep => time.sleep 2019-01-28 13:00:26 +01:00
Gina Häußge f3f1061f9d ❇️ Configurable terminal log size in comm layer
See https://discourse.octoprint.org/t/logging-terminal-information-on-failed-print/7047/3?u=foosel
2019-01-28 12:03:16 +01:00
Matthias Urlichs bba95e9000 dup future statement 2019-01-28 11:12:51 +01:00
Matthias Urlichs fa81791c29 NO we do NOT open text files in binary mode 2019-01-28 11:12:29 +01:00
Matthias Urlichs a4072723bf tabs vs. spaces 2019-01-28 11:11:46 +01:00
Matthias Urlichs d451acdd4f "futures" is py2 only 2019-01-28 11:11:34 +01:00
Matthias Urlichs a1a15e40e0 Replace all bare "except:" handlers
These are never what we want, as they swallow KeyboardInterrupt.

TODO: many of these handlers really should be more specific and/or
log that they replaced an unparseable value with a default.
2019-01-28 07:50:55 +01:00
Matthias Urlichs 0c264ca0d2 less encompassing exception 2019-01-28 07:50:55 +01:00
Matthias Urlichs 9e4b0f83d8 misc 2019-01-28 07:50:55 +01:00
Matthias Urlichs 2b8d831308 bad patch 2019-01-28 07:50:55 +01:00
Matthias Urlichs fcb0f877b8 py23 2019-01-28 07:50:55 +01:00
Matthias Urlichs c74e3a0a0b don't multiply with -1 2019-01-28 07:50:55 +01:00
Matthias Urlichs ea64c017e8 event tags etc. are not supposed to be binary 2019-01-28 07:50:55 +01:00
Matthias Urlichs 70a104e32a shebang python2 => python 2019-01-28 07:50:54 +01:00
Matthias Urlichs 75a37f5ce7 missing comma
merge error
2019-01-28 07:50:54 +01:00
Matthias Urlichs e4d083028c hashlib fix from razer 2019-01-28 07:50:54 +01:00
Matthias Urlichs 6bab550830 unicode/basestring confabulation 2019-01-28 07:37:28 +01:00
Matthias Urlichs f9916783e9 whitespace 2019-01-28 07:34:19 +01:00
Matthias Urlichs e00375e586 don't use six 2019-01-27 17:49:20 +01:00
Matthias Urlichs 41fab8a36c atomic_write: use keyword for mode argument
this will allow us to define atomic_write as keyword-only
as soon as py2 compatibility is dropped.
2019-01-27 17:42:36 +01:00
Matthias Urlichs c05b6572c5 Fix coding= headers 2019-01-27 17:36:16 +01:00
Matthias Urlichs 1ae6b73f7a use setup.py from razer 2019-01-27 17:34:35 +01:00
Matthias Urlichs 670ca15997 Merge remote-tracking branch 'origin/maintenance' into py23 2019-01-27 17:28:46 +01:00
Matthias Urlichs ea5ef34cc1 Merge commit 'ac3b8ebfccfc626c19d1ae731df65cd408f9b9c4' into py23 2019-01-27 17:16:14 +01:00
Matthias Urlichs 958fc7600d Merge commit 'e0543de8ef5c1f67d4064e84a5e7ecacbdf1029e' into py23 2019-01-27 17:15:52 +01:00
Matthias Urlichs 13d894e74b Merge commit '9cfcbd3929cd7fbea4e585f01e101a3dc5055ee1' into py23 2019-01-27 17:14:15 +01:00
Matthias Urlichs 353309fc60 Merge commit 'd3334b29d9124b8a9e9c2dbfcdd6e125e471c412' into py23 2019-01-27 17:13:28 +01:00
Matthias Urlichs 3501179257 Merge commit '41e74df8d33b4f8b332ca278db478a70dcfe7aec' into py23 2019-01-27 17:12:24 +01:00
Matthias Urlichs f993f744ba Merge commit 'c623e90ebc59b90b4f4cf582ab8185b2872acff4'; commit 'f416e96414f33fb31afdf4dfbf3c863e3db35543'; commit '9ecf39febe31a44e5f5db28249ebbf006ac1580c'; commit '582b03f21fe3d808bf4e11bbba90af54b6651b34'; commit 'f5c8b04958170f19f1806b1722bf5e857ded3dce'; commit '36818057a3b4769a77731f3be8bc661437db7132'; commit 'd987cb23c119132b287f70f1c979aac8c9fff7d2' into py23 2019-01-27 17:10:01 +01:00
Gina Häußge 68410cb3d7 🐛 Fix an issue with plugin sorting
If we just uninstalled a plugin there might not be a PluginInfo object.
In that case assume the plugin is not bundled (not False = True)
2019-01-25 16:14:45 +01:00
Gina Häußge db009e3ba2 🐛 backup: do not translate plugin name
Only translate it at template level, not before.

Fixes #3012
2019-01-25 15:48:35 +01:00
Gina Häußge 09d3c44161 🐛 unicode-ify octoprint.plugin.core
Fixes #3012
2019-01-25 15:39:31 +01:00
Gina Häußge c2814651f9 errortracking: keep disabled on unreleased versions
We don't want to track errors during development, unless overridden
via config flag.
2019-01-23 12:23:38 +01:00
Gina Häußge eb46815789 Slight refactoring for improved testability & fix tests 2019-01-22 15:40:08 +01:00
Kevin McCormack 449fa0c7ec WIP Update test_system 2019-01-21 12:49:57 -05:00
Kevin McCormack 0489dfeaee [WIP] Add disk usage API endpoint 2019-01-20 10:02:13 -05:00
Gina Häußge a9b395dac8 ✨ Dedicated settings for webcam/timelapse support
Implements #2974
2019-01-18 16:58:34 +01:00
Gina Häußge 44a40b8297 errortracking: fix typo -_- 2019-01-18 14:36:46 +01:00
Gina Häußge 49728f18c6 errortracking: add missing dependency 2019-01-18 14:27:26 +01:00
Gina Häußge f6ec0bca6e errortracking: first throw at an implementation
Currently uses a sponsored sentry instance on sentry.io. Error tracking
is disabled by default and currently still has to be enabled through
manual configuration in config.yaml (plugins.errortracking.enabled=true)
2019-01-18 14:13:26 +01:00
Gina Häußge 6a069de240 Put generic templates after javascript assets
That way it's possible for plugins to reference already loaded libraries
or constants in any injected generic templates.
2019-01-18 14:10:47 +01:00
Gina Häußge 2287c65784 forcelogin: ui_render sorting key of 0
If third party UIPlugin want to override the forcelogin plugin, they'll
need to return a negative sorting key.
2019-01-17 17:55:24 +01:00
Gina Häußge 3b26a2f7d2 Take bundle status into account for plugin sorting 2019-01-17 17:54:24 +01:00
Gina Häußge 18ffdcff6b forcelogin: Accept auth via apikey & auth headers
So far we only checked for keys or auth headers on the API, the plugin
so far only checked if there was an existing cookie via a passive login.

Now it will try to login the user from any provided api keys or
authorization headers as well and only fall back to the passive login if
that doesn't succeed. A call to the frontend with either will thus not
trigger the login dialog.

See #2997
2019-01-17 17:33:00 +01:00
Gina Häußge faab946aeb Add missing , 🤦‍♀️ 2019-01-17 15:34:57 +01:00
Gina Häußge a48e069aa6 Fix race condition on start of SD print
If an M27 to query SD status came after the change of state to printing
but before the M24 to actually start the print on the printer's side the
firmware would report "Not SD printing" and OctoPrint would consequently
cancel the just start job right away.

This patch introduces a new "Starting" state that will be active while
preparing a print job (in case of SD: selecting the file, setting file
position & finally starting the print). The comm layer treats as
nearly identically to the Printing state, the only difference is in the
treatment of received "not sd printing" messages which will be ignored
while still Starting.

Additionally this patch introduces a "two strikes rule" for "not sd
printing" messages (which can be configured to be another number of
strikes). Only if OctoPrint receives two consecutive "not sd printing"
messages from the printer will it actually cancel the printer. This is
to work around a potential (albeit very very unlikely) race condition
that still exists even with the starting state.

Fixes #3001
2019-01-17 13:16:07 +01:00
Gina Häußge d4d5bed514 Fix broken sdcard upload success handling
Spotted by @devildant, thanks!

Closes #3005
2019-01-17 10:49:48 +01:00
Gina Häußge 97f84f120c Improve inline docs for serial.disconnectOnErrors behaviour
See #3002
2019-01-16 19:17:10 +01:00
Gina Häußge cdc69ea93c tracking: add elapsed time to cancelled tracking event 2019-01-16 18:50:51 +01:00
Gina Häußge 467dd344cf docs: document time field in PrintCancelled payload 2019-01-16 18:48:53 +01:00
Gina Häußge 6b9c9f47da Don't send reason field in PrintCancelled event payload 2019-01-16 18:47:40 +01:00
Gina Häußge b7f17531d2 tracking: fix tracking not starting fully during runtime
We didn't start the ping thread and also not the throttle state monitor
if switched on during run time.
2019-01-16 18:38:47 +01:00
Gina Häußge 987379d6e7 Merge branch 'maintenance' into pr/2968
# Conflicts:
#	src/octoprint/plugins/tracking/__init__.py
2019-01-16 18:34:30 +01:00
Gina Häußge 62b1d91901 tracking: refactored individual enable check
Way less repetition this way.
2019-01-16 18:33:41 +01:00
Gina Häußge 7cb5013b08 tracking: always generate a uuid on startup
But just in case still check if it's set before doing anything with it.
2019-01-16 18:29:49 +01:00
Gina Häußge 06a3baa588 Merge branch 'maintenance' into pr/2900 2019-01-16 17:52:06 +01:00
Gina Häußge 07934d26eb Refactored some things and added more docs
There was still some redundancy due to how SD upload so far was
implemented. Things are now better reusable from hooks.

Also fixed the problem that OctoPrint would *always* use the first hook,
whether it actually handled the upload or not.
2019-01-16 17:51:53 +01:00
Gina Häußge 3ae97a3e13 Add user & job owner to print job events
Adds print job owner (= user who selected/started a job) and user who
started/paused/resumed/cancelled a job to the print job events as
applicable.

Also added logging of print job events to octoprint.log with this
information.

Plugins can use the event data for further logging or tracking.

Implements #2982
2019-01-16 14:04:16 +01:00
Gina Häußge 5f22e68985 Add clear button to files search
I would have preferred it to just depend on the default styling of
search type inputs in browsers, which at least on Webkit and IE will add
a clear button automatically, but Firefox doesn't add one and the
corresponding ticket [1] also doesn't look like that will change soon.

So a custom implementation it is. Hooray.

Implements #2983

[1] https://bugzilla.mozilla.org/show_bug.cgi?id=558594
2019-01-16 12:01:03 +01:00
Gina Häußge df1dc17c51 Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2019-01-16 10:29:30 +01:00
Gina Häußge 71aa405b26 Merge pull request #3004 from gloomyandy/pr_write_timeout
Use non blocking I/O for writes to implement write timeout (take 2)
2019-01-16 10:29:02 +01:00
Gina Häußge 2d2986922d Merge pull request #2986 from tedder/responsive_login_page
make login page responsive
2019-01-16 10:27:59 +01:00
Andy Shaw 7b5dbef166 Use non blocking I/O for writes to implement write timeout
Currently write timeouts are not really implemented (as they are set to 10000 seconds). The current code also has the unwanted side effect of casuing the use of a select call (in the Linux PySerial library) even when a write does not need to block. This call to select can in some odd cases cause the write to block for the duration of the set timeout which in turn triggers a transmission error. See issue https://github.com/foosel/OctoPrint/issues/2996

This change addresses both issues by allowing the use of the existing write retry code to handle timeouts and by using non-blocking write mode to avoid the use of select.
2019-01-15 19:33:51 +00:00
Gina Häußge da61a49bd8 Forgot something 2019-01-15 17:28:13 +01:00
Gina Häußge 002802bb20 Deprecate appkey API in favor of Application Keys Plugin
Slated to be removed in 1.4.0. AFAIK nobody used it anyhow.
2019-01-15 17:25:58 +01:00
Gina Häußge 45b59494ca Add new hook too allow plugins to register custom events
Implements #2965
2019-01-15 16:54:50 +01:00
Gina Häußge 83530ec7b9 Logging: deletion confirmation & bulk delete
Implements #2962
2019-01-15 15:09:42 +01:00
Gina Häußge 918b70185e Set max-height on PNotify notifications
Fixes #2959
2019-01-15 14:51:57 +01:00
Gina Häußge 6aa89b77dc autologin: also check against v6 representation of v4 networks
See #2976
2019-01-14 12:03:53 +01:00
Gina Häußge 1679b45cd6 Merge pull request #2978 from agrif/fix/plugin-module-names
Use module name when loading plugins from entry points.
2019-01-11 15:11:06 +01:00
Gina Häußge 4728a1a5a9 Merge pull request #2993 from hgross/fix/restore-on-docker-volumes
Fix #2992 (restore mechanism on docker volumes)
2019-01-11 14:54:45 +01:00
Gina Häußge c35a387520 Merge pull request #2973 from melgish/bugfix/2971
use jQuery for checked state.
2019-01-11 14:53:01 +01:00
Gina Häußge d7aae66886 Add --disable-pip-version-check to pip calls
Users get too confused by the warning the lack of it generates on plugin
installs/uninstalls and updates of any kind through pip. An FAQ entry
on that matter hasn't helped, so we are now pulling out the nuclear
option to reduce support overhead.

Implements #2988
2019-01-11 14:23:48 +01:00
Henning Groß 67ab9d577a Merge branch 'maintenance' into fix/restore-on-docker-volumes 2019-01-08 10:58:19 +01:00
MirceaDan d987cb23c1 Merge branch 'devel' into dev/py23_metaclass 2019-01-07 21:41:14 -08:00
Henning Gross 10d045d743 Added @hgross to AUTHORS.md 2019-01-07 22:25:29 +01:00
Henning Gross 44818993ff #2992 use shutil.move instead of os.rename 2019-01-07 21:49:21 +01:00
tedder 970b9c3384 make login page responsive
with responsive plugins like TouchUI, all of the pages render on mobile just fine.. except the login page. I was tired of scrolling much wider than my phone's display to make it show up, so I did some investigation. Turns out it was just missing the meta viewport.
2019-01-02 19:53:21 -08:00
Aaron Griffith 89f94be96a Use module name when loading plugins from entry points. 2018-12-29 21:52:11 -05:00
Nicholas J. Fiorello Jr 52cfd93301 use jQuery for checked state. 2018-12-24 18:11:47 -05:00
tedder 2a8d103dc6 handle missing uuid at sha time
Even if a user doesn't have a uuid at startup, they might enable tracking later and .. then a uuid isn't created until the next startup. For this reason and others, we shouldn't pass None to sha.update. Also, by adding a 'uuid missing' string to the log post, we can now track how many instances are missing a uuid for some reason. (though these may show now as a uuid of 'None').
2018-12-22 14:47:52 -08:00
Gina Häußge d452051c0a Add systemd file
As discussed in #1716
2018-12-19 14:47:52 +01:00
Gina Häußge 99b32fc6c3 Merge remote-tracking branch 'origin/maintenance' into maintenance 2018-12-19 13:37:51 +01:00
Gina Häußge 5b4f4e3d77 Tentatively support Python 3 while that is being worked on 2018-12-19 13:36:55 +01:00
Gina Häußge c66b451efd Merge branch 'maintenance' into devel 2018-12-19 13:35:42 +01:00
Gina Häußge 4e9437114b Change wording & exception type 2018-12-19 13:35:18 +01:00
Connor Wolf 52c7321c78 Handle unsupported version at runtime.
If you have an ancient setuptools, 4a36ddb3aa
won't successfully prevent installing. These changes will at least give a sane error,
rather then  just barfing on random syntax errors due to the `unicode` type not
being present in py3k.

Cherry picked from 2f20f2d
2018-12-19 13:34:37 +01:00
Gina Häußge ef94646083 printer_safety: Added version restriction to anycubic detection
Had to refactor check system to make this possible. Checks are now
implemented in classes that allow to track state.
2018-12-19 13:17:45 +01:00
Unknown 37f3396be3 try fix default function 2018-12-18 19:32:31 +01:00
Unknown f8f461b804 add callback for on success/error for hook sdcopy 2018-12-18 19:07:15 +01:00
Unknown 5396daa7f6 move default fuction to local fuction + minor fix 2018-12-18 18:47:16 +01:00
Gina Häußge bb51dc23fc Merge pull request #2960 from jubaleth/fix/ExceptionMessageCorrection
Exception message correction
2018-12-18 11:06:35 +01:00
Jubaleth 2733838574 Corrected plugin manager failure exception message 2018-12-17 18:57:22 +01:00
Gina Häußge a23d92158b tracking: Track uptime of OctoPrint in ping event
That will give us an idea if the current hypothesis that quite a number
of people are shutting down their instance at night is correct or not,
which in turn will inform future startup optimizations.
2018-12-17 17:47:22 +01:00
Gina Häußge 99225244f1 Add full version string to API 2018-12-17 14:20:42 +01:00
Gina Häußge e30f1b9f82 Add "::1/128" to localNetworks for auto login
See BillyBlaze/OctoPrint-TouchUI#266
2018-12-17 12:29:19 +01:00
Unknown 054bbead72 clean doc + add default function + reduce parameter 2018-12-13 21:28:49 +01:00
Unknown 30294e9009 replace tab by space 2018-12-13 18:39:29 +01:00
Gina Häußge bf5bc14c87 backup: fix needed space calculation
It wasn't taking excludes into account. Now its calculation mirrors the
zip file creation.
2018-12-13 16:29:22 +01:00
Gina Häußge f6dd13af7a tracking: add printer safety warnings to tracking
We want to get an idea how many people are running unsafe firmware.
2018-12-13 15:24:24 +01:00
Gina Häußge 5760b4b264 tracking: check enabled state before preparing payload
Otherwise if tracking is disabled we still do the work and then throw
it away, which is kinda stupid.

Also fixes potential issues with using things like the unique_id when
it hasn't in fact been set due to disabled tracking.
2018-12-13 13:13:02 +01:00
Gina Häußge 49b995b234 Set 10min idle timeout on tornado under windows
Possible workaround for #2916
2018-12-12 16:06:15 +01:00
Gina Häußge 8cf5ca9589 tracking: Track firmware/communication errors 2018-12-12 15:41:36 +01:00
Gina Häußge ae36a3905a printer safety: Mark Malyan M200 fw 4.0+ as safe
Implements #2947
2018-12-12 15:25:38 +01:00
Gina Häußge bfd847f0a6 GCODE viewer: Bring back the layer count 2018-12-12 15:16:17 +01:00
Gina Häußge e14cb44e13 Fix merge error & forcelogin plugin 2018-12-12 14:39:39 +01:00
Gina Häußge 17ad63dabf Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/templates/tabs/temperature.jinja2
2018-12-10 15:01:16 +01:00
Gina Häußge ef81702219 Merge remote-tracking branch 'origin/maintenance' into maintenance 2018-12-10 14:59:55 +01:00
Gina Häußge 7cbe6244ae Merge branch 'staging/maintenance' into maintenance 2018-12-10 14:59:39 +01:00
Gina Häußge 112a8b9c8b Merge branch 'rc/maintenance' 2018-12-10 13:01:23 +01:00
Gina Häußge 98b692d845 Preparing release of 1.3.10 2018-12-10 12:44:25 +01:00
Gina Häußge f4f7c87640 Always show actual received from printer instead of off
Regardless how cold the temperature is, display it in the table. Some
people otherwise seem to think that OctoPrint "can't handle"
temperatures below 10°C and will blame it for MINTEMP errors triggered
in the firmware.
2018-12-06 11:49:23 +01:00
MirceaDan 39cda08d07 added six to required deps
i believe six was already brought in by other packages, but better to be specified in clear than to assume other will install it.
2018-12-03 10:41:46 -08:00
Gina Häußge 3a1611e5c4 Merge branch 'maintenance' into devel 2018-12-03 14:17:32 +01:00
Gina Häußge 5af5cbbb37 Merge branch 'staging/maintenance' into maintenance 2018-12-03 14:16:50 +01:00
Gina Häußge a657ebd528 staging/maintenance is now 1.3.10rc5.dev 2018-12-03 14:16:31 +01:00
Gina Häußge e628aedbc1 Preparing release of 1.3.10rc4 2018-12-03 12:42:28 +01:00
MirceaDan 7736cf1e6d import configparser py3
compat with py3
import configparser
2018-12-02 16:10:37 -08:00
MirceaDan 41e74df8d3 click.disable_unicode_literals_warning = True
when importing from future unicode literals those warning will need to be disabled
2018-12-02 15:44:20 -08:00
MirceaDan ac3b8ebfcc winreg compatibility with python3
_winreg has been renamed in winreg in py3
2018-12-02 15:24:19 -08:00
MirceaDan e0543de8ef print is a function + header
made print a function and added imports from future and encoding
2018-12-02 02:30:47 -08:00
MirceaDan f243a52823 all files start now with same 2 lines
# coding=utf-8
from __future__ import absolute_import, division, print_function
2018-12-02 02:13:12 -08:00
MirceaDan 94013ddb70 py23 compat for defining metaclasses
in python 3 and py2 metaclases are define ddiferentley, using six to get to a common solution
2018-12-02 01:25:27 -08:00
MirceaDan 9cfcbd3929 unquote works properley now with py2 and py3
py3 support directley to provide encoding, py2 has to do more work
2018-12-02 01:12:12 -08:00
MirceaDan 6cfbdc6062 py23 urlib compat
unquote was move dto a diferent location
2018-12-01 22:44:01 -08:00
MirceaDan d3334b29d9 fix for tests and previous commit regarding estimations
tests needed updated None replaced with -1
2018-12-01 22:26:30 -08:00
MirceaDan 94ce6f1dd1 cannot compare number with None
TypeError: '<' not supported between instances of 'float' and 'NoneType'
2018-12-01 20:02:22 -08:00
MirceaDan c623e90ebc chnaged teh default from binary to text mode
seams like open was defaulting to text mode, since now is specified in clear i made sure it matches with teh previous default
2018-12-01 17:43:19 -08:00
MirceaDan b6e49b59a7 unitest update to decode utf8
TypeError: write() argument 1 must be unicode, not str
2018-12-01 17:11:07 -08:00
MirceaDan f416e96414 defined unicode as str or used basestring
in py3 unicode does not exists is default str type but it exists in py2, wrote code to make it run in both py2 and py3
2018-12-01 17:00:37 -08:00
MirceaDan 347f53baa4 file must be open in text mode
those files must be opened in text mode in python3
2018-12-01 16:36:11 -08:00
MirceaDan 9ecf39febe we need a list not a map object
AssertionError: Second sequence is not a list: <map object at 0x7f7b0d3811d0>
2018-12-01 16:26:43 -08:00
MirceaDan 582b03f21f async is a function in py3
SyntaxError:Can't assign to function call

declared the dictionary using a diferent format that works in both py2 and py3

/src/octoprint/server/api/system.py", line 192
    async=True,
        ^
SyntaxError: invalid syntax
2018-12-01 16:13:20 -08:00
MirceaDan ff0b94c78d py23 compat: list is needed not a view
in py3 keys() returns a view but in this cases we need a list
2018-12-01 15:42:01 -08:00
MirceaDan f5c8b04958 DeprecationWarning: The 'warn' method is deprecated, use 'warning' instead
DeprecationWarning: The 'warn' method is deprecated, use 'warning' instead
2018-12-01 15:07:04 -08:00
MirceaDan 36818057a3 commands to be able to develop for py2 and py3 in same time
this way we can test both py2 and py3
2018-12-01 13:13:19 -08:00
MirceaDan a5cff5bc3d this file must be opened in text mode
the version file must be read in text mode
2018-12-01 12:19:30 -08:00
MirceaDan a4bff305b3 name update
filled in full name
2018-12-01 12:08:10 -08:00
MirceaDan 6b149e2fc9 fixed unitests for io.open change
the fixups needed change to use io.open in mock
some io.open needed to be read as text
2018-12-01 11:57:10 -08:00
Gina Häußge 38fce1665b backup: signal restore done before reboot 2018-11-30 20:07:18 +01:00
Gina Häußge f51a98768c backup: more feedback during restore
The upload of a backup can take a while, so pop up the work dialog as
soon as that starts, not only when it is finished.
2018-11-30 20:06:57 +01:00
Gina Häußge 4d04c323f6 backup: use base version for version check 2018-11-30 20:06:24 +01:00
Gina Häußge 94116bfd53 backup: fix on_restore_failed calls 2018-11-30 18:33:58 +01:00
Gina Häußge a05761e63f backup: better error logging 2018-11-30 18:29:55 +01:00
Gina Häußge 89469d38ae printer safety: Fix localization of warning 2018-11-30 17:06:07 +01:00
Gina Häußge bd2616e888 backup: exclude generated, logs & watched
We don't need these in the backup, and in fact they only make things
more bloated and/or complicated.
2018-11-30 16:53:26 +01:00
Gina Häußge 02e996436d backup: restore is not supported on windows
Sadly the stupid file locking of windows makes it impossible to
hot swap the config directory. In order to support windows a two step
approach would be needed. Maybe at a later date, currently simply not
worth the effort tbh considering how seldomly windows is used as OS for
OctoPrint.
2018-11-30 16:53:19 +01:00
Gina Häußge a3f2e0b56c backup: fix plugin compatibility check on restore
Fixes #2920
2018-11-30 16:21:58 +01:00
MirceaDan 337e49208a py23 compat: using io.open instead of open
for python3 and python2 to work teh same io.open must be used for file handling
2018-11-30 00:32:57 -08:00
Gina Häußge b052925424 Merge remote-tracking branch 'origin/devel' into devel
# Conflicts:
#	tests/filemanager/test_filemanager.py
2018-11-28 17:37:47 +01:00
Gina Häußge 970c867ee4 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/plugins/forcelogin/__init__.py
#	src/octoprint/server/util/sockjs.py
#	src/octoprint/users.py
2018-11-28 16:33:11 +01:00
Gina Häußge c4295d6a81 Merge branch 'staging/maintenance' into maintenance 2018-11-28 14:57:14 +01:00
Gina Häußge d60cab1962 staging/maintenance is now 1.3.10rc4.dev 2018-11-28 14:56:39 +01:00
Gina Häußge b01e327f9d Preparing release of 1.3.10rc3 2018-11-28 12:56:02 +01:00
Gina Häußge 09af2813d0 Add dedicated issue templates 2018-11-27 14:21:13 +01:00
Gina Häußge 2f69a84352 Use max of comm & temp timeout as serial timeout
That way we avoid issues if the user has set a longer temperature
reporting interval than (busy) communication timeout.

See #2905
2018-11-26 15:33:37 +01:00
Gina Häußge 13260fa219 tracking: file path instead of just name in print events
Closes #2908
2018-11-26 14:10:03 +01:00
Gina Häußge 9a90093dda tracking: file path instead of just name in print events
Closes #2908
2018-11-26 14:08:33 +01:00
Gina Häußge 8292408c79 Remove image from changelog, replace with text
Closes #2909
2018-11-26 12:05:58 +01:00
Gina Häußge 9165f83084 printer safety: Mark stock Micro3D fw as unsafe
See https://github.com/donovan6000/iMe/issues/67#issuecomment-441454163
2018-11-26 10:27:20 +01:00
Gina Häußge c2ef371089 Docs: add documentation for some config params 2018-11-23 11:12:40 +01:00
Gina Häußge fa9472d4aa Fix SWU restart command again
Accidentally committed something I only changed for a test. Oops.
2018-11-22 15:54:02 +01:00
Gina Häußge 037e92c447 Recognize incomplete startups and set safe mode flag 2018-11-22 15:52:18 +01:00
Gina Häußge 170804d4df Create a backup of working config.yaml after startup 2018-11-22 13:47:02 +01:00
Gina Häußge ac129a2576 Only patch sarge's async on python 2 2018-11-22 13:10:59 +01:00
Gina Häußge db8d420860 Decorator for sarge that translate async to async_
Should work around issues with third party plugins that haven't yet
adapted.
2018-11-22 12:37:28 +01:00
Gina Häußge 7d7cbb1760 Some reordering in the settings 2018-11-21 16:14:23 +01:00
Gina Häußge 89979f1bee Revert "Hardening against bad plugins"
Making on_after_startup asynchronous unearths some odd issue that causes
subsequent callback calls to duplicate. It might just be PyCharm's
debugger (disabling it makes the problem go away and I so far couldn't
reproduce it without it), but just in the case that I introduced some
weird race condition with this _async approach I'm removing it. I'd
rather have badly implemented plugins break the startup then the startup
being inherently broken from the get go.

Added a couple more warnings in the docs though.
2018-11-21 16:14:06 +01:00
Gina Häußge bd241e8e6c backup: allow zip64 2018-11-21 12:19:04 +01:00
Gina Häußge 7939b0ae4d backup: better error reporting 2018-11-21 12:10:03 +01:00
Gina Häußge 6b57ba2d7d printer_safety: detect iMe on Micro3D
See donovan6000/iMe#67
2018-11-20 12:42:52 +01:00
Gina Häußge 2c5465f9a6 Got rid of an unused import 2018-11-20 12:42:50 +01:00
Gina Häußge 1565129cfb docs: warning about blocking ops in some plugin callbacks 2018-11-20 12:42:49 +01:00
Gina Häußge b8d4a58207 SWU: remove one thread level
on_after_startup now runs in its own thread, no need to spawn yet
another.
2018-11-20 12:42:43 +01:00
Gina Häußge 900f03dc8a SWU: add a timeout to the wait on environment info 2018-11-20 12:24:50 +01:00
Gina Häußge 0c4c4a9d18 Hardening against bad plugins
We don't want on_after_startup or on_event handling to get blocked by
some rogue plugin that decides to block or outright kill the thread.
2018-11-20 12:19:17 +01:00
Gina Häußge ff4ed38329 Track user logout on socket 2018-11-19 15:24:12 +01:00
Gina Häußge 5f78ab7b73 Register for plugin messages on socket connect
Second part of the fix for #2898
2018-11-19 15:22:45 +01:00
Gina Häußge 6556d555bd forcelogin: Keep message backlog while not authed
First part of the fix for #2898
2018-11-19 15:22:33 +01:00
Gina Häußge d318ff82b8 More error resilience in the local ip check
Should solve #2897
2018-11-16 13:57:11 +01:00
Gina Häußge ff53a826f9 tracking: Fix link of plugin in plugin manager 2018-11-16 13:19:31 +01:00
Unknown abb14dc17a add hook for sdcard copy + documentation 2018-11-16 11:17:05 +01:00
Unknown a45c86eed1 Revert "add self param to error_hook + update documentation"
This reverts commit c30380d423.
2018-11-16 11:03:35 +01:00
Unknown c30380d423 add self param to error_hook + update documentation 2018-11-16 11:02:15 +01:00
Gina Häußge d79e777911 Update german translation 2018-11-15 14:42:48 +01:00
Gina Häußge 335e635ec7 printer_safety_check: Make a text translateable 2018-11-15 14:17:06 +01:00
Gina Häußge a5754a8552 pi_support: Add link to the new FAQ entry 2018-11-15 14:16:27 +01:00
Gina Häußge a8c91ff6ba pi_support: Better wording in popover & highlight current 2018-11-15 12:57:02 +01:00
Gina Häußge 6285fd8010 Allow dynamic values in ko popover binding 2018-11-15 12:40:03 +01:00
Gina Häußge c69f20c648 Mark py3 as supported for development even though it's not 2018-11-13 16:23:28 +01:00
Gina Häußge 88c93a7c11 Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
2018-11-13 16:22:07 +01:00
Gina Häußge 92629468c0 Merge remote-tracking branch 'origin/maintenance' into maintenance
# Conflicts:
#	setup.py
2018-11-13 16:17:56 +01:00
Gina Häußge 56a1d4f966 Merge branch 'staging/maintenance' into maintenance 2018-11-13 16:17:08 +01:00
Gina Häußge 799aedcaed staging/maintenance is now 1.3.10rc3.dev 2018-11-13 16:16:43 +01:00
Gina Häußge de42ce73f7 Preparing release of 1.3.10rc2 2018-11-13 12:43:06 +01:00
Gina Häußge 962e09906e tracking: Fix translatability of a message 2018-11-13 12:42:31 +01:00
Gina Häußge f607f55683 printer_safety_check: Detect Ender 3 stock fw
As reported in https://discourse.octoprint.org/t/thermal-runaway-protection-absent-on-creality-ender-3/2787
2018-11-13 11:17:24 +01:00
Gina Häußge 8e464f59ac Reapply "Updated several dependencies to current version"
This reverts commit e14c00f135.
2018-11-12 17:27:37 +01:00
Gina Häußge 91b524813c Minimum python version is now 2.7.9 2018-11-12 17:27:37 +01:00
Gina Häußge 1b45047826 tracking: wizard changes
* spinners for the enable/disable buttons
  * error handler for persisting the decision that unlocks the wizard

Might help to work around issues less than a hand full of people have
now observed where the wizard's buttons are non functional but the
wizard itself is active and blocking.

More data needed to reproduce and debug the core issue though.
2018-11-12 15:23:17 +01:00
Gina Häußge edd4d90b12 tracking: tracking.js -> usage.js
To work around some ad blockers that might block this otherwise - which
is kinda funny since the js file doesn't do any tracking, it just
makes the setup wizard for the opt-in functional 🤦‍♀️
2018-11-12 14:33:43 +01:00
Gina Häußge 0a3ad8a880 tracking: add time & reason for failure to print_failed
(cherry picked from commit b7e373c)
2018-11-12 14:33:43 +01:00
Gina Häußge 82615791a2 Add time & reason for failure to PrintFailed event
(cherry picked from commit dae0264)
2018-11-12 14:33:42 +01:00
Gina Häußge 4548be34f0 Always trigger SettingsUpdated event on new save
So far it was only triggered when saving via the REST API, causing some
issues here and there.
2018-11-12 11:40:21 +01:00
Gina Häußge 2b5af2c36a Add docs for octoprint.util.commandline 2018-11-09 18:16:57 +01:00
Gina Häußge a939130748 Better description for Error event 2018-11-08 18:39:03 +01:00
Gina Häußge b7e373c40f tracking: add time & reason for failure to print_failed 2018-11-08 17:41:45 +01:00
Gina Häußge dae0264a58 Add time & reason for failure to PrintFailed event 2018-11-08 17:41:27 +01:00
Gina Häußge b2e50e13d4 Blacklist broken regex version 2018-11-08 15:54:05 +01:00
Gina Häußge cb4404a833 Merge branch 'pr/2878' into staging/maintenance 2018-11-08 15:50:13 +01:00
Gina Häußge 38bb81cfe7 tracking: add throttle events, slightly change throttle payload
Also adjusted helper signature in pi_support plugin slightly.

Addon to #2878
2018-11-08 15:49:11 +01:00
Gina Häußge 1667f9bd52 Fix bug introduced in 4caf4ef09 2018-11-08 14:00:48 +01:00
Gina Häußge 1ec61a9fe6 Give the favicon mask SVG width and height attrs
Otherwise it won't render correctly in Firefox due to drawImage silently
failing, see also https://bugzilla.mozilla.org/show_bug.cgi?id=700533

Closes #2879
2018-11-08 13:42:19 +01:00
tedder 98c84b6bb9 fix test, match dict 2018-11-08 01:34:45 +00:00
tedder 76f48b3b13 PR feedback: throttle state and uuid
- add a way to get the raw value only from throttle state (glad I already plumbed it into the object!)
- add warning about not sending uuid, modify the log entry too
2018-11-08 01:29:15 +00:00
Gina Häußge 8596ae5c4a SWU: Make sure check providers are in the correct format
Just in case there's some odd data in `config.yaml` as reported in https://github.com/foosel/OctoPrint/issues/2871#issuecomment-436507623
2018-11-07 11:10:31 +01:00
tedder c1482eaacd add throttle_state to tracking
- weave the throttle_state through pi_support and tracking. This should come in handy to see how many throttled Pis are out there, as well as if it is correllated with canceled prints.
- upgraded disclosure of tracking information so it shows as INFO-level in the logs and all the information is dumped. If tracking.octoprint.org gets it, I should have it too :)
2018-11-06 15:37:45 -08:00
Gina Häußge e23fe4a925 forcelogin: Fix issue when running with acl disabled
Closes one variant of #2876
2018-11-06 17:34:01 +01:00
Gina Häußge 8939537fb5 Merge branch 'staging/maintenance' into maintenance 2018-11-06 15:57:18 +01:00
Gina Häußge 2f08b90200 Merge branch 'master' into staging/maintenance 2018-11-06 15:56:33 +01:00
Gina Häußge 68ca2c5e51 Pin regex dependency to last known working version
See #2874 and https://bitbucket.org/mrabarnett/mrab-regex/issues/301/typeerror-character-mapping-must-return
2018-11-06 15:52:41 +01:00
Gina Häußge 343195477b Fix connection fail if fw doesn't send start
Closes #2872
2018-11-06 14:47:39 +01:00
Gina Häußge 4caf4ef09b Fix GCODE viewer not being able to load files
Side effect of the ForcedLogin plugin and a bug in
get_flask_user_from_request.

Closes #2873
2018-11-06 14:02:49 +01:00
Gina Häußge 54677f96f4 Merge branch 'maintenance' into devel 2018-11-06 12:32:25 +01:00
Gina Häußge 0ba987e126 maintenance is now 1.3.11.dev 2018-11-06 12:31:53 +01:00
Gina Häußge 0325628693 staging/maintenance is now 1.3.10rc2.dev 2018-11-06 12:29:28 +01:00
Gina Häußge e522633c98 Merge branch 'maintenance' into devel
# Conflicts:
#	AUTHORS.md
#	src/octoprint/plugins/pluginmanager/__init__.py
#	src/octoprint/plugins/softwareupdate/__init__.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/__init__.py
#	src/octoprint/server/util/flask.py
#	src/octoprint/server/util/sockjs.py
#	src/octoprint/server/util/tornado.py
#	src/octoprint/static/js/app/client/base.js
#	src/octoprint/users.py
2018-11-06 11:57:57 +01:00
Gina Häußge e14c00f135 Revert "Updated several dependencies to current version"
This reverts commit 4ed5f7e

The updates cause issues on very old python environments (distribute
instead of setuptools, e.g. OctoPi 0.12) due to new package formats.

We'll postpone them to 1.3.11, since OctoPrint 1.3.10 will then refuse
to upgrade in such environments anyhow.
2018-11-05 14:25:10 +01:00
Gina Häußge b0a4a49f99 Changelog for 1.3.10rc1 2018-11-05 13:18:05 +01:00
Gina Häußge 5b4839369e appkeys: Probe endpoint to check for workflow support
Also adjusted docs and js client lib accordingly.
2018-11-05 12:50:05 +01:00
Gina Häußge 1ff02b9f1c Update bundled German translation 2018-11-05 11:59:48 +01:00
Gina Häußge e2c1fa3d43 Appkeys: request creation should respond with 201 2018-11-02 17:04:58 +01:00
Gina Häußge 39a466e316 Appkeys: Make timeout thread safe 2018-11-02 12:53:30 +01:00
Gina Häußge 9e940eacc3 Merge branch 'fix_appkey_orphan_dialogs' of https://github.com/fieldOfView/OctoPrint into pr/2869 2018-11-02 12:27:16 +01:00
Gina Häußge 2e38f237de Fix cancel snippet for shared nozzle setups
See https://discourse.octoprint.org/t/prusa-mmu2-how-to-properly-configure/4937/
2018-11-02 12:20:05 +01:00
fieldOfView 7f36ffdafd Expire request_access when the client stops polling 2018-11-02 11:04:06 +01:00
Gina Häußge 39b2da3230 Merge pull request #2868 from gdombiak/extrude_speed2
Documentation fixed and extrusion speed value check
2018-11-02 10:52:42 +01:00
fieldOfView c489829efb Add myself to AUTHORS.md
because it's a requirement for a PR
2018-11-02 09:31:56 +01:00
fieldOfView e30e129e2a Close request_access dialogs on other open connections when a decision is made
Once a decision is made on one connection (browser window), dialogs on other connections are no longer relevant.
2018-11-02 09:22:30 +01:00
Gaston Dombiak 32d5b25013 Removed unnecessary variable initialization 2018-11-01 21:44:42 -07:00
Gaston Dombiak 6227a0dfb9 1) Fixed documentation about speed unit and 2) extrusion speed is now limited to printer profile max value 2018-10-31 20:45:56 -07:00
Gina Häußge e234c6146e Better detection of ipv6 support
Apparently socket.has_ipv6 doesn't actually do what it says in the docs
(state whether the underlying platform supports ipv6). It returns True
even when ipv6 has manually been disabled for whatever reason. So we
will no longer trust this but instead attempt to actually create a v6
socket and only if that succeeds assume that v6 is indeed supported on
the platform.
2018-10-31 13:39:54 +01:00
Gina Häußge c146731e5a Merge pull request #2865 from gdombiak/extrude_speed
Extrude speed
2018-10-31 11:58:28 +01:00
Gina Häußge 5ee242be4a Fix doc bug: mm/s => mm/min 2018-10-31 11:54:17 +01:00
Gaston Dombiak 556878a774 Merge branch 'maintenance' into extrude_speed 2018-10-30 19:09:05 -07:00
Gaston Dombiak 00aa4876e9 Added support to specify extrude/retract speed. Only at REST API. No UI changes were made 2018-10-30 19:01:20 -07:00
Gina Häußge f72f948744 Merge pull request #2828 from tedder/devel_ted_py3_round3
tedder's python3 fixes, round 3
2018-10-30 17:36:38 +01:00
Gina Häußge 3ad4818488 Use read instead of write mode in _load_yaml 2018-10-30 16:56:14 +01:00
Gina Häußge b3cc44cea5 Fix build error
`octoprint_setuptools` is imported into the build before the dependencies are installed, hence we don't have `past.builtins` yet. Since the `basestring` type was only needed for some asserts here that *usually* shouldn't be needed we can just comment out that stuff for now.
2018-10-30 16:46:12 +01:00
Gina Häußge 2f89082df2 Missed something in yesterday's changes to contrib guide 2018-10-19 13:14:52 +02:00
Gina Häußge 108db045ce Small changes to the contribution guidelines
* allow PRs against `maintenance` branch for improvements and small
    new features
  * suggest getting in touch on the forum for larger changes
2018-10-18 18:06:01 +02:00
tedder 9cb3631ad0 first py3 fix 2018-09-22 18:05:32 -07:00
tedder 743ff35bcf add some yaml wrappers for the test environment 2018-09-22 18:05:10 -07:00
tedder df706f61db import locally for py3 mock compatability 2018-09-22 17:21:33 -07:00
tedder 791e759b40 keys() doesn't return a list, so restoring the contract. 2018-09-22 17:21:05 -07:00
tedder 22fdc1d933 final open mock tactic: add a central global. 2018-09-22 16:58:24 -07:00
tedder aa383e3ca1 fix all __builtin__.open patch/mock calls 2018-09-22 16:15:22 -07:00
tedder 472fda6645 setuptools py3 compatability 2018-09-22 16:02:44 -07:00
tedder bd35de80c3 fix test_file_helpers, couldn't figureout a non-conditional way to do this 2018-09-22 15:55:19 -07:00
tedder 52fe19e5f9 fix util.to_unicode for py2/py3. 2018-09-22 15:54:29 -07:00
tedder c2f09b1715 fixes to test_comm_helpers 2018-09-22 13:14:27 -07:00
Gina Häußge 1ccc1fa47b Merge pull request #2807 from tedder/201809_py3_devel_prep_b
201809 py3 devel prep batch b
2018-09-21 12:20:44 +02:00
tedder 2972d38cef use a number instead of a string for safe_dump 2018-09-18 08:54:58 -07:00
tedder 4662606907 PR feedback: use future instead of six
Tests pass.
2018-09-18 08:37:34 -07:00
Gina Häußge 2c50aa789a Merge branch 'pr/2733' into devel
# Conflicts:
#	src/octoprint/plugins/discovery/__init__.py
2018-09-18 17:30:30 +02:00
Gina Häußge 9e62b250ac Merge pull request #2804 from cameroncros/system-api-documentation
Fixed up documentation for system api. Now correctly matches current behaviour
2018-09-18 17:11:32 +02:00
Gina Häußge 03722e5e70 Merge branch 'pr/2731' into devel
# Conflicts:
#	src/octoprint/cli/analysis.py
2018-09-18 17:06:37 +02:00
tedder 7867052339 another 'set equality', this one to fix map/list mappings 2018-09-02 00:44:30 -07:00
tedder 8a0252ccfe add patch workaround for py2/py3 2018-09-02 00:16:06 -07:00
tedder e84293c415 add py3compat to CaseInsensitiveSet 2018-09-01 22:34:36 -07:00
tedder 250e83ad7e more specific asserts
This lets the testing framework show the test error better.
2018-09-01 22:32:47 -07:00
tedder 660724741c quick refactor for deprecated 'assertEquals'
It's been quietly allowed but was dropped in py3.
2018-09-01 22:31:33 -07:00
tedder a5f87597ad refactor and upgrade tests
Some prepwork for py3. Tossing these together:
- assertItemsEqual doesn't do what it says on the box. It only said "hey, these lists have the same number of items". Not content or anything. Changing that to SetEqual, which is much closer to what is wanted- ensuring that lists have the same content without caring about their order.
- use assertRaises instead of try/catch
- update some mocks, especially mock_open.
- include the refactored test_get_recovery_data sent to the maintenance branch in #2806.
2018-09-01 22:27:10 -07:00
Cameron Cross ebef35a573 Fixed up documentation for system api. Now correctly matches current behaviour. 2018-09-02 10:03:21 +10:00
Gina Häußge 44fcd4e305 Merge branch 'maintenance' into devel 2018-07-25 17:38:45 +02:00
Gina Häußge 90704e292b Merge branch 'maintenance' into devel 2018-07-25 16:57:00 +02:00
Gina Häußge b83dd76c89 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/static/js/app/viewmodels/printerstate.js
2018-07-20 12:27:36 +02:00
Gina Häußge 7ab4b90d07 Fix a flask import 2018-07-16 15:32:19 +02:00
Gina Häußge fd4ff2bf37 Merge branch 'maintenance' into devel
# Conflicts:
#	AUTHORS.md
#	src/octoprint/plugin/__init__.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/__init__.py
#	tests/timelapse/test_timelapse_helpers.py
2018-07-16 15:29:02 +02:00
sti2d 76f93d8875 Fix import changes on python 3
Try python3 import & revert back to python2 if ImportError is raised
this include BaseHttpServer -> http.server, StringIO -> io, HTMLParser -> html.parser
2018-07-14 10:09:28 +02:00
sti2d 30359f52ab In python 3, map/filter return specific object types that :
* are not directly iterable
* doesn't work with len() function
* doesn't allow list concatenation

This commit wraps all relevant map/filter outputs into a list object type
2018-07-14 09:22:27 +02:00
sti2d 0020f029d1 Python yaml now use numeric value for indent attribute, this commit take care of that 2018-07-14 07:06:18 +02:00
Gina Häußge d248df3826 Merge branch 'maintenance' into devel 2018-07-06 17:00:19 +02:00
Gina Häußge dc19ad4c4c Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/server/util/__init__.py
2018-07-06 14:40:46 +02:00
Salandora 88a962b3ab Fix for _test_url
Snapshot test threw a 500 Internal Error.
After some investigation (no exception got thrown, except in debug mode) I noticed that the test url function tried to access octoprint util which was not imported.
Because util was used in different locations of this function I decided to put it at the top of the function right after import requests.
2018-07-01 03:07:49 +02:00
Gina Häußge 033e567d2a Merge pull request #2701 from Salandora/fix/firstRunWizard
Fix add user part of the first run wizard
2018-06-25 12:54:47 +02:00
Marc Hannappel d03d4b7b4c Fix add user part of the first run wizard 2018-06-25 10:15:28 +02:00
Gina Häußge 38ddd3102d Fix another broken permission
Closes #2689
2018-06-22 12:49:51 +02:00
Gina Häußge 6dd501217a Remove an unnecessary debug line 2018-06-22 11:48:57 +02:00
Gina Häußge e58387b4f2 Make new additions from 1.3.x use permissions 2018-06-20 16:36:15 +02:00
Gina Häußge 1de58b7be1 error => fail 2018-06-20 16:31:13 +02:00
Gina Häußge 58d8deefcd Merge branch 'maintenance' into devel
# Conflicts:
#	AUTHORS.md
#	setup.py
#	src/octoprint/plugins/announcements/static/js/announcements.js
#	src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
#	src/octoprint/server/api/__init__.py
#	src/octoprint/static/css/octoprint.css
#	src/octoprint/static/js/app/dataupdater.js
#	src/octoprint/static/js/app/viewmodels/printerstate.js
2018-06-20 16:29:18 +02:00
Gina Häußge f8e6e4e3db Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/plugins/printer_safety_check/__init__.py
2018-06-05 11:12:42 +02:00
Gina Häußge a92372ec7e Fix permission on temperature set button
Closes #2662
2018-05-24 10:36:20 +02:00
Gina Häußge 7b773f6fd2 Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
#	src/octoprint/templates/dialogs/settings/accesscontrol.jinja2
#	src/octoprint/templates/sidebar/files_header.jinja2
2018-05-18 13:45:42 +02:00
Gina Häußge 69681a27d6 Fix the unrendered timelapse list being visible when empty 2018-05-17 17:27:00 +02:00
Gina Häußge 0adcfc693d Merge branch 'pr/2410' into devel 2018-05-17 16:29:09 +02:00
Gina Häußge b73507fd2b Increase default bitrate for timelapses 2018-05-17 16:27:18 +02:00
Gina Häußge bea6bd013c Some small fixes
* fixed whitespace
  * less repetition for output/capture format
  * value range check for ffmpegVideoCodec as suggested
2018-05-17 16:23:50 +02:00
Gina Häußge 9a881012e2 Add new 3rd party lib to list 2018-05-16 18:36:07 +02:00
Gina Häußge d62df7643b Use resize sensor to fix progress bar text widths
Closes #2635
2018-05-16 18:29:39 +02:00
Gina Häußge 7d40320a5b SWU: Fix another leftover wrong permission name 2018-05-15 17:05:54 +02:00
Gina Häußge 09456b923f SWU: Fix update button not working
Closes #2641
2018-05-15 17:01:12 +02:00
Gina Häußge 39e6c11c39 Fix overflown tabdrop tabs not being selectable
Closes #2643
2018-05-15 16:45:38 +02:00
Koen Kooi 5aef014773 unit tests: timelapse: add videocodec test
This test checks if both videocodec and container format have been set
correctly.

Signed-off-by: Koen Kooi <koen@dominion.thruhere.net>
2018-05-15 10:42:11 +02:00
Koen Kooi 9738884ff8 messages.pot: add videocodec settings entries
Signed-off-by: Koen Kooi <koen@dominion.thruhere.net>
2018-05-15 10:42:11 +02:00
Koen Kooi 27b625a614 timelapse: pick container and suffix based on setting
Signed-off-by: Koen Kooi <koen@dominion.thruhere.net>
2018-05-15 10:42:07 +02:00
Koen Kooi 096e9fc326 timelapse: change videocodecs to predefined list 2018-05-11 12:19:39 +02:00
Koen Kooi f577d6b45d timelapse: add setting for videocodec
Signed-off-by: Koen Kooi <koen@dominion.thruhere.net>
2018-05-11 12:19:34 +02:00
Gina Häußge bd7a28af5b Fix unit test 2018-05-10 18:35:25 +02:00
Gina Häußge 104b0a504c Merge branch 'pr/2586' into devel
# Conflicts:
#	AUTHORS.md
#	src/octoprint/server/util/sockjs.py
#	src/octoprint/static/js/app/viewmodels/timelapse.js
2018-05-10 18:18:05 +02:00
Gina Häußge 40bfbe0d7b knockoutify progress bar
Also hide it when we are not rendering anything.
2018-05-10 18:15:49 +02:00
Gina Häußge 4bf5984ace ffmpeg needs help for continuous progress reporting
See https://stackoverflow.com/a/35422274
2018-05-10 18:15:25 +02:00
Gina Häußge 8369d311bf Small refactoring & fixed tests 2018-05-03 17:42:30 +02:00
Gina Häußge d8eb57548d Merge branch 'dev/granularPermissions' into devel
# Conflicts:
#	src/octoprint/server/api/files.py
#	src/octoprint/server/api/job.py
#	src/octoprint/static/js/app/viewmodels/users.js
2018-04-26 19:27:11 +02:00
Gina Häußge d8072f0e05 Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
2018-04-26 19:10:16 +02:00
Gina Häußge 3d7016f500 Fixed/removed completely outdated & broken tests 2018-04-26 19:09:03 +02:00
Gina Häußge 41e3a0390f Removed CombinedPermissions
We now support adding other permissions to Permissions on creation, so
there's no need for this anymore.

Adjusted plugin permission addition accordingly by merging "regular" and
"combined" types.

Migrated log download permission.

Fixed some stuff here and there that I can't remember right now.
2018-04-26 19:08:30 +02:00
Gina Häußge 42a9a1976d Fix anonymous user & disabled ACL mode 2018-04-26 18:25:27 +02:00
Gina Häußge 569991e55c removeable => removable, changable => changeable 2018-04-26 13:06:14 +02:00
ZachNo b7adf115ee Changed to CommandlineCaller, added test
Now using CommandlineCaller using a custom logger function.
Added test in test_timelapse_helpers.py for _process_ffmpeg_output
2018-04-21 21:44:52 -04:00
Gina Häußge 7cf0f552f5 Track group flags from default groups 2018-04-20 20:31:10 +02:00
Gina Häußge 246c614635 Allow plugins to declare permissions as default for standard groups 2018-04-20 20:00:34 +02:00
Gina Häußge df62f08ec3 React to permission changes & fix timelapse permissions 2018-04-20 14:32:21 +02:00
Gina Häußge b6f71eeb3b restricted_access => require_firstrun
We don't want to require a login session anymore in most cases, we have granular permissions for this.
2018-04-20 14:08:02 +02:00
Gina Häußge e2a7e07a0a Fix some imports 2018-04-20 14:04:38 +02:00
Gina Häußge b3acd36092 Don't try to login/out anonymous users 2018-04-20 14:02:39 +02:00
Gina Häußge 7a037b9c66 Make sure to update data if current permissions change 2018-04-19 22:01:52 +02:00
Gina Häußge c1cf359b43 Fix a group duplication bug 2018-04-19 18:49:05 +02:00
Gina Häußge 2d883d6d20 Make "users" group mandatory for logged in users
That makes the migration scenario way easier and also makes sense
in general.
2018-04-19 14:55:47 +02:00
Zachary N 2fa18f5855 Merge branch 'devel' into dev/timelapseProgress 2018-04-16 18:25:48 -04:00
ZachNo a4ce92c963 Added timelapse render progress bar
For issue @485

Added progress bar to the Timelapse tab between the settings and files
Added code to process the output of ffmpeg and compute a percentage
Added code to communicate the percentage from the server to the client
Added myself to the authors

Changed tests to reflect new loglevel
2018-04-16 06:05:25 -04:00
Gina Häußge c84d39a803 Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/server/__init__.py
2018-04-13 17:23:42 +02:00
Gina Häußge d59eaa2a91 Admins are also users 2018-04-12 19:49:04 +02:00
Gina Häußge f7ad87449a Identify groups by a key & add group role 2018-04-12 19:07:59 +02:00
Gina Häußge 08bfae216c Merge branch 'devel' into dev/permission
# Conflicts:
#	src/octoprint/plugins/printer_safety_check/__init__.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/util/sockjs.py
2018-04-12 16:37:27 +02:00
Gina Häußge 64db784d8d Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/server/__init__.py
2018-04-12 16:35:53 +02:00
Gina Häußge 5a91b8db48 Some permission changes & fixes 2018-04-12 16:34:17 +02:00
Gina Häußge 58f73f3ed9 Merge branch 'maintenance' into devel 2018-04-09 17:03:30 +02:00
Gina Häußge 1852578136 Merge branch 'devel' into dev/permission
# Conflicts:
#	src/octoprint/plugins/logging/__init__.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/util/sockjs.py
#	src/octoprint/static/css/octoprint.css
2018-04-04 16:47:51 +02:00
Gina Häußge fdb2ba8146 Merge branch 'maintenance' into devel 2018-04-04 12:41:37 +02:00
Gina Häußge 92ea6ee9aa Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/util/tornado.py
2018-03-29 17:01:18 +02:00
Gina Häußge fb4e95bf8e Merge branch 'maintenance' into devel 2018-03-23 16:29:30 +01:00
Gina Häußge cedbf039d2 Consolidate json encoding like in 1.3.x 2018-03-20 16:12:32 +01:00
Gina Häußge d1711f0376 Merge branch 'devel' into dev/permission
# Conflicts:
#	src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
#	src/octoprint/server/__init__.py
#	src/octoprint/server/util/flask.py
#	src/octoprint/server/util/sockjs.py
#	src/octoprint/static/css/octoprint.css
#	src/octoprint/static/js/app/viewmodels/printerstate.js
#	src/octoprint/templates/tabs/timelapse.jinja2
2018-03-20 16:10:19 +01:00
Gina Häußge 047b9f544a Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/server/__init__.py
#	src/octoprint/server/util/__init__.py
#	src/octoprint/server/util/flask.py
#	src/octoprint/users.py
2018-03-19 17:24:11 +01:00
Gina Häußge 8ea7528d41 Show control tab if webcam or control allowed 2018-03-17 18:03:41 +01:00
Gina Häußge 43bf55d503 Migrate logging plugin to new permission system 2018-02-20 15:43:20 +01:00
Gina Häußge b9a5e1db69 Merge branch 'devel' into dev/permission
# Conflicts:
#	src/octoprint/plugins/corewizard/__init__.py
#	src/octoprint/plugins/pluginmanager/__init__.py
#	src/octoprint/plugins/softwareupdate/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/job.py
#	src/octoprint/server/api/log.py
#	src/octoprint/server/util/__init__.py
#	src/octoprint/server/views.py
#	src/octoprint/static/css/octoprint.css
#	src/octoprint/static/js/app/main.js
#	src/octoprint/static/js/app/viewmodels/log.js
#	src/octoprint/static/js/app/viewmodels/loginstate.js
#	src/octoprint/static/js/app/viewmodels/printerstate.js
#	src/octoprint/static/js/app/viewmodels/users.js
#	src/octoprint/static/less/octoprint.less
#	src/octoprint/templates/dialogs/settings/logs.jinja2
#	src/octoprint/templates/tabs/control.jinja2
#	src/octoprint/util/__init__.py
2018-02-20 15:42:43 +01:00
Gina Häußge 03d421c629 Merge remote-tracking branch 'origin/devel' into devel 2018-02-20 13:17:41 +01:00
Gina Häußge 066e7d1e39 flask.ext.foo => flask_foo 2018-02-20 13:15:30 +01:00
Gina Häußge 4fd641dc74 Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/server/__init__.py
2018-02-20 12:55:55 +01:00
Gina Häußge 16b690089d Merge pull request #2328 from tedder/grammar_fix_setup
grammatical fix in text
2018-01-12 15:31:09 +01:00
tedder a77fbfe0c2 grammatical fix in text
[It's a common error](https://brians.wsu.edu/2016/05/31/setup-set-up/); I'm not sure if it needs to be fixed in all three places or perhaps only in the .pot file.
2017-12-27 19:57:47 -08:00
Gina Häußge b36a776f51 Merge branch 'maintenance' into devel 2017-12-12 13:09:41 +01:00
Gina Häußge 9c39dd7303 Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
2017-12-05 16:02:19 +01:00
Gina Häußge eb5a3d1d36 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/static/js/app/main.js
2017-12-01 16:10:12 +01:00
Gina Häußge d465f23309 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/plugins/corewizard/__init__.py
#	src/octoprint/plugins/discovery/__init__.py
#	src/octoprint/plugins/pluginmanager/__init__.py
2017-11-29 18:19:08 +01:00
Gina Häußge 987a6b3cf8 PLUGIN_SOFTWAREUPDATE_ACCESS is no longer used 2017-11-28 16:49:22 +01:00
Gina Häußge 6b3d68f9aa Backwards compatibility for user_permission 2017-11-28 16:25:03 +01:00
Gina Häußge fcd34265c8 Fix empty active checkbox 2017-11-28 13:21:20 +01:00
Gina Häußge 088b0cf1e7 Merge branch 'devel' into dev/permission
# Conflicts:
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/__init__.py
#	src/octoprint/server/util/flask.py
2017-11-28 13:19:54 +01:00
Gina Häußge e6061fdd9c Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/server/util/flask.py
2017-11-28 13:08:34 +01:00
Gina Häußge cf8a30cc4e Reordering: Put settings related things together 2017-11-28 12:20:14 +01:00
Gina Häußge 6ba1e10b8b Fix API key generation 2017-11-28 12:14:30 +01:00
Gina Häußge 2a96864c07 Merge branch 'devel' into dev/permission
# Conflicts:
#	src/octoprint/templates/dialogs/settings/accesscontrol.jinja2
2017-11-28 12:07:39 +01:00
Gina Häußge 48fceac0fe Merge branch 'maintenance' into devel 2017-11-27 17:27:30 +01:00
Gina Häußge ad246deb9e Merge branch 'maintenance' into devel 2017-11-24 14:05:41 +01:00
Gina Häußge c2509fad9c Add icon to add printer profile/add cura profile
To consolidate with access control buttons.
2017-11-23 19:09:45 +01:00
Gina Häußge eeb216e08d More work on the permissions
* permissions and groups are now optional fields on users - if not
    provided, will be set to empty permissions and default groups
  * description is now an optional field on groups - if not provided
    will be set to an empty string
  * Made the group manager a bit leaner
  * Removed code duplication for group and user editor
  * OctoPrint.access.groups.update now takes an object just like the add
    method - this enables to do partial updates and also is way easier
    to remember
  * Some bugs fixed
  * Added wrappers for the old add/remove/changeRolesForUser methods -
    just a simple rename is not correct since those took roles, not
    permissions. Needs some tests, haven't been able to do that yet.
2017-11-23 19:09:14 +01:00
Gina Häußge 2761608c1e Refactor user list to better fit user details
Also fix default group pre fill in user add dialog.
2017-11-23 15:59:04 +01:00
Gina Häußge 27536388f2 Refactor access control settings
Also fix some issues that were left over from/introduced by earlier
commits.
2017-11-22 19:28:07 +01:00
Gina Häußge 21c8bd54f5 __hash__ and __eq__ for OctoPrintPermission 2017-11-22 15:31:17 +01:00
Gina Häußge fa5619fad7 Fix group permission propagation
Also refactored some bits
2017-11-22 15:28:58 +01:00
Gina Häußge 022c59a094 Fix unit tests again 2017-11-21 14:36:30 +01:00
Gina Häußge bc8abdfc62 First throw at securing the socket & propagating user changes
The socket client will now authenticate with the socket after login,
using the session id from the login response. This will associate the
session with the socket server side. Any messages to the client apart
from "connected" and "reauthRequired", will be checked against the
STATUS permission and not be sent if that is missing from the current
user (which might also be the anonymous/guest user).

A logout of the session and any changes of the user or their permissions
will trigger trigger a reauthRequired message to be sent over the
socket, instructing the client to either perform a new passive login to
update the user's permissions, or to logout altogether (server side
logout or user removal).

Known bugs:

  * Changing group permissions sometimes doesn't propagate through -
    seems to be caused by the code not properly finding the login
    sessions of affected users based on the changed group. Not yet sure
    what's up there.

Open points:

  * Deactivation of a user's account also needs to invalidate the
    session
  * Session timeout needs to be evaluated (currently 30min, unclear if
    that suffices)
  * possibly more I can't think of right now
2017-11-21 14:24:17 +01:00
Gina Häußge d8cffc4b22 Merge branch 'devel' into dev/permission
# Conflicts:
#	src/octoprint/plugins/announcements/static/js/announcements.js
#	src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js
#	src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
#	src/octoprint/server/__init__.py
#	src/octoprint/static/css/octoprint.css
#	src/octoprint/static/js/app/viewmodels/connection.js
#	src/octoprint/static/js/app/viewmodels/control.js
#	src/octoprint/static/js/app/viewmodels/files.js
#	src/octoprint/static/js/app/viewmodels/gcode.js
#	src/octoprint/static/js/app/viewmodels/log.js
#	src/octoprint/static/js/app/viewmodels/loginstate.js
#	src/octoprint/static/js/app/viewmodels/navigation.js
#	src/octoprint/static/js/app/viewmodels/printerprofiles.js
#	src/octoprint/static/js/app/viewmodels/printerstate.js
#	src/octoprint/static/js/app/viewmodels/settings.js
#	src/octoprint/static/js/app/viewmodels/temperature.js
#	src/octoprint/static/js/app/viewmodels/terminal.js
#	src/octoprint/static/js/app/viewmodels/timelapse.js
#	src/octoprint/static/js/app/viewmodels/users.js
2017-11-21 11:42:28 +01:00
Gina Häußge 312760f86a flask.ext.babel => flask_babel 2017-11-21 11:33:55 +01:00
Gina Häußge 5ea22c602c Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/plugins/announcements/__init__.py
#	src/octoprint/server/util/tornado.py
2017-11-21 10:30:38 +01:00
Gina Häußge 7540aa6b72 No longer require API keys for anonymous access
Old behaviour of insisting on API key presence for each and every
request can however still be enforced.

Making this part of the granular permission system epic since only then
will people be able to more finely tune what data will be available for
anonymous users.

Solves #1681
2017-11-17 15:57:45 +01:00
Gina Häußge 84cc89832b Docs: Adapt web ui startup diagram 2017-11-14 17:36:53 +01:00
Gina Häußge 9554079e4b Slight refactoring of CoreUI init order
We must not fire the StartupComplete callback before we've signaled that
we are done loading the UI in the UiStateViewModel.
2017-11-14 16:49:43 +01:00
Gina Häußge 481faf8da1 Fix graph initialization
We only want to initialize it when the graph is actually visible. For
this we hook into tab changes, user changes and StartupComplete. That
will hopefully ensure that once it DOES become visible it will get
initialized, but not before.
2017-11-14 16:49:42 +01:00
Gina Häußge fd6c7cd48f Make needlogin only become true after loading finishes 2017-11-14 16:49:36 +01:00
Gina Häußge 9441ea572d Return anonymous user object on API
If we have logged out or passive login failed, that way we'll still get
the needs of the anonymous user. One less GET request to make from the
frontend which also means one less potential race condition during
initialization.
2017-11-14 16:45:35 +01:00
Gina Häußge 0414e4a6a6 Fix a binding 2017-11-14 16:42:40 +01:00
Gina Häußge 158f14df89 Fix alignment of default marker in group list
Also slightly change wording of columns ("Group" is kinda redundant)
2017-11-09 19:07:58 +01:00
Gina Häußge 93a80fe256 Have group actions mirror group flags in UI
Disable edit action for unchangeable groups, disable remove action for
unremovable groups.
2017-11-09 19:02:47 +01:00
Gina Häußge 398e10588c Slight changes in permission resolution
* We now use a set key (derived from name used for setting the
    attribute on Permissions or provided in permission definition from
    plugins)
  * We do a multipass resolution of combined plugin permissions (the
    former approach was limited to two passes)

We also do logging on the permissions added through plugins. Also did
some code deduplication while at it.
2017-11-09 18:54:51 +01:00
Gina Häußge 6d1f610085 Full page loading and login screens 2017-11-09 14:14:13 +01:00
Gina Häußge bd95dad85e Move permissions into JS init script & socket
No need for an AJAX request that might produce a race condition.
2017-11-09 12:08:03 +01:00
Gina Häußge bf8301bd6a Fix CombinedPermission creation from plugins 2017-11-09 11:41:58 +01:00
Gina Häußge 231006ab26 Fix ApiUser creation for key 2017-11-09 11:18:12 +01:00
Gina Häußge 744f4d0f42 Require CONNECTION permission for connection panel 2017-11-08 16:24:59 +01:00
Gina Häußge ad269751b8 Require PRINT permission for print/pause/cancel 2017-11-08 16:22:12 +01:00
Gina Häußge 4c77f07bc9 Default guest permissions mirror prior versions 2017-11-08 16:18:14 +01:00
Gina Häußge e974cb8ec5 Refactored (Permissions|Group|User)Manager
* Removed PermissionsManager and merged functionality of that into
    Permissions class
  * Decoupled GroupManager from UserManager
  * Renamed some things for less redundancy
  * Removed unused YAML conversion methods
  * Stricter differentiation between Manager parent class and concrete
    implementations
  * Marked broken tests as skipped and broken, separated them further
    and added some
2017-11-08 15:59:31 +01:00
Gina Häußge 48c02e1018 Backwards compatibility for user.roles
Also includes not throwing that data away in users.yaml - we don't want
to prevent people from switching back and forth between 1.3.x and 1.4.0
during the RC period (or ourselves during development ;)), so we need to
stay backwards compatible here at least until 1.5.0.
2017-11-07 12:56:29 +01:00
Gina Häußge f398ee90b0 Fix a merge error
And while at it also introduce groups and permission manager factories,
just like for the user manager.
2017-11-02 17:59:54 +01:00
Gina Häußge 23fcdc0365 Refactor SettingsPlugin.on_settings_load
Use current_user.has_permission instead of current_user.is_admin.
2017-11-02 16:38:27 +01:00
Gina Häußge e91da1cd8d include_doc => includedoc 2017-11-02 15:02:25 +01:00
Gina Häußge 4e0d3725cb Refactor someName => some_name in access classes 2017-11-02 14:30:35 +01:00
Gina Häußge f45cb1560f Fix SessionUserTestCase 2017-11-02 14:14:57 +01:00
Gina Häußge 7214b9f2c2 Fix (dis)connect button 2017-11-02 12:48:48 +01:00
Gina Häußge 37990996b7 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/server/util/flask.py
2017-11-02 11:12:22 +01:00
Marc Hannappel 024b58097e Check the connection sidebar a litte bit more, if the Connection permission is not granted, but the status permission is, one will be able to view the current settings, but not change them. 2017-11-02 09:23:07 +01:00
Marc Hannappel 2cc1fe7fe2 Fix a merge mistake 2017-11-02 09:21:23 +01:00
Marc Hannappel e0cd48df92 Fix a wrong _.all to _.any 2017-11-02 09:21:00 +01:00
Marc Hannappel d45d2f5123 Merge branch 'maintenance' of github.com:foosel/OctoPrint into dev/permission 2017-11-02 08:33:32 +01:00
Marc Hannappel eb5e2c94a3 Fix a misalignment problem with the temperature graph 2017-10-27 15:19:41 +02:00
Marc Hannappel ced74f5b45 Some minor fixes 2017-10-27 15:18:51 +02:00
Marc Hannappel 01e557a689 Merge branch 'maintenance' of github.com:foosel/OctoPrint into dev/permission 2017-10-27 14:24:30 +02:00
Gina Häußge b8b01558ce Merge branch 'maintenance' into devel 2017-10-27 14:24:21 +02:00
Marc Hannappel 08c90e0909 Merge branch 'maintenance' of github.com:foosel/OctoPrint into dev/permission 2017-10-27 09:11:26 +02:00
Marc Hannappel 052408982a Revert "Some Changed to the temperature.js file"
This reverts commit ce2463588d.
2017-10-25 15:11:53 +02:00
Marc Hannappel 68c57cc4eb Merge branch 'maintenance' of github.com:foosel/OctoPrint into dev/permission 2017-10-25 14:43:38 +02:00
Marc Hannappel 9eb4f3f843 Forgot to remove <<<<<< HEAD 2017-10-25 11:22:30 +02:00
Marc Hannappel 4ad7b38648 Changed a few == to === in temperature.js 2017-10-25 11:20:37 +02:00
Marc Hannappel ce2463588d Some Changed to the temperature.js file 2017-10-25 11:17:51 +02:00
Marc Hannappel 9804e3eca0 Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission 2017-10-25 11:10:58 +02:00
Gina Häußge e9fb3a3ebb Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/server/util/__init__.py
2017-10-25 09:32:38 +02:00
Marc Hannappel b65b97870f Remove a unnecessary function of the new permission system 2017-10-25 09:13:07 +02:00
Marc Hannappel 0c243e0dc2 Changed a few == to === 2017-10-25 09:12:24 +02:00
Marc Hannappel d88b1fbec0 Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission 2017-10-25 09:11:13 +02:00
Marc Hannappel 0781cb1d41 Add a confirmation dialog to the delete request of a group. 2017-10-23 11:11:47 +02:00
Marc Hannappel eb2ed341a2 Fixeda bug where the group description was not sent to the server side, which caused an exception while creating a group. 2017-10-23 11:11:06 +02:00
Marc Hannappel e5f6824304 Redo the Migration part from old role system to new permission System 2017-10-23 11:08:32 +02:00
Gina Häußge 880124bbe0 Merge branch 'maintenance' into devel 2017-10-17 11:07:02 +02:00
Gina Häußge b719fd1c15 Merge branch 'maintenance' into devel 2017-10-16 16:21:14 +02:00
Gina Häußge 464b431741 Merge branch 'maintenance' into devel 2017-10-11 16:28:12 +02:00
Marc Hannappel ff0e4f50da Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission 2017-10-11 10:19:18 +02:00
Gina Häußge 8ba23e84ca Merge branch 'maintenance' into devel 2017-10-04 15:04:30 +02:00
Marc Hannappel 4cbddf66d3 Merge branch 'maintenance' of github.com:foosel/OctoPrint into dev/permission 2017-10-04 09:55:51 +02:00
Marc Hannappel 9ba9c3b9c5 Merge devel into dev/Permissions with some additions
- Fixed a forgoten refactoring inside the first run wizard
 - Added possibility to also throw a warning when deprecated JavaScript Variables are used
 - Therefore made the whole deprecation logging a bit more generic, so it will be easy to reuse it in the future
 - Reintroduces the "deprecated" USER_ARRAY as a non deprecated array, so we have a central place where we can adjust the permissions for users (only valid for first run and creating the user group on migration)
 - User group will be created on first run now and when migrating from an older version
2017-09-28 09:00:05 +02:00
Gina Häußge adbcc07bae Merge branch 'maintenance' into devel 2017-08-25 14:57:00 +02:00
Marc Hannappel 83ed6a4297 Added additional Permissions in the bundled Plugins 2017-07-27 16:14:36 +02:00
Marc Hannappel 1c07974f6c Adjust the bundled Plugins to the new hasPermission functions 2017-07-27 16:11:45 +02:00
Marc Hannappel c3e430b472 Split loginState.hasPermission in hasPermission and hasPermissionKo, the ko version returns a knockout pureComputed and uses the hasPermission version, hasPermission version does the normal check and is intended to be used in functions.
Also adjust the permission checks to the splitted functions, and integrate new checks to hide elements and get rid of console errors
2017-07-27 16:04:58 +02:00
Marc Hannappel a8fef06aa8 Add ability to register combined permission to the permission manager, they will not show up in the regular permission list 2017-07-27 16:01:20 +02:00
Marc Hannappel 281eb346a5 Add a unioned permission objects, this mostly is used for the api GET methods 2017-07-27 15:55:55 +02:00
Marc Hannappel 15c8bd7d6d More bugfixes, additionally add a can() function to the PluginIdentityContextManager, and replace the dicts with OrderedDicts 2017-07-27 15:51:20 +02:00
Marc Hannappel d0d1da3456 Fix a few bugs and remove some now unnecessary functions 2017-07-27 15:26:00 +02:00
Gina Häußge 7c73ff78bc Merge branch 'maintenance' into devel 2017-07-27 14:39:14 +02:00
Marc Hannappel e0309dc6c0 Added announcement permission to the announcement plugin 2017-07-26 14:35:30 +02:00
Gina Häußge cd6009c180 Merge branch 'maintenance' into devel
# Conflicts:
#	docs/plugins/hooks.rst
#	src/octoprint/server/__init__.py
2017-07-26 14:31:08 +02:00
Marc Hannappel 29bd4e96d6 Add PluginPermissionDecorator and PluginIdentityContext to handle @Permissions.PLUGIN_X_Y.require() decorator correctly. This is necessary, because at the time of the evaluation these Permissions can't be already initialized. So I added a new PluginIdentityContext which will look for the permissions when needed and check them, if they can't be found it will raise a UnknownPermission Exception 2017-07-26 13:45:57 +02:00
Marc Hannappel 5d5ca0d7aa Fix AnonymousUser 2017-07-26 13:42:17 +02:00
Marc Hannappel e7df4b8d6d Revert permission_test, change get_session to session, Some smaller fixes (missing semicolon, added some $root in jinja templates) 2017-07-26 13:39:38 +02:00
Marc Hannappel fbd8a97ffd Merge branch 'devel' of github:foosel/OctoPrint into dev/permission 2017-07-17 09:02:32 +02:00
Gina Häußge 4147ffa503 Merge branch 'maintenance' into devel 2017-07-14 11:29:49 +02:00
Marc Hannappel be2ef79686 Fix OctoPrintJsonEncoder to properly work with wrapt, additionally fix a wrong Permission name and combine 2 lines of code 2017-07-10 08:33:28 +02:00
Marc Hannappel 120406d115 Merge branch 'devel' of github:foosel/OctoPrint into dev/permission 2017-07-05 11:44:24 +02:00
Marc Hannappel d72ae6102b Added missing files/folders 2017-07-05 10:07:20 +02:00
Marc Hannappel 4adfad8708 Added custom attribute permission_test for template.sidebar and template.tab this shall be used to set the visibility permission/s, therefore added a tabs.js file (name can still change, but I don't find a better name right now) and fixes a few brackets 2017-07-05 10:02:24 +02:00
Gina Häußge 2e6d65378f Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/server/util/flask.py
#	src/octoprint/static/js/app/main.js
#	src/octoprint/users.py
2017-07-05 09:30:00 +02:00
Marc Hannappel 4ec1a9af39 Refactor a huge amount of code thanks to design failure, also add some comments and make things more translatable 2017-07-05 08:16:31 +02:00
Marc Hannappel 1109bd35e7 Replace a few leftovers of isUser with new permissions, also fix a few permission checks 2017-07-05 08:01:11 +02:00
Gina Häußge 24dc12023b Merge branch 'maintenance' into devel 2017-06-13 16:01:36 +02:00
Marc Hannappel f53be57f0d Added User wrapper, this makes sure we stay backwards compatible 2017-06-09 09:31:50 +02:00
Marc Hannappel 9db4559b0c User dict's get method, Renamed GroupCantbeChanged to GroupCantBeChanged, some smaller styling fixes 2017-06-09 09:28:03 +02:00
Marc Hannappel 23a249ca0f Fix headers, as mentioned in the comments 2017-06-09 09:24:59 +02:00
Gina Häußge 3171958a8c Merge branch 'maintenance' into devel 2017-06-02 16:36:08 +02:00
Marc Hannappel 422f1b2b5e Combine user, permissions and group tests as access test, Fix a problem with GroupsCantbeChanged 2017-06-02 11:23:44 +02:00
Gina Häußge fed3ec9616 Merge branch 'maintenance' into devel 2017-06-01 16:12:53 +02:00
Gina Häußge 751867d5b8 Merge branch 'maintenance' into devel 2017-05-31 16:58:56 +02:00
Mark Walker c4fcc59efd Fix typo: TRANFERING_FILE 2017-05-30 00:29:30 -07:00
Gina Häußge 528bbba6ed Merge branch 'maintenance' into devel 2017-05-29 13:46:59 +02:00
Gina Häußge 905c05ba06 Merge branch 'maintenance' into devel 2017-05-24 18:06:43 +02:00
Gina Häußge fcacf28c45 Merge branch 'maintenance' into devel 2017-05-24 14:53:40 +02:00
Gina Häußge 3e5d82c665 Merge branch 'maintenance' into devel 2017-05-19 18:18:59 +02:00
Marc Hannappel 1bea7654b8 More work on the tests 2017-05-19 11:46:06 +02:00
Marc Hannappel 38ea778ccf Fix warning_factory warning 2017-05-19 11:45:45 +02:00
Marc Hannappel 31f300f6d8 Use lower case names for method names split with an underscore 2017-05-19 11:44:54 +02:00
Marc Hannappel 4e8bb688aa Some adjustments in the users.py, remove sorting of permissions and groups, user has_permission instead of is_admin, not p in s -> p not in s 2017-05-19 09:49:38 +02:00
Marc Hannappel 563d623278 Use dict() instead of [] for the permissionManager, raise Exception if someone tries to add an already known permission 2017-05-19 09:47:21 +02:00
Marc Hannappel 24790e8b2a Use gettext for Permission description. Fix __repr__ for Permissions, Group and User. 2017-05-19 09:45:11 +02:00
Marc Hannappel 58806dee68 Adjusted the permissionslist from [] to None, Fixed some styling 2017-05-19 08:59:35 +02:00
Gina Häußge 4fda12b512 Merge branch 'maintenance' into devel 2017-05-17 14:00:17 +02:00
Gina Häußge 0c62465a22 Merge branch 'maintenance' into devel 2017-05-17 12:22:19 +02:00
Marc Hannappel 785b0caaf2 Fixed a few left overs of the old hasPermission check in the pluginmanager and softwareupdater
Fixed a few left overs from removing the groups and permissions enabled property
2017-05-12 08:46:35 +02:00
Gina Häußge 3d4c50d481 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/server/api/settings.py
2017-05-11 17:43:42 +02:00
Marc Hannappel c0975ed15e Started to adjust the tests to the new permission system 2017-05-10 13:56:09 +02:00
Marc Hannappel ce6de6efa6 Moved users.py to new access package, add wrapper file users.py for backwards compatibility
Removed the Enabled stuff from Permissions and Groups, because both have an always on requirement
Fixed a wrong Permission
Moved the previously splitted javascript access client back into one file
2017-05-10 13:52:30 +02:00
Marc Hannappel 561c1fc338 Fixed the comment about rereference functions 2017-05-05 15:01:13 +02:00
Marc Hannappel e94affe588 Refactored the way the permissions gets checked on the frontend, also made corresponding changes to the backend 2017-05-05 14:55:17 +02:00
Marc Hannappel 43e3648ba7 Fixed a few missing thing, Added a few Comments to some functions to explain their functionality 2017-05-05 14:53:07 +02:00
Marc Hannappel 63938c6fd3 Added migration steps from old permission system to new permission system
Combined users, permissions and groups as access.users, access.permissions and access.groups
Many refactorings inside the javascript part
Added general javascript deprecated function, logs a message to the javascript console
Adjusted the user add and edit modals to recenter themself when uncollapsing the groups and/or permissions sections
2017-05-03 11:21:43 +02:00
Marc Hannappel 9cab4d510a WIP: More Refactorings 2017-04-18 16:37:45 +02:00
Marc Hannappel 41621826d8 WIP: More Refactorings 2017-04-12 10:41:43 +02:00
Marc Hannappel 2149030dbb Added Function to register default permissions, WIP 2017-04-12 09:09:47 +02:00
Marc Hannappel 8c0bd7e5e3 Fix leftover merge conflict 2017-04-12 09:08:43 +02:00
Marc Hannappel 5283682c47 Readded somehow lost import requests 2017-04-12 08:37:38 +02:00
Marc Hannappel b53d20d2ee WIP: Refactored the groups and permissions into access 2017-04-12 08:34:06 +02:00
Marc Hannappel ed6bdf97d1 Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission 2017-04-12 08:33:27 +02:00
Marc Hannappel 93cfa564f7 WIP: Some more Refactorings 2017-04-12 08:21:06 +02:00
Marc Hannappel 579b8fce96 Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission 2017-04-12 08:18:41 +02:00
Shawn Bruce d1d9462423 Add octoprint.timelapse.capture.[pre/post] hooks (#1854)
* Add octoprint.timelapse.capture.pre and octoprint.timelapse.capture.post hooks

* Adjust underline length
2017-04-11 18:29:52 +02:00
Gina Häußge 299f9c4a26 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/plugins/pluginmanager/__init__.py
2017-04-04 15:28:28 +02:00
Gina Häußge 5c27e974fb Merge branch 'maintenance' into devel 2017-03-19 10:53:58 +01:00
Gina Häußge 53bd4b1ea9 Merge branch 'maintenance' into devel 2017-03-16 18:10:38 +01:00
Gina Häußge 3d10fff7de Merge branch 'maintenance' into devel 2017-03-13 17:48:49 +01:00
Gina Häußge 8107d65504 Merge branch 'maintenance' into devel 2017-03-09 18:44:54 +01:00
Gina Häußge 9a4cebfb61 Merge branch 'maintenance' into devel 2017-03-09 12:04:35 +01:00
Shawn Bruce 5c81833415 Only reset scroll position for settings content. (Fixes #1812) 2017-03-08 14:16:17 -05:00
Gina Häußge d88ca50de0 Merge branch 'maintenance' into devel 2017-03-08 18:11:54 +01:00
Andy Werner b75b53d05a Fix an issue in user settings
* UserSettings: crashed if overwrite an existing key with primitive value by same key with complex value. Also reduced number of calls to user.get_setting()

* Updated tests
2017-03-07 10:35:33 +01:00
Marc Hannappel c2cae5b2fc Added ability to give a description to groups 2017-03-01 11:47:23 +01:00
Gina Häußge 30e962b447 Merge branch 'maintenance' into devel 2017-02-24 15:28:01 +01:00
Gina Häußge f710bb535e Merge branch 'devel' into pr/kevans91/dep-up 2017-02-21 16:41:02 +01:00
Gina Häußge 814b02900b Fixed a test left-over
Thanks for the heads-up @kevans91
2017-02-21 16:39:51 +01:00
Gina Häußge 4958353335 Fix repr for User and SessionUser 2017-02-21 14:00:50 +01:00
Gina Häußge 9884c52c4e Upgrade to current versions again 2017-02-21 13:23:52 +01:00
Gina Häußge 0cd4fc8655 Enable template auto reload by default
We have our own cache, and that would get confused by not
allowing a reload of the templates at runtime, which Flask 0.11+
will not allow anymore unless this setting is set to True.
2017-02-21 13:21:42 +01:00
Gina Häußge 5d07c5a0b2 Updated mirrored methods of custom tornado http server
Should now be up to date with stock implementation again.
2017-02-21 13:21:18 +01:00
Gina Häußge cf20b3a3c3 flask.ext.foo => flask_foo for things new on devel 2017-02-21 13:19:44 +01:00
Gina Häußge dbe4acd47d flask.request.json => flask.request.get_json()
Old property is deprecated as of Flask 0.11
2017-02-21 13:18:59 +01:00
Gina Häußge b7a0f5bee5 Compatibility layer for plugins depending on user.is_anonymous() etc
Logs a deprecation warning when any of the made-property fields is
accessed as a getter and return value. Implements __eq__, __ne__,
__bool__ and __nonzero__ to allow things like "user.is_anonymous ==
True" or "not user.is_anonymous" is used.

Careful with serialization to json, needs "bool(...)" wrapper to not
cause an exception (or inclusion in a custom serializer).

Affected fields:

  * is_anonymous
  * is_authenticated
  * is_active
  * is_user
  * is_admin

To be removed again in OctoPrint 1.5.0
2017-02-21 12:24:21 +01:00
Gina Häußge 0adb62b485 Compatibility layer for plugins depending on flask.ext
Logs a deprecation warning when anything from flask.ext is accessed,
imports flask_<name> instead and returns it.

To be removed again in OctoPrint 1.5.0
2017-02-21 11:56:31 +01:00
Gina Häußge a439608fe7 Merge pull request #1786 from ghulands/safari_fix
Issue #1780: Safari Webcam Fix.
2017-02-21 09:17:05 +01:00
Greg Hulands e82efd24d3 Issue #1780: Safari Webcam Fix. 2017-02-20 11:02:07 -08:00
Gina Häußge 3d1f3ed068 Merge branch 'dep-up' of https://github.com/kevans91/OctoPrint into pr/kevans91/dep-up 2017-02-20 14:48:59 +01:00
Gina Häußge bac972de53 Merge branch 'maintenance' into devel 2017-02-20 14:34:42 +01:00
Marc Hannappel 95310991b8 Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission 2017-02-17 14:15:51 +01:00
Marc Hannappel f60a759dca Some Refactorings to the Granular Permission System 2017-02-17 13:57:02 +01:00
Gina Häußge 4f6f829dc3 Merge branch 'maintenance' into devel 2017-02-17 13:49:56 +01:00
Marc Hannappel 8962ebd175 More wor done on the Encoder/Decoder part, additionally cherry-picked the Update flask commit from @kevans91 2017-02-15 17:00:52 +01:00
Kyle Evans 218b3c87db Cherry-picked
Update flask, flask-{login,principal,babel,assets} versions to the latest, flask.ext. => flask_
2017-02-15 16:47:58 +01:00
Marc Hannappel c12a0f8cdf Added OctoPrintJson Encoder and Decoder 2017-02-13 16:32:41 +01:00
Gina Häußge 4a41ccb4e6 Merge pull request #1768 from eyal0/same_device_view_model
add sameDevice to SlicingViewModel
2017-02-13 12:50:53 +01:00
Marc Hannappel 0d1f53d58d Moved Yaml Representer and Constructors into src/octoprint/util/yaml.py 2017-02-13 11:56:24 +01:00
Eyal Soha fea07917fa add sameDevice to SlicingViewModel 2017-02-12 12:35:57 +02:00
Gina Häußge 003c2e0dca Merge pull request #1748 from eyal0/add_same_device_to_slicing_api
Add sameDevice to api/slicing API
2017-02-08 11:49:52 +01:00
Eyal Soha ce38ef6289 add same device to the slicing API 2017-02-02 10:47:41 +02:00
Gina Häußge 2457c58817 Merge branch 'maintenance' into devel 2017-01-25 12:55:29 +01:00
Gina Häußge ab6dd66bad Merge branch 'maintenance' into devel 2017-01-25 12:51:45 +01:00
Gina Häußge d430fe35c5 Merge branch 'maintenance' into devel 2017-01-20 16:29:08 +01:00
Gina Häußge 9650c71155 Merge branch 'maintenance' into devel
# Conflicts:
#	AUTHORS.md
2017-01-13 15:12:25 +01:00
Marc Hannappel 95da7551d2 Added the possibility to set default Groups and fixed a typo 2017-01-13 14:47:18 +01:00
Marc Hannappel 667473f90e Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission 2017-01-13 12:41:55 +01:00
Gina Häußge cf9e17ebfd Merge branch 'maintenance' into devel 2017-01-12 19:05:15 +01:00
Gina Häußge ec55909305 Merge branch 'devel' of github.com:foosel/OctoPrint into devel 2017-01-11 12:17:12 +01:00
Gina Häußge 3e03f7c12a Merge branch 'maintenance' into devel 2017-01-11 12:15:07 +01:00
Gina Häußge edc2005b2c Merge pull request #1703 from noahsmartin/nm/pollingComment
Changed old comments to not claim a method does more than it really does
2017-01-11 11:17:49 +01:00
Noah Martin 72f3fa6eda Changed old comments to not claim a method does more than it really does, because comments are there to clear up confusion, might as well start here.
poll_temperature and poll_sd_status are called by a RepeatedTimer now, the methods don't re-enqueue themselves.
2017-01-10 23:36:55 -08:00
Gina Häußge 48c02c6f55 Merge pull request #1665 from jammi/ttySfix
Octoprint /dev/ttyS* addition
2017-01-09 17:10:32 +01:00
Gina Häußge 8b7643332b Merge branch 'devel' of github.com:foosel/OctoPrint into devel 2017-01-09 16:38:44 +01:00
Kyle Evans 639619ff93 Partially revert 57de36a 2017-01-09 08:51:52 -06:00
Kyle Evans 0a08ef0ed4 Merge branch 'devel' into dep-up 2016-12-27 23:46:39 -06:00
Marc Hannappel b3f35c579b Little update to the active tab using hash from URL, forgot to add a check if the hash is valid, fixed this now 2016-12-21 10:56:11 +01:00
Marc Hannappel bcb74d01b6 Added active tab using hash from URL feature, as requested in issue #203 2016-12-21 10:51:19 +01:00
Marc Hannappel 8a8b88af13 Fix folders doesn't get listed when performing a filtering in file section, issue #1667 2016-12-21 09:44:24 +01:00
Marc Hannappel 58ed405c88 Fix Files not shown when user logged in, if guest user had no permission to view files 2016-12-21 09:33:23 +01:00
Marc Hannappel a3d4f80599 Add GuestUser to handle guest permission, fix some missing braces 2016-12-21 09:06:18 +01:00
Marc Hannappel 7bfd55f3f0 Fix admin und guest group 2016-12-21 09:02:38 +01:00
Juha-Jarmo Heinonen 153b5de1d4 Added /dev/ttyS* into serial ports to find.
OctoPrint was unable to find any of the serial ports on my CubieBoard, which are all ttyS devices; this fixes that issue.
2016-12-19 20:49:23 +02:00
Marc Hannappel 932b7a094d Added manually edited octopint.css file 2016-12-19 11:15:35 +01:00
Marc Hannappel 47b8c661e7 Changed a few more isAdmin to new Permissions.SETTINGS, started implementing the Groupsystem, refactored a few things with the Permissions 2016-12-16 14:27:41 +01:00
Marc Hannappel 3bb0f51d08 Ugly fix for Temperature graph not displayed correctly 2016-12-12 13:41:56 +01:00
Marc Hannappel 32fc5ccd3e Fix a bug with gcode_viewer, make loginState.hasPermission commands pureComputedObservables 2016-12-12 13:40:48 +01:00
Marc Hannappel 4f3cba32da Initial work for Granular Permission System, actually only per User Permission, Group system still needs to be programmed 2016-12-12 09:17:47 +01:00
Kyle Evans b2c60ba884 Rebase to devel now that 1.3.0 has released 2016-12-08 08:56:40 -06:00
Kyle Evans 537ed2d11f Rebase to devel 2016-11-27 00:32:38 -06:00
Kyle Evans f318cc5e28 Update 970880d, flask.ext.login -> flask_login 2016-11-10 13:12:02 -06:00
Kyle Evans 1001cc607e Merge branch 'devel' into dep-up 2016-11-10 12:37:21 -06:00
Kyle Evans 35d480bc48 Clean up bogus whitespace changes/inconsistency 2016-10-25 21:36:47 -05:00
Kyle Evans 37f51ef983 Botched the initial Flask-Login update -- is_active(), is_authenticated(), and is_anonymous() got converted into properties, so we should do the same 2016-10-07 11:37:36 -05:00
Kyle Evans 943d7ce31a Update Click 2016-10-06 21:35:43 -05:00
Kyle Evans bc54ddf19f Update psutil 2016-10-06 21:25:48 -05:00
Kyle Evans 7d091d18ee Update semantic_version 2016-10-06 21:19:54 -05:00
Kyle Evans 599e24634c Update requests 2016-10-06 21:16:31 -05:00
Kyle Evans e998edd083 Update pkginfo 2016-10-06 21:12:46 -05:00
Kyle Evans e15ca55558 Update rsa 2016-10-06 21:11:33 -05:00
Kyle Evans 23a2801284 Update pyserial 2016-10-06 21:08:45 -05:00
Kyle Evans 9a6da3f46f Update PyYAML 2016-10-06 21:03:29 -05:00
Kyle Evans fbb881bb42 Update Tornado, adapt CustomHTTPServer to new usage 2016-10-06 21:00:14 -05:00
Kyle Evans 87d65c150b Update werkzeug 2016-10-06 20:30:12 -05:00
Kyle Evans bb2fcd5b00 Update flask, flask-{login,principal,babel,assets} versions to the latest, flask.ext. => flask_ 2016-10-06 20:25:04 -05:00
447 changed files with 28887 additions and 16201 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/
@@ -1,3 +1,9 @@
---
name: Bug report
about: Create a report to help improve OctoPrint
---
<!--
READ THE FOLLOWING FIRST:
@@ -12,7 +18,7 @@ plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the community forum at
discourse.octoprint.org, NOT here.
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
reports fully fill out the bug reporting template (if you don't know
@@ -39,9 +45,10 @@ don't know what you did to get it to happen in the first place.
Ideally provide exact steps to follow in order to reproduce your problem:
-->
1. ...
2. ...
3. ...
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
<!--
If you encountered a problem with specific files of any sorts, make sure
+21
View File
@@ -0,0 +1,21 @@
---
name: Feature request
about: Suggest an idea for this project
---
<!--
Please make sure to add [Request] to your issue's title. Thank you!
-->
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+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),
+3
View File
@@ -31,9 +31,12 @@ OctoPrint.egg-info
*.codekit
venv
venv2
venv3
venv26
venv27
venv33
venv34
venv35
venv36
venv37
+11 -1
View File
@@ -1,12 +1,22 @@
---
language: python
dist: xenial
matrix:
include:
- python: '3.7'
env: RUN_FLAKE8=true
python:
- "3.7"
- "3.6"
- "2.7"
install:
- pip install -e .[develop]
script:
- nosetests --with-doctest
- test -n "$RUN_FLAKE8" || pytest
- test -z "$RUN_FLAKE8" || flake8 --ignore=D,E,W,F401 src/ tests setup.py
sudo: false
git:
depth: 250
+12 -9
View File
@@ -18,16 +18,19 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.9
# maintenance is currently the branch for preparation of maintenance release 1.3.13
# so are any fix/... and improve/... branches
maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
maintenance 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
fix/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
improve/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.9rc5
# staging/maintenance is currently the branch for preparation of 1.3.12rc4
# so is regressionfix/...
staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
staging/maintenance 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 pep440-dev
regressionfix/.* 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 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 the branch for preparation of 1.4.0rc3
staging/devel 1.4.0rc3 e603b98d0dc552e570034aae52291737695dd0f6 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
+24 -1
View File
@@ -69,12 +69,13 @@ date of first contribution):
* [Philipp Baum](https://github.com/philphilphil)
* [Kyle Evans](https://github.com/kevans91)
* [Javier Martínez Arrieta](https://github.com/Javierma)
* ["MirceaDan"](https://github.com/ByReaL)
* [Mircea Dan Gheorghe](https://github.com/ByReaL)
* [Ovidiu Hossu](https://github.com/MoonshineSG)
* [Eyck Jentzsch](https://github.com/eyck)
* [Mathias Rangel Wulff](https://github.com/mathiasrw)
* [Clemens Niemeyer](https://github.com/clemniem)
* ["I-am-me"](https://github.com/I-am-me)
* [J-J Heinonen](https://github.com/jammi)
* [Noah Martin](https://github.com/noahsmartin)
* [Eyal Soha](https://github.com/eyal0)
* [Greg Hulands](https://github.com/ghulands)
@@ -91,7 +92,29 @@ date of first contribution):
* [Ganey](https://github.com/ganey)
* [Sven Lohrmann](https://github.com/malnvenshorn)
* [Andy Castille](https://github.com/klikini)
* [Zachary Nofzinger](https://github.com/ZachNo)
* [Gaston Dombiak](https://github.com/gdombiak)
* [Brad Fisher](https://github.com/bradcfisher)
* [Aldo Hoeben](https://github.com/fieldofview)
* [Henning Groß](https://github.com/hgross)
* [Jubaleth](https://github.com/jubaleth)
* [Matthias Urlichs](https://github.com/smurfix)
* [Daniel Joyce](https://github.com/DanielJoyce)
* [Andy Qua](https://github.com/AndyQ)
* [Fabio Santos](https://github.com/Fabi0San)
* [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 -1902
View File
File diff suppressed because it is too large. Load diff
+9 -9
View File
@@ -36,14 +36,14 @@ nothing but ticket management.
- If you want to post a **feature request** or a **documentation request**, add `[Request]`
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
something is **not** what qualifies as a request here, use the
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
[community forum at community.octoprint.org](https://community.octoprint.org) for
such support issues.
- If you are a **developer** that wants to brainstorm a pull request or possible
changes to the plugin system, please get in touch on the
[community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/development).
[community forum at community.octoprint.org](https://community.octoprint.org/c/development).
- If you need **support**, have a **question** or some **other reason** that
doesn't fit any of the above categories, the issue tracker is not the right place.
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/support) instead.
Consult the [community forum at community.octoprint.org](https://community.octoprint.org/c/support) instead.
No matter what kind of ticket you create, never mix two or more "ticket reasons"
into one ticket: One ticket per bug, request, brainstorming thread please.
@@ -75,7 +75,7 @@ following section *completely* and also follow the instructions in the
**OctoPrint doesn't manage your network connection or your webcam nor
can it fix your printer not getting detected as a serial interface** -
if you have any kinds of problems with that, get in touch on the
[community forum](https://discourse.octoprint.org).
[community forum](https://community.octoprint.org).
**This is not the bug tracker of OctoPi**, which is the preconfigured
Raspberry Pi image including OctoPrint among other things - that one can be found
@@ -126,7 +126,7 @@ following section *completely* and also follow the instructions in the
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
very diligent here!
If in doubt about any of the above - get in touch on the [community forum](https://discourse.octoprint.org)
If in doubt about any of the above - get in touch on the [community forum](https://community.octoprint.org)
instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
there.
@@ -153,7 +153,7 @@ plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the community forum at
discourse.octoprint.org, NOT here.
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
reports fully fill out the bug reporting template (if you don't know
@@ -275,11 +275,11 @@ all requested information or your ticket will be closed.
### Where can I find which version and branch I'm on?
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
Please refer to [this FAQ entry](https://community.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
### Where can I find those log files you keep talking about?
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
Please refer to [this FAQ entry](https://community.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
### Where can I find my browser's error console?
@@ -302,7 +302,7 @@ the documentation.
system - maybe that's the actual PR you have been waiting for to contribute :)
2. If you plan to make **any large or otherwise disruptive changes to the
code or appearance, please get in touch on the
[forums](https://discourse.octoprint.org/c/development)** first so
[forums](https://community.octoprint.org/c/development)** first so
that we can determine if it's a good time for your specific pull
request. It might be that we're currently in the process of making
heavy changes to the code locations you'd target as well, or your
+16 -12
View File
@@ -3,7 +3,7 @@
![GitHub release](https://img.shields.io/github/release/foosel/OctoPrint.svg?colorB=brightgreen)
[![Travis build status](https://img.shields.io/travis/foosel/OctoPrint.svg)](https://travis-ci.org/foosel/OctoPrint)
[![Discourse topics](https://img.shields.io/discourse/https/discourse.octoprint.org/users.svg)](https://discourse.octoprint.org)
[![Discourse topics](https://img.shields.io/discourse/https/community.octoprint.org/users.svg)](https://community.octoprint.org)
[![IRC](https://img.shields.io/badge/chat-on%20irc-brightgreen.svg)](https://chat.octoprint.org)
[![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d)
@@ -13,7 +13,7 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme).
The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme).
The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint).
@@ -31,16 +31,16 @@ 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
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) where there are other active users who might be
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.
## Contributing
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
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org)
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).
If you think something is bad about OctoPrint or its documentation the way it is, please help
@@ -61,18 +61,19 @@ which is a custom SD card image that includes OctoPrint plus dependencies.
The generic steps that should basically be done regardless of operating system
and runtime environment are the following (as *regular
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
you already have Python 2.7, pip and virtualenv set up on your system:
you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your system:
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
@@ -83,7 +84,7 @@ OctoPrint via `pip`:
You should do this every time after pulling from the repository, since the dependencies may have changed.
OctoPrint currently only supports Python 2.7.
OctoPrint currently supports Python 2.7, 3.6 and 3.7.
## Usage
@@ -142,5 +143,8 @@ be edited from OctoPrint's settings dialog.
## Special Thanks
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
Cross-browser testing services are kindly provided by [BrowserStack](https://www.browserstack.com/).
Profiling is done with the help of [PyVmMonitor](https://www.pyvmmonitor.com).
Error tracking is powered and sponsored by [Sentry](https://sentry.io).
+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.
+26 -26
View File
@@ -6,58 +6,58 @@ thanks to everyone who contributed!
## Patreon Patrons
* Andre Bubel
* Andrew Moorby
* Arnljot Arntsen
* BigTreeTech
* Boris Hussein
* Brad Jackson
* Brian E. Tyler
* Christian Petropolis
* Christian Wolf
* COLLE+McVOY
* D Brian Kimmel
* DeltaMaker 3D Printers
* E3D BigBox
* Dorian Gray
* Eric Betts
* Ernesto Martinez
* F. Kunsmann
* Frank Sander
* Franziska Kunsmann
* GadgetAngel
* George Robles
* günter weber
* Hydra Research LLC
* James Seigel
* Jeff Moe
* Greg Holloway
* Hugh Blemings
* jean-claude migneault
* Jeff Renfer
* Jefferson Hunt
* Jeremiah Avery
* Joseph Payne
* Josh Daniels
* John Robinson (JRo)
* Joshua Wills
* Justin Kaufman
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Kodama Inc.
* Lewis Newby
* LulzBot®
* Kenneth Jiang
* Kyle Menigoz
* LA 3D Printer Repair
* Lee Dohm
* Makespace Madrid
* Mark Walker
* Martin Beattie
* Martin Majewski
* Michael Aumock
* Miles Flavel
* mitchell hirsch
* Noe Ruiz
* Mosaic Manufacturing
* OMER MEHMET SUTAS
* Patrick Glyré
* Patrick McGinnis
* Prof Yuh Wen Chen
* Randy C. Will
* Ranjib Dey
* Robert Gusek
* Roger Strolz
* Roy Cortes
* Rudolff Vang
* Samer Najia
* Ronald Griehsler
* Shawn Lewis
* Simon Hallam
* Stefan Krister
* Sven Mueller
* Symbiotic Devices
* Thomas Hatley
* Timothy D Hoogland
* The3DprintingMagic.com
* Trent Shumay
* Ulrich Kempken
* Vladislav Kuzemchik
and 1351 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1678 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
+1 -1
View File
@@ -9,6 +9,7 @@
* [Bootstrap Slider Knockout Binding](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT
* [Bootstrap Slider](http://seiyria.com/bootstrap-slider/): Apache License 2.0
* [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0
* [css-element-queries](https://github.com/marcj/css-element-queries): MIT
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
* [Flot](http://www.flotcharts.org/): MIT
* [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
@@ -36,7 +37,6 @@
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
* [chainmap](https://bitbucket.org/jeunice/chainmap): Python
* [Click](http://click.pocoo.org/): BSD
* [dateutil](https://dateutil.readthedocs.io/): BSD
* [emoji](https://github.com/carpedm20/emoji/): BSD
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
* [Flask](http://flask.pocoo.org/): BSD
-170
View File
@@ -1,170 +0,0 @@
.. _sec-api-apps:
****
Apps
****
.. contents::
.. _sec-api-apps-sessionkey:
Session Keys
============
OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based
validity and are generated by OctoPrint for requesting apps.
Obtaining those keys is based on a handshake procedure backed by cryptographic signatures using RSA. OctoPrint needs to
be aware of apps and their associated public keys (this can be achieved either via entries in ``config.yaml`` or by
installing app specific plugins which implement the ``AppPlugin`` type).
Apps can be registered within OctoPrint via ``config.yaml`` by adding them to the ``api`` > ``apps`` section, using the
application's id concatenated with its version as key, with the public key provided as item ``pubkey`` (stripped of the
``BEGIN RSA PUBLIC KEY`` and ``END RSA PUBLIC KEY`` separators and also newlines) and optionally also whether the app is
enabled or not (defaults to enabled, so can be left out if it's not to be set to disabled explicitly).
Example:
.. sourcecode:: yaml
api:
apps:
"com.example.my_octoprint_app:0.9":
pubkey: MEgCQQDYkr5Fv/YXK5ZL1uwRN4A61IagZaYLGqJ5JJGFo8wDrmpAMRqE9kK4+5hIDblC5DzfEr5oP7OA3tRO48Rf5yInAgMBAAE=
enabled: false
"com.example.my_octoprint_app:1.0":
pubkey: MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4osvb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
In the example, the app ``com.example.my_octoprint_app`` in version 0.9 has been disabled (e.g. due to the key having
leaked) whereas version 1.0 is fully registered with OctoPrint and may verify app session keys.
.. _sec-api-apps-sessionkey-workflow:
Workflow
--------
Apps perform the handshake by first requesting a temporary key with very limited validity,
then sending a message back to OctoPrint containing their id, version, the temporary key and a signature created with their
private key over these three pieces of data. OctoPrint then tries to verify the signature and if successful unlocks the
key to be used as a fully recognized API key.
For performing the handshake a special API exists within OctoPrint for which no API key is needed which is described below.
.. _sec-api-apps-sessionkey-get:
Obtaining a temporary session key
---------------------------------
.. http:get:: /apps/auth
Retrieve a temporary session key with a minimum validity. It can only be used as a proper API key after having been
:ref:`verified <sec-api-apps-sessionkey-verify>`.
Returns the temporary session key and the timestamp until it's valid.
**Example**:
.. sourcecode:: http
GET /apps/auth HTTP/1.1
Host: example.com
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"unverifiedKey": "F43A844750F74AD080FE9F438D47B33C",
"validUntil": 1416220357.011
}
:statuscode 200: No error
.. _sec-api-apps-sessionkey-verify:
Verifying a temporary session key
---------------------------------
.. http:post:: /apps/auth
Verify a formerly :ref:`retrieved <sec-api-apps-sessionkey-get>` temporary session key by providing credentials and a
cryptographic signature over these credentials and the temporary key.
Returns the now verified session key and the new validity.
**Example**:
.. sourcecode:: http
POST /apps/auth HTTP/1.1
Host: example.com
Content-Type: application/json
{
"appid": "com.example.my_octoprint_app",
"appversion": "1.0",
"key": "F43A844750F74AD080FE9F438D47B33C",
"_sig": "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
}
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"key": "F43A844750F74AD080FE9F438D47B33C",
"validUntil": 1416227497.011
}
.. _sec-api-apps-sessionkey-signature:
Creating the signature
----------------------
The signature is created by concatenating the ``appid``, ``appversion`` and ``key`` fields, separated by a ``:`` (colon),
signing the result with the app's private key using SHA-1 and then BASE64-encoding the result, stripping newlines.
Example for signature generation using Python and the `Python RSA library <https://pypi.python.org/pypi/rsa>`_:
.. sourcecode:: python
import base64
import rsa
appid = "com.example.my_octoprint_app"
version = "1.0"
unverified_key = "F43A844750F74AD080FE9F438D47B33C"
message_to_sign = appid + ":" + version + ":" + unverified_key
// => "com.example.my_octoprint_app:1.0:F43A844750F74AD080FE9F438D47B33C"
private_key = rsa.PrivateKey.load_pkcs1("...")
signature = base64.encodestring(rsa.sign(message_to_sign, private_key, "SHA-1")).replace("\n", "")
// => "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
.. _sec-api-apps-sessionkey-testing:
Testing your implementation
---------------------------
If you want to use app session keys, here is the key pair with which the above examples were created, in order for you
to verify your signature implementation::
-----BEGIN RSA PRIVATE KEY-----
MIIBPQIBAAJBAIhZ+Ls1zxtyd9kkm0DprhHIwL6woGUw5vbk5U00Hgva/ROIY7va
NUpHiiy9vijO2VtFbkaR2JjRPYslx8Ni+QkCAwEAAQJARK4lFo+FEcs3yR2iQjEy
p+yaAbNQJ4hZXlVvltLAYICzOM3kyKx53/eKU59NjskLz9q6QxfleymYPWAgl4NW
fQIjAJVH8MjwNcaAquTM9z2OiFi3OC8WgaKOi5W/T+r2+B70wG8CHwDp08dqOZ/u
xcBiy4Wzpcme9bckqoVuS3gWMm+YqgcCIwCMFU07kkY0NyumtzxPdIA4F/7OGSWf
IHqWFEfvasAddHlbAh8A5UgkB3Zf7Bt+7aFSBnlvve6FWm/XDPL12xYztYgrAiIa
W3miN6FjIm+8TDowrk+nyYXG2GZefeY7QXOjYr6tlDn0
-----END RSA PRIVATE KEY-----
-----BEGIN RSA PUBLIC KEY-----
MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4os
vb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
-----END RSA PUBLIC KEY-----
+1 -1
View File
@@ -59,7 +59,7 @@ Issue a connection command
Issue a connection command. Currently available command are:
connect
Instructs OctoPrint to connect to the printer. Additional parameters are:
Instructs OctoPrint to connect or, if already connected, reconnect to the printer. Additional parameters are:
* ``port``: Optional, specific port to connect to. If not set the current ``portPreference`` will be used, or if
no preference is available auto detection will be attempted.
+11
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:
+30 -14
View File
@@ -11,9 +11,9 @@ General information
Authorization
=============
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
configured one, a user specific one if "Access Control" is enabled or an app and user specific one as generated
by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
If :ref:`Access Control <sec-features-access_control>` is enabled OctoPrint's API expects an API key to be supplied with each request. This API
key can be either the globally configured one, a user specific one or an app and user specific one as generated by the
authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
@@ -26,8 +26,6 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
Host: example.com
X-Api-Key: abcdef...
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`403`.
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
.. sourcecode:: http
@@ -37,6 +35,24 @@ For testing purposes it is also possible to supply the API key via a query param
Please be advised that clients should use the header field variant if at all possible.
If the key is missing or invalid, OctoPrint will treat the request as it would any unauthenticated anonymous request to the endpoint.
Consequently, if the bundled :ref:`ForceLogin plugin <sec-bundledplugins-forcelogin>` is active (which is the default), that means
that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login <sec-api-general-login>`
will be denied with a :http:statuscode:`403`.
.. warning::
If :ref:`Access Control <sec-features-access_control>` is disabled, OctoPrint will treat any unauthenticated anonymous requests and thus also requests
with an invalid or outright missing API key as requests with full admin rights!
.. note::
The API key requirements changed in 1.3.11. Up to that version, even if Access Control was disabled, all requests needed to
be supplied with an API Key. To make the webinterface work under these circumstances, an unauthenticated anonymous API key was injected into the
HTML page and also available on the :ref:`Push API <sec-api-push>`. The presence and ready availability of this unauthenticated
anonymous "UI API key" caused confusion and false alarm among users and didn't contribute to the security of the platform in a
meaningful way, so it was finally abandoned in 1.3.11.
.. _fig-api-general-globalapikey:
.. figure:: ../images/settings-global-api-key.png
:align: center
@@ -58,11 +74,6 @@ Please be advised that clients should use the header field variant if at all pos
The API key options in the "Change password" dialog. Users can generate and revoke their custom API key here.
.. note::
OctoPrint's web interface uses a custom API key that is freshly generated on every server start. This key is not
intended to be used by any other client and would not be very useful in any case, since it basically represents
a completely anonymous client.
.. _sec-api-general-contenttype:
Content Type
@@ -137,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
@@ -146,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:
-1
View File
@@ -9,7 +9,6 @@ REST API
general.rst
version.rst
apps.rst
connection.rst
files.rst
job.rst
+7 -2
View File
@@ -212,7 +212,8 @@ Retrieve information about the current job
"filepos": 337942,
"printTime": 276,
"printTimeLeft": 912
}
},
"state": "Printing"
}
:statuscode 200: No error
@@ -243,4 +244,8 @@ Job information response
- 1
- :ref:`sec-api-datamodel-jobs-progress`
- Information regarding the progress of the current print job
* - ``state``
- 1
- String
- A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused",
"Cancelling", "Error" or "Offline".
+161 -6
View File
@@ -22,6 +22,11 @@ Bed
corresponding resource returns temperature information including an optional history. Note that Bed commands
are only available if the currently selected printer profile has a heated bed.
See :ref:`sec-api-printer-bedcommand`.
Chamber
Chamber commands allow setting the temperature and temperature offset for the printer's heated chamber. Querying
the corresponding resource returns temperature information including an option history. Note that Chamber commands
are only available if the currently selected printer profile has a heated chamber.
See :ref:`sec-api-printer-chambercommand`.
SD card
SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the
corresponding resource returns the current SD card state.
@@ -219,7 +224,7 @@ Issue a print head command
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
interpreted as an integer signifying the speed in mm/s, to append to the command.
interpreted as an integer signifying the speed in mm/min, to append to the command.
home
Homes the print head in all of the given axes. Additional parameters are:
@@ -345,7 +350,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:
@@ -362,6 +367,8 @@ Issue a tool command
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
* ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer
profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the command.
flowrate
Changes the flow rate factor to apply to extrusion of the tool.
@@ -621,12 +628,12 @@ Issue a bed command
are:
target
Sets the given target temperature on the printer's tools. Additional parameters:
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 tools. Additional parameters:
Sets the given temperature offset on the printer's bed. Additional parameters:
* ``offset``: Offset to set.
@@ -708,7 +715,7 @@ Retrieve the current bed state
an :http:statuscode:`409`.
.. note::
If you want both tool and bed temperature information at the same time, take a look at
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>`.
**Example**
@@ -758,6 +765,154 @@ Retrieve the current bed state
:statuscode 409: If the printer is not operational or the selected printer profile
does not have a heated bed.
.. _sec-api-printer-chambercommand:
Issue a chamber command
=======================
.. http:post:: /api/printer/chamber
Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands
are:
target
Sets the given target temperature on the printer's chamber. Additional parameters:
* ``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:
* ``offset``: Offset to set.
All of these commands may only be sent if the printer is currently operational. Otherwise a :http:statuscode:`409`
is returned.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
If no heated chamber is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires user rights.
**Example Target Temperature Request**
Set the target temperature for the printer's heated chamber to 50°C.
.. sourcecode:: http
POST /api/printer/chamber HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "target",
"target": 50
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example Offset Temperature Request**
Set the temperature offset for the heated chamber to -5°C.
.. sourcecode:: http
POST /api/printer/chamber HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "offset",
"offset": -5
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: The command to issue, either ``target`` or ``offset``.
:json object target: ``target`` command: The target temperature to set.
:json object offset: ``offset`` command: The offset temperature to set.
:statuscode 204: No error
:statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the
request is otherwise invalid.
:statuscode 409: If the printer is not operational or the selected printer profile
does not have a heated chamber.
.. _sec-api-printer-chamberstate:
Retrieve the current chamber state
==================================
.. http:get:: /api/printer/chamber
Retrieves the current temperature data (actual, target and offset) plus optionally a (limited) history (actual, target,
timestamp) for the printer's heated chamber.
It's also possible to retrieve the temperature history by supplying the ``history`` query parameter set to ``true``. The
amount of returned history data points can be limited using the ``limit`` query parameter.
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
If no heated chamber is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
.. 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>`.
**Example**
Query the chamber temperature data and also include the temperature history but limit it to two entries.
.. sourcecode:: http
GET /api/printer/chamber?history=true&limit=2 HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"chamber": {
"actual": 50.221,
"target": 70.0,
"offset": 5
},
"history": [
{
"time": 1395651928,
"chamber": {
"actual": 50.221,
"target": 70.0
}
},
{
"time": 1395651926,
"chamber": {
"actual": 49.1123,
"target": 70.0
}
}
]
}
:query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response
too. If no ``limit`` parameter is given, all available temperature history data will be returned.
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
will be returned. Will be ignored if ``history`` is not enabled.
:statuscode 200: No error
:statuscode 409: If the printer is not operational or the selected printer profile
does not have a heated chamber.
.. _sec-api-printer-sdcommand:
Issue an SD command
+9
View File
@@ -52,6 +52,7 @@ Retrieve all printer profiles
"height": 200
},
"heatedBed": true,
"heatedChamber": false,
"axes": {
"x": {
"speed": 6000,
@@ -93,6 +94,7 @@ Retrieve all printer profiles
"height": 200
},
"heatedBed": true,
"heatedChamber": true,
"axes": {
"x": {
"speed": 6000,
@@ -184,6 +186,7 @@ Add a new printer profile
"height": 200
},
"heatedBed": true,
"heatedChamber": false,
"axes": {
"x": {
"speed": 6000,
@@ -267,6 +270,7 @@ Add a new printer profile
"height": 300
},
"heatedBed": false,
"heatedChamber": false,
"axes": {
"x": {
"speed": 6000,
@@ -352,6 +356,7 @@ Update an existing printer profile
"height": 200
},
"heatedBed": true,
"heatedChamber": false,
"axes": {
"x": {
"speed": 6000,
@@ -578,6 +583,10 @@ Profile
- 0..1
- ``boolean``
- Whether the printer has a heated bed (``true``) or not (``false``)
* - ``heatedChamber``
- 0..1
- ``boolean``
- Whether the printer has a heated chamber (``true``) or not (``false``)
* - ``axes``
- 0..1
- Object
+6 -4
View File
@@ -274,10 +274,10 @@ Fetch template data
"plugin_name": "Action Command Prompt Support"
},
{
"id": "plugin_cura",
"name": "CuraEngine (<= 15.04)",
"plugin_id": "cura",
"plugin_name": "CuraEngine (<= 15.04)"
"id": "plugin_curalegacy",
"name": "Cura Legacy",
"plugin_id": "curalegacy",
"plugin_name": "Cura Legacy"
}
],
"sidebar": [
@@ -514,6 +514,8 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
-
* - ``webcam.ffmpegThreads``
-
* - ``webcam.ffmpegVideoCodec``
-
* - ``webcam.watermark``
-
* - ``webcam.flipH``
+14 -14
View File
@@ -42,22 +42,22 @@ List All Slicers and Slicing Profiles
Content-Type: application/json
{
"cura": {
"key": "cura",
"displayName": "CuraEngine",
"curalegacy": {
"key": "curalegacy",
"displayName": "Cura Legacy",
"default": true,
"profiles": {
"high_quality": {
"key": "high_quality",
"displayName": "High Quality",
"default": false,
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
"resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality"
},
"medium_quality": {
"key": "medium_quality",
"displayName": "Medium Quality",
"default": true,
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
"resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality"
}
}
}
@@ -81,7 +81,7 @@ List Slicing Profiles of a Specific Slicer
.. sourcecode:: http
GET /api/slicing/cura/profiles HTTP/1.1
GET /api/slicing/curalegacy/profiles HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
@@ -95,13 +95,13 @@ List Slicing Profiles of a Specific Slicer
"key": "high_quality",
"displayName": "High Quality",
"default": false,
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
"resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality"
},
"medium_quality": {
"key": "medium_quality",
"displayName": "Medium Quality",
"default": true,
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
"resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality"
}
}
@@ -125,7 +125,7 @@ Retrieve Specific Profile
.. sourcecode:: http
GET /api/slicing/cura/profiles/quick_test HTTP/1.1
GET /api/slicing/curalegacy/profiles/quick_test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
@@ -137,7 +137,7 @@ Retrieve Specific Profile
{
"displayName": "Just a test",
"description": "This is just a test",
"resource": "http://example.com/api/slicing/cura/profiles/quick_test",
"resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test",
"data": {
"bottom_layer_speed": 20.0,
"bottom_thickness": 0.3,
@@ -174,14 +174,14 @@ Add Slicing Profile
.. sourcecode:: http
PUT /api/slicing/cura/profiles/quick_test HTTP/1.1
PUT /api/slicing/curalegacy/profiles/quick_test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: application/json
{
"displayName": "Just a test",
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
"description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count",
"data": {
"layer_height": 0.2,
"skirt_line_count": 3
@@ -197,8 +197,8 @@ Add Slicing Profile
{
"displayName": "Just a test",
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
"resource": "http://example.com/api/slicing/cura/profiles/quick_test"
"description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count",
"resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test"
}
:param slicer: The identifying key of the slicer for which to add the profile
+47 -23
View File
@@ -38,30 +38,21 @@ List all registered system commands
{
"action": "shutdown",
"name": "Shutdown",
"command": "sudo shutdown -h now",
"confirm": "<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
"resource": "http://example.com/api/system/commands/core/shutdown"
},
{
"action": "reboot",
"name": "Reboot",
"command": "sudo reboot",
"confirm": "<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
"resource": "http://example.com/api/system/commands/core/reboot"
},
{
"action": "restart",
"name": "Restart OctoPrint",
"command": "sudo service octoprint restart",
"confirm": "<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
"resource": "http://example.com/api/system/commands/core/restart"
}
@@ -99,30 +90,21 @@ List all registered system commands for a source
{
"action": "shutdown",
"name": "Shutdown",
"command": "sudo shutdown -h now",
"confirm": "<b>You are about to shutdown the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"confirm": "<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"source": "core",
"resource": "http://example.com/api/system/commands/core/shutdown"
},
{
"action": "reboot",
"name": "Reboot",
"command": "sudo reboot",
"confirm": "<b>You are about to reboot the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"confirm": "<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"source": "core",
"resource": "http://example.com/api/system/commands/core/reboot"
},
{
"action": "restart",
"name": "Restart OctoPrint",
"command": "sudo service octoprint restart",
"confirm": "<b>You are about to restart the OctoPrint server.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"confirm": "<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"source": "core",
"resource": "http://example.com/api/system/commands/core/restart"
}
@@ -184,18 +166,60 @@ List all response
- Description
* - ``core``
- 0..n
- List of :ref:`command definitions <sec-api-system-commands-definiton>`
- List of :ref:`client command definitions <sec-api-client-system-commands-definiton>`
- List of all core commands defined.
* - ``custom``
- 0..n
- List of :ref:`command definitions <sec-api-system-commands-definiton>`
- List of :ref:`client command definitions <sec-api-client-system-commands-definiton>`
- List of all custom commands defined in ``config.yaml``.
.. _sec-api-client-system-commands-definiton:
Client command definitions
--------------------------
A restricted form of the full :ref:`command definition <sec-api-system-commands-definiton>`.
For exposing via the API.
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- The name of the command to display in the System menu.
* - ``action``
- 1
- string
- An identifier to refer to the command programmatically. The special ``action`` string
``divider`` signifies a divider in the menu.
* - ``confirm``
- 0..1
- string
- If present and set, this text will be displayed to the user in a confirmation dialog
they have to acknowledge in order to really execute the command.
* - ``source``
- 1
- string
- Source of the command definition, currently either ``core`` (for system actions defined by
OctoPrint itself) or ``custom`` (for custom system commands defined by the user through ``config.yaml``).
* - ``resource``
- 1
- string
- The URL of the command to use for executing it.
.. _sec-api-system-commands-definiton:
Command definition
------------------
The full command definition is not available via the API.
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
+4 -2
View File
@@ -7,7 +7,8 @@ Version information
.. http:get:: /api/version
Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing
the API version, ``server`` containing the server version.
the API version, ``server`` containing the server version, ``text`` containing the server version including
the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance).
**Example Request**
@@ -26,7 +27,8 @@ Version information
{
"api": "0.1",
"server": "1.1.0"
"server": "1.3.10",
"text": "OctoPrint 1.3.10"
}
:statuscode 200: No error
+57 -25
View File
@@ -40,15 +40,18 @@ of the following steps:
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
enters their username which is also their user ID into the App.
2. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
authorization process.
3. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
4. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
signals that no decision has been made yet.
5. The User either accepts or denies the access request which makes the Webinterface send a
6. The User either accepts or denies the access request which makes the Webinterface send a
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
6. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
an HTTP :http:statuscode:`404`.
@@ -61,31 +64,35 @@ of the following steps:
participant Webinterface
participant Server
note over User, Server: Step 1 & 2
note over User, Server: Step 1, 2 & 3
User->>App: enters URL of instance to connect to
User->>App: enters URL of instance to connect to and optional user_id
App->>Server: GET /plugin/appkeys/probe
alt Workflow unsupported
Server->>App: 404
App->>User: alternative workflow, copy-paste key manually
else Workflow supported
alt Limit to specific user
User->>App: enters user_id
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
else
App->>Server: POST /plugin/appkeys/request, (app_name)
end
note over User, Server: Step 3
note over User, Server: Step 4
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
Webinterface-->>User: Display confirmation dialog
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
note over User, Server: Step 4
note over User, Server: Step 5
loop
loop Poll for decision
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 202
end
note over User, Server: Step 5 & 6
note over User, Server: Step 6 & 7
alt User accepts
@@ -105,11 +112,27 @@ of the following steps:
end
end
.. _sec-bundledplugins-appkeys-api:
API
---
.. _sec-bundledplugins-appkeys-api-probe:
Probe for workflow support
..........................
.. http:get:: /plugin/appkeys/probe
Probes for support of the workflow.
Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned
(usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange.
:status 204: the workflow is supported
.. _sec-bundledplugins-appkeys-api-startauthprocess:
Start authorization process
@@ -131,12 +154,6 @@ Start authorization process
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
is logged in on.
.. note::
If this endpoint produces an HTTP :http:statuscode:`404` and the instance URL is correct, the bundled
Application Keys Plugin has in all likelihood been disabled by the user. Fall back on manual API key copy-pasting
by the user.
:json app: application identifier to use for the request, case insensitive
:json user: optional user id to restrict the decision to the specified user
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
@@ -154,6 +171,11 @@ Poll for decision on existing request
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
HTTP :http:statuscode:`404` if the request has been denied or timed out.
.. note::
The request will be considered stale and deleted internally if the polling endpoint for it isn't called
for more than 5s.
:status 200: access granted, API key in response body
:status 202: no decision has been made yet, continue polling
:status 404: access denied or request timed out
@@ -452,6 +474,15 @@ JavaScript Client Library
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts)
Probes for workflow support.
See :ref:`Probe for workflow support <sec-bundledplugins-appkeys-api-probe>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
Starts a new authorization request for the provided ``app`` identifier.
@@ -481,9 +512,10 @@ JavaScript Client Library
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
Convenience function that issues a request and then automatically starts polling for a decision on the returned
polling endpoint every 1s, until either a positive or negative decision is returned. On success the returned
promise is resolved with the generated API key as argument.
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support
for the workflow, the promise is rejected.
**Example usage**
+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
-130
View File
@@ -1,130 +0,0 @@
.. _sec-bundledplugins-cura:
Cura
====
The Cura Plugin allows slicing of STL files uploaded to OctoPrint directly via
the `CuraEngine <http://github.com/Ultimaker/CuraEngine>`_ **up to and
including version 15.04.x** and supersedes the slicing support integrated into
OctoPrint so far. It comes bundled with OctoPrint starting with version 1.2.0.
.. note::
Versions of CuraEngine later than 15.04.x have changed their calling
parameters in such a way that the current implementation of OctoPrint's Cura plugin
is not compatible to it. For this reason, please use only CuraEngine versions up to
and including 15.04 for now, as available in the ``legacy`` branch of the CuraEngine
repository on Github.
The plugin offers a settings module that allows configuring the path to the
CuraEngine executable to use, as well as importing and managing slicing
profiles to be used. Please note that the Cura Plugin will use the printer
parameters you configured within OctoPrint (meaning bed size and extruder
count and offsets) for slicing.
.. _sec-bundledplugins-cura-firststeps:
First Steps
-----------
Before you can slice from within OctoPrint, you'll need to
#. :ref:`Install CuraEngine <sec-bundledplugins-cura-installing>`
#. :ref:`Configure the path to CuraEngine within OctoPrint <sec-bundledplugins-cura-configuring>`
#. :ref:`Export a slicing profile from Cura and import it within OctoPrint <sec-bundledplugins-cura-profiles>`
.. note::
OctoPi 0.12.0 and later ships with steps 1 and 2 already done, you only need to
supply one or more slicing profiles to get going :)
.. _sec-bundledplugins-cura-installing:
Installing CuraEngine
---------------------
You'll need a build of ``legacy`` branch of `CuraEngine <http://github.com/Ultimaker/CuraEngine>`_
in order to be able to use the Cura OctoPrint plugin. You can find the ``legacy`` branch
`here <https://github.com/ultimaker/curaengine/tree/legacy>`__.
If you previously used the `old variant of the Cura integration <https://github.com/foosel/OctoPrint/wiki/Cura-Integration>`_,
you probably still have a fully functional binary lying around in the
installation folder of the full install of Cura you used then -- just put the
path to that in the plugin settings.
.. _sec-bundledplugins-cura-installing-raspbian:
Compiling for Raspbian
++++++++++++++++++++++
Raspbian Jessie and later
~~~~~~~~~~~~~~~~~~~~~~~~~
Building on Raspbian Jessie and later is as easy as::
sudo apt-get -y install gcc-4.7 g++-4.7
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
cd CuraEngine
make
After this has completed, you'll find your shiny new build of CuraEngine in
the `build` folder (full path for above example:
``~/CuraEngine/build/CuraEngine``).
Raspbian Wheezy
~~~~~~~~~~~~~~~
You'll need to install a new version of gcc and g++ and patch CuraEngine's
Makefile (see `this post <http://umforum.ultimaker.com/index.php?/topic/5943-recent-build-of-curaengine-wont-compile-on-raspberry-pi/#entry58539>`_)
in order for the compilation to work on current Raspbian builds (e.g. OctoPi)::
sudo apt-get -y install gcc-4.7 g++-4.7
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
cd CuraEngine
wget http://bit.ly/curaengine_makefile_patch -O CuraEngine.patch
patch < CuraEngine.patch
make CXX=g++-4.7
After this has completed, you'll find your shiny new build of CuraEngine in
the `build` folder (full path for above example:
``~/CuraEngine/build/CuraEngine``).
.. _sec-bundledplugins-cura-configuring:
Configuring the plugin
----------------------
The Cura plugin needs to be configured with the full path to your copy of the
CuraEngine executable that it's supposed to use. You can do this either via
the Cura plugin settings dialog or by manually configuring the path to the
executable via ``config.yaml``, example:
.. code-block:: yaml
plugins:
cura:
cura_engine: /path/to/CuraEngine
.. _sec-bundledplugins-cura-profiles:
Using Cura Profiles
-------------------
The Cura Plugin supports importing your existing profiles for Cura **up to and
including Cura 15.04.x**. Newer Cura releases (e.g. 15.06 or 2.x) use a different
internal format that will *not* work with the current version of the Cura Plugin.
You can find downloads of Cura 15.04.x for Windows, Mac and Linux `on Ultimaker's download page <https://ultimaker.com/en/products/cura-software/list>`_.
In order to export a slicing profile from the Cura desktop UI, open it,
set up your profile, then click on "File" and there on "Save Profile". You can
import the .ini-file this creates via the "Import Profile" button in the
Cura Settings within OctoPrint.
.. _sec-bundledplugins-cura-sourcecode:
Source code
-----------
The source of the Cura plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/cura``.
+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
+40
View File
@@ -0,0 +1,40 @@
.. _sec-bundledplugins-errortracking:
Error Tracking Plugin
=====================
The Error Tracking plugin will cause any logged exceptions in the server and the browser interface to be sent to
OctoPrint's `Sentry instance <https://sentry.io/>`_.
By enabling it you help to gather detailed information on the cause of bugs or other issues. This is especially
valuable on release candidates, which is why this plugin will also prompt you to enable error tracking if it detects
that you are subscribed to an RC release channel.
By default, even when enabled it will only be active if you are running a released OctoPrint version, so either a stable
release or a release candidate.
The Error Tracking plugin is using a Sentry instance kindly provided by `sentry.io <https://sentry.io/>`_. For information on their service
please refer to their `Security & Compliance documentation <https://sentry.io/security/>`_
and their `Privacy Policy <https://sentry.io/privacy/>`_.
The Error Tracking plugin has been bundled with OctoPrint since version 1.3.11.
.. _sec-bundledplugins-errortracking-configuration:
Configuring the plugin
----------------------
The plugin supports the following configuration keys:
* ``enabled``: Whether to enable error tracking. Defaults to ``false``.
* ``enabled_unreleased``: Whether to also enable tracking on unreleased OctoPrint versions (anything not stable releases
or release candidates). Defaults to ``false``.
* ``unique_id``: Unique instance identifier, auto generated on first activation
.. _sec-bundledplugins-errortracking-sourcecode:
Source Code
-----------
The source of the Error Tracking plugin is bundled with OctoPrint and can be
found in its source repository under ``src/octoprint/plugins/errortracking``.
+2 -1
View File
@@ -9,10 +9,11 @@ Bundled Plugins
action_command_prompt.rst
announcements.rst
tracking.rst
appkeys.rst
backup.rst
cura.rst
discovery.rst
errortracking.rst
forcelogin.rst
logging.rst
pluginmanager.rst
+39
View File
@@ -82,6 +82,45 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
- hidden
- plugins
.. _sec-bundledplugins-pluginmanager-events:
Events
------
plugin_pluginmanager_install_plugin
A plugin was installed.
Payload:
* ``id``: the identifier of the installed plugin
* ``version``: the version of the installed plugin
* ``source``: source from which the plugin was installed, can be an URL or a path in the local file system
* ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path``
plugin_pluginmanager_uninstall_plugin
A plugin was uninstalled.
Payload:
* ``id``: the identifier of the uninstalled plugin
* ``version``: the version of the uninstalled plugin
plugin_pluginmanager_enable_plugin
A plugin was enabled.
Payload:
* ``id``: the identifier of the enabled plugin
* ``version``: the version of the enabled plugin
plugin_pluginmanager_disabled_plugin
A plugin was disabled.
Payload:
* ``id``: the identifier of the disabled plugin
* ``version``: the version of the disabled plugin
.. _sec-bundledplugins-pluginmanager-hooks:
Hooks
@@ -29,6 +29,20 @@ If you know of further printers/printer firmwares that need to be added here, pl
unexpectedly and with `catastrophic <https://www.thissmarthouse.net/dont-burn-your-house-down-3d-printing-a-cautionary-tale/>`_
`results <https://www.reddit.com/r/3Dprinting/comments/6cekgk/house_fire_thanks_to_cheap_printer_from_china/>`_.
.. _sec-bundledplugins-printer_safety_check-events:
Events
------
warning
A printer safety warning was triggered.
Payload:
* ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``)
* ``check_name``: name of check that was triggered (e.g. ``aneta8``)
* ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``)
.. _sec-bundledplugins-printer_safety_check-source:
Source Code
+29 -2
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:
@@ -325,6 +329,29 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing
branch: devel
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
.. _sec-bundledplugins-softwareupdate-events:
Events
------
plugin_softwareupdate_update_succeeded
An update succeeded.
Payload:
* ``target``: update target
* ``from_version``: version from which was updated
* ``to_version``: version to which was updated
plugin_softwareupdate_update_failed
An update failed.
Payload:
* ``target``: update target
* ``from_version``: version from which was updated
* ``to_version``: version to which was updated
.. _sec-bundledplugins-softwareupdate-hooks:
Hooks
@@ -362,8 +389,8 @@ octoprint.plugin.softwareupdate.check_config
.. code-block:: python
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
def get_update_information(*args, **kwargs):
return dict(
+45
View File
@@ -0,0 +1,45 @@
.. _sec-bundledplugins-tracking:
Anonymous Usage Tracking Plugin
===============================
The Anonymous Usage Tracking plugin provides valuable insights into how many instances running what versions of
OctoPrint are out there, whether they are successfully completing print jobs and various other metrics.
By enabling it you help to identify problems with new releases and release candidates early on, and to better tailor
OctoPrint's future development to actual use.
For details on what gets tracked, please refer to `tracking.octoprint.org <https://tracking.octoprint.org>`_
and also the `Privacy Policy at tracking.octoprint.org <https://tracking.octoprint.org/privacy>`_.
The Anonymous Usage Tracking plugin has been bundled with OctoPrint since version 1.3.10.
.. _sec-bundledplugins-tracking-configuration:
Configuring the plugin
----------------------
The plugin supports the following configuration keys:
* ``enabled``: Whether to enable usage tracking. Defaults to ``false``.
* ``unique_id``: Unique instance identifier, auto generated on first activation
* ``server``: The tracking server to track against. Defaults to a tracking endpoint on ``https://tracking.octoprint.org``.
* ``ping``: How often to send a ``ping`` tracking event, in seconds. Defaults to a 15min interval.
* ``events``: Granular configuration of enabled tracking events. All default to ``true``.
* ``startup``: Whether to track startup/shutdown events
* ``printjob``: Whether to track print job related events (start, completion, cancel, ...)
* ``commerror``: Whether to track communication errors with the printer
* ``plugin``: Whether to track plugin related events (install, uninstall, ...)
* ``update``: Whether to track update related events (update successful or not, ...)
* ``printer``: Whether to track printer related events (connected, firmware, ...)
* ``printer_safety_check``: Whether to track warnings of the :ref:`Printer Safety Check <sec-bundledplugins-printer_safety_check>`
* ``throttled``: Whether to track throttle events detected on the underlying system
.. _sec-bundledplugins-tracking-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/tracking``.
+10 -8
View File
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
#
# OctoPrint documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 02 17:08:50 2013.
@@ -49,8 +51,8 @@ source_suffix = '.rst'
master_doc = 'index'
# General information about the project.
project = u'OctoPrint'
copyright = u'%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else u'%d, Gina Häußge' % year_since
project = 'OctoPrint'
copyright = '%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else '%d, Gina Häußge' % year_since
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -207,8 +209,8 @@ htmlhelp_basename = 'OctoPrintdoc'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
#latex_documents = [
# ('index', 'OctoPrint.tex', u'OctoPrint Documentation',
# u'Gina Häußge', 'manual'),
# ('index', 'OctoPrint.tex', 'OctoPrint Documentation',
# 'Gina Häußge', 'manual'),
#]
# The name of an image file (relative to this directory) to place at the top of
@@ -237,8 +239,8 @@ htmlhelp_basename = 'OctoPrintdoc'
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'octoprint', u'OctoPrint Documentation',
[u'Gina Häußge'], 1)
('index', 'octoprint', 'OctoPrint Documentation',
['Gina Häußge'], 1)
]
# If true, show URL addresses after external links.
@@ -251,8 +253,8 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'OctoPrint', u'OctoPrint Documentation',
u'Gina Häußge', 'OctoPrint', 'One line description of project.',
('index', 'OctoPrint', 'OctoPrint Documentation',
'Gina Häußge', 'OctoPrint', 'One line description of project.',
'Miscellaneous'),
]
+66 -8
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.
@@ -29,7 +29,7 @@ Use the following settings to enable access control:
# The user manager implementation to use for accessing user information. Currently only a filebased
# user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml
# in the default configuration folder, see below)
userManager: octoprint.users.FilebasedUserManager
userManager: octoprint.access.users.FilebasedUserManager
# The YAML user file to use. If left out defaults to users.yaml in the default configuration folder.
userFile: /path/to/users.yaml
@@ -62,6 +62,18 @@ Use the following settings to enable access control:
# header and login the user without further checks. Use with caution.
checkBasicAuthenticationPassword: true
# Whether to trust remote user headers. If you have setup authentication in front of
# OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will
# be logged into OctoPrint as the user provided in the header. Your should ONLY ENABLE THIS if your
# OctoPrint instance is only accessible through a connection locked down through an authenticating reverse proxy!
trustRemoteUser: false
# Header used by the reverse proxy to convey the authenticated user.
remoteUserHeader: REMOTE_USER
# If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.
addRemoteUsers: false
.. _sec-configuration-config_yaml-api:
API
@@ -81,7 +93,8 @@ Settings for the REST API:
# Whether to allow cross origin access to the API or not
allowCrossOrigin: false
# Additional app api keys, see REST API > Apps in the docs
# Additional app api keys, see REST API > Apps in the docs.
# Deprecated since 1.3.11, to be removed in 1.4.0!
apps:
"some.app.identifier:some_version":
pubkey: <RSA pubkey>
@@ -277,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:
@@ -322,6 +338,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# Whether the simulated printer should also simulate a heated bed or not
hasBed: true
# Whether the simulated printer should also simulate a heated chamber or not
hasChamber: false
# If enabled, reports the set target temperatures as separate messages from the firmware
#
# True: > M109 S220.0
@@ -409,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
@@ -562,6 +580,9 @@ Use the following settings to enable or disable OctoPrint features:
- M117
- M118
# whether G90/G91 also influence absolute/relative mode of extruders
g90InfluencesExtruder: false
.. _sec-configuration-config_yaml-folder:
Folder
@@ -666,6 +687,11 @@ plugins are tracked:
_disabled:
- ...
# Identifiers of plugins for which python compatibility information will be ignored and
# the plugin considered compatible in any case. Only for development, do NOT use in production.
_forcedCompatible:
- ...
# The rest are individual plugin settings, each tracked by their identifier, e.g.:
some_plugin:
some_setting: true
@@ -806,6 +832,19 @@ Use the following settings to configure the serial connection to the printer:
additionalBaudrates:
- 123456
# Commands which should not be sent to the printer, e.g. because they are known to block serial
# communication until physical interaction with the printer as is the case on most firmwares with
# the default M0 and M1.
blockedCommands:
- M0
- M1
# Commands which should cause OctoPrint to pause any ongoing prints.
pausingCommands:
- M0
- M1
- M25
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
# homing, dwelling, auto leveling etc. Defaults to the below commands.
longRunningCommands:
@@ -932,6 +971,13 @@ Use the following settings to configure the server:
# reset the setting to false
startOnceInSafeMode: false
# Signals to OctoPrint that the last startup was incomplete. OctoPrint will then startup
# in safe mode
incompleteStartup: false
# Set this to true to make OctoPrint ignore incomplete startups. Helpful for development.
ignoreIncompleteStartup: false
# Secret key for encrypting cookies and such, randomly generated on first run
secretKey: someSecretKey
@@ -1058,6 +1104,15 @@ Use the following settings to configure the server:
# How many days to leave unused entries in the preemptive cache config
until: 7
# Configuration of the client IP check to warn about connections from external networks
ipCheck:
# whether to enable the check, defaults to true
enabled: true
# additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24"
trustedSubnets: []
.. note::
@@ -1087,14 +1142,14 @@ Settings for the built-in slicing support:
slicing:
# Whether to enable slicing support or not
enabled:
enabled: true
# Default slicer to use
defaultSlicer: cura
defaultSlicer: null
# Default slicing profiles per slicer
defaultProfiles:
cura: ...
curalegacy: ...
.. _sec-configuration-config_yaml-system:
@@ -1197,6 +1252,9 @@ Use the following settings to configure webcam support:
# Should be left at 1 for RPi1.
ffmpegThreads: 1
# Videocodec to be used for encoding. Defaults to mpeg2video.
ffmpegVideoCodec: mpeg2video
# The bitrate to use for rendering the timelapse video. This gets directly passed to ffmpeg.
bitrate: 5000k
+3 -3
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
@@ -39,8 +39,8 @@ A list of important components for which an increase in logging might be interes
* ``octoprint.filemanager``: the file management layer
* ``octoprint.plugin``: the plugin sub system
* ``octoprint.plugins.<plugin>``: the plugin ``<plugin>``, e.g. ``octoprint.plugins.discovery`` to change the log level of
the `Discovery plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_ or ``octoprint.plugins.cura``
to change the log level of the `Cura plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_.
the :ref:`Discovery plugin <sec-bundledplugins-discovery>` or ``octoprint.plugins.backup``
to change the log level of the :ref:`Backup plugin <sec-bundledplugins-backup>`.
* ``octoprint.slicing``: the slicing sub system
This list will be expanded when deemed necessary.
+49 -11
View File
@@ -14,18 +14,34 @@ below.
* Prerequisites:
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
* 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 a virtual environment in the checked out source folder to use for installing and running OctoPrint and its
dependencies (this avoids potential versioning issues for the dependencies with system wide installed
instances): ``virtualenv venv``
* Activate the virtual environment: ``source venv/bin/activate`` (Linux, MacOS) or
``source venv/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
* 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``
* 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)
* 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: ``pip install -e .[develop,plugins]``
including its regular *and* development and plugin development dependencies:
* ``pip install -e .[develop,plugins]``
When the virtual environment is activated you can then:
@@ -33,11 +49,19 @@ When the virtual environment is activated you can then:
* run the test suite from the checked out source folder via ``nosetests --with-doctest``
* build the documentation from the ``docs`` sub folder of the checked out sources via ``sphinx-build -b html . _build``
To switch the activated virtual environment, simply activate the new environment as described above.
To deactivate the virtual environment and return to the system's default Python: ``deactivate``.
.. _sec-development-environment-source-linux:
Linux
.....
.. todo::
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
location, please substitute accordingly.
@@ -70,7 +94,7 @@ Then:
.. code-block:: none
cd ~/devel
git clone https://github.com/foosel/OctoPrint.git
git clone -b devel https://github.com/foosel/OctoPrint.git
cd OctoPrint
virtualenv venv
source ./venv/bin/activate
@@ -85,12 +109,16 @@ environment.
Windows
.......
.. todo::
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different
location, please substitute accordingly.
First download & install:
* `Python 2.7.12 Windows x86 MSI installer <https://www.python.org/downloads/release/python-2712/>`_
* `Python 2.7.15 Windows x86 MSI installer <https://www.python.org/downloads/release/python-2715/>`_
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
@@ -120,6 +148,10 @@ Mac OS X
This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Setup-on-Mac/>`_.
Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks.
.. todo::
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
location, please substitute accordingly.
@@ -158,6 +190,10 @@ You'll need a user account with administrator privileges.
IDE Setup
---------
.. todo::
This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development.
.. todo::
Using another IDE than the ones below? Please send a
@@ -170,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
+111 -51
View File
@@ -6,15 +6,6 @@ Events
.. contents::
.. note::
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
to indicate what to do with the command contained.
.. _sec-events-configuration:
Configuration
@@ -47,6 +38,13 @@ Example
- event: PrintDone
command: python ~/growl.py -t mygrowlserver -d "Completed {file}" -a OctoPrint -i http://raspi/Octoprint_logo.png
type: system
- event:
- PrintStarted
- PrintFailed
- PrintDone
- PrintCancelled
command: python ~/growl.py -t mygrowlserver -d "Event {__eventname} ({name})" -a OctoPrint -i http://raspi/Octoprint_logo.png
type: system
- event: Connected
command:
- M115
@@ -62,6 +60,7 @@ Placeholders
You can use the following generic placeholders in your event hooks:
* ``{__currentZ}``: the current Z position of the head if known, -1 if not available
* ``{__eventname}`` : the name of the event hook being triggered
* ``{__filename}`` : name of currently selected file, or ``NO FILE`` if no file is selected
* ``{__filepath}`` : path in origin location of currently selected file, or ``NO FILE`` if no file is selected
* ``{__fileorigin}`` : origin of currently selected file, or ``NO FILE`` if no file is selected
@@ -85,6 +84,12 @@ and its origin via the placeholder ``{origin}``.
Available Events
================
.. note::
Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook <sec-plugins-hook-events-register_custom_events>`.
.. _sec-events-available_events-server:
Server
------
@@ -99,7 +104,8 @@ ClientOpened
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
@@ -110,6 +116,19 @@ ClientClosed
* ``remoteAddress``: the remote address (IP) of the client that disconnected
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
@@ -118,6 +137,8 @@ ConnectivityChanged
* ``old``: Old connectivity value (true for online, false for offline)
* ``new``: New connectivity value (true for online, false for offline)
.. _sec-events-available_events-printer_commmunication:
Printer communication
---------------------
@@ -141,7 +162,11 @@ Disconnected
The server has disconnected from the printer
Error
An error has occurred in the printer communication.
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:
@@ -156,6 +181,8 @@ PrinterStateChanged
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
* ``state_string``: Text representation of the new state.
.. _sec-events-available_events-file_handling:
File handling
-------------
@@ -169,9 +196,7 @@ Upload
.. deprecated:: 1.3.0
* ``file``: the file's path within its storage location
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
FileAdded
A file has been added to a storage.
@@ -253,9 +278,7 @@ MetadataAnalysisStarted
.. deprecated:: 1.3.0
* ``file``: the file's path within its storage location
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
MetadataAnalysisFinished
The metadata analysis of a file has finished.
@@ -269,9 +292,7 @@ MetadataAnalysisFinished
.. deprecated:: 1.3.0
* ``file``: the file's path within its storage location
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's path within its storage location. To be removed in 1.4.0.
FileSelected
A file has been selected for printing.
@@ -284,10 +305,8 @@ FileSelected
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
FileDeselected
No file is selected any more for printing.
@@ -311,6 +330,8 @@ TransferDone
* ``local``: the file's name as stored locally
* ``remote``: the file's name as stored on SD
.. _sec-events-available_events-printing:
Printing
--------
@@ -322,13 +343,14 @@ PrintStarted
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who started the print job (if available)
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintFailed
A print failed.
@@ -338,13 +360,15 @@ PrintFailed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the elapsed time of the print when it failed, in seconds (float)
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintDone
A print completed successfully.
@@ -354,14 +378,14 @@ PrintDone
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the time needed for the print, in seconds (float)
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintCancelling
The print is about to be cancelled.
@@ -371,6 +395,9 @@ PrintCancelling
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who cancelled the print job (if available)
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
PrintCancelled
@@ -381,7 +408,12 @@ PrintCancelled
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of cancelling, if available
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``time``: the elapsed time of the print when it was cancelled, in seconds (float)
* ``user``: the user who cancelled the print job (if available)
* ``position``: the print head position at the time of cancelling (if available, not available if recording of the
position on cancel is disabled)
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
@@ -395,10 +427,8 @@ PrintCancelled
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintPaused
The print has been paused.
@@ -408,7 +438,11 @@ PrintPaused
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of pausing, if available
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who paused the print job (if available)
* ``position``: the print head position at the time of pausing (if available, not available if the recording of
the position on pause is disabled or the pause is completely handled by the printer's firmware)
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
@@ -422,10 +456,8 @@ PrintPaused
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
PrintResumed
The print has been resumed.
@@ -435,13 +467,16 @@ PrintResumed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``size``: the file's size in bytes (if available)
* ``owner``: the user who started the print job (if available)
* ``user``: the user who resumed the print job (if available)
.. deprecated:: 1.3.0
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``)
* ``filename``: the file's name
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
* ``filename``: the file's name. To be removed in 1.4.0.
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
.. _sec-events-available_events-gcode_processing:
GCODE processing
----------------
@@ -504,6 +539,8 @@ ToolChange
* ``old``: old tool index
* ``new``: new tool index
.. _sec-events-available_events-timelapses:
Timelapses
----------
@@ -558,6 +595,8 @@ MovieFailed
returned a non-0 return code, ``no_frames`` if no frames were captured that could be rendered
to a timelapse, or ``unknown`` for any other reason of failure to render.
.. _sec-events-available_events-slicing:
Slicing
-------
@@ -566,6 +605,7 @@ SlicingStarted
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -577,6 +617,7 @@ SlicingDone
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -589,6 +630,7 @@ SlicingCancelled
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -599,6 +641,7 @@ SlicingFailed
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -614,7 +657,7 @@ SlicingProfileAdded
* ``profile``: the profile that was added
SlicingProfileModified
A new slicing profile was modified.
A slicing profile was modified.
Payload:
@@ -629,8 +672,25 @@ SlicingProfileDeleted
* ``slicer``: the slicer for which the profile was deleted
* ``profile``: the profile that was deleted
.. _sec-events-available_events-settings:
Settings
--------
SettingsUpdated
The internal settings were updated.
The settings were updated via the REST API.
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
+2 -2
View File
@@ -21,12 +21,12 @@ 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
printer!**
printer**, and without the need for an :ref:`API key <sec-api-general-authorization>`!
Upon first start a configuration wizard is provided which allows configuration
of the first administrator account or alternatively disabling Access Control
(which is **NOT** recommended for systems that are directly accessible via the
Internet!).
internet or other untrusted networks!).
.. hint::
+5 -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
@@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows:
.. code-block:: jinja
:caption: Default ``disable_hotends`` snippet
{% if printer_profile.extruder.sharedNozzle %}
M104 T0 S0
{% else %}
{% for tool in range(printer_profile.extruder.count) %}
M104 T{{ tool }} S0
{% endfor %}
{% endif %}
The ``disable_bed`` snippet is defined as follows:
+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.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 58 KiB

+2 -2
View File
@@ -11,7 +11,7 @@ and released under the `GNU Affero General Public License V3 <http://www.gnu.org
Its website can be found at `octoprint.org <https://octoprint.org/>`_.
The community forum is available at `discourse.octoprint.org <https://discourse.octoprint.org/>`_.
The community forum is available at `community.octoprint.org <https://community.octoprint.org/>`_.
The FAQ can be accessed by following `faq.octoprint.org <https://faq.octoprint.org/>`_.
@@ -23,7 +23,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!
.. note::
This documentation currently focuses primarily on developers and less on end users. If you are interested in
helping to change this, please get in touch `on the forum <https://discourse.octoprint.org/>`_!
helping to change this, please get in touch `on the forum <https://community.octoprint.org/>`_!
Contents
========
+58
View File
@@ -210,6 +210,64 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.printer.getChamberState(data, opts)
Retrieves the current printer chamber state/temperature information, and optionally also the temperature
history.
The ``flags`` object can be used to specify the data to retrieve further via the following
properties:
* ``history``: a boolean value to specify whether the temperature history should be included (``true``)
or not (``false``), defaults to it not being included
* ``limit``: an integer value to specify how many history entries to include
See :ref:`Retrieve the current bed state <sec-api-printer-chamberstate>` for more details.
:param object flags: Flags that further specify which data to retrieve, see above for details
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.printer.setChamberTargetTemperature(target, opts)
Sets the given temperature on the printer's heated chamber (if available).
``target`` is expected to be the target temperature as a float value.
**Example:**
Set the chamber to 50°C.
.. code-block:: javascript
OctoPrint.printer.setChamberTargetTemperature(50.0);
See the ``target`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
:param float target: The target to set
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.printer.setChamberTemperatureOffset(offset, opts)
Sets the given temperature offset for the printer's heated chamber (if available).
``offset`` is expected to be the temperature offset to set.
**Example:**
Set the offset for the chamber to -5°C.
.. code-block:: javascript
OctoPrint.printer.setChamberTemperatureOffset(-5);
See the ``offset`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
:param object offsets: The offsets to set
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.printer.jog(amounts, opts)
Jogs the specified axes by the specified ``amounts``.
+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
+3 -3
View File
@@ -1,9 +1,9 @@
.. _sec-modules-users:
octoprint.users
---------------
octoprint.access.users
----------------------
.. automodule:: octoprint.users
.. automodule:: octoprint.access.users
:members:
+6
View File
@@ -6,4 +6,10 @@ octoprint.util
.. automodule:: octoprint.util
:members:
.. _sec-modules-util-commandline:
octoprint.util.commandline
--------------------------
.. automodule:: octoprint.util.commandline
:members:
+15
View File
@@ -13,6 +13,7 @@ plugin subsystem about themselves. These are simple package attributes defined i
# ...
__plugin_name__ = "My Plugin"
__plugin_pythoncompat__ = ">=2.7,<4"
def __plugin_load__():
# whatever you need to do to load your plugin, if anything at all
pass
@@ -52,6 +53,20 @@ The following properties are recognized:
``__plugin_license__``
License of your plugin, optional, overrides the license specified in ``setup.py`` if provided.
.. _sec-plugins-controlproperties-plugin_pythoncompat:
``__plugin_pythoncompat__``
Python compatibility string of your plugin, optional, defaults to ``>=2.7,<3`` if not set and thus Python 2 but no
Python 3 compatibility.
If your plugin is compatible to Python 3, you should set this to ``>=2.7,<4``, otherwise your plugin will not load
on OctoPrint instances installed under Python 3.
.. code-block:: python
__plugin_pythoncompat__ = ">=2.7,<4"
.. _sec-plugins-controlproperties-plugin_implementation:
``__plugin_implementation__``
+22 -22
View File
@@ -54,8 +54,8 @@ We'll start at the most basic form a plugin can take - just a few simple lines o
.. code-block:: python
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
__plugin_name__ = "Hello World"
__plugin_version__ = "1.0.0"
@@ -89,8 +89,8 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
:emphasize-lines: 4-8,13
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
@@ -289,8 +289,8 @@ and ``__plugin_description__`` from ``__init__.py``:
.. code-block:: python
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
@@ -314,8 +314,8 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
:emphasize-lines: 10
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
@@ -362,8 +362,8 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
:emphasize-lines: 7
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
@@ -428,8 +428,8 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``:
:emphasize-lines: 8, 10, 12-13
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
@@ -462,8 +462,8 @@ Adjust your plugin's ``__init__.py`` like this:
:emphasize-lines: 15-16
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
@@ -569,8 +569,8 @@ again since we don't use that anymore:
:emphasize-lines: 15-19
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
@@ -666,8 +666,8 @@ like so:
:emphasize-lines: 9,22-25
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
@@ -846,8 +846,8 @@ a reference to our CSS file:
:emphasize-lines: 26
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
@@ -931,8 +931,8 @@ Then adjust our returned assets to include our LESS file as well:
:emphasize-lines: 27
:linenos:
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import octoprint.plugin
+251 -57
View File
@@ -28,6 +28,7 @@ or as ``postfix`` (after the existing lines).
.. code-block:: python
:linenos:
from past import basestring
self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts")
# ...
@@ -35,7 +36,7 @@ or as ``postfix`` (after the existing lines).
for hook in self._gcodescript_hooks:
try:
retval = self._gcodescript_hooks[hook](self, "gcode", scriptName)
except:
except Exception:
self._logger.exception("Error while processing gcodescript hook %s" % hook)
else:
if retval is None:
@@ -44,10 +45,8 @@ or as ``postfix`` (after the existing lines).
continue
def to_list(data):
if isinstance(data, str):
data = map(str.strip, data.split("\n"))
elif isinstance(data, unicode):
data = map(unicode.strip, data.split("\n"))
if isinstance(data, basestring):
data = map(x.strip() for x in data.split("\n"))
if isinstance(data, (list, tuple)):
return list(data)
@@ -201,30 +200,93 @@ Available plugin hooks
.. contents::
:local:
.. _sec-plugins-hook-accesscontrol-appkey:
.. _sec-plugins-hook-permissions:
octoprint.accesscontrol.appkey
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:: acl_appkey_hook(*args, **kwargs)
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
By handling this hook plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
within the system.
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.
Overrides this to return your additional app information to be used for validating app session keys. You'll
need to return a list of 3-tuples of the format (id, version, public key).
The provided ``components`` is a dictionary containing the already initialized system components:
The ``id`` should be the (unique) identifier of the app. Using a domain prefix might make sense here, e.g.
``org.octoprint.example.MyApp``.
* ``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`
``version`` should be a string specifying the version of the app for which the public key is valid. You can
provide the string ``any`` here, in which case the provided public key will be valid for all versions of the
app for which no specific public key is defined.
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
Finally, the public key is expected to be provided as a PKCS1 string without newlines.
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
:return: A list of 3-tuples as described above
:rtype: list
.. _sec-plugins-hook-accesscontrol-keyvalidator:
@@ -237,7 +299,7 @@ octoprint.accesscontrol.keyvalidator
``apikey`` will be the API key as read from the request headers.
Hook handlers are expected to return a :class:`~octoprint.users.User` instance here that will then be considered that
Hook handlers are expected to return a :class:`~octoprint.access.users.User` instance here that will then be considered that
user making the request. By returning ``None`` or nothing at all, hook handlers signal that they do not handle the
provided key.
@@ -255,7 +317,7 @@ octoprint.accesscontrol.keyvalidator
:param str apikey: The API key to validate
:return: The user in whose name the request will be processed further
:rtype: :class:`~octoprint.users.User`
:rtype: :class:`~octoprint.access.users.User`
.. _sec-plugins-hook-cli-commands:
@@ -380,10 +442,10 @@ octoprint.cli.commands
OctoPrint's CLI.
:rtype: list
.. _sec-plugins-hook-comm-firmware-info:
.. _sec-plugins-hook-comm-protocol-firmware-info:
octoprint.comm.firmware.info
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
octoprint.comm.protocol.firmware.info
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs)
@@ -413,10 +475,10 @@ octoprint.comm.firmware.info
:param str firmware_name: The name of the parsed capability
:param dict firmware_data: All data contained in the ``M115`` report
.. _sec-plugins-hook-comm-firmware-capabilities:
.. _sec-plugins-hook-comm-protocol-firmware-capabilities:
octoprint.comm.firmware.capabilities
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
octoprint.comm.firmware.protocol.capabilities
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs)
@@ -762,9 +824,10 @@ octoprint.comm.protocol.scripts
make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match
handled scripts. If not, None should be returned directly.
If the hook handler has something to add to the specified script, it may return a 2-tuple or a 3-tuple with the first entry
If the hook handler has something to add to the specified script, it may return a 2-tuple, a 3-tuple or a 4-tuple with the first entry
defining the prefix (what to *prepend* to the script in question), the second entry defining the postfix (what to
*append* to the script in question), and finally if desired a dictionary of variables to be made available to the script. Both prefix and postfix can be None to signify that nothing should be prepended
*append* to the script in question), and finally if desired a dictionary of variables to be made available to the script on third and additional tags to set on the
commands on fourth position. Both prefix and postfix can be None to signify that nothing should be prepended
respectively appended.
The returned prefix and postfix entries may be either iterables of script lines or a string including newlines of the script lines (which
@@ -903,6 +966,34 @@ octoprint.comm.transport.serial.factory
:rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and
optionally ``baudrate`` and ``timeout`` attributes as described above.
.. _sec-plugins-hook-events-register_custom_events:
octoprint.events.register_custom_events
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: register_custom_events_hook(*args, **kwargs)
Return a list of custom :ref:`events <sec-events>` to register in the system for your plugin.
Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object
will be the returned value transformed into upper case ``CAMEL_CASE`` and prefixed with ``PLUGIN_<IDENTIFIER>``. Their
value will be prefixed with ``plugin_<identifier>_``.
Example:
Consider the following hook part of a plugin with the identifier ``myplugin``. It will register two custom events
in the system, ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_CUSTOM_EVENT`` with value ``plugin_myplugin_my_custom_event``
and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``.
.. code-block:: python
:linenos:
def register_custom_events(*args, **kwargs):
return ["my_custom_event", "my_other_custom_event"]
:return: A list of custom events to register
:rtype: list
.. _sec-plugins-hook-filemanager-analysis-factory:
octoprint.filemanager.analysis.factory
@@ -1029,9 +1120,8 @@ octoprint.printer.factory
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
* ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
* ``user_manager``: The :class:`~octoprint.users.UserManager`
* ``user_manager``: The :class:`~octoprint.access.users.UserManager`
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
If the factory returns anything but ``None``, it will be assigned to the global ``printer`` instance.
@@ -1089,6 +1179,91 @@ octoprint.printer.estimation.factory
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
:rtype: class or function
.. _sec-plugins-hook-octoprint-printer-sdcardupload:
octoprint.printer.sdcardupload
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs)
Via this hook plugins can change the way files are being uploaded to the sd card of the printer.
Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback``
or ``failure_callback`` on the end of the file transfer, depending on whether it was successful or not.
The ``start_callback`` has the following signature:
.. code-block:: python
def start_callback(local_filename, remote_filename):
# ...
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
to be created on the ``sdcard`` storage.
``success_callback`` and ``failure_callback`` both have the following signature:
.. code-block:: python
def success_or_failure_callback(local_filename, remote_filename, elapsed):
# ...
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
to be created on the ``sdcard`` storage. ``elapsed`` is the elapsed time in seconds.
If the hook is going to handle the upload, it must return the (future) remote filename of the file on the ``sdcard``
storage. If it returns ``None`` (or an otherwise falsy value), OctoPrint will interpret this as the hook not going to
handle the file upload, in which case the next hook or - if no other hook is registered - the default implementation
will be called.
**Example**
The following example creates a dummy SD card uploader that does nothing but sleep for ten seconds when a file
is supposed to be uploaded. Note that the long running process of sleeping for ten seconds is extracted into its
own thread, which is important in order to not block the main application!
.. code-block:: python
import threading
import logging
import time
def nop_upload_to_sd(printer, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs):
logger = logging.getLogger(__name__)
remote_name = printer._get_free_remote_name(filename)
logger.info("Starting dummy SDCard upload from {} to {}".format(filename, remote_name))
sd_upload_started(filename, remote_name)
def process():
logger.info("Sleeping 10s...")
time.sleep(10)
logger.info("And done!")
sd_upload_succeeded(filename, remote_name, 10)
thread = threading.Thread(target=process)
thread.daemon = True
thread.start()
return remote_name
__plugin_name__ = "No-op SDCard Upload Test"
__plugin_hooks__ = {
"octoprint.printer.sdcardupload": nop_upload_to_sd
}
.. versionadded:: 1.3.11
:param object printer: the :py:class:`~octoprint.printer.PrinterInterface` instance the hook was called from
:param str filename: filename on the ``local`` storage
:param str path: path of the file in the local file system
:param function sd_upload_started: callback for when the upload started
:param function sd_upload_success: callback for successful finish of upload
:param function sd_upload_failure: callback for failure of upload
:return: the name of the file on the ``sdcard`` storage or ``None``
:rtype: string or ``None``
.. _sec-plugins-hook-server-http-after_request:
octoprint.server.api.after_request
@@ -1211,6 +1386,14 @@ octoprint.server.http.routes
view of the blueprint will thus not be reachable since processing of the request will directly be handed over
to your defined handler class.
.. important::
If you want your route to support CORS if it's enabled in OctoPrint, your `RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_
needs to implement the :class:`~octoprint.server.util.tornado.CorsSupportMixin` for this to work. Note that all of
:class:`~octoprint.server.util.tornado.LargeResponseHandler`, :class:`~octoprint.server.util.tornado.UrlProxyHandler`,
:class:`~octoprint.server.util.tornado.StaticDataHandler` and :class:`~octoprint.server.util.tornado.DeprecatedEndpointHandler`
already implement this mixin.
.. important::
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
@@ -1238,6 +1421,20 @@ octoprint.server.http.routes
:return: a list of 3-tuples with additional routes as defined above
:rtype: list
.. _sec-plugins-hook-server-sockjs-authed:
octoprint.server.sockjs.authed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
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
.. _sec-plugins-hook-server-sockjs-register:
octoprint.server.sockjs.register
@@ -1416,37 +1613,34 @@ octoprint.ui.web.templatetypes
:return: a list of 3-tuples (template type, rule, sorting spec)
:rtype: list
.. _sec-plugins-hook-users-factory:
.. _sec-plugins-hook-timelapse-capture-pre:
octoprint.users.factory
~~~~~~~~~~~~~~~~~~~~~~~
octoprint.timelapse.capture.pre
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
.. py:function:: capture_pre_hook(filename)
Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will
be called only once during initial server startup.
Perform specific actions prior to capturing a timelapse frame.
The provided ``components`` is a dictionary containing the already initialized system components:
``filename`` will be the future path of the frame to be saved.
* ``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`
* ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
:param str filename: The future path of the frame to be saved.
:return: None
:rtype: None
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
.. _sec-plugins-hook-timelapse-capture-post:
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.users.FilebasedUserManager` will be instantiated, linked to the default user storage
file ``~/.octoprint/users.yaml``.
octoprint.timelapse.capture.post
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: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
.. py:function:: capture_post_hook(filename, success)
Perform specific actions after capturing a timelapse frame.
``filename`` will be the path of the frame that should have been saved.
``sucesss`` indicates whether the capture was successful or not.
:param str filename: The path of the frame that should have been saved.
:param boolean success: Indicates whether the capture was successful or not.
:return: None
:rtype: None
+1 -3
View File
@@ -41,10 +41,8 @@ An overview of these properties follows.
OctoPrint's file manager, an instance of :class:`octoprint.filemanager.FileManager`.
``self._printer``
OctoPrint's printer management object, an instance of :class:`octoprint.printer.PrinterInterface`.
``self._app_session_manager``
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
``self._user_manager``
OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`.
OctoPrint's user manager, an instance of :class:`octoprint.access.users.UserManager`.
``self._connectivity_checker``
OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`.
+44 -9
View File
@@ -68,11 +68,14 @@ calls are done is as follows:
* Plugins with a return value that is not ``None`` for :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`
for the provided sorting context will be ordered among each other first. If the returned order number is equal for
two or more implementations, the plugin's identifier will be the next sorting criteria.
* After that follow plugins which returned ``None`` (the default). They are sorted by their identifier.
two or more implementations, they will be sorted first by whether they come bundled with OctoPrint or not, then by
their identifier.
* After that follow plugins which returned ``None`` (the default). They are first sorted by whether they come bundled
with OctoPrint or not, then by their identifier.
Example: Consider three plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
``plugin_a``, ``plugin_b`` and ``plugin_c``. ``plugin_a`` doesn't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
Example: Consider four plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called
``plugin_a``, ``plugin_b``, ``plugin_c`` and ``plugin_d``, the latter coming bundled with OctoPrint. ``plugin_a``
and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`.
``plugin_b`` and ``plugin_c`` both return ``1`` for the sorting context ``StartupPlugin.on_startup``, ``None`` otherwise:
.. code-block:: python
@@ -99,7 +102,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
class PluginB(octoprint.plugin.StartupPlugin):
def get_sorting_key(context):
def get_sorting_key(self, context):
if context == "StartupPlugin.on_startup":
return 1
return None
@@ -120,7 +123,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
class PluginC(octoprint.plugin.StartupPlugin):
def get_sorting_key(context):
def get_sorting_key(self, context):
if context == "StartupPlugin.on_startup":
return 1
return None
@@ -134,13 +137,45 @@ Example: Consider three plugin implementations implementing the :class:`~octopri
__plugin_implementation__ = PluginC()
.. code-block:: python
:linenos:
:caption: plugin_d.py
# in this example this is bundled with OctoPrint
import octoprint.plugin
class PluginD(octoprint.plugin.StartupPlugin):
def on_startup(self, *args, **kwargs):
self._logger.info("PluginD starting up")
def on_after_startup(self, *args, **kwargs):
self._logger.info("PluginD started up")
__plugin_implementation__ = PluginD()
OctoPrint will detect that ``plugin_b`` and ``plugin_c`` define a order number, and since it's identical for both (``1``)
will order both plugins based on their plugin identifier. ``plugin_a`` doesn't define a sort key and hence will be
put after the other two. The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_a``.
will order both plugins based first on their bundling status and then on their plugin identifier.
``plugin_a`` and ``plugin_d`` don't define a sort key and hence will be
put after the other two, with ``plugin_d`` coming *before* ``plugin_a`` since it comes bundled with OctoPrint.
The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_d``, ``plugin_a``.
Now, the execution order of the ``on_after_startup`` method will be determined based on another sorting context,
``StartupPlugin.on_after_startup`` for which all of the plugins return ``None``. Hence, the execution order of the
``on_after_startup`` method will be purely ordered by plugin identifier, ``plugin_a``, ``plugin_b``, ``plugin_c``.
``on_after_startup`` method will be ordered first by bundle status, then by plugin identifier: ``plugin_d``, ``plugin_a``, ``plugin_b``, ``plugin_c``.
This will result in the following messages to be generated:
.. code-block:: none
Plugin B starting up
Plugin C starting up
Plugin D starting up
Plugin A starting up
Plugin D started up
Plugin A started up
Plugin B started up
Plugin C started up
.. _sec-plugins-mixins-injectedproperties:
+43 -30
View File
@@ -220,6 +220,11 @@ onUserLoggedIn(user)
onUserLoggedOut()
Called when a user gets logged out of the web app.
onUserPermissionsChanged(user)
Called when a change in the permissions of the current user is detected. The user data of the just logged in user
will be provided as only parameter. Note that this may also be triggered for not logged in guests if the guest
group is modified. In this case ``user`` will be undefined.
onTabChange(next, current)
Called before the main tab view switches to a new tab, so `before` the new tab becomes visible. Called with the
next (changed to) and current (still visible) tab's hash (e.g. ``#control``). Note that ``current`` might be undefined
@@ -313,13 +318,13 @@ Web interface startup
sequenceDiagram
participant Main
participant onServerConnect
participant fetchSettings
participant bindViewModels
participant DataUpdater
participant LoginStateViewModel
participant SettingsViewModel
participant UiStateViewModel
Note right of DataUpdater: connectCallback = undefined
Note over DataUpdater: connectCallback = undefined
Note over UiStateViewModel: loaded = false
activate Main
@@ -337,52 +342,60 @@ Web interface startup
Main->>+DataUpdater: connectCallback = onServerConnect
Note right of DataUpdater: connectCallback = onServerConnect
DataUpdater-->>-Main: ok
Main->>+onServerConnect: call
onServerConnect->>+LoginStateViewModel: passiveLogin
LoginStateViewModel-->>onServerConnect: ok
onServerConnect-->>Main: ok
deactivate onServerConnect
Main->>+Main: onServerConnect
Main->>+LoginStateViewModel: passiveLogin
LoginStateViewModel-->>Main: ok
Main-->>Main: ok
deactivate Main
deactivate Main
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
Note over Main,LoginStateViewModel: Session available!
LoginStateViewModel-X+onServerConnect: done
Note over Main,UiStateViewModel: Session available!
LoginStateViewModel-X+Main: done
deactivate LoginStateViewModel
deactivate LoginStateViewModel
onServerConnect->>+DataUpdater: initialized
Main->>+DataUpdater: initialized
Note right of DataUpdater: initialized = true
DataUpdater->DataUpdater: trigger stored callbacks
DataUpdater-->>-onServerConnect: ok
onServerConnect-X+Main: done
deactivate onServerConnect
DataUpdater-->>-Main: ok
Main->>+fetchSettings: call
Note right of fetchSettings: trigger onStartup
Main->>+Main: fetchSettings
Note right of Main: trigger onStartup
fetchSettings-->>Main: ok
Main->>+SettingsViewModel: requestData
SettingsViewModel-->>Main: ok
deactivate Main
deactivate Main
fetchSettings->>+fetchSettings: asynchronous settings fetch
fetchSettings->>+bindViewModels: call
SettingsViewModel->>+SettingsViewModel: asynchronous settings fetch
Note over Main,UiStateViewModel: Settings available!
SettingsViewModel-X+Main: done
deactivate SettingsViewModel
deactivate SettingsViewModel
Main->>+Main: bindViewModels
loop for each view model
bindViewModels->bindViewModels: trigger onBeforeBinding
bindViewModels->bindViewModels: trigger onBoundTo
bindViewModels->bindViewModels: trigger onAfterBinding
Main->Main: trigger onBeforeBinding
Main->Main: trigger onBoundTo
Main->Main: trigger onAfterBinding
end
bindViewModels->bindViewModels: trigger onAllBound
Main->Main: trigger onAllBound
opt User is logged in
bindViewModels->>+LoginStateViewModel: onAllBound
Main->>+LoginStateViewModel: onAllBound
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
LoginStateViewModel-->>-bindViewModels: ok
LoginStateViewModel-->>-Main: ok
end
bindViewModels->bindViewModels: trigger onStartupComplete
bindViewModels-->>-fetchSettings: ok
deactivate fetchSettings
deactivate fetchSettings
Main->>+UiStateViewModel: loaded
Note right of UiStateViewModel: loaded = true
UiStateViewModel-->>-Main: ok
Main->Main: trigger onStartupComplete
deactivate Main
deactivate Main
.. _sec-plugins-viewmodels-reconnect:
+7 -7
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
@@ -84,7 +84,7 @@ class CodeBlockExt(CodeBlock):
return node
# replace all created literal_blocks with literal_block_ext instances
return map(find_and_wrap_literal_block, code_block)
return list(map(find_and_wrap_literal_block, code_block))
def _wrap_literal_block(self, node):
literal = literal_block_ext.from_literal_block(node)
@@ -160,10 +160,10 @@ class PygmentsBridgeExt(object):
# for py3, recognize interactive sessions, but do not try parsing...
lexer = sphinx.highlighting.lexers['pycon3']
elif lang == 'guess':
try:
# try:
lexer = sphinx.highlighting.guess_lexer(source)
except Exception:
lexer = sphinx.highlighting.lexers['none']
# except Exception:
# lexer = sphinx.highlighting.lexers['none']
else:
if lang in sphinx.highlighting.lexers:
lexer = sphinx.highlighting.lexers[lang]
@@ -255,4 +255,4 @@ def setup(app):
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
return dict(version="0.1")
return dict(version="0.1")
+7 -8
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
@@ -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:
+5
View File
@@ -0,0 +1,5 @@
[pytest]
testpaths = src tests
addopts = --doctest-modules
--doctest-repr=octoprint.util:pp
--ignore=src/octoprint/vendor
+7 -3
View File
@@ -1,4 +1,6 @@
#!/usr/bin/env python2
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
@@ -8,15 +10,17 @@ basedir = os.path.dirname(os.path.realpath(__file__))
old = os.path.join(basedir, "octoprint")
if os.path.exists(old):
# rename left-overs from old file structure
print """
print("""
Found left-overs from old file structure, renaming to
"octoprint.backup". Please remove this manually (I don't
dare to do so myself since you might have changes in there
I don't know anything about).
"""
""")
os.rename(old, os.path.join(basedir, "octoprint.backup"))
sys.path.insert(0, os.path.join(basedir, "src"))
import octoprint
if len(sys.argv) == 1:
sys.argv.append("serve")
octoprint.main()
+17
View File
@@ -0,0 +1,17 @@
# init/systemd files for OctoPrint.
Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octoprint. If you have a different
setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly.
## init
```
octoprint.default => /etc/default/octoprint
octoprint.init => /etc/init.d/octoprint
```
## systemd
```
octoprint.service => /etc/systemd/system/octoprint.service
```
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=The snappy web interface for your 3D printer
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=pi
ExecStart=/home/pi/OctoPrint/venv/bin/octoprint
[Install]
WantedBy=multi-user.target
+3
View File
@@ -1,6 +1,9 @@
[metadata]
license_file = LICENSE.txt
[bdist_wheel]
universal = 1
[versioneer]
VCS = git
style = pep440-tag
+92 -43
View File
@@ -9,75 +9,97 @@ import versioneer
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
import octoprint_setuptools
import setuptools
#-----------------------------------------------------------------------------------------------------------------------
# Supported python versions
PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11
# 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
# changes that might affect plugins, or due to other observed problems
"flask>=0.10.1,<0.11", # newer versions require newer Jinja versions
"flask>=0.12,<0.13", # newer versions require newer Jinja versions
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
# 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
"Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"Flask-Principal>=0.4,<0.5",
"Flask-Login>=0.4.1,<0.5",
"Flask-Babel>=0.12,<0.13",
"Flask-Assets>=0.12,<0.13",
"werkzeug>=0.14.1,<0.15",
"PyYAML>=3.13,<4",
"markdown>=3.0,<3.1",
"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.1,<3.2",
"pyserial>=3.4,<3.5",
"netaddr>=0.7.19,<0.8",
"watchdog>=0.9.0,<0.10",
"sarge==0.1.5post0",
"netifaces>=0.10.7,<0.11",
"pylru>=1.1,<1.2",
"netifaces>=0.10.9,<0.11",
"pylru>=1.2,<1.3",
"rsa>=4.0,<5",
"pkginfo>=1.4.2,<1.5",
"requests>=2.20.0,<3",
"semantic_version>=2.6,<2.7",
"psutil>=5.4.8,<5.5",
"pkginfo>=1.5.0.1,<1.6",
"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",
"chainmap>=1.0.2,<1.1",
"future>=0.17,<0.18",
"scandir>=1.9,<1.10",
"websocket-client>=0.53,<0.54",
"python-dateutil>=2.7.5,<2.8",
"wrapt>=1.10.11,<1.11",
"futures>=3.2,<3.3",
"emoji>=0.5.1,<0.6",
"monotonic>=1.5,<1.6",
"frozendict>=1.2,<1.3"
"future>=0.18.2,<0.19",
"websocket-client>=0.56,<0.57",
"wrapt>=1.11.2,<1.12",
"emoji>=0.5.4,<0.6",
"frozendict>=1.2,<1.3",
"sentry-sdk==0.13.2",
"filetype>=1.0.5,<2"
]
if sys.platform == "darwin":
INSTALL_REQUIRES.append("appdirs>=1.4.0")
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"futures>=3.3,<3.4",
"monotonic>=1.5,<1.6",
"scandir>=1.10,<1.11",
"chainmap>=1.0.3,<1.1",
"typing>=3.7.4.1,<4"
]
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"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",
"nose>=1.3.7,<1.4",
# Testing dependencies - SEE ALSO tox.ini
"mock>=3.0.5,<4",
"pytest==4.6.6",
"pytest-doctest-custom>=1.0.0,<1.1",
"ddt",
# linter
"flake8",
# Documentation dependencies
"sphinx>=1.8.1,<1.9",
"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
@@ -89,6 +111,23 @@ EXTRA_REQUIRES = dict(
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
# adapted from https://hynek.me/articles/conditional-python-dependencies/
if int(setuptools.__version__.split(".", 1)[0]) < 18:
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
# would get lost there
assert "bdist_wheel" not in sys.argv
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
if sys.version_info[0] < 3:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
if sys.platform == "darwin":
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
else:
# environment markers supported
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
#-----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
@@ -99,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)
@@ -114,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()
@@ -137,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",
]
@@ -159,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
@@ -180,6 +225,10 @@ def params():
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"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",
@@ -192,7 +241,7 @@ def params():
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
project_urls={
"Community Forum": "https://discourse.octoprint.org",
"Community Forum": "https://community.octoprint.org",
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
"Source": "https://github.com/foosel/OctoPrint",
"Funding": "https://donate.octoprint.org"
+33 -17
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env python2
# coding=utf-8
from __future__ import absolute_import, division, print_function
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import io
import sys
import logging as log
@@ -103,8 +104,12 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
if callable(after_logging):
after_logging(**kwargs)
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
safe_mode = safe_mode or settings_safe_mode
settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None
settings_incomplete_startup_safemode = "incomplete_startup" \
if settings.getBoolean(["server", "incompleteStartup"]) \
and not settings.getBoolean(["server", "ignoreIncompleteStartup"]) \
else None
safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode
kwargs["safe_mode"] = safe_mode
if callable(after_safe_mode):
after_safe_mode(**kwargs)
@@ -141,7 +146,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
ignore_blacklist=ignore_blacklist,
connectivity_checker=connectivity_checker)
except Exception as ex:
raise FatalStartupError("Could not initialize settings manager", cause=ex)
raise FatalStartupError("Could not initialize plugin manager", cause=ex)
kwargs["plugin_manager"] = plugin_manager
if callable(after_plugin_manager):
@@ -293,7 +298,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
config_from_file = {}
if os.path.exists(logging_file) and os.path.isfile(logging_file):
import yaml
with open(logging_file, "r") as f:
with io.open(logging_file, 'rt', encoding='utf-8') as f:
config_from_file = yaml.safe_load(f)
# we merge that with the default config
@@ -342,9 +347,12 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
import os
# we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins
import octoprint.plugins
logger = log.getLogger(__name__ + ".startup")
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True),
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), "octoprint.plugins", True),
settings.getBaseFolder("plugins")]
plugin_entry_points = ["octoprint.plugin"]
plugin_disabled_list = settings.get(["plugins", "_disabled"])
@@ -363,13 +371,16 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
return True
plugin_validators.append(validator)
compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"])
from octoprint.plugin import plugin_manager
pm = plugin_manager(init=True,
plugin_folders=plugin_folders,
plugin_entry_points=plugin_entry_points,
plugin_disabled_list=plugin_disabled_list,
plugin_blacklist=plugin_blacklist,
plugin_validators=plugin_validators)
plugin_validators=plugin_validators,
compatibility_ignored_list=compatibility_ignored_list)
settings_overlays = dict()
disabled_from_overlays = dict()
@@ -399,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 = []
@@ -482,7 +495,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
if os.stat(path).st_mtime + ttl < time.time():
return None
with bom_aware_open(path, encoding="utf-8", mode="r") as f:
with bom_aware_open(path, encoding="utf-8", mode='rt') as f:
result = yaml.safe_load(f)
if isinstance(result, list):
@@ -496,12 +509,12 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
if cache is not None:
try:
with bom_aware_open(cache, encoding="utf-8", mode="w") as f:
with bom_aware_open(cache, encoding="utf-8", mode='wt') as f:
yaml.safe_dump(result, f)
except:
logger.info("Fetched plugin blacklist but couldn't write it to its cache file.")
except:
logger.info("Unable to fetch plugin blacklist from {}, proceeding without it.".format(url))
except Exception as e:
logger.info("Fetched plugin blacklist but couldn't write it to its cache file: %s", e)
except Exception as e:
logger.info("Unable to fetch plugin blacklist from {}, proceeding without it: {}".format(url, e))
return result
try:
@@ -528,7 +541,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
logger.info("Blacklist processing done")
return blacklist
except:
except Exception:
logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.")
@@ -595,6 +608,9 @@ def main():
# cut off stuff from the beginning
args = args[-1 * sys_args_length:] if sys_args_length else []
from octoprint.util.fixes import patch_sarge_async_on_py2
patch_sarge_async_on_py2()
from octoprint.cli import octo
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
+3 -3
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env python2
# coding=utf-8
from __future__ import absolute_import, division, print_function
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
if __name__ == "__main__":
import octoprint
+46 -11
View File
@@ -1,3 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
@@ -9,13 +11,14 @@
# versioneer-0.15+dev (https://github.com/warner/python-versioneer)
"""Git implementation of _version.py."""
from __future__ import absolute_import, division, print_function
import errno
import io
import os
import re
import subprocess
import sys
import logging
def get_keywords():
@@ -41,7 +44,7 @@ def get_config():
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440-post"
cfg.style = "pep440-tag"
cfg.tag_prefix = ""
cfg.parentdir_prefix = ""
cfg.versionfile_source = "src/octoprint/_version.py"
@@ -130,7 +133,7 @@ def git_get_keywords(versionfile_abs):
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
f = io.open(versionfile_abs, "rt", encoding="utf-8")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
@@ -156,11 +159,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
refs = set(r.strip() for r in refnames.strip("()").split(","))
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
tags = set(r[len(TAG):] for r in refs if r.startswith(TAG))
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
@@ -169,7 +172,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
tags = set(r for r in refs if re.search(r'\d', r))
if verbose:
print("discarding '%s', no digits" % ",".join(refs-tags))
@@ -254,7 +257,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
abbrev_ref_out = run_command(GITS,
["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
if abbrev_ref_out is not None:
if abbrev_ref_out is not None and abbrev_ref_out != "HEAD":
pieces["branch"] = abbrev_ref_out.strip()
# now we have TAG-NUM-gHEX or HEX
@@ -305,17 +308,18 @@ def git_parse_lookup_file(path):
if not os.path.exists(path):
return []
import re
lookup = []
with open(path, "r") as f:
with io.open(path, "rt", encoding="utf-8") as f:
for line in f:
if '#' in line:
line = line[:line.rindex("#")]
line = line[:line.index("#")]
line = line.strip()
if not line:
continue
try:
split_line = map(lambda x: x.strip(), line.split())
split_line = list(map(lambda x: x.strip(), line.split()))
if not len(split_line):
continue
@@ -336,7 +340,8 @@ def git_parse_lookup_file(path):
continue
lookup.append(entry)
except:
except Exception:
logging.getLogger(__name__).exception("Versioneer problem")
break
return lookup
@@ -354,6 +359,9 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
current_branch = stdout.strip()
if current_branch == "HEAD":
raise NotThisMethod("not on a branch")
for matcher, render, tag, ref_commit in lookup:
if matcher.match(current_branch):
if tag is None or ref_commit is None:
@@ -441,6 +449,31 @@ def render_pep440(pieces):
return rendered
def render_pep440_tag(pieces):
"""TAG[[.postDISTANCE].dev0+gHEX] -- Just the tag if not dirty, else more info
Useful for projects that want commit based tracking on some branches
but have the master branch only report tags, to allow for commits that
do not modify actual code (e.g. to .github/* or docs).
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]+gHEX
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
return rendered
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
@@ -591,6 +624,8 @@ def render(pieces, style):
rendered = render_pep440_old(pieces)
elif style == "pep440-dev":
rendered = render_pep440_dev(pieces)
elif style == "pep440-tag":
rendered = render_pep440_tag(pieces)
elif style == "git-describe":
rendered = render_git_describe(pieces)
elif style == "git-describe-long":
+7
View File
@@ -0,0 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
ADMIN_GROUP = "admins"
USER_GROUP = "users"
GUEST_GROUP = "guests"
READONLY_GROUP = "readonly"
+601
View File
@@ -0,0 +1,601 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Marc Hannappel <salandora@gmail.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import io
import logging
import os
from functools import partial
import yaml
from past.builtins import basestring
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 octoprint.vendor.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"""
GroupNeed = partial(Need, 'group')
GroupNeed.__doc__ = """A need with the method preset to `"group"`."""
class GroupPermission(Permission):
def __init__(self, key):
need = GroupNeed(key)
super(GroupPermission, self).__init__(need)
class GroupManager(object):
@classmethod
def default_permissions_for_group(cls, group):
result = []
for permission in Permissions.all():
if group in permission.default_groups:
result.append(permission)
return result
def __init__(self):
self._logger = logging.getLogger(__name__)
self._group_change_listeners = []
self._init_defaults()
@property
def groups(self):
return []
@property
def admin_group(self):
return self.find_group(ADMIN_GROUP)
@property
def user_group(self):
return self.find_group(USER_GROUP)
@property
def guest_group(self):
return self.find_group(GUEST_GROUP)
def _init_defaults(self):
self.add_group(ADMIN_GROUP,
"Admins",
"Administrators",
self.default_permissions_for_group(ADMIN_GROUP),
[],
changeable=False,
removable=False,
save=False)
self.add_group(USER_GROUP,
"Users",
"All logged in users",
self.default_permissions_for_group(USER_GROUP),
[],
default=True,
removable=False,
toggleable=False,
save=False)
self.add_group(GUEST_GROUP,
"Guests",
"Anyone who is not currently logged in",
self.default_permissions_for_group(GUEST_GROUP),
[],
removable=False,
toggleable=False,
save=False),
self.add_group(READONLY_GROUP,
"Read-only Access",
"Group to gain read-only access",
self.default_permissions_for_group(READONLY_GROUP),
[],
changeable=False,
removable=False,
save=False)
def register_listener(self, listener):
self._group_change_listeners.append(listener)
def unregister_listener(self, listener):
self._group_change_listeners.remove(listener)
def add_group(self, key, name, description, permissions, subgroups,
default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True):
pass
def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True):
pass
def remove_group(self, key, save=True, notify=True):
pass
def find_group(self, key):
return None
def _to_permissions(self, *permissions):
return list(filter(lambda x: x is not None,
[Permissions.find(permission) for permission in permissions]))
def _from_permissions(self, *permissions):
return [permission.key for permission in permissions]
def _from_groups(self, *groups):
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])
def _to_group(self, group):
# noinspection PyCompatibility
if isinstance(group, Group):
return group
elif isinstance(group, basestring):
return self.find_group(group)
elif isinstance(group, dict):
return self.find_group(group.get("key"))
else:
return None
def _notify_listeners(self, action, group, *args, **kwargs):
method = "on_group_{}".format(action)
for listener in self._group_change_listeners:
try:
getattr(listener, method)(group, *args, **kwargs)
except Exception:
self._logger.exception("Error notifying listener {!r} via {}".format(listener, method))
class GroupChangeListener(object):
def on_group_added(self, group):
pass
def on_group_removed(self, group):
pass
def on_group_permissions_changed(self, group, added=None, removed=None):
pass
def on_group_subgroups_changed(self, group, added=None, removed=None):
pass
class FilebasedGroupManager(GroupManager):
def __init__(self, path=None):
if path is None:
path = settings().get(["accessControl", "groupfile"])
if path is None:
path = os.path.join(settings().getBaseFolder("base"), "groups.yaml")
self._groupfile = path
self._groups = dict()
self._dirty = False
GroupManager.__init__(self)
self._load()
def _load(self):
if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile):
try:
with io.open(self._groupfile, 'rt', encoding='utf-8') as f:
data = yaml.safe_load(f)
if not "groups" in data:
groups = data
data = dict(groups=groups)
groups = data.get("groups", dict())
tracked_permissions = data.get("tracked", list())
for key, attributes in groups.items():
if key in self._groups:
# group is already there (from the defaults most likely)
if not self._groups[key].is_changeable():
# group may not be changed -> bail
continue
removable = self._groups[key].is_removable()
changeable = self._groups[key].is_changeable()
toggleable = self._groups[key].is_toggleable()
else:
removable = True
changeable = True
toggleable = True
permissions = self._to_permissions(*attributes.get("permissions", []))
default_permissions = self.default_permissions_for_group(key)
for permission in default_permissions:
if not permission.key in tracked_permissions and not permission in permissions:
permissions.append(permission)
subgroups = attributes.get("subgroups", [])
group = Group(key, attributes.get("name", ""),
description=attributes.get("description", ""),
permissions=permissions,
subgroups=subgroups,
default=attributes.get("default", False),
removable=removable,
changeable=changeable,
toggleable=toggleable)
self._groups[key] = group
for group in self._groups.values():
group._subgroups = self._to_groups(*group._subgroups)
except Exception:
self._logger.exception("Error while loading groups from file {}".format(self._groupfile))
def _save(self, force=False):
if self._groupfile is None or not self._dirty and not force:
return
groups = dict()
for key in self._groups.keys():
group = self._groups[key]
groups[key] = dict(
name=group._name,
description=group._description,
permissions=self._from_permissions(*group._permissions),
subgroups=self._from_groups(*group._subgroups),
default=group._default
)
data = dict(groups=groups,
tracked=[x.key for x in Permissions.all()])
with atomic_write(self._groupfile, mode='wt', permissions=0o600, max_permissions=0o666) as f:
import yaml
yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True)
self._dirty = False
self._load()
@property
def groups(self):
return list(self._groups.values())
@property
def default_groups(self):
return [group for group in self._groups.values() if group.is_default()]
def find_group(self, key):
if key is None:
return None
return self._groups.get(key)
def add_group(self, key, name, description, permissions, subgroups, default=False, removable=True,
changeable=True, toggleable=True, overwrite=False, notify=True, save=True):
if key in self._groups and not overwrite:
raise GroupAlreadyExists(key)
if not permissions:
permissions = []
permissions = self._to_permissions(*permissions)
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
subgroups = self._to_groups(*subgroups)
assert(all(map(lambda g: isinstance(g, Group), subgroups)))
group = Group(key, name,
description=description,
permissions=permissions,
subgroups=subgroups,
default=default,
changeable=changeable,
removable=removable,
toggleable=toggleable)
self._groups[key] = group
if save:
self._dirty = True
self._save()
if notify:
self._notify_listeners("added", group)
def remove_group(self, key, save=True, notify=True):
"""Removes a Group by key"""
group = self._to_group(key)
if group is None:
raise UnknownGroup(key)
if not group.is_removable():
raise GroupUnremovable(key)
del self._groups[key]
self._dirty = True
if save:
self._save()
if notify:
self._notify_listeners("removed", group)
def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True):
group = self._to_group(key)
if group is None:
raise UnknownGroup(key)
if not group.is_changeable():
raise GroupCantBeChanged(key)
if description is not None and description != group.get_description():
group.change_description(description)
self._dirty = True
notifications = []
if permissions is not None:
permissions = self._to_permissions(*permissions)
assert (all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
removed_permissions = list(set(group._permissions) - set(permissions))
added_permissions = list(set(permissions) - set(group._permissions))
if removed_permissions:
self._dirty |= group.remove_permissions_from_group(removed_permissions)
if added_permissions:
self._dirty |= group.add_permissions_to_group(added_permissions)
notifications.append((("permissions_changed", group),
dict(added=added_permissions, removed=removed_permissions)))
if subgroups is not None:
subgroups = self._to_groups(*subgroups)
assert(all(map(lambda g: isinstance(g, Group), subgroups)))
removed_subgroups = list(set(group._subgroups) - set(subgroups))
added_subgroups = list(set(subgroups) - set(group._subgroups))
if removed_subgroups:
self._dirty = group.remove_subgroups_from_group(removed_subgroups)
if added_subgroups:
self._dirty = group.add_subgroups_to_group(added_subgroups)
notifications.append((("subgroups_changed", group),
dict(added=added_subgroups, removed=removed_subgroups)))
if default is not None:
group.change_default(default)
self._dirty = True
if self._dirty:
if save:
self._save()
if notify:
for args, kwargs in notifications:
self._notify_listeners(*args, **kwargs)
class GroupAlreadyExists(Exception):
def __init__(self, key):
Exception.__init__(self, "Group %s already exists" % key)
class UnknownGroup(Exception):
def __init__(self, key):
Exception.__init__(self, "Unknown group: %s" % key)
class GroupUnremovable(Exception):
def __init__(self, key):
Exception.__init__(self, "Group can't be removed: %s" % key)
class GroupCantBeChanged(Exception):
def __init__(self, key):
Exception.__init__(self, "Group can't be changed: %s" % key)
class Group(object):
def __init__(self, key, name, description="", permissions=None, subgroups=None, default=False, removable=True, changeable=True, toggleable=True):
self._key = key
self._name = name
self._description = description
self._permissions = permissions
self._subgroups = subgroups
self._default = default
self._removable = removable
self._changeable = changeable
self._toggleable = toggleable
def as_dict(self):
from octoprint.access.permissions import OctoPrintPermission
return dict(
key=self.key,
name=self.get_name(),
description=self._description,
permissions=list(map(lambda p: p.key, self._permissions)),
subgroups=list(map(lambda g: g.key, self._subgroups)),
needs=OctoPrintPermission.convert_needs_to_dict(self.needs),
default=self._default,
removable=self._removable,
changeable=self._changeable,
toggleable=self._toggleable
)
@property
def key(self):
return self._key
def get_name(self):
return self._name
def get_description(self):
return self._description
def is_default(self):
return self._default
def is_changeable(self):
return self._changeable
def is_removable(self):
return self._removable
def is_toggleable(self):
return self._toggleable
def add_permissions_to_group(self, permissions):
"""Adds a list of permissions to a group"""
if not self.is_changeable():
raise GroupCantBeChanged(self.key)
# Make sure the permissions variable is of type list
if not isinstance(permissions, list):
permissions = [permissions]
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
dirty = False
for permission in permissions:
if permissions not in self.permissions:
self._permissions.append(permission)
dirty = True
return dirty
def remove_permissions_from_group(self, permissions):
"""Removes a list of permissions from a group"""
if not self.is_changeable():
raise GroupCantBeChanged(self.key)
# Make sure the permissions variable is of type list
if not isinstance(permissions, list):
permissions = [permissions]
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
dirty = False
for permission in permissions:
if permission in self._permissions:
self._permissions.remove(permission)
dirty = True
return dirty
def add_subgroups_to_group(self, subgroups):
"""Adds a list of subgroups to a group"""
if not self.is_changeable():
raise GroupCantBeChanged(self.key)
# Make sure the subgroups variable is of type list
if not isinstance(subgroups, list):
subgroups = [subgroups]
assert(all(map(lambda g: isinstance(g, Group), subgroups)))
dirty = False
for group in subgroups:
if group.is_toggleable() and group not in self._subgroups:
self._subgroups.append(group)
dirty = True
return dirty
def remove_subgroups_from_group(self, subgroups):
"""Removes a list of subgroups from a group"""
"""Adds a list of subgroups to a group"""
if not self.is_changeable():
raise GroupCantBeChanged(self.key)
# Make sure the subgroups variable is of type list
if not isinstance(subgroups, list):
subgroups = [subgroups]
assert (all(map(lambda g: isinstance(g, Group), subgroups)))
dirty = False
for group in subgroups:
if group.is_toggleable() and group in self._subgroups:
self._subgroups.remove(group)
dirty = True
return dirty
def change_default(self, default):
"""Changes the default flag of a Group"""
if not self.is_changeable():
raise GroupCantBeChanged(self.key)
self._default = default
def change_description(self, description):
"""Changes the description of a group"""
self._description = description
@property
def permissions(self):
if Permissions.ADMIN in self._permissions:
return Permissions.all()
return list(filter(lambda p: p is not None, self._permissions))
@property
def subgroups(self):
return filter(lambda g: g is not None, self._subgroups)
@property
def needs(self):
needs = set()
needs.add(GroupNeed(self.key))
for p in self.permissions:
needs = needs.union(p.needs)
for g in self.subgroups:
needs = needs.union(g.needs)
return needs
def has_permission(self, permission):
if Permissions.ADMIN.get_name() in self._permissions:
return True
return permission.needs.issubset(self.needs)
def __repr__(self):
return '{}("{}", "{}", description="{}", permissions={!r}, ' \
'default={}, removable={}, changeable={})'.format(self.__class__.__name__,
self._key,
self._name,
self._description,
self._permissions,
bool(self._default),
bool(self._removable),
bool(self._changeable))
def __hash__(self):
return self.key.__hash__()
def __eq__(self, other):
return isinstance(other, Group) and other.key == self.key
+368
View File
@@ -0,0 +1,368 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Marc Hannappel <salandora@gmail.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
from future.utils import with_metaclass
from flask import g, abort
from flask_babel import gettext
from octoprint.vendor.flask_principal import Permission, PermissionDenied, RoleNeed, Need
from functools import wraps
from collections import OrderedDict, defaultdict
# noinspection PyCompatibility
from past.builtins import basestring
from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP
class OctoPrintPermission(Permission):
@classmethod
def convert_needs_to_dict(cls, needs):
ret_needs = defaultdict(list)
for need in needs:
if need.value not in ret_needs[need.method]:
ret_needs[need.method].append(need.value)
return ret_needs
@classmethod
def convert_to_needs(cls, needs):
result = []
for need in needs:
# noinspection PyCompatibility
if isinstance(need, Need):
result.append(need)
elif isinstance(need, Permission):
result += need.needs
elif isinstance(need, basestring):
result.append(RoleNeed(need))
return result
def __init__(self, name, description, *needs, **kwargs):
self._name = name
self._description = description
self._dangerous = kwargs.pop("dangerous", False)
self._default_groups = kwargs.pop("default_groups", [])
self._key = None
Permission.__init__(self, *self.convert_to_needs(needs))
def as_dict(self):
return dict(
key=self.key,
name=self.get_name(),
dangerous=self._dangerous,
default_groups=self._default_groups,
description=self.get_description(),
needs=self.convert_needs_to_dict(self.needs)
)
@property
def key(self):
return self._key
@key.setter
def key(self, value):
self._key = value
@property
def default_groups(self):
return self._default_groups
def get_name(self):
return self._name
def get_description(self):
return self._description
def union(self, other):
"""Create a new OctoPrintPermission with the requirements of the union of this
and other.
:param other: The other permission
"""
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
p.excludes.update(self.excludes.union(other.excludes))
return p
def difference(self, other):
"""Create a new OctoPrintPermission consisting of requirements in this
permission and not in the other.
"""
p = self.__class__(self._name, self._description, *self.needs.difference(other.needs))
p.excludes.update(self.excludes.difference(other.excludes))
return p
def __repr__(self):
return '{}({!r}, {!r}, {})'.format(self.__class__.__name__,
self.get_name(),
self.get_description(),
', '.join(map(repr, self.needs)))
def __hash__(self):
return self.get_name().__hash__()
def __eq__(self, other):
return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
class PluginOctoPrintPermission(OctoPrintPermission):
def __init__(self, *args, **kwargs):
self.plugin = kwargs.pop("plugin", None)
OctoPrintPermission.__init__(self, *args, **kwargs)
def as_dict(self):
result = OctoPrintPermission.as_dict(self)
result["plugin"] = self.plugin
return result
class PluginIdentityContext(object):
"""Identity context for not initialized Permissions
Needed to support @Permissions.PLUGIN_X_Y.require()
Will search the permission when needed
"""
def __init__(self, key, http_exception=None):
self.key = key
self.http_exception = http_exception
"""The permission of this principal
"""
@property
def identity(self):
"""The identity of this principal
"""
return g.identity
def can(self):
"""Whether the identity has access to the permission
"""
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
return permission.can()
def __call__(self, f):
@wraps(f)
def _decorated(*args, **kw):
with self:
rv = f(*args, **kw)
return rv
return _decorated
def __enter__(self):
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
# check the permission here
if not permission.can():
if self.http_exception:
abort(self.http_exception, permission)
raise PermissionDenied(permission)
def __exit__(self, *args):
return False
class PluginPermissionDecorator(Permission):
"""Decorator Class for not initialized Permissions
Needed to support @Permissions.PLUGIN_X_Y.require()
"""
def __init__(self, key):
self.key = key
def require(self, http_exception=None):
return PluginIdentityContext(self.key, http_exception)
class PermissionsMetaClass(type):
permissions = OrderedDict()
def __new__(mcs, name, bases, args):
cls = type.__new__(mcs, name, bases, args)
for key, value in args.items():
if isinstance(value, OctoPrintPermission):
value.key = key
mcs.permissions[key] = value
delattr(cls, key)
return cls
def __setattr__(cls, key, value):
if isinstance(value, OctoPrintPermission):
if key in cls.permissions:
raise PermissionAlreadyExists(key)
value.key = key
cls.permissions[key] = value
def __getattr__(cls, key):
permission = cls.permissions.get(key)
if key.startswith("PLUGIN_") and permission is None:
return PluginPermissionDecorator(key)
return permission
def all(cls):
return list(cls.permissions.values())
def filter(cls, cb):
return list(filter(cb, cls.all()))
def find(cls, p, filter=None):
key = None
if isinstance(p, OctoPrintPermission):
key = p.key
elif isinstance(p, dict):
key = p.get("key")
elif isinstance(p, basestring):
key = p
if key is None:
return None
return cls.match(lambda p: p.key == key, filter=filter)
def match(cls, match, filter=None):
if callable(filter):
permissions = cls.filter(filter)
else:
permissions = cls.all()
for permission in permissions:
if match(permission):
return permission
return None
class Permissions(with_metaclass(PermissionsMetaClass)):
# Special permission
ADMIN = OctoPrintPermission("Admin",
gettext("Admin is allowed to do everything"),
RoleNeed("admin"),
dangerous=True,
default_groups=[ADMIN_GROUP])
STATUS = OctoPrintPermission("Status",
gettext("Allows to gather status information, e.g. job progress, "
"printer state, temperatures, ..."),
RoleNeed("status"),
default_groups=[USER_GROUP, READONLY_GROUP])
CONNECTION = OctoPrintPermission("Connection",
gettext("Allows to connect to and disconnect from a printer"),
RoleNeed("connection"),
default_groups=[USER_GROUP])
WEBCAM = OctoPrintPermission("Webcam",
gettext("Allows to watch the webcam stream"),
RoleNeed("webcam"),
default_groups=[USER_GROUP, READONLY_GROUP])
SYSTEM = OctoPrintPermission("System",
gettext("Allows to run system commands, e.g. restart OctoPrint, "
"shutdown or reboot the system"),
RoleNeed("system"),
dangerous=True)
FILES_LIST = OctoPrintPermission("File List",
gettext("Allows to retrieve a list of all uploaded files, including"
"their metadata (e.g. date, file size, analysis results, ...)"),
RoleNeed("files_list"),
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_UPLOAD = OctoPrintPermission("File Upload",
gettext("Allows users to upload new files"),
RoleNeed("files_upload"),
default_groups=[USER_GROUP])
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,
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_DELETE = OctoPrintPermission("File Delete",
gettext("Allows users to delete files"),
RoleNeed("files_delete"), FILES_LIST,
default_groups=[USER_GROUP])
FILES_SELECT = OctoPrintPermission("File Select",
gettext("Allows to select a file for printing"),
RoleNeed("files_select"), FILES_LIST,
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,
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,
default_groups=[USER_GROUP, READONLY_GROUP])
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
gettext("Allows to watch the terminal tab but not to send commands "
"to the printer from it"),
RoleNeed("monitor_terminal"),
default_groups=[USER_GROUP, READONLY_GROUP])
CONTROL = OctoPrintPermission("Control",
gettext("Allows to control of the printer by using the temperature controls,"
"the control tab or sending commands through the terminal."),
RoleNeed("control"),
default_groups=[USER_GROUP])
SLICE = OctoPrintPermission("Slice",
gettext("Allows to slice files"),
RoleNeed("slice"),
default_groups=[USER_GROUP])
TIMELAPSE_LIST = OctoPrintPermission("Timelapse List",
gettext("Allows to list timelapse videos"),
RoleNeed("timelapse_list"),
default_groups=[USER_GROUP, READONLY_GROUP])
TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download",
gettext("Allows to download timelapse videos"),
RoleNeed("timelapse_download"),
default_groups=[USER_GROUP, READONLY_GROUP])
TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete",
gettext("Allows to delete timelapse videos and unrendered timelapses"),
RoleNeed("timelapse_delete"),
default_groups=[USER_GROUP])
TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin",
gettext("Allows to change the timelapse settings and delete or "
"render unrendered timelapses. Includes the \"Timelapse List\","
"\"Timelapse Delete\" and \"Timelapse Download\" permissions"),
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP])
SETTINGS = OctoPrintPermission("Settings",
gettext("Allows to manage settings"),
RoleNeed("settings"),
dangerous=True)
class PermissionAlreadyExists(Exception):
def __init__(self, permission):
Exception.__init__(self, "Permission %s already exists" % permission)
class UnknownPermission(Exception):
def __init__(self, permissionname):
Exception.__init__(self, "Unknown permission: %s" % permissionname)
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -1,11 +1,12 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import octoprint
import sys
@@ -137,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)
+7 -5
View File
@@ -1,10 +1,11 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
#~~ "octoprint util" commands
@@ -34,6 +35,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
import time
import yaml
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
throttle_callback = None
@@ -52,7 +54,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
start_time = time.time()
start_time = monotonic_time()
progress_callback = None
if progress:
@@ -68,9 +70,9 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
max_extruders=maxt,
g90_extruder=g90_extruder)
click.echo("DONE:{}s".format(time.time() - start_time))
click.echo("DONE:{}s".format(monotonic_time() - start_time))
click.echo("RESULTS:")
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=4, allow_unicode=True))
if __name__ == "__main__":
gcode_command()
+10 -6
View File
@@ -1,10 +1,13 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import io
import json
import octoprint_client
@@ -12,6 +15,7 @@ import octoprint_client
from octoprint.cli import get_ctx_obj_option, bulk_options
from octoprint import init_settings, FatalStartupError
from past.builtins import unicode
class JsonStringParamType(click.ParamType):
name = "json"
@@ -19,7 +23,7 @@ class JsonStringParamType(click.ParamType):
def convert(self, value, param, ctx):
try:
return json.loads(value)
except:
except Exception:
self.fail("%s is not a valid json string" % value, param, ctx)
@@ -143,16 +147,16 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with open(file_path, "rb") as fp:
with io.open(file_path, 'rt') as fp:
data = json.load(fp)
else:
import yaml
with open(file_path, "rb") as fp:
with io.open(file_path, 'rt') as fp:
data = yaml.safe_load(fp)
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with open(file_path, "rb") as fp:
with io.open(file_path, 'rb') as fp:
data = fp.read()
r = ctx.obj.client.post(path, data, timeout=timeout)
+6 -5
View File
@@ -1,11 +1,12 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
from octoprint import init_settings, FatalStartupError
@@ -17,7 +18,7 @@ import pprint
def _to_settings_path(path):
if not isinstance(path, (list, tuple)):
path = filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
return path
def _set_helper(settings, path, value, data_type=None):
@@ -207,7 +208,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
elif as_raw:
output = value
else:
@@ -232,7 +233,7 @@ def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
elif as_raw:
output = value
else:
+5 -3
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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'
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import click
click.disable_unicode_literals_warning = True
from past.builtins import basestring
@@ -116,7 +117,8 @@ class OctoPrintDevelCommands(click.MultiCommand):
if key in options:
val = options[key]
else:
raw = raw if isinstance(raw, basestring) else str(raw)
if not isinstance(raw, basestring):
raw = str(raw)
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
if not no_input:
+7 -5
View File
@@ -1,11 +1,12 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_option
@@ -88,11 +89,12 @@ class OctoPrintPluginCommands(click.MultiCommand):
commands = hook(self, pass_octoprint_ctx)
for command in commands:
if not isinstance(command, click.Command):
self._logger.warn("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
self._logger.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
continue
result[name + self.sep + command.name] = command
except:
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
except Exception:
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
extra=dict(plugin=name))
return result
+43 -17
View File
@@ -1,17 +1,18 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
import sys
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode,
def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode,
ignore_blacklist, octoprint_daemon=None):
"""Initializes the environment and starts up the server."""
@@ -26,6 +27,15 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if safe_mode == "flag":
reason = "command line flag"
elif safe_mode == "settings":
reason = "setting in config.yaml"
elif safe_mode == "incomplete_startup":
reason = "problem during last startup"
else:
reason = "unknown"
logger.info("Reason for safe mode: {}".format(reason))
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
@@ -101,6 +111,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
environment_detector=environment_detector,
host=host,
port=port,
v6_only=v6_only,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
@@ -111,9 +122,13 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
server_options = bulk_options([
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
help="Specify the host on which to bind the server."),
help="Specify the host address on which to bind the server."),
click.option("--port", type=click.INT, callback=set_ctx_obj_option,
help="Specify the port on which to bind the server."),
click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."),
click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."),
click.option("--logging", type=click.Path(), callback=set_ctx_obj_option,
help="Specify the config file to use for configuring logging."),
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
@@ -123,7 +138,7 @@ server_options = bulk_options([
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
help="Disable processing of the plugin blacklist.")
])
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6``
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
daemon_options = bulk_options([
@@ -153,11 +168,11 @@ def enable_safemode(ctx, **kwargs):
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
else:
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
@server_commands.command(name="serve")
@@ -172,6 +187,8 @@ def serve_command(ctx, **kwargs):
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
@@ -179,10 +196,13 @@ def serve_command(ctx, **kwargs):
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
run_server(basedir, configfile, host, port, debug,
if v4 and not host:
host = "0.0.0.0"
run_server(basedir, configfile, host, port, v6, debug,
allow_root, logging, verbosity, safe_mode,
ignore_blacklist)
@@ -209,6 +229,8 @@ if sys.platform != "win32" and sys.platform != "darwin":
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
@@ -217,9 +239,12 @@ if sys.platform != "win32" and sys.platform != "darwin":
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
if v4 and not host:
host = "0.0.0.0"
if pid is None:
click.echo("No path to a pidfile set",
file=sys.stderr)
@@ -227,14 +252,15 @@ if sys.platform != "win32" and sys.platform != "darwin":
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity,
safe_mode, ignore_blacklist):
def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config,
verbosity, safe_mode, ignore_blacklist):
Daemon.__init__(self, pidfile)
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._v6_only = v6_only
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
@@ -243,12 +269,12 @@ if sys.platform != "win32" and sys.platform != "darwin":
self._ignore_blacklist = ignore_blacklist
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
self._ignore_blacklist, octoprint_daemon=self)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
safe_mode, ignore_blacklist)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging,
verbosity, safe_mode, ignore_blacklist)
if command == "start":
octoprint_daemon.start()
+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", [])))
+10 -9
View File
@@ -1,12 +1,13 @@
# coding=utf-8
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
Generic linux daemon base class
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
"""
from __future__ import absolute_import, division, print_function
import sys, os, time, signal
import io, sys, os, time, signal
class Daemon:
"""
@@ -60,9 +61,9 @@ class Daemon:
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(os.devnull, 'a+')
se = open(os.devnull, 'a+')
si = io.open(os.devnull, 'rt', encoding='utf-8')
so = io.open(os.devnull, 'at+', encoding='utf-8')
se = io.open(os.devnull, 'at+', encoding='utf-8')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
@@ -133,7 +134,7 @@ class Daemon:
except OSError:
try:
self.remove_pidfile()
except:
except Exception:
self.error("Daemon found not running, but could not remove stale pidfile")
return False
else:
@@ -142,7 +143,7 @@ class Daemon:
def get_pid(self):
"""Get the pid from the pidfile."""
try:
with open(self.pidfile,'r') as pf:
with io.open(self.pidfile,'rt', encoding='utf-8') as pf:
pid = int(pf.read().strip())
except (IOError, ValueError):
pid = None
@@ -150,7 +151,7 @@ class Daemon:
def set_pid(self, pid):
"""Write the pid to the pidfile."""
with open(self.pidfile,'w+') as f:
with io.open(self.pidfile,'wt+', encoding='utf-8') as f:
f.write(str(pid) + '\n')
def remove_pidfile(self):
+23 -17
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import
# -*- 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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
import copy
import logging
import os
import platform
import sys
import threading
import yaml
@@ -16,6 +15,7 @@ import psutil
from octoprint.plugin import EnvironmentDetectionPlugin
from octoprint.util.platform import get_os
from octoprint.util.version import get_python_version_string
class EnvironmentDetector(object):
@@ -25,10 +25,15 @@ class EnvironmentDetector(object):
self._cache = None
self._cache_lock = threading.RLock()
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
self._logger = logging.getLogger(__name__)
try:
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
except Exception:
# just in case, see #3100...
self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager")
self._environment_plugins = []
@property
def environment(self):
with self._cache_lock:
@@ -54,7 +59,7 @@ class EnvironmentDetector(object):
self.notify_plugins()
return environment
except:
except Exception:
self._logger.exception("Unexpected error while detecting environment")
with self._cache_lock:
self._cache = dict()
@@ -70,22 +75,22 @@ class EnvironmentDetector(object):
# determine python version
try:
result["version"] = platform.python_version()
except:
result["version"] = get_python_version_string()
except Exception:
self._logger.exception("Error detecting python version")
# determine if we are running from a virtual environment
try:
if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)):
result["virtualenv"] = sys.prefix
except:
except Exception:
self._logger.exception("Error detecting whether we are running in a virtual environment")
# try to find pip version
try:
import pkg_resources
result["pip"] = pkg_resources.get_distribution("pip").version
except:
except Exception:
self._logger.exception("Error detecting pip version")
return result
@@ -105,7 +110,7 @@ class EnvironmentDetector(object):
result["freq"] = cpu_freq.max
if ram and hasattr(ram, "total"):
result["ram"] = ram.total
except:
except Exception:
self._logger.exception("Error while detecting hardware environment")
return result
@@ -118,9 +123,10 @@ class EnvironmentDetector(object):
additional = implementation.get_additional_environment()
if additional is not None and isinstance(additional, dict) and len(additional):
result[implementation._identifier] = additional
except:
except Exception:
self._logger.exception("Error while fetching additional "
"environment data from plugin {}".format(implementation._identifier))
"environment data from plugin {}".format(implementation._identifier),
extra=dict(plugin=implementation._identifier))
return result
@@ -134,7 +140,7 @@ class EnvironmentDetector(object):
try:
_log(self._format())
except:
except Exception:
self._logger.exception("Error logging detected environment")
def _format(self):
@@ -145,10 +151,10 @@ class EnvironmentDetector(object):
dumped_environment = yaml.safe_dump(environment,
default_flow_style=False,
indent=" ",
indent=4,
allow_unicode=True).strip()
environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n")))
return u"Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
environment["os"]["id"].title(),
environment["os"]["platform"],
environment_lines)
@@ -162,6 +168,6 @@ class EnvironmentDetector(object):
for implementation in self._environment_plugins:
try:
implementation.on_environment_detected(environment)
except:
except Exception:
self._logger.exception("Error while sending environment "
"detection result to plugin {}".format(implementation._identifier))
+67 -44
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -14,6 +14,7 @@ except ImportError:
import Queue as queue
import threading
import collections
import re
from octoprint.settings import settings
import octoprint.plugin
@@ -23,7 +24,7 @@ _instance = None
def all_events():
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")]
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)]
class Events(object):
@@ -46,6 +47,10 @@ class Events(object):
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
USER_LOGGED_OUT = "UserLoggedOut"
# File management
UPLOAD = "Upload"
FILE_SELECTED = "FileSelected"
@@ -119,6 +124,23 @@ class Events(object):
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
@classmethod
def register_event(cls, event, prefix=None):
name = cls._to_identifier(event)
if prefix:
event = prefix + event
name = cls._to_identifier(prefix) + name
setattr(cls, name, event)
return name, event
# based on https://stackoverflow.com/a/1176023
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
@classmethod
def _to_identifier(cls, name):
s1 = cls._first_cap_re.sub(r'\1_\2', name)
return cls._all_cap_re.sub(r'\1_\2', s1).upper()
def eventManager():
global _instance
@@ -135,6 +157,7 @@ class EventManager(object):
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
self._startup_signaled = False
self._shutdown_signaled = False
@@ -156,21 +179,20 @@ class EventManager(object):
self._shutdown_signaled = True
eventListeners = self._registeredListeners[event]
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
for listener in eventListeners:
self._logger.debug("Sending action to %r" % listener)
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except:
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
except Exception:
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=(event, payload),
initialized=True)
args=(event, payload))
self._logger.info("Event loop shut down")
except:
except Exception:
self._logger.exception("Ooops, the event bus worker loop crashed")
def fire(self, event, payload=None):
@@ -209,14 +231,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.3.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
@@ -227,19 +241,18 @@ class EventManager(object):
return
self._registeredListeners[event].append(callback)
self._logger.debug("Subscribed listener %r for event %s" % (callback, event))
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
def unsubscribe (self, event, callback):
"""
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
"""
if not callback in self._registeredListeners[event]:
# callback not subscribed to event, just return
return
self._registeredListeners[event].remove(callback)
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
try:
self._registeredListeners[event].remove(callback)
except ValueError:
# not registered
pass
def join(self, timeout=None):
self._worker.join(timeout)
@@ -282,7 +295,7 @@ class DebugEventListener(GenericEventListener):
def __init__(self):
GenericEventListener.__init__(self)
events = filter(lambda x: not x.startswith("__"), dir(Events))
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
self.subscribe(events)
def eventCallback(self, event, payload):
@@ -316,26 +329,33 @@ class CommandTrigger(GenericEventListener):
self._logger.info("Invalid subscription definition, not a dictionary: {!r}".format(subscription))
continue
if not "event" in subscription.keys() or not "command" in subscription.keys() \
or not "type" in subscription.keys() or not subscription["type"] in ["system", "gcode"]:
if not "event" in subscription or not "command" in subscription \
or not "type" in subscription or not subscription["type"] in ["system", "gcode"]:
self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(subscription))
continue
if "enabled" in subscription.keys() and not subscription["enabled"]:
if "enabled" in subscription and not subscription["enabled"]:
self._logger.info("Disabled command trigger: {!r}".format(subscription))
continue
event = subscription["event"]
events = subscription["event"]
command = subscription["command"]
commandType = subscription["type"]
debug = subscription["debug"] if "debug" in subscription else False
if not event in self._subscriptions.keys():
self._subscriptions[event] = []
self._subscriptions[event].append((command, commandType, debug))
# "event" in the configuration can be a string, or
# a list of strings. If it's the former, convert it
# into the latter.
if not isinstance(events, (tuple, list, set)):
events = [events]
if not event in eventsToSubscribe:
eventsToSubscribe.append(event)
for event in events:
if event not in self._subscriptions:
self._subscriptions[event] = []
self._subscriptions[event].append((command, commandType, debug))
if event not in eventsToSubscribe:
eventsToSubscribe.append(event)
self.subscribe(eventsToSubscribe)
@@ -355,12 +375,12 @@ class CommandTrigger(GenericEventListener):
if isinstance(command, (tuple, list, set)):
processedCommand = []
for c in command:
processedCommand.append(self._processCommand(c, payload))
processedCommand.append(self._processCommand(c, event, payload))
else:
processedCommand = self._processCommand(command, payload)
processedCommand = self._processCommand(command, event, payload)
self.executeCommand(processedCommand, commandType, debug=debug)
except KeyError as e:
self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command)
except KeyError:
self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command)
def executeCommand(self, command, commandType, debug=False):
if commandType == "system":
@@ -388,10 +408,10 @@ class CommandTrigger(GenericEventListener):
commandExecutioner(command)
except subprocess.CalledProcessError as e:
if debug:
self._logger.warn("Command failed with return code {}: {}".format(e.returncode, str(e)))
self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e)))
else:
self._logger.warn("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
except:
self._logger.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
except Exception:
self._logger.exception("Command failed")
t = threading.Thread(target=process)
@@ -406,13 +426,14 @@ class CommandTrigger(GenericEventListener):
self._logger.info("Executing GCode commands: %r" % command)
self._printer.commands(commands)
def _processCommand(self, command, payload):
def _processCommand(self, command, event, payload):
"""
Performs string substitutions in the command string based on a few current parameters.
The following substitutions are currently supported:
- {__currentZ} : current Z position of the print head, or -1 if not available
- {__eventname} : the name of the event hook being triggered
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
- {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected
- {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected
@@ -429,11 +450,13 @@ class CommandTrigger(GenericEventListener):
import json
try:
json_string = json.dumps(payload)
except:
except Exception:
self._logger.exception("JSON: Cannot dump %r", payload)
json_string = ""
params = {
"__currentZ": "-1",
"__eventname": event,
"__filename": "NO FILE",
"__filepath": "NO PATH",
"__progress": "0",
+75 -49
View File
@@ -1,11 +1,12 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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"
import logging
import io
import os
import octoprint.plugin
@@ -17,6 +18,7 @@ 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
@@ -30,10 +32,6 @@ extensions = dict(
def full_extension_tree():
result = dict(
# extensions for 3d model files
model=dict(
stl=ContentTypeMapping(["stl"], "application/sla")
),
# extensions for printable machine code
machinecode=dict(
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
@@ -74,6 +72,18 @@ def full_extension_tree():
else:
return merged
slicer_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
for plugin in slicer_plugins:
try:
plugin_result = plugin.get_slicer_extension_tree()
if plugin_result is None or not isinstance(plugin_result, dict):
continue
result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger)
except Exception:
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
"tree entries from SlicerPlugin {name}".format(name=plugin._identifier),
extra=dict(plugin=plugin._identifier))
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
for name, hook in extension_tree_hooks.items():
try:
@@ -81,13 +91,15 @@ def full_extension_tree():
if hook_result is None or not isinstance(hook_result, dict):
continue
result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger)
except:
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name))
except Exception:
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
"tree entries from hook {name}".format(name=name),
extra=dict(plugin=name))
return result
def get_extensions(type, subtree=None):
if not subtree:
if subtree is None:
subtree = full_extension_tree()
for key, value in subtree.items():
@@ -101,7 +113,7 @@ def get_extensions(type, subtree=None):
return None
def get_all_extensions(subtree=None):
if not subtree:
if subtree is None:
subtree = full_extension_tree()
result = []
@@ -120,7 +132,7 @@ def get_all_extensions(subtree=None):
return result
def get_path_for_extension(extension, subtree=None):
if not subtree:
if subtree is None:
subtree = full_extension_tree()
for key, value in subtree.items():
@@ -136,11 +148,11 @@ def get_path_for_extension(extension, subtree=None):
return None
def get_content_type_mapping_for_extension(extension, subtree=None):
if not subtree:
if subtree is None:
subtree = full_extension_tree()
for key, value in subtree.items():
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions
list_extension_matches = isinstance(value, (list, tuple)) and extension in value
if content_extension_matches or list_extension_matches:
@@ -213,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()
@@ -220,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():
@@ -319,38 +336,41 @@ 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["hash"]
hash = source_meta.get("hash", "n/a")
import io
links = [("model", dict(name=source_path))]
_, stl_name = self.split_path(source_location, source_path)
file_obj = StreamWrapper(os.path.basename(dest_path),
io.BytesIO(u";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")),
io.FileIO(tmp_path, "rb"))
io.BytesIO(";Generated from {stl_name} (hash: {hash})\n".format(**locals()).encode("ascii", "replace")),
io.FileIO(tmp_path, 'rb'))
printer_profile = self._printer_profile_manager.get(printer_profile_id)
self.add_file(dest_location, dest_path, file_obj,
display=display, links=links, allow_overwrite=True,
printer_profile=printer_profile, analysis=_analysis)
end_time = time.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))
end_time = octoprint.util.monotonic_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:
@@ -370,9 +390,9 @@ class FileManager(object):
slicer = self._slicing_manager.get_slicer(slicer_name)
import time
start_time = time.time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
start_time = octoprint.util.monotonic_time()
eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name,
"stl": source_path,
"stl_location": source_location,
"gcode": dest_path,
"gcode_location": dest_location,
@@ -415,16 +435,20 @@ class FileManager(object):
if self._last_slicing_progress != progress_int:
self._last_slicing_progress = progress_int
for callback in self._slicing_progress_callbacks:
try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
except: self._logger.exception("Exception while pushing slicing progress")
try:
callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
except Exception:
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):
for plugin in self._progress_plugins:
try:
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
except:
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier)
except Exception:
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier,
extra=dict(plugin=plugin._identifier))
import threading
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
@@ -446,8 +470,8 @@ class FileManager(object):
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
if not destinations:
destinations = self._storage_managers.keys()
if isinstance(destinations, (str, unicode, basestring)):
destinations = list(self._storage_managers.keys())
if isinstance(destinations, basestring):
destinations = [destinations]
result = dict()
@@ -459,11 +483,11 @@ class FileManager(object):
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
for hook in self._preprocessor_hooks.values():
for name, hook in self._preprocessor_hooks.items():
try:
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
except:
self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook))
except Exception:
self._logger.exception("Error when calling preprocessor hook for plugin {}, ignoring".format(name), extra=dict(plugin=name))
continue
if hook_file_object is not None:
@@ -622,9 +646,9 @@ class FileManager(object):
pos=pos,
date=time.time())
try:
with atomic_write(self._recovery_file, max_permissions=0o666) as f:
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
except:
with atomic_write(self._recovery_file, mode='wt', max_permissions=0o666) as f:
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=2, allow_unicode=True)
except Exception:
self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file))
def delete_recovery_data(self):
@@ -633,7 +657,7 @@ class FileManager(object):
try:
os.remove(self._recovery_file)
except:
except Exception:
self._logger.exception("Error deleting recovery data file {}".format(self._recovery_file))
def get_recovery_data(self):
@@ -642,10 +666,12 @@ class FileManager(object):
import yaml
try:
with open(self._recovery_file) as f:
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:
except Exception:
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
self.delete_recovery_data()
+24 -21
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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'
@@ -18,6 +18,8 @@ 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")):
@@ -95,27 +97,28 @@ class AnalysisQueue(object):
self._queues[entry.type].dequeue(entry.location, entry.path)
def dequeue_folder(self, destination, path):
for queue in self._queues.values():
queue.dequeue_folder(destination, path)
for q in self._queues.values():
q.dequeue_folder(destination, path)
def pause(self):
for queue in self._queues.values():
queue.pause()
for q in self._queues.values():
q.pause()
def resume(self):
for queue in self._queues.values():
queue.resume()
for q in self._queues.values():
q.resume()
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):
"""
@@ -173,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:
@@ -249,20 +255,17 @@ class AbstractAnalysisQueue(object):
self._current_progress = 0
try:
start_time = time.time()
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
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:
result = self._do_analysis()
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, time.time() - start_time))
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time))
self._finished_callback(self._current, result)
finally:
self._current = None
@@ -382,7 +385,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
if not p.commands[0].process:
# the process might have been set to None in case of any exception
raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command)))
raise RuntimeError("Error while trying to run command {}".format(" ".join(command)))
try:
# let's wait for stuff to finish
+3 -2
View File
@@ -1,5 +1,6 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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'
class FileDestinations(object):
+159 -86
View File
@@ -1,16 +1,17 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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"
import io
import logging
import os
import pylru
import shutil
import re
import pylru
import copy
try:
from os import scandir, walk
@@ -19,7 +20,6 @@ except ImportError:
from octoprint.util import atomic_write
from contextlib import contextmanager
from copy import deepcopy
from past.builtins import basestring
@@ -28,7 +28,7 @@ from slugify import Slugify
import octoprint.filemanager
from octoprint.util import is_hidden_path, to_unicode
from octoprint.util import is_hidden_path, to_unicode, to_bytes
class StorageInterface(object):
"""
@@ -450,11 +450,11 @@ class LocalFileStorage(StorageInterface):
This storage type implements :func:`path_on_disk`.
"""
_UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]")
_UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
@classmethod
def _no_unicode_variations(cls, text):
return cls._UNICODE_VARIATIONS.sub(u"", text)
return cls._UNICODE_VARIATIONS.sub("", text)
_SLUGIFY = Slugify()
_SLUGIFY.safe_chars = "-_.()[] "
@@ -463,7 +463,7 @@ class LocalFileStorage(StorageInterface):
def _slugify(cls, text):
text = to_unicode(text)
text = cls._no_unicode_variations(text)
text = demojize(text, delimiters=(u"", u""))
text = demojize(text, delimiters=("", ""))
return cls._SLUGIFY(text)
def __init__(self, basefolder, create=False):
@@ -485,6 +485,8 @@ class LocalFileStorage(StorageInterface):
import threading
self._metadata_lock_mutex = threading.RLock()
self._metadata_locks = dict()
self._persisted_metadata_lock_mutex = threading.RLock()
self._persisted_metadata_locks = dict()
self._metadata_cache = pylru.lrucache(10)
@@ -500,10 +502,10 @@ class LocalFileStorage(StorageInterface):
if os.path.exists(old_metadata_path):
# load the old metadata file
try:
with open(old_metadata_path) as f:
with io.open(old_metadata_path, 'rt', encoding='utf-8') as f:
import yaml
self._old_metadata = yaml.safe_load(f)
except:
except Exception:
self._logger.exception("Error while loading old metadata file")
# make sure the metadata is initialized as far as possible
@@ -514,7 +516,7 @@ class LocalFileStorage(StorageInterface):
try:
import shutil
shutil.move(old_metadata_path, backup_path)
except:
except Exception:
self._logger.exception("Could not rename old metadata.yaml file")
else:
@@ -597,10 +599,10 @@ class LocalFileStorage(StorageInterface):
path = self.sanitize_path(to_unicode(path))
base = self.path_in_storage(path)
if base:
base += u"/"
base += "/"
else:
path = self.basefolder
base = u""
base = ""
return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive)
def add_folder(self, path, ignore_existing=True, display=None):
@@ -883,6 +885,8 @@ class LocalFileStorage(StorageInterface):
if not name in metadata:
return
metadata = self._copied_metadata(metadata, name)
if not key in metadata[name] or overwrite:
metadata[name][key] = data
metadata_dirty = True
@@ -907,19 +911,20 @@ class LocalFileStorage(StorageInterface):
if not key in metadata[name]:
return
metadata = self._copied_metadata(metadata, name)
del metadata[name][key]
self._save_metadata(path, metadata)
def split_path(self, path):
path = to_unicode(path)
split = path.split(u"/")
split = path.split("/")
if len(split) == 1:
return u"", split[0]
return "", split[0]
else:
return self.join_path(*split[:-1]), split[-1]
def join_path(self, *path):
return u"/".join(map(to_unicode, path))
return "/".join(map(to_unicode, path))
def sanitize(self, path):
"""
@@ -948,23 +953,23 @@ class LocalFileStorage(StorageInterface):
path = to_unicode(path)
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, u"/")
path = path.split(u"/")
path = path.replace(os.path.sep, "/")
path = path.split("/")
if isinstance(path, (list, tuple)):
if len(path) == 1:
name = to_unicode(path[0])
path = u""
path = ""
else:
name = to_unicode(path[-1])
path = self.join_path(*map(to_unicode, path[:-1]))
if not path:
path = u""
path = ""
return path, name
def sanitize_name(self, name):
"""
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
``(``, and ``)`` as is.
"""
@@ -973,11 +978,11 @@ class LocalFileStorage(StorageInterface):
if name is None:
return None
if u"/" in name or u"\\" in name:
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
result = self._slugify(name).replace(u" ", u"_")
if result and result != u"." and result != u".." and result[0] == u".":
result = self._slugify(name).replace(" ", "_")
if result and result != "." and result != ".." and result[0] == ".":
# hidden files under *nix
result = result[1:]
return result
@@ -991,12 +996,12 @@ class LocalFileStorage(StorageInterface):
path = to_unicode(path)
if len(path):
if path[0] == u"/":
if path[0] == "/":
path = path[1:]
elif path[0] == u"." and path[1] == u"/":
elif path[0] == "." and path[1] == "/":
path = path[2:]
path_elements = path.split(u"/")
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
@@ -1016,16 +1021,16 @@ class LocalFileStorage(StorageInterface):
counter = 1
while os.path.exists(sanitized_path):
counter += 1
sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext))
sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext))
sanitized_path = os.path.join(path, sanitized)
try:
shutil.move(entry_path, sanitized_path)
self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
return sanitized, sanitized_path
except:
self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
except Exception:
self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
raise
return entry, entry_path
@@ -1033,12 +1038,12 @@ class LocalFileStorage(StorageInterface):
def path_in_storage(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, (str, unicode, basestring)):
if isinstance(path, basestring):
path = to_unicode(path)
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, u"/")
if path.startswith(u"/"):
path = path.replace(os.path.sep, "/")
if path.startswith("/"):
path = path[1:]
return path
@@ -1050,10 +1055,7 @@ class LocalFileStorage(StorageInterface):
##~~ internals
def _add_history(self, name, path, data):
metadata = self._get_metadata(path)
if not name in metadata:
metadata[name] = dict()
metadata = self._copied_metadata(self._get_metadata(path), name)
if not "hash" in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
@@ -1071,6 +1073,8 @@ class LocalFileStorage(StorageInterface):
if not name in metadata or not "history" in metadata[name]:
return
metadata = self._copied_metadata(metadata, name)
try:
metadata[name]["history"][index].update(data)
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
@@ -1084,6 +1088,8 @@ class LocalFileStorage(StorageInterface):
if not name in metadata or not "history" in metadata[name]:
return
metadata = self._copied_metadata(metadata, name)
try:
del metadata[name]["history"][index]
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
@@ -1093,9 +1099,9 @@ class LocalFileStorage(StorageInterface):
def _calculate_stats_from_history(self, name, path, metadata=None, save=True):
if metadata is None:
metadata = self._get_metadata(path)
metadata = self._copied_metadata(self._get_metadata(path), name)
if not name in metadata or not "history" in metadata[name]:
if not "history" in metadata[name]:
return
# collect data from history
@@ -1114,8 +1120,8 @@ class LocalFileStorage(StorageInterface):
print_time = history_entry["printTime"]
try:
print_time = float(print_time)
except:
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
except Exception:
self._logger.warning("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
continue
if not printer_profile in former_print_times:
@@ -1164,12 +1170,9 @@ class LocalFileStorage(StorageInterface):
if file_type:
file_type = file_type[0]
metadata = self._get_metadata(path)
metadata = self._copied_metadata(self._get_metadata(path), name)
metadata_dirty = False
if not name in metadata:
metadata[name] = dict()
if not "hash" in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
@@ -1241,13 +1244,10 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def _remove_links(self, name, path, links):
metadata = self._get_metadata(path)
metadata = self._copied_metadata(self._get_metadata(path), name)
metadata_dirty = False
if not name in metadata or not "hash" in metadata[name]:
hash = self._create_hash(os.path.join(path, name))
else:
hash = metadata[name]["hash"]
hash = metadata[name].get("hash", self._create_hash(os.path.join(path, name)))
for rel, data in links:
if (rel == "model" or rel == "machinecode") and "name" in data:
@@ -1255,6 +1255,7 @@ class LocalFileStorage(StorageInterface):
ref_rel = "model" if rel == "machinecode" else "machinecode"
for link in metadata[data["name"]]["links"]:
if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash:
metadata[data["name"]] = copy.deepcopy(metadata[data["name"]])
metadata[data["name"]]["links"].remove(link)
metadata_dirty = True
@@ -1299,7 +1300,7 @@ class LocalFileStorage(StorageInterface):
entry_is_file = entry.is_file()
entry_is_dir = entry.is_dir()
entry_stat = entry.stat()
except:
except Exception:
# error while trying to fetch file metadata, that might be thanks to file already having
# been moved or deleted - ignore it and continue
continue
@@ -1311,7 +1312,7 @@ class LocalFileStorage(StorageInterface):
entry_name = new_entry_name
entry_path = new_entry_path
entry_stat = os.stat(entry_path)
except:
except Exception:
# error while trying to rename the file, we'll continue here and ignore it
continue
@@ -1330,10 +1331,14 @@ class LocalFileStorage(StorageInterface):
if entry_name in metadata and isinstance(metadata[entry_name], dict):
entry_metadata = metadata[entry_name]
if not "display" in entry_metadata and entry_display != entry_name:
if not metadata_dirty:
metadata = self._copied_metadata(metadata, entry_name)
metadata[entry_name]["display"] = entry_display
entry_metadata["display"] = entry_display
metadata_dirty = True
else:
if not metadata_dirty:
metadata = self._copied_metadata(metadata, entry_name)
entry_metadata = self._add_basic_metadata(path, entry_name,
display_name=entry_display,
save=False,
@@ -1363,10 +1368,14 @@ class LocalFileStorage(StorageInterface):
if entry_name in metadata and isinstance(metadata[entry_name], dict):
entry_metadata = metadata[entry_name]
if not "display" in entry_metadata and entry_display != entry_name:
if not metadata_dirty:
metadata = self._copied_metadata(metadata, entry_name)
metadata[entry_name]["display"] = entry_display
entry_metadata["display"] = entry_display
metadata_dirty = True
elif entry_name != entry_display:
if not metadata_dirty:
metadata = self._copied_metadata(metadata, entry_name)
entry_metadata = self._add_basic_metadata(path, entry_name,
display_name=entry_display,
save=False,
@@ -1408,7 +1417,7 @@ class LocalFileStorage(StorageInterface):
extended_entry_data["size"] = get_size()
result[entry_name] = extended_entry_data
except:
except Exception:
# So something went wrong somewhere while processing this file entry - log that and continue
self._logger.exception("Error while processing entry {}".format(entry_path))
continue
@@ -1450,6 +1459,8 @@ class LocalFileStorage(StorageInterface):
entry_data["display"] = display_name
entry_data.update(additional_metadata)
metadata = copy.copy(metadata)
metadata[entry] = entry_data
if save:
@@ -1462,7 +1473,7 @@ class LocalFileStorage(StorageInterface):
blocksize = 65536
hash = hashlib.sha1()
with open(path, "rb") as f:
with io.open(path, 'rb') as f:
buffer = f.read(blocksize)
while len(buffer) > 0:
hash.update(buffer)
@@ -1481,6 +1492,8 @@ class LocalFileStorage(StorageInterface):
if not name in metadata:
return
metadata = copy.copy(metadata)
if "hash" in metadata[name]:
hash = metadata[name]["hash"]
for m in metadata.values():
@@ -1494,7 +1507,7 @@ class LocalFileStorage(StorageInterface):
def _update_metadata_entry(self, path, name, data):
with self._get_metadata_lock(path):
metadata = self._get_metadata(path)
metadata = copy.copy(self._get_metadata(path))
metadata[name] = data
self._save_metadata(path, metadata)
@@ -1513,58 +1526,91 @@ class LocalFileStorage(StorageInterface):
with self._get_metadata_lock(destination_path):
self._update_metadata_entry(destination_path, destination_name, source_data)
def _get_metadata(self, path):
with self._get_metadata_lock(path):
if path in self._metadata_cache:
return deepcopy(self._metadata_cache[path])
def _get_metadata(self, path, force=False):
import json
self._migrate_metadata(path)
if not force:
metadata = self._metadata_cache.get(path)
if metadata:
return metadata
metadata_path = os.path.join(path, ".metadata.json")
self._migrate_metadata(path)
metadata_path = os.path.join(path, ".metadata.json")
metadata = None
with self._get_persisted_metadata_lock(path):
if os.path.exists(metadata_path):
with open(metadata_path) as f:
with io.open(metadata_path, 'rt', encoding='utf-8') as f:
try:
import json
metadata = json.load(f)
except:
except Exception:
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
else:
if isinstance(metadata, dict):
self._metadata_cache[path] = deepcopy(metadata)
return metadata
def valid_json(value):
try:
json.dumps(value, allow_nan=False)
return True
except:
return False
if isinstance(metadata, dict):
old_size = len(metadata)
metadata = { k: v for k, v in metadata.items() if valid_json(v) }
metadata = { k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) }
new_size = len(metadata)
if new_size != old_size:
self._logger.info("Deleted {} stale or invalid entries from metadata for path {}".format(old_size - new_size,
path))
self._save_metadata(path, metadata)
else:
with self._get_metadata_lock(path):
self._metadata_cache[path] = metadata
return metadata
else:
return dict()
def _save_metadata(self, path, metadata):
import json
with self._get_metadata_lock(path):
self._metadata_cache[path] = metadata
with self._get_persisted_metadata_lock(path):
metadata_path = os.path.join(path, ".metadata.json")
try:
import json
with atomic_write(metadata_path) as f:
json.dump(metadata, f, indent=4, separators=(",", ": "))
except:
with atomic_write(metadata_path, mode='wb') as f:
f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": "))))
except Exception:
self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
else:
self._metadata_cache[path] = deepcopy(metadata)
def _delete_metadata(self, path):
with self._get_metadata_lock(path):
if path in self._metadata_cache:
del self._metadata_cache[path]
with self._get_persisted_metadata_lock(path):
metadata_files = (".metadata.json", ".metadata.yaml")
for metadata_file in metadata_files:
metadata_path = os.path.join(path, metadata_file)
if os.path.exists(metadata_path):
try:
os.remove(metadata_path)
except:
except Exception:
self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals()))
if path in self._metadata_cache:
del self._metadata_cache[path]
@staticmethod
def _copied_metadata(metadata, name):
metadata = copy.copy(metadata)
metadata[name] = copy.deepcopy(metadata.get(name, dict()))
return metadata
def _migrate_metadata(self, path):
# we switched to json in 1.3.9 - if we still have yaml here, migrate it now
import yaml
import json
with self._get_metadata_lock(path):
with self._get_persisted_metadata_lock(path):
metadata_path_yaml = os.path.join(path, ".metadata.yaml")
metadata_path_json = os.path.join(path, ".metadata.json")
@@ -1574,13 +1620,16 @@ class LocalFileStorage(StorageInterface):
if os.path.exists(metadata_path_json):
# already migrated
# TODO 1.3.10 Remove ".metadata.yaml" files
try:
os.remove(metadata_path_yaml)
except Exception:
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
return
with open(metadata_path_yaml) as f:
with io.open(metadata_path_yaml, 'rt', encoding='utf-8') as f:
try:
metadata = yaml.safe_load(f)
except:
except Exception:
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
return
@@ -1588,10 +1637,13 @@ class LocalFileStorage(StorageInterface):
# looks invalid, ignore it
return
with atomic_write(metadata_path_json) as f:
json.dump(metadata, f, indent=4, separators=(",", ": "))
with atomic_write(metadata_path_json, mode='wb') as f:
f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": "))))
# TODO 1.3.10 Remove ".metadata.yaml" files
try:
os.remove(metadata_path_yaml)
except Exception:
self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals()))
@contextmanager
def _get_metadata_lock(self, path):
@@ -1613,3 +1665,24 @@ class LocalFileStorage(StorageInterface):
del self._metadata_locks[path]
else:
self._metadata_locks[path] = (counter, lock)
@contextmanager
def _get_persisted_metadata_lock(self, path):
with self._persisted_metadata_lock_mutex:
if path not in self._persisted_metadata_locks:
import threading
self._persisted_metadata_locks[path] = (0, threading.RLock())
counter, lock = self._persisted_metadata_locks[path]
counter += 1
self._persisted_metadata_locks[path] = (counter, lock)
yield lock
with self._persisted_metadata_lock_mutex:
counter = self._persisted_metadata_locks[path][0]
counter -= 1
if counter <= 0:
del self._persisted_metadata_locks[path]
else:
self._persisted_metadata_locks[path] = (counter, lock)
+5 -5
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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'
@@ -64,7 +64,7 @@ class DiskFileWrapper(AbstractFileWrapper):
shutil.copy2(self.path, path)
def stream(self):
return io.open(self.path, "rb")
return io.open(self.path, 'rb')
class StreamWrapper(AbstractFileWrapper):
"""
@@ -87,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper):
"""
import shutil
with atomic_write(path, "wb") as dest:
with atomic_write(path, mode='wb') as dest:
with self.stream() as source:
shutil.copyfileobj(source, dest)
@@ -142,7 +142,7 @@ class MultiStream(io.RawIOBase):
for stream in self.streams:
try:
stream.close()
except:
except Exception:
pass
def readable(self, *args, **kwargs):
+22 -16
View File
@@ -1,8 +1,12 @@
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from past.builtins import basestring, unicode
from octoprint.logging import handlers
from typing import Union
def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args):
"""
Logs to the provided handler only.
@@ -77,17 +81,17 @@ def get_divider_line(c, message=None, length=78, indent=3):
Examples:
>>> get_divider_line("-")
>>> get_divider_line("-") # doctest: +ALLOW_UNICODE
'------------------------------------------------------------------------------'
>>> get_divider_line("=", length=10)
>>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE
'=========='
>>> get_divider_line("-", message="Hi", length=10)
>>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE
'--- Hi ---'
>>> get_divider_line("-", message="A slightly longer text")
>>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE
'--- A slightly longer text ---------------------------------------------------'
>>> get_divider_line("-", message="A slightly longer text", indent=5)
>>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE
'----- A slightly longer text -------------------------------------------------'
>>> get_divider_line("-", message="Hello World!", length=10)
>>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE
'--- Hello World!'
>>> get_divider_line(None)
Traceback (most recent call last):
@@ -120,7 +124,7 @@ def get_divider_line(c, message=None, length=78, indent=3):
formatted divider line
"""
assert isinstance(c, (str, unicode, bytes)), "c is not text"
assert isinstance(c, basestring), "c is not text"
assert len(c) == 1, "c is not a single character"
assert isinstance(length, int), "length is not an int"
assert isinstance(indent, int), "indent is not an int"
@@ -128,7 +132,7 @@ def get_divider_line(c, message=None, length=78, indent=3):
if message is None:
return c * length
assert isinstance(message, (str, unicode, bytes)), "message is not text"
assert isinstance(message, basestring), "message is not text"
space = length - 2 * (indent + 1)
if space >= len(message):
@@ -137,14 +141,16 @@ def get_divider_line(c, message=None, length=78, indent=3):
return c * indent + " " + message
def prefix_multilines(text, prefix=": "):
def prefix_multilines(text, prefix=u": "):
# type: (Union[unicode, bytes], unicode) -> unicode
from octoprint.util import to_unicode
lines = text.splitlines()
if not lines:
return ""
return u""
if len(lines) == 1:
return lines[0]
return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line,
lines[1:]))
return to_unicode(lines[0])
return to_unicode(lines[0]) + u"\n" + u"\n".join(map(lambda line: prefix + to_unicode(line),
lines[1:]))
+10 -3
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import logging.handlers
import os
@@ -18,7 +18,7 @@ class AsyncLogHandlerMixin(logging.Handler):
def emit(self, record):
try:
self._executor.submit(self._emit, record)
except:
except Exception:
self.handleError(record)
def _emit(self, record):
@@ -29,6 +29,8 @@ class AsyncLogHandlerMixin(logging.Handler):
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
# clean up old files on handler start
@@ -40,6 +42,10 @@ class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler
class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler):
rollover_callbacks = []
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(OctoPrintLogHandler, self).__init__(*args, **kwargs)
@classmethod
def registerRolloverCallback(cls, callback, *args, **kwargs):
cls.rollover_callbacks.append((callback, args, kwargs))
@@ -67,6 +73,7 @@ class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandle
cls.do_rollover = True
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(SerialLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
+35 -61
View File
@@ -1,4 +1,6 @@
# coding=utf-8
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the
registered plugin types.
@@ -13,40 +15,30 @@ registered plugin types.
:members:
"""
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"
import os
import logging
import threading
from octoprint.settings import settings as s
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
from octoprint.plugin.types import *
from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin
from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules
from octoprint.util import deprecated
from octoprint.util import deprecated, to_native_str
# singleton
_instance = None
def _validate_plugin(phase, plugin_info):
if phase == "after_load":
if plugin_info.implementation is not None and isinstance(plugin_info.implementation, AppPlugin):
# transform app plugin into hook
import warnings
warnings.warn("{name} uses deprecated plugin mixin AppPlugin, use octoprint.accesscontrol.appkey hook instead".format(name=plugin_info.key), DeprecationWarning)
hooks = plugin_info.hooks
if not "octoprint.accesscontrol.appkey" in hooks:
hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
return True
def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None,
plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
plugin_validators=None):
plugin_validators=None, compatibility_ignored_list=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
@@ -72,6 +64,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will
not be enabled since they might depend on functionality that is no longer available.
plugin_validators (list): A list of additional plugin validators through which to process each plugin.
compatibility_ignored_list (list): A list of plugin keys for which it will be ignored if they are flagged as
incompatible. This is for development purposes only and should not be used in production.
Returns:
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
@@ -95,6 +89,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
if plugin_restart_needing_hooks is None:
plugin_restart_needing_hooks = ["octoprint.server.http.*",
"octoprint.printer.factory",
"octoprint.access.permissions",
"octoprint.timelapse.extensions"]
if plugin_obsolete_hooks is None:
@@ -113,7 +108,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
plugin_blacklist=plugin_blacklist,
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
plugin_obsolete_hooks=plugin_obsolete_hooks,
plugin_validators=plugin_validators)
plugin_validators=plugin_validators,
compatibility_ignored_list=compatibility_ignored_list)
else:
raise ValueError("Plugin Manager not initialized yet")
return _instance
@@ -161,14 +157,15 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
try:
get_preprocessors, set_preprocessors = instance.get_settings_preprocessors()
except:
except Exception:
logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key))
return None
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None,
initialized=True):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
@@ -204,9 +201,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
is determined be presence of injected ``_identifier`` property.
initialized (boolean): Ignored.
"""
if not isinstance(types, (list, tuple)):
@@ -216,18 +211,21 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
if kwargs is None:
kwargs = dict()
logger = logging.getLogger(__name__)
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
if initialized and not hasattr(plugin, "_identifier"):
if not hasattr(plugin, "_identifier"):
continue
if hasattr(plugin, method):
logger.debug("Calling {} on {}".format(method, plugin._identifier))
try:
result = getattr(plugin, method)(*args, **kwargs)
if callback:
callback(plugin._identifier, plugin, result)
except Exception as exc:
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
logger.exception("Error while calling plugin %s" % plugin._identifier, extra=dict(plugin=plugin._identifier))
if error_callback:
error_callback(plugin._identifier, plugin, exc)
@@ -303,6 +301,17 @@ class PluginSettings(object):
.. method:: set_boolean(path, value, force=False)
Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it.
.. method:: save(force=False, trigger_event=False)
Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings
will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated``
:ref:`event <sec-events-available_events-settings>` to get triggered.
:param force: Force saving to ``config.yaml`` even if there are no changes.
:type force: boolean
:param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event <sec-events-available_events-settings>` on save.
:type trigger_event: boolean
"""
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
@@ -497,7 +506,7 @@ class PluginSettings(object):
self.settings.remove(self._prefix_path())
def __getattr__(self, item):
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
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:
@@ -513,44 +522,9 @@ class PluginSettings(object):
def _func(*args, **kwargs):
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
_func.__name__ = item
_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)
##~~ deprecated methods follow
# TODO: Remove with release of 1.3.0
globalGet = deprecated("globalGet has been renamed to global_get",
includedoc="Replaced by :func:`global_get`",
since="1.2.0-dev-546")(global_get)
globalGetInt = deprecated("globalGetInt has been renamed to global_get_int",
includedoc="Replaced by :func:`global_get_int`",
since="1.2.0-dev-546")(global_get_int)
globalGetFloat = deprecated("globalGetFloat has been renamed to global_get_float",
includedoc="Replaced by :func:`global_get_float`",
since="1.2.0-dev-546")(global_get_float)
globalGetBoolean = deprecated("globalGetBoolean has been renamed to global_get_boolean",
includedoc="Replaced by :func:`global_get_boolean`",
since="1.2.0-dev-546")(global_get_boolean)
globalSet = deprecated("globalSet has been renamed to global_set",
includedoc="Replaced by :func:`global_set`",
since="1.2.0-dev-546")(global_set)
globalSetInt = deprecated("globalSetInt has been renamed to global_set_int",
includedoc="Replaced by :func:`global_set_int`",
since="1.2.0-dev-546")(global_set_int)
globalSetFloat = deprecated("globalSetFloat has been renamed to global_set_float",
includedoc="Replaced by :func:`global_set_float`",
since="1.2.0-dev-546")(global_set_float)
globalSetBoolean = deprecated("globalSetBoolean has been renamed to global_set_boolean",
includedoc="Replaced by :func:`global_set_boolean`",
since="1.2.0-dev-546")(global_set_boolean)
globalGetBaseFolder = deprecated("globalGetBaseFolder has been renamed to global_get_basefolder",
includedoc="Replaced by :func:`global_get_basefolder`",
since="1.2.0-dev-546")(global_get_basefolder)
getPluginLogfilePath = deprecated("getPluginLogfilePath has been renamed to get_plugin_logfile_path",
includedoc="Replaced by :func:`get_plugin_logfile_path`",
since="1.2.0-dev-546")(get_plugin_logfile_path)
+203 -89
View File
@@ -1,4 +1,6 @@
# coding=utf-8
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
In this module resides the core data structures and logic of the plugin system. It is implemented in an OctoPrint-agnostic
way and could be extracted into a separate Python module in the future.
@@ -20,32 +22,58 @@ way and could be extracted into a separate Python module in the future.
"""
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"
import os
import imp
import io
from collections import defaultdict, namedtuple, OrderedDict
import logging
import fnmatch
import inspect
import sys
import pkg_resources
import pkginfo
from past.builtins import basestring
from past.builtins import unicode
from octoprint.util import to_unicode, sv
from octoprint.util.version import is_python_compatible, get_python_version_string
try:
from os import scandir
except ImportError:
from scandir import scandir
if sys.version_info[0] == 2:
# noinspection PyDeprecation
import imp
else:
# deprecated in Python 3.4+ and hence vendored for now
import octoprint.vendor.imp as imp
# noinspection PyDeprecation
def _find_module(name, path=None):
if path is not None:
spec = imp.find_module(name, [path])
else:
spec = imp.find_module(name)
return spec[1], spec
# noinspection PyDeprecation
def _load_module(name, spec):
f, filename, details = spec
return imp.load_module(name, f, filename, details)
EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version")
FolderOrigin = namedtuple("FolderOrigin", "type, folder")
ModuleOrigin = namedtuple("PackageOrigin", "type, module_name, folder")
class PluginInfo(object):
"""
@@ -90,6 +118,18 @@ class PluginInfo(object):
attr_license = '__plugin_license__'
""" Module attribute from which to retrieve the plugin's license. """
attr_pythoncompat = '__plugin_pythoncompat__'
"""
Module attribute from which to retrieve the plugin's python compatibility string.
If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to
Python 2 but not Python 3.
To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
Bundled plugins will automatically be assumed to be compatible.
"""
attr_hooks = '__plugin_hooks__'
""" Module attribute from which to retrieve the plugin's provided hooks. """
@@ -145,10 +185,12 @@ class PluginInfo(object):
self.enabled = True
self.blacklisted = False
self.forced_disabled = False
self.incompatible = False
self.bundled = False
self.loaded = False
self.managable = True
self.needs_restart = False
self.invalid_syntax = False
self._name = name
self._version = version
@@ -160,12 +202,14 @@ class PluginInfo(object):
self._logger = logging.getLogger(__name__)
self._cached_parsed_metadata = parsed_metadata
if self._cached_parsed_metadata is None:
self._cached_parsed_metadata = self._parse_metadata()
def validate(self, phase, additional_validators=None):
result = True
if phase == "before_import":
result = not self.forced_disabled and not self.blacklisted and result
result = not self.forced_disabled and not self.blacklisted and not self.incompatible and not self.invalid_syntax and result
elif phase == "before_load":
# if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__
@@ -209,11 +253,11 @@ class PluginInfo(object):
if self.version:
return "{name} ({version})".format(name=self.name, version=self.version)
else:
return self.name
return to_unicode(self.name)
def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""),
show_location=False, location_str=" - {location}",
show_enabled=False, enabled_strs=("* ", " ", "X ")):
show_enabled=False, enabled_strs=("* ", " ", "X ", "C ")):
"""
Long string representation of the plugin's information. Will return a string of the format ``<enabled><str(self)><bundled><location>``.
@@ -221,8 +265,9 @@ class PluginInfo(object):
The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows:
``enabled_str``
a 3-tuple, the first entry being the string to insert when the plugin is enabled, the second
entry the string to insert when it is not, the third entry the string when it is blacklisted.
a 4-tuple, the first entry being the string to insert when the plugin is enabled, the second
entry the string to insert when it is not, the third entry the string when it is blacklisted
and the fourth when it is incompatible.
``bundled_str``
a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second
entry the string to insert when it is not.
@@ -242,17 +287,24 @@ class PluginInfo(object):
str: The long string representation of the plugin as described above
"""
if show_enabled:
ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1])
if self.incompatible:
ret = to_unicode(enabled_strs[3])
elif self.blacklisted:
ret = to_unicode(enabled_strs[2])
elif not self.enabled:
ret = to_unicode(enabled_strs[1])
else:
ret = to_unicode(enabled_strs[0])
else:
ret = ""
ret += str(self)
ret += unicode(self)
if show_bundled:
ret += bundled_strs[0] if self.bundled else bundled_strs[1]
ret += to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1])
if show_location and self.location:
ret += location_str.format(location=self.location)
ret += to_unicode(location_str).format(location=self.location)
return ret
@@ -379,10 +431,23 @@ class PluginInfo(object):
default=self._license,
incl_metadata=True)
@property
def pythoncompat(self):
"""
Python compatibility string of the plugin module as defined in :attr:`attr_pythoncompat` if available, otherwise
defaults to ``>=2.7,<3``.
Returns:
str: Python compatibility string of the plugin
"""
return self._get_instance_attribute(self.__class__.attr_pythoncompat,
default=">=2.7,<3",
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:
@@ -486,8 +551,6 @@ class PluginInfo(object):
@property
def parsed_metadata(self):
if self._cached_parsed_metadata is None:
self._cached_parsed_metadata = self._parse_metadata()
return self._cached_parsed_metadata
def _parse_metadata(self):
@@ -512,18 +575,19 @@ class PluginInfo(object):
try:
import ast
with open(path, "rb") as f:
root = ast.parse(f.read())
with io.open(path, 'rb') as f:
root = ast.parse(f.read(), filename=path)
assignments = filter(lambda x: isinstance(x, ast.Assign) and x.targets,
root.body)
assignments = list(filter(lambda x: isinstance(x, ast.Assign) and x.targets,
root.body))
def extract_target_ids(node):
return map(lambda x: x.id,
filter(lambda x: isinstance(x, ast.Name), node.targets))
return list(map(lambda x: x.id,
filter(lambda x: isinstance(x, ast.Name), node.targets)))
for key in (self.__class__.attr_name, self.__class__.attr_version, self.__class__.attr_author,
self.__class__.attr_description, self.__class__.attr_url, self.__class__.attr_license):
self.__class__.attr_description, self.__class__.attr_url, self.__class__.attr_license,
self.__class__.attr_pythoncompat):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
@@ -536,8 +600,11 @@ class PluginInfo(object):
result[key] = a.value.args[0].s
break
except:
pass
except SyntaxError:
self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key))
self.invalid_syntax = True
except Exception:
self._logger.exception("Error while parsing AST from {} for plugin {}".format(path, self.key))
return result
@@ -552,7 +619,7 @@ class PluginManager(object):
def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None,
plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None,
plugin_obsolete_hooks=None, plugin_validators=None):
plugin_obsolete_hooks=None, plugin_validators=None, compatibility_ignored_list=None):
self.logger = logging.getLogger(__name__)
if logging_prefix is None:
@@ -567,6 +634,8 @@ class PluginManager(object):
plugin_disabled_list = []
if plugin_blacklist is None:
plugin_blacklist = []
if compatibility_ignored_list is None:
compatibility_ignored_list = []
self.plugin_folders = plugin_folders
self.plugin_bases = plugin_bases
@@ -577,6 +646,7 @@ class PluginManager(object):
self.plugin_obsolete_hooks = plugin_obsolete_hooks
self.plugin_validators = plugin_validators
self.logging_prefix = logging_prefix
self.compatibility_ignored_list = compatibility_ignored_list
self.enabled_plugins = dict()
self.disabled_plugins = dict()
@@ -628,7 +698,7 @@ class PluginManager(object):
@property
def plugin_hooks(self):
return {key: map(lambda v: (v[1], v[2]), value) for key, value in self._plugin_hooks.items()}
return {key: list(map(lambda v: (v[1], v[2]), value)) for key, value in self._plugin_hooks.items()}
def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False):
added, found = self._find_plugins(existing=existing, ignore_uninstalled=ignore_uninstalled)
@@ -651,7 +721,7 @@ class PluginManager(object):
ignored_uninstalled=ignore_uninstalled)
result_added.update(added)
result_found += found
except:
except Exception:
self.logger.exception("Error fetching plugins from folders")
if self.plugin_entry_points:
@@ -662,7 +732,7 @@ class PluginManager(object):
ignore_uninstalled=ignore_uninstalled)
result_added.update(added)
result_found += found
except:
except Exception:
self.logger.exception("Error fetching plugins from entry points")
return result_added, result_found
@@ -674,15 +744,18 @@ class PluginManager(object):
for folder in folders:
try:
flagged_readonly = False
package = None
if isinstance(folder, (list, tuple)):
if len(folder) == 2:
folder, flagged_readonly = folder
elif len(folder) == 3:
folder, package, flagged_readonly = folder
else:
continue
actual_readonly = not os.access(folder, os.W_OK)
if not os.path.exists(folder):
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
self.logger.warning("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
continue
for entry in scandir(folder):
@@ -714,15 +787,22 @@ class PluginManager(object):
bundled = flagged_readonly
plugin = self._import_plugin_from_module(key, folder=folder, bundled=bundled)
module_name = None
if package:
module_name = "{}.{}".format(package, key)
plugin = self._import_plugin_from_module(key, module_name=module_name, folder=folder, bundled=bundled)
if plugin:
plugin.origin = FolderOrigin("folder", folder)
if module_name:
plugin.origin = ModuleOrigin("module", module_name, folder)
else:
plugin.origin = FolderOrigin("folder", folder)
plugin.managable = not flagged_readonly and not actual_readonly
plugin.enabled = False
added[key] = plugin
except:
except Exception:
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
except:
except Exception:
self.logger.exception("Error processing folder {}".format(folder))
return added, found
@@ -752,7 +832,7 @@ class PluginManager(object):
for entry in gen:
try:
yield entry
except:
except Exception:
self.logger.exception("Something went wrong while processing the entry points of a package in the "
"Python environment - broken entry_points.txt in some package?")
@@ -772,7 +852,7 @@ class PluginManager(object):
package_name = entry_point.dist.project_name
try:
entry_point_metadata = EntryPointMetadata(entry_point)
except:
except Exception:
self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name))
else:
kwargs.update(dict(
@@ -802,7 +882,7 @@ class PluginManager(object):
plugin.location))
added[key] = plugin
except:
except Exception:
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
return added, found
@@ -812,17 +892,17 @@ class PluginManager(object):
# TODO error handling
try:
if folder:
module = imp.find_module(key, [folder])
location, spec = _find_module(key, path=folder)
elif module_name:
module = imp.find_module(module_name)
location, spec = _find_module(module_name)
else:
return None
except:
self.logger.warn("Could not locate plugin {key}".format(key=key))
except Exception:
self.logger.exception("Could not locate plugin {key}".format(key=key))
return None
# Create a simple dummy entry first ...
plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author,
plugin = PluginInfo(key, location, None, name=name, version=version, description=summary, author=author,
url=url, license=license)
plugin.bundled = bundled
@@ -831,21 +911,34 @@ class PluginManager(object):
plugin.forced_disabled = True
if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)):
self.logger.warn("Plugin {} is blacklisted.".format(plugin))
self.logger.warning("Plugin {} is blacklisted.".format(plugin))
plugin.blacklisted = True
python_version = get_python_version_string()
if self._is_plugin_incompatible(key, plugin):
if plugin.invalid_syntax:
self.logger.warning("Plugin {} can't be compiled under Python {} due to invalid syntax".format(plugin, python_version))
else:
self.logger.warning("Plugin {} is not compatible to Python {} (compatibility string: {}).".format(plugin, python_version, plugin.pythoncompat))
plugin.incompatible = True
if not plugin.validate("before_import", additional_validators=self.plugin_validators):
return plugin
# ... then create and return the real one
return self._import_plugin(key, *module,
name=name, version=version, summary=summary, author=author, url=url,
license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata)
return self._import_plugin(key, spec,
module_name=module_name, name=name, location=plugin.location, version=version,
summary=summary, author=author, url=url, license=license, bundled=bundled,
parsed_metadata=plugin.parsed_metadata)
def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
def _import_plugin(self, key, spec, module_name=None, name=None, location=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
try:
instance = imp.load_module(key, f, filename, description)
plugin = PluginInfo(key, filename, instance,
if module_name:
module = _load_module(module_name, spec)
else:
module = _load_module(key, spec)
plugin = PluginInfo(key, location, module,
name=name,
version=version,
description=summary,
@@ -853,8 +946,9 @@ class PluginManager(object):
url=url,
license=license,
parsed_metadata=parsed_metadata)
plugin.bundled = bundled
except:
except Exception:
self.logger.exception("Error loading plugin {key}".format(key=key))
return None
@@ -870,6 +964,11 @@ class PluginManager(object):
def _is_plugin_blacklisted(self, key):
return key in self.plugin_blacklist
def _is_plugin_incompatible(self, key, plugin):
return not plugin.bundled \
and not is_python_compatible(plugin.pythoncompat) \
and key not in self.compatibility_ignored_list
def _is_plugin_version_blacklisted(self, key, version):
def matches_plugin(entry):
if isinstance(entry, (tuple, list)) and len(entry) == 2:
@@ -892,7 +991,7 @@ class PluginManager(object):
incl_all_found=True)
# let's clean everything we DIDN'T find first
removed = [key for key in self.enabled_plugins.keys() + self.disabled_plugins.keys() if key not in found]
removed = [key for key in list(self.enabled_plugins.keys()) + list(self.disabled_plugins.keys()) if key not in found]
for key in removed:
try:
del self.enabled_plugins[key]
@@ -925,7 +1024,7 @@ class PluginManager(object):
try:
if plugin.loaded and not plugin.forced_disabled:
if plugin.blacklisted:
self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin))
self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin))
continue
self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup)
except PluginNeedsRestart:
@@ -967,7 +1066,7 @@ class PluginManager(object):
def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True):
if not name in self.plugins:
self.logger.warn("Trying to load an unknown plugin {name}".format(**locals()))
self.logger.warning("Trying to load an unknown plugin {name}".format(**locals()))
return
if plugin is None:
@@ -985,12 +1084,12 @@ class PluginManager(object):
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
except PluginLifecycleException as e:
raise e
except:
except Exception:
self.logger.exception("There was an error loading plugin %s" % name)
def unload_plugin(self, name):
if not name in self.plugins:
self.logger.warn("Trying to unload unknown plugin {name}".format(**locals()))
self.logger.warning("Trying to unload unknown plugin {name}".format(**locals()))
return
plugin = self.plugins[name]
@@ -1013,7 +1112,7 @@ class PluginManager(object):
self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals()))
except PluginLifecycleException as e:
raise e
except:
except Exception:
self.logger.exception("There was an error unloading plugin {name}".format(**locals()))
# make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins
@@ -1024,7 +1123,7 @@ class PluginManager(object):
def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False):
if not name in self.disabled_plugins:
self.logger.warn("Tried to enable plugin {name}, however it is not disabled".format(**locals()))
self.logger.warning("Tried to enable plugin {name}, however it is not disabled".format(**locals()))
return
if plugin is None:
@@ -1044,7 +1143,7 @@ class PluginManager(object):
self._activate_plugin(name, plugin)
except PluginLifecycleException as e:
raise e
except:
except Exception:
self.logger.exception("There was an error while enabling plugin {name}".format(**locals()))
return False
else:
@@ -1066,7 +1165,7 @@ class PluginManager(object):
def disable_plugin(self, name, plugin=None):
if not name in self.enabled_plugins:
self.logger.warn("Tried to disable plugin {name}, however it is not enabled".format(**locals()))
self.logger.warning("Tried to disable plugin {name}, however it is not enabled".format(**locals()))
return
if plugin is None:
@@ -1080,7 +1179,7 @@ class PluginManager(object):
self._deactivate_plugin(name, plugin)
except PluginLifecycleException as e:
raise e
except:
except Exception:
self.logger.exception("There was an error while disabling plugin {name}".format(**locals()))
return False
else:
@@ -1105,7 +1204,7 @@ class PluginManager(object):
try:
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
continue
self._plugin_hooks[hook].append((order, name, callback))
@@ -1124,7 +1223,7 @@ class PluginManager(object):
try:
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
continue
try:
@@ -1183,7 +1282,7 @@ class PluginManager(object):
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
hooks = hooks[0]
hooks = filter(lambda hook: hook is not None, hooks)
hooks = list(filter(lambda hook: hook is not None, hooks))
if not hooks:
return False
if not plugin or not plugin.hooks:
@@ -1217,7 +1316,7 @@ class PluginManager(object):
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
hooks = hooks[0]
hooks = filter(lambda hook: hook is not None, hooks)
hooks = list(filter(lambda hook: hook is not None, hooks))
if not hooks:
return False
if not hook:
@@ -1255,7 +1354,7 @@ class PluginManager(object):
if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)):
mixins = mixins[0]
mixins = filter(lambda mixin: mixin is not None, mixins)
mixins = list(filter(lambda mixin: mixin is not None, mixins))
if not mixins:
return False
if not plugin or not plugin.implementation:
@@ -1325,7 +1424,7 @@ class PluginManager(object):
for factory in inject_factories:
try:
return_value = factory(name, implementation)
except:
except Exception:
self.logger.exception("Exception while executing injection factory %r" % factory)
else:
if return_value is not None:
@@ -1360,9 +1459,9 @@ class PluginManager(object):
def log_all_plugins(self, show_bundled=True, bundled_str=(" (bundled)", ""), show_location=True,
location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!", "#"),
location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!", "#", "*"),
only_to_handler=None):
all_plugins = self.enabled_plugins.values() + self.disabled_plugins.values()
all_plugins = list(self.enabled_plugins.values()) + list(self.disabled_plugins.values())
def _log(message, level=logging.INFO):
if only_to_handler is not None:
@@ -1380,9 +1479,11 @@ class PluginManager(object):
location_str=location_str,
show_enabled=show_enabled,
enabled_strs=enabled_str),
sorted(self.plugins.values(), key=lambda x: str(x).lower())))
_log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins),
plugins=formatted_plugins))
sorted(self.plugins.values(), key=lambda x: unicode(x).lower())))
legend = "Prefix legend: {1} = disabled, {2} = blacklisted, {3} = incompatible".format(*enabled_str)
_log("{count} plugin(s) registered with the system:\n{plugins}\n{legend}".format(count=len(all_plugins),
plugins=formatted_plugins,
legend=legend))
def get_plugin(self, identifier, require_enabled=True):
"""
@@ -1473,17 +1574,18 @@ class PluginManager(object):
if sorting_context is not None and isinstance(impl[1], SortablePlugin):
try:
sorting_value = impl[1].get_sorting_key(sorting_context)
except:
except Exception:
self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
if sorting_value is not None:
try:
int(sorting_value)
sorting_value = int(sorting_value)
except ValueError:
self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
self.logger.warning("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
sorting_value = None
return sorting_value is None, sorting_value, impl[0]
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
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)]
@@ -1501,7 +1603,7 @@ class PluginManager(object):
assert callable(f)
implementations = self.get_implementations(*types, sorting_context=kwargs.get("sorting_context", None))
return filter(f, implementations)
return list(filter(f, implementations))
def get_helpers(self, name, *helpers):
"""
@@ -1532,7 +1634,8 @@ class PluginManager(object):
def register_message_receiver(self, client):
"""
Registers a ``client`` for receiving plugin messages. The ``client`` needs to be a callable accepting two
input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself).
input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself), and one
optional keyword argument, ``permissions`` (an optional list of permissions to test against).
"""
if client is None:
@@ -1544,25 +1647,32 @@ class PluginManager(object):
Unregisters a ``client`` for receiving plugin messages.
"""
self.registered_clients.remove(client)
try:
self.registered_clients.remove(client)
except ValueError:
# not registered
pass
def send_plugin_message(self, plugin, data):
def send_plugin_message(self, plugin, data, permissions=None):
"""
Sends ``data`` in the name of ``plugin`` to all currently registered message receivers by invoking them
with the two arguments.
with the three arguments.
Arguments:
plugin (str): The sending plugin's identifier.
data (object): The message.
permissions (list): A list of permissions to test against in the client.
"""
for client in self.registered_clients:
try: client(plugin, data)
except: self.logger.exception("Exception while sending plugin data to client")
try:
client(plugin, data, permissions=permissions)
except Exception:
self.logger.exception("Exception while sending plugin data to client")
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):
@@ -1613,13 +1723,14 @@ def is_editable_install(install_dir, package, module, location):
if os.path.isfile(package_link):
expected_target = os.path.normcase(os.path.realpath(location))
try:
with open(package_link) as f:
with io.open(package_link, 'rt', encoding='utf-8') as f:
contents = f.readlines()
for line in contents:
target = os.path.normcase(os.path.realpath(os.path.join(line.strip(), module)))
if target == expected_target:
return True
except:
except Exception:
raise # TODO really ignore this?
pass
return False
@@ -1639,10 +1750,13 @@ class EntryPointMetadata(pkginfo.Distribution):
for metadata_file in metadata_files:
try:
return self.entry_point.dist.get_metadata(metadata_file)
except:
except (IOError, OSError):
# file not found, metadata file might be missing, ignore
# IOError: file not found in Py2
# OSError (specifically FileNotFoundError): file not found in Py3
pass
warnings.warn('No package metadata found for package: {}'.format(self.entry_point.module_name))
warnings.warn('No package metadata found for package {}'.format(self.entry_point.module_name))
class Plugin(object):
+49 -34
View File
@@ -1,4 +1,6 @@
# coding=utf-8
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent
class, :class:`OctoPrintPlugin`.
@@ -16,8 +18,6 @@ Please note that the plugin implementation types are documented in the section
"""
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"
@@ -25,9 +25,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
# noinspection PyCompatibility
from past.builtins import basestring
class OctoPrintPlugin(Plugin):
"""
The parent class of all OctoPrint plugin mixins.
@@ -69,7 +66,7 @@ class OctoPrintPlugin(Plugin):
.. attribute:: _app_session_manager
The :class:`~octoprint.users.SessionManager` instance. Injected by the plugin core system upon initialization of
The :class:`~octoprint.access.users.SessionManager` instance. Injected by the plugin core system upon initialization of
the implementation.
.. attribute:: _plugin_lifecycle_manager
@@ -79,7 +76,7 @@ class OctoPrintPlugin(Plugin):
.. attribute:: _user_manager
The :class:`~octoprint.users.UserManager` instance. Injected by the plugin core system upon initialization
The :class:`~octoprint.access.users.UserManager` instance. Injected by the plugin core system upon initialization
of the implementation.
.. attribute:: _connectivity_checker
@@ -159,6 +156,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
externally reachable, use :func:`on_after_startup` instead or additionally.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``StartupPlugin.on_startup``.
:param string host: the host the server will listen on, may be ``0.0.0.0``
@@ -171,6 +172,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
"""
Called just after launch of the server, so when the listen loop is actually running already.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``StartupPlugin.on_after_startup``.
"""
@@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
"""
Called upon the imminent shutdown of OctoPrint.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``ShutdownPlugin.on_shutdown``.
"""
pass
@@ -785,7 +794,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
def get_ui_custom_etag(self):
"""
Allows to use a custom way to calculate the ETag, instead of the default method (hashing
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
OctoPrint's version, tracked file paths and ``LastModified`` value).
Returns:
str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
@@ -1382,8 +1391,9 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
# noinspection PyMethodMayBeStatic
def is_blueprint_protected(self):
"""
Whether a valid API key is needed to access the blueprint (the default) or not. Note that this only restricts
access to the blueprint's dynamic methods, static files are always accessible without API key.
Whether a login session is needed to access the blueprint if the forcelogin plugin is enabled or not. Requiring
a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files
are always accessible.
"""
return True
@@ -1487,6 +1497,8 @@ class SettingsPlugin(OctoPrintPlugin):
from flask_login import current_user
import copy
from octoprint.access.permissions import Permissions
data = copy.deepcopy(self._settings.get_all_data(merged=True))
if self.config_version_key in data:
del data[self.config_version_key]
@@ -1530,8 +1542,8 @@ class SettingsPlugin(OctoPrintPlugin):
else:
node[key] = None
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous(),
admin=lambda: current_user is not None and not current_user.is_anonymous() and current_user.is_admin(),
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous,
admin=lambda: current_user is not None and current_user.has_permission(Permissions.SETTINGS),
never=lambda: False)
for level, condition in conditions.items():
@@ -1607,8 +1619,8 @@ class SettingsPlugin(OctoPrintPlugin):
"""
Retrieves the list of paths in the plugin's settings which be restricted on the REST API.
Override this in your plugin's implementation to restrict whether a path should only be returned to logged in
users & admins, only to admins, or never on the REST API.
Override this in your plugin's implementation to restrict whether a path should only be returned to users with
the SETTINGS permission, any logged in users, or never on the REST API.
Return a ``dict`` with the keys ``admin``, ``user``, ``never`` mapping to a list of paths (as tuples or lists of
the path elements) for which to restrict access via the REST API accordingly. Paths returned for the ``admin``
@@ -1802,6 +1814,10 @@ class EventHandlerPlugin(OctoPrintPlugin):
"""
Called by OctoPrint upon processing of a fired event on the platform.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
Arguments:
event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
for possible values
@@ -1840,8 +1856,9 @@ class SlicerPlugin(OctoPrintPlugin):
The human readable name of the slicer. This will be displayed to the user during slicer selection.
same_device
True if the slicer runs on the same device as OctoPrint, False otherwise. Slicers running on the same
device will not be allowed to slice while a print is running due to performance reasons. Slice requests
against slicers running on the same device will result in an error.
device will not be allowed to slice on systems with less than two CPU cores (or an unknown number) while a
print is running due to performance reasons. Slice requests against slicers running on the same device and
less than two cores will result in an error.
progress_report
``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise.
source_file_types
@@ -1864,6 +1881,21 @@ class SlicerPlugin(OctoPrintPlugin):
destination_extensions=["gco", "gcode", "g"]
)
# noinspection PyMethodMayBeStatic
def get_slicer_extension_tree(self):
"""
Fetch additional entries to put into the extension tree for accepted files
By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support
additional/other file types will want to override this.
For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook <sec-plugins-hook-filemanager-extensiontree>`.
Returns: (dict) a dictionary containing a valid extension subtree.
"""
from octoprint.filemanager import ContentTypeMapping
return dict(model=dict(stl=ContentTypeMapping(["stl"], "application/sla")))
def get_slicer_profiles(self, profile_path):
"""
Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer.
@@ -2046,20 +2078,3 @@ class ProgressPlugin(OctoPrintPlugin):
:param int progress: Current progress as a value between 0 and 100
"""
pass
class AppPlugin(OctoPrintPlugin):
"""
Using the :class:`AppPlugin mixin` plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
within the system.
.. deprecated:: 1.2.0
Refer to the :ref:`octoprint.accesscontrol.appkey hook <sec-plugins-hook-accesscontrol-appkey>` instead.
"""
# noinspection PyMethodMayBeStatic
def get_additional_apps(self):
return []
+2 -1
View File
@@ -1 +1,2 @@
# make our plugins testable
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
@@ -1,4 +1,4 @@
# coding=utf-8
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -7,6 +7,9 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
import octoprint.plugin
from octoprint.server import user_permission
from octoprint.access import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
import flask
from flask_babel import gettext
@@ -34,17 +37,39 @@ class Prompt(object):
class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
COMMAND = "M876"
CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT"
# noinspection PyMissingConstructor
def __init__(self):
self._prompt = None
self._selection_command = None
self._enable = "detected"
self._command = None
self._enable_emergency_sending = False
self._enable_signal_support = False
self._cap_prompt_support = False
def initialize(self):
self._selection_command = self._settings.get([b"selection_command"])
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
# Additional permissions hook
def get_additional_permissions(self):
return [
dict(key="INTERACT",
name="Interact with printer prompts",
description=gettext("Allows to see and interact with printer prompts"),
default_groups=[USER_GROUP],
roles=["interact"])
]
#~ AssetPlugin
@@ -52,14 +77,28 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
return dict(js=["js/action_command_prompt.js"],
clientjs=["clientjs/action_command_prompt.js"])
#~ EventHandlerPlugin
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
def get_settings_defaults(self):
return dict(selection_command=None)
return dict(enable="detected",
command=self.COMMAND,
enable_emergency_sending=True,
enable_signal_support=True)
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._selection_command = self._settings.get([b"selection_command"])
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
#~ SimpleApiPlugin
@@ -68,7 +107,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
def on_api_command(self, command, data):
if command == "select":
if not user_permission.can():
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
@@ -81,7 +120,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
self._answer_prompt(choice)
def on_api_get(self, request):
if not user_permission.can():
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
return flask.jsonify()
@@ -96,72 +135,108 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
#~ action command handler
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not action.startswith(b"prompt_"):
return
if self._selection_command is None:
self._logger.info("Got a prompt command from the printer but no selection command is defined")
if not action.startswith("prompt_"):
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = b""
parameter = ""
else:
action, parameter = parts
if action == b"prompt_begin":
if action == "prompt_begin":
if self._prompt is not None and self._prompt.active:
self._logger.warn("Prompt is already defined")
self._logger.warning("Prompt is already defined")
return
self._prompt = Prompt(parameter.strip())
elif action == b"prompt_choice" or action == b"prompt_button":
elif action == "prompt_choice" or action == "prompt_button":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warn("Prompt is already active")
self._logger.warning("Prompt is already active")
return
self._prompt.add_choice(parameter.strip())
elif action == b"prompt_show":
elif action == "prompt_show":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warn("Prompt is already active")
self._logger.warning("Prompt is already active")
return
self._show_prompt()
elif action == b"prompt_end":
elif action == "prompt_end":
if self._prompt is None:
return
self._close_prompt()
self._prompt = None
#~ queuing handling
def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs):
if gcode != self._command:
return
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending:
return
if not "S" in cmd:
# we only force-send M876 Sx
return
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode)
#~ capability reporting
def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs):
if capability == self.CAP_PROMPT_SUPPORT and enabled:
self._cap_prompt_support = True
if self._enable == "detected" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
#~ prompt handling
def _show_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
self._prompt.activate()
self._plugin_manager.send_plugin_message(self._identifier, dict(action="show",
text=self._prompt.text,
choices=self._prompt.choices))
def _close_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
self._prompt = None
self._plugin_manager.send_plugin_message(self._identifier, dict(action="close"))
def _answer_prompt(self, choice):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
self._close_prompt()
self._printer.commands([self._selection_command.format(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__ = {
b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
@@ -3,11 +3,22 @@ $(function() {
var self = this;
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.isUser()) return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
OctoPrint.plugins.action_command_prompt.get()
.done(self.fromResponse);
@@ -15,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) {
@@ -42,8 +62,9 @@ $(function() {
};
self._closePrompt = function() {
if (self._modal) {
self._modal.modal("hide");
var modal = self.modal();
if (modal) {
modal.modal("hide");
}
};
@@ -52,17 +73,21 @@ $(function() {
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (!self.loginState.isUser()) return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
if (plugin !== "action_command_prompt") {
return;
}
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;
}
@@ -73,6 +98,7 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: ActionCommandPromptViewModel,
dependencies: ["loginStateViewModel"]
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>
@@ -2,10 +2,43 @@
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Selection Command') }}</label>
<label class="control-label">{{ _('Enable support')}}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.selection_command">
<div class="help-block">{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace <code>{choice}</code> with the index of the selected choice. E.g. <code>M876 S{choice}</code> will become <code>M123 S1</code>') }}</div>
<label class="radio">
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="detected" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('If detected as supported by the firmware (<code>PROMPT_SUPPORT</code> capability)') }}
</label>
<label class="radio">
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="always" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('Always') }}
</label>
<label class="radio">
<input type="radio" name="pluginActionCommandPromptEnableGroup" value="never" data-bind="checked: settings.plugins.action_command_prompt.enable"> {{ _('Never') }}
</label>
</div>
</div>
<div class="advanced_options">
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.advanced_options', container: '.hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<div class="control-group">
<label class="control-label">{{ _('Dialog command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.command">
<div class="help-block">{{ _('Use this to define the dialog command. Default is <code>M876</code>. You normally should not have to change this.') }}</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.action_command_prompt.enable_emergency_sending"> {{ _('Enable force sending of the configured command to bypass blocking firmware routines if detected as supported. You normally should not have to change this.') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.action_command_prompt.enable_signal_support"> {{ _('Enable signaling to the firmware that we support <code>prompt_*</code> actions if detected as supported. You normally should not have to change this.') }}
</label>
</div>
</div>
</div>
</div>
</form>
+89 -55
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
# -*- 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'
@@ -9,23 +9,27 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms
import octoprint.plugin
import calendar
import codecs
import io
import os
import re
import time
import threading
import sys
PY2 = sys.version_info[0] < 3
import feedparser
import flask
from collections import OrderedDict
from octoprint.server import admin_permission
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.util import utmify
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
from octoprint.util import utmify, count, monotonic_time
from flask_babel import gettext
from octoprint import __version__ as OCTOPRINT_VERSION
class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
@@ -42,6 +46,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
self._slugify = Slugify()
self._slugify.safe_chars = "-_."
# Additional permissions hook
def get_additional_permissions(self):
return [
dict(key="READ",
name="Read announcements",
description=gettext("Allows to read announcements"),
default_groups=[ADMIN_GROUP],
roles=["read"]),
dict(key="MANAGE",
name="Manage announcement subscriptions",
description=gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" "
"permission"),
default_groups=[ADMIN_GROUP],
roles=["manage"],
permissions=["PLUGIN_ANNOUNCEMENTS_READ"])
]
# StartupPlugin
def on_after_startup(self):
@@ -87,7 +109,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
ttl=6*60,
display_limit=3,
summary_limit=300)
settings["enabled_channels"] = settings["channels"].keys()
settings["enabled_channels"] = list(settings["channels"].keys())
return settings
def get_settings_version(self):
@@ -127,14 +149,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
def get_template_configs(self):
return [
dict(type="settings", name=gettext("Announcements"), template="announcements_settings.jinja2", custom_bindings=True),
dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.isAdmin")
dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)")
]
# Blueprint Plugin
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"])
@restricted_access
@admin_permission.require(403)
@no_firstrun_access
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
def get_channel_data(self):
from octoprint.settings import valid_boolean_trues
@@ -153,7 +175,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
for key, data in channel_configs.items():
read_until = channel_configs[key].get("read_until", None)
entries = sorted(self._to_internal_feed(channel_data.get(key, []), read_until=read_until), key=lambda e: e["published"], reverse=True)
unread = len(filter(lambda e: not e["read"], entries))
unread = count(filter(lambda e: not e["read"], entries))
if read_until is None and entries:
last = entries[0]["published"]
@@ -174,14 +196,16 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
def etag():
import hashlib
hash = hashlib.sha1()
hash.update(repr(sorted(enabled)))
hash.update(repr(sorted(forced)))
hash.update(OCTOPRINT_VERSION)
def hash_update(value):
hash.update(value.encode("utf-8"))
hash_update(repr(sorted(enabled)))
hash_update(repr(sorted(forced)))
hash_update(OCTOPRINT_VERSION)
for channel in sorted(channel_configs.keys()):
hash.update(repr(channel_configs[channel]))
hash_update(repr(channel_configs[channel]))
channel_data = self._get_channel_data_from_cache(channel, channel_configs[channel])
hash.update(repr(channel_data))
hash_update(repr(channel_data))
return hash.hexdigest()
@@ -194,8 +218,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
unless=lambda: force)(view)()
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
@restricted_access
@admin_permission.require(403)
@no_firstrun_access
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
def channel_command(self, channel):
from octoprint.server.util.flask import get_json_command_from_request
from octoprint.server import NO_CONTENT
@@ -212,6 +236,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
self._mark_read_until(channel, until)
elif command == "toggle":
if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can():
return flask.make_response("Insufficient rights", 403)
self._toggle(channel)
return NO_CONTENT
@@ -339,7 +365,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
now = time.time()
if os.stat(channel_path).st_mtime + ttl > now:
d = feedparser.parse(channel_path)
self._logger.debug(u"Loaded channel {} from cache at {}".format(key, channel_path))
self._logger.debug("Loaded channel {} from cache at {}".format(key, channel_path))
return d
return None
@@ -351,18 +377,18 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
url = config["url"]
try:
start = time.time()
start = monotonic_time()
r = requests.get(url, timeout=30)
r.raise_for_status()
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
except Exception as e:
self._logger.info("Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start))
except Exception:
self._logger.exception(
u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e)))
"Could not fetch channel {} from {}".format(key, config["url"]))
return None
response = r.text
channel_path = self._get_channel_cache_path(key)
with codecs.open(channel_path, mode="w", encoding="utf-8") as f:
with io.open(channel_path, mode="wt", encoding="utf-8") as f:
f.write(response)
return feedparser.parse(response)
@@ -376,16 +402,16 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
internal_entry = self._to_internal_entry(entry, read_until=read_until)
if internal_entry:
result.append(internal_entry)
except:
except Exception:
self._logger.exception("Error while converting entry from feed, skipping it")
return result
def _to_internal_entry(self, entry, read_until=None):
"""Convert feed entries to internal data structure."""
timestamp = entry.get("published_parsed",
entry.get("updated_parsed",
None))
timestamp = entry.get("published_parsed", None)
if timestamp is None:
timestamp = entry.get("updated_parsed", None)
if timestamp is None:
return None
@@ -413,22 +439,22 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
_image_tag_re = re.compile(r'<img.*?/?>')
def _strip_images(text):
"""
>>> _strip_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
u"<a href='test.html'>I'm a link</a> and this is an image: "
>>> _strip_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">")
u'One and two and three and four '
>>> _strip_images(u"No images here")
u'No images here'
>>> _strip_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>") # doctest: +ALLOW_UNICODE
"<a href='test.html'>I'm a link</a> and this is an image: "
>>> _strip_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">") # doctest: +ALLOW_UNICODE
'One and two and three and four '
>>> _strip_images("No images here") # doctest: +ALLOW_UNICODE
'No images here'
"""
return _image_tag_re.sub('', text)
def _replace_images(text, callback):
"""
>>> callback = lambda img: "foobar"
>>> _replace_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback)
u"<a href='test.html'>I'm a link</a> and this is an image: foobar"
>>> _replace_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback)
u'One foobar and two foobar and three foobar and four foobar'
>>> _replace_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback) # doctest: +ALLOW_UNICODE
"<a href='test.html'>I'm a link</a> and this is an image: foobar"
>>> _replace_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback) # doctest: +ALLOW_UNICODE
'One foobar and two foobar and three foobar and four foobar'
"""
result = text
for match in _image_tag_re.finditer(text):
@@ -440,14 +466,14 @@ def _replace_images(text, callback):
_image_src_re = re.compile(r'src=(?P<quote>[\'"]*)(?P<src>.*?)(?P=quote)(?=\s+|>)')
def _lazy_images(text, placeholder=None):
"""
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png")
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="ph.png" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png")
u'One <img src="ph.png" data-src="one.jpg"> and two <img src="ph.png" data-src=\\'two.jpg\\' > and three <img src="ph.png" data-src=three.jpg> and four <img src="ph.png" data-src="four.png" alt="four">'
>>> _lazy_images(u"No images here")
u'No images here'
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>") # doctest: +ALLOW_UNICODE
'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png") # doctest: +ALLOW_UNICODE
'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="ph.png" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png") # doctest: +ALLOW_UNICODE
'One <img src="ph.png" data-src="one.jpg"> and two <img src="ph.png" data-src=\\'two.jpg\\' > and three <img src="ph.png" data-src=three.jpg> and four <img src="ph.png" data-src="four.png" alt="four">'
>>> _lazy_images("No images here") # doctest: +ALLOW_UNICODE
'No images here'
"""
if placeholder is None:
# 1px transparent gif
@@ -466,18 +492,22 @@ def _lazy_images(text, placeholder=None):
def _strip_tags(text):
"""
>>> _strip_tags(u"<a href='test.html'>Hello world</a>&lt;img src='foo.jpg'&gt;")
u"Hello world&lt;img src='foo.jpg'&gt;"
>>> _strip_tags(u"&#62; &#x3E; Foo")
u'&#62; &#x3E; Foo'
>>> _strip_tags("<a href='test.html'>Hello world</a>&lt;img src='foo.jpg'&gt;") # doctest: +ALLOW_UNICODE
"Hello world&lt;img src='foo.jpg'&gt;"
>>> _strip_tags("&#62; &#x3E; Foo") # doctest: +ALLOW_UNICODE
'&#62; &#x3E; Foo'
"""
from HTMLParser import HTMLParser
try:
# noinspection PyCompatibility
from html.parser import HTMLParser
except ImportError:
# noinspection PyCompatibility
from HTMLParser import HTMLParser
class TagStripper(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
def __init__(self, **kw):
HTMLParser.__init__(self, **kw)
self._fed = []
def handle_data(self, data):
@@ -492,7 +522,7 @@ def _strip_tags(text):
def get_data(self):
return "".join(self._fed)
tag_stripper = TagStripper()
tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False)
tag_stripper.feed(text)
return tag_stripper.get_data()
@@ -504,3 +534,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin you might miss i
"regarding security or other critical issues concerning OctoPrint.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = AnnouncementPlugin()
__plugin_hooks__ = {
'octoprint.access.permissions': __plugin_implementation__.get_additional_permissions
}
@@ -4,6 +4,7 @@ $(function() {
self.loginState = parameters[0];
self.settings = parameters[1];
self.access = parameters[2];
self.channels = new ItemListHelper(
"plugin.announcements.channels",
@@ -67,7 +68,7 @@ $(function() {
};
self.markRead = function(channel, until, reload) {
if (!self.loginState.isAdmin()) return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
reload = !!reload;
@@ -93,7 +94,7 @@ $(function() {
};
self.toggleChannel = function(channel) {
if (!self.loginState.isAdmin()) return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE)) return;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
@@ -118,7 +119,7 @@ $(function() {
};
self.retrieveData = function(force) {
if (!self.loginState.isAdmin()) return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
var url = PLUGIN_BASEURL + "announcements/channels";
if (force) {
@@ -136,7 +137,7 @@ $(function() {
};
self.fromResponse = function(data) {
if (!self.loginState.isAdmin()) return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
@@ -157,7 +158,7 @@ $(function() {
};
self.showAnnouncementDialog = function(channel) {
if (!self.loginState.isAdmin()) return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
// lazy load images that still need lazy-loading
$("#plugin_announcements_dialog_content article img").lazyload();
@@ -194,7 +195,7 @@ $(function() {
};
self.displayAnnouncements = function(channels) {
if (!self.loginState.isAdmin()) return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
@@ -321,12 +322,12 @@ $(function() {
self.settings.show("settings_plugin_announcements");
};
self.onUserLoggedIn = function() {
self.retrieveData();
};
self.onUserLoggedOut = function() {
self.hideAnnouncements();
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) {
self.hideAnnouncements();
} else {
self.retrieveData();
}
};
self.onStartup = function() {
@@ -344,7 +345,7 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: AnnouncementsViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel"],
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
elements: ["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
});
});
Loaded 100 of 447 files, more files were not shown because too many files have changed in this diff. Show more